-
Notifications
You must be signed in to change notification settings - Fork 10
/
index.js
208 lines (173 loc) · 6.83 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
import fs from 'fs/promises';
import path from 'path';
import { checkResourceExists, normalizePathnameForWindows } from '@greenwood/cli/src/lib/resource-utils.js';
import { zip } from 'zip-a-folder';
// https://docs.netlify.com/functions/create/?fn-language=js
function generateOutputFormat(id) {
const handlerAlias = '$handler';
return `
import { handler as ${handlerAlias} } from './__${id}.js';
export async function handler (event, context = {}) {
const { rawUrl, body, headers = {}, httpMethod } = event;
const contentType = headers['content-type'] || '';
let format = body;
if (['GET', 'HEAD'].includes(httpMethod.toUpperCase())) {
format = null
} else if (contentType.includes('application/x-www-form-urlencoded')) {
const searchParams = new URLSearchParams(body);
const formData = new FormData();
for (const key of searchParams.keys()) {
const value = searchParams.get(key);
formData.append(key, value);
}
// when using FormData, let Request set the correct headers
// or else it will come out as multipart/form-data
// https://stackoverflow.com/a/43521052/417806
format = formData;
delete headers['content-type'];
} else if(contentType.includes('application/json')) {
format = JSON.stringify(body);
}
const request = new Request(rawUrl, {
body: format,
method: httpMethod,
headers: new Headers(headers)
});
const response = await ${handlerAlias}(request, context);
return {
statusCode: response.status,
body: await response.text(),
headers: response.headers || new Headers()
};
}
`;
}
async function setupOutputDirectory(id, outputRoot, outputType) {
const outputFormat = generateOutputFormat(id, outputType);
const filename = outputType === 'api'
? `api-${id}`
: `${id}`;
await fs.mkdir(outputRoot, { recursive: true });
await fs.writeFile(new URL(`./${filename}.js`, outputRoot), outputFormat);
await fs.writeFile(new URL('./package.json', outputRoot), JSON.stringify({
type: 'module'
}));
}
// TODO manifest options, like node version?
// https://github.com/netlify/zip-it-and-ship-it#options
async function createOutputZip(id, outputType, outputRootUrl, projectDirectory) {
const filename = outputType === 'api'
? `api-${id}`
: `${id}`;
await zip(
normalizePathnameForWindows(outputRootUrl),
normalizePathnameForWindows(new URL(`./netlify/functions/${filename}.zip`, projectDirectory))
);
}
async function netlifyAdapter(compilation) {
const { outputDir, projectDirectory, scratchDir } = compilation.context;
const { basePath } = compilation.config;
const adapterOutputUrl = new URL('./netlify/functions/', scratchDir);
const ssrPages = compilation.graph.filter(page => page.isSSR);
const apiRoutes = compilation.manifest.apis;
// https://docs.netlify.com/routing/redirects/
// https://docs.netlify.com/routing/redirects/rewrites-proxies/
// When you assign an HTTP status code of 200 to a redirect rule, it becomes a rewrite.
let redirects = '';
if (!await checkResourceExists(adapterOutputUrl)) {
await fs.mkdir(adapterOutputUrl, { recursive: true });
}
const files = await fs.readdir(outputDir);
const isExecuteRouteModule = files.find(file => file.startsWith('execute-route-module'));
await fs.mkdir(new URL('./netlify/functions/', projectDirectory), { recursive: true });
for (const page of ssrPages) {
const { id } = page;
const outputType = 'page';
const outputRoot = new URL(`./${id}/`, adapterOutputUrl);
await setupOutputDirectory(id, outputRoot, outputType);
await fs.cp(
new URL(`./_${id}.js`, outputDir),
new URL(`./_${id}.js`, outputRoot),
{ recursive: true }
);
await fs.cp(
new URL(`./__${id}.js`, outputDir),
new URL(`./__${id}.js`, outputRoot),
{ recursive: true }
);
// TODO quick hack to make serverless pages are fully self-contained
// for example, execute-route-module.js will only get code split if there are more than one SSR pages
// https://github.com/ProjectEvergreen/greenwood/issues/1118
if (isExecuteRouteModule) {
await fs.cp(
new URL(`./${isExecuteRouteModule}`, outputDir),
new URL(`./${isExecuteRouteModule}`, outputRoot)
);
}
// TODO how to track SSR resources that get dumped out in the public directory?
// https://github.com/ProjectEvergreen/greenwood/issues/1118
const ssrPageAssets = (await fs.readdir(outputDir))
.filter(file => !path.basename(file).startsWith('_')
&& !path.basename(file).startsWith('execute')
&& path.basename(file).endsWith('.js')
);
for (const asset of ssrPageAssets) {
await fs.cp(
new URL(`./${asset}`, outputDir),
new URL(`./${asset}`, outputRoot),
{ recursive: true }
);
}
await createOutputZip(id, outputType, new URL(`./${id}/`, adapterOutputUrl), projectDirectory);
redirects += `${basePath}/${id}/ /.netlify/functions/${id} 200
`;
}
if (apiRoutes.size > 0) {
redirects += `${basePath}/api/* /.netlify/functions/api-:splat 200`;
}
for (const [key] of apiRoutes) {
const outputType = 'api';
const id = key.replace(`${basePath}/api/`, '');
const outputRoot = new URL(`./api/${id}/`, adapterOutputUrl);
await setupOutputDirectory(id, outputRoot, outputType);
// TODO ideally all functions would be self contained
// https://github.com/ProjectEvergreen/greenwood/issues/1118
await fs.cp(
new URL(`./api/${id}.js`, outputDir),
new URL(`./__${id}.js`, outputRoot),
{ recursive: true }
);
if (await checkResourceExists(new URL('./api/assets/', outputDir))) {
await fs.cp(
new URL('./api/assets/', outputDir),
new URL('./assets/', outputRoot),
{ recursive: true }
);
}
const ssrApiAssets = (await fs.readdir(new URL('./api/', outputDir)))
.filter(file => new RegExp(/^[\w][\w-]*\.[a-zA-Z0-9]{4,20}\.[\w]{2,4}$/).test(path.basename(file)));
for (const asset of ssrApiAssets) {
await fs.cp(
new URL(`./${asset}`, new URL('./api/', outputDir)),
new URL(`./${asset}`, outputRoot),
{ recursive: true }
);
}
// NOTE: All functions must live at the top level
// https://github.com/netlify/netlify-lambda/issues/90#issuecomment-486047201
await createOutputZip(id, outputType, outputRoot, projectDirectory);
}
if (redirects !== '') {
await fs.writeFile(new URL('./_redirects', outputDir), redirects);
}
}
const greenwoodPluginAdapterNetlify = (options = {}) => [{
type: 'adapter',
name: 'plugin-adapter-netlify',
provider: (compilation) => {
return async () => {
await netlifyAdapter(compilation, options);
};
}
}];
export { greenwoodPluginAdapterNetlify };