-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
plugin-ssr.ts
302 lines (277 loc) · 9.51 KB
/
plugin-ssr.ts
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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
import { join } from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import type { Plugin as VitePlugin } from 'vite';
import type { AstroAdapter } from '../../../@types/astro.js';
import { isFunctionPerRouteEnabled } from '../../../integrations/hooks.js';
import { isServerLikeOutput } from '../../../prerender/utils.js';
import { routeIsRedirect } from '../../redirects/index.js';
import { addRollupInput } from '../add-rollup-input.js';
import type { BuildInternals } from '../internal.js';
import { eachPageFromAllPages } from '../internal.js';
import type { AstroBuildPlugin } from '../plugin.js';
import type { StaticBuildOptions } from '../types.js';
import { SSR_MANIFEST_VIRTUAL_MODULE_ID } from './plugin-manifest.js';
import { MIDDLEWARE_MODULE_ID } from './plugin-middleware.js';
import { ASTRO_PAGE_MODULE_ID } from './plugin-pages.js';
import { RENDERERS_MODULE_ID } from './plugin-renderers.js';
import { getPathFromVirtualModulePageName, getVirtualModulePageNameFromPath } from './util.js';
export const SSR_VIRTUAL_MODULE_ID = '@astrojs-ssr-virtual-entry';
export const RESOLVED_SSR_VIRTUAL_MODULE_ID = '\0' + SSR_VIRTUAL_MODULE_ID;
function vitePluginSSR(
internals: BuildInternals,
adapter: AstroAdapter,
options: StaticBuildOptions
): VitePlugin {
return {
name: '@astrojs/vite-plugin-astro-ssr-server',
enforce: 'post',
options(opts) {
return addRollupInput(opts, [SSR_VIRTUAL_MODULE_ID]);
},
resolveId(id) {
if (id === SSR_VIRTUAL_MODULE_ID) {
return RESOLVED_SSR_VIRTUAL_MODULE_ID;
}
},
async load(id) {
if (id === RESOLVED_SSR_VIRTUAL_MODULE_ID) {
const { allPages } = options;
const imports: string[] = [];
const contents: string[] = [];
const exports: string[] = [];
let i = 0;
const pageMap: string[] = [];
for (const [path, pageData] of eachPageFromAllPages(allPages)) {
if (routeIsRedirect(pageData.route)) {
continue;
}
const virtualModuleName = getVirtualModulePageNameFromPath(ASTRO_PAGE_MODULE_ID, path);
let module = await this.resolve(virtualModuleName);
if (module) {
const variable = `_page${i}`;
// we need to use the non-resolved ID in order to resolve correctly the virtual module
imports.push(`const ${variable} = () => import("${virtualModuleName}");`);
const pageData2 = internals.pagesByComponent.get(path);
if (pageData2) {
pageMap.push(`[${JSON.stringify(pageData2.component)}, ${variable}]`);
}
i++;
}
}
contents.push(`const pageMap = new Map([\n ${pageMap.join(',\n ')}\n]);`);
exports.push(`export { pageMap }`);
const middleware = await this.resolve(MIDDLEWARE_MODULE_ID);
const ssrCode = generateSSRCode(adapter, middleware!.id);
imports.push(...ssrCode.imports);
contents.push(...ssrCode.contents);
return [...imports, ...contents, ...exports].join('\n');
}
return void 0;
},
async generateBundle(_opts, bundle) {
// Add assets from this SSR chunk as well.
for (const [, chunk] of Object.entries(bundle)) {
if (chunk.type === 'asset') {
internals.staticFiles.add(chunk.fileName);
}
}
for (const [, chunk] of Object.entries(bundle)) {
if (chunk.type === 'asset') {
continue;
}
if (chunk.modules[RESOLVED_SSR_VIRTUAL_MODULE_ID]) {
internals.ssrEntryChunk = chunk;
}
}
},
};
}
export function pluginSSR(
options: StaticBuildOptions,
internals: BuildInternals
): AstroBuildPlugin {
const ssr = isServerLikeOutput(options.settings.config);
const functionPerRouteEnabled = isFunctionPerRouteEnabled(options.settings.adapter);
return {
targets: ['server'],
hooks: {
'build:before': () => {
let vitePlugin =
ssr && functionPerRouteEnabled === false
? vitePluginSSR(internals, options.settings.adapter!, options)
: undefined;
return {
enforce: 'after-user-plugins',
vitePlugin,
};
},
'build:post': async () => {
if (!ssr) {
return;
}
if (functionPerRouteEnabled) {
return;
}
if (!internals.ssrEntryChunk) {
throw new Error(`Did not generate an entry chunk for SSR`);
}
// Mutate the filename
internals.ssrEntryChunk.fileName = options.settings.config.build.serverEntry;
},
},
};
}
export const SPLIT_MODULE_ID = '@astro-page-split:';
export const RESOLVED_SPLIT_MODULE_ID = '\0@astro-page-split:';
function vitePluginSSRSplit(
internals: BuildInternals,
adapter: AstroAdapter,
options: StaticBuildOptions
): VitePlugin {
const functionPerRouteEnabled = isFunctionPerRouteEnabled(options.settings.adapter);
return {
name: '@astrojs/vite-plugin-astro-ssr-split',
enforce: 'post',
options(opts) {
if (functionPerRouteEnabled) {
const inputs = new Set<string>();
for (const [path, pageData] of eachPageFromAllPages(options.allPages)) {
if (routeIsRedirect(pageData.route)) {
continue;
}
inputs.add(getVirtualModulePageNameFromPath(SPLIT_MODULE_ID, path));
}
return addRollupInput(opts, Array.from(inputs));
}
},
resolveId(id) {
if (id.startsWith(SPLIT_MODULE_ID)) {
return '\0' + id;
}
},
async load(id) {
if (id.startsWith(RESOLVED_SPLIT_MODULE_ID)) {
const imports: string[] = [];
const contents: string[] = [];
const exports: string[] = [];
const path = getPathFromVirtualModulePageName(RESOLVED_SPLIT_MODULE_ID, id);
const virtualModuleName = getVirtualModulePageNameFromPath(ASTRO_PAGE_MODULE_ID, path);
let module = await this.resolve(virtualModuleName);
if (module) {
// we need to use the non-resolved ID in order to resolve correctly the virtual module
imports.push(`import * as pageModule from "${virtualModuleName}";`);
}
const middleware = await this.resolve(MIDDLEWARE_MODULE_ID);
const ssrCode = generateSSRCode(adapter, middleware!.id);
imports.push(...ssrCode.imports);
contents.push(...ssrCode.contents);
exports.push('export { pageModule }');
return [...imports, ...contents, ...exports].join('\n');
}
return void 0;
},
async generateBundle(_opts, bundle) {
// Add assets from this SSR chunk as well.
for (const [, chunk] of Object.entries(bundle)) {
if (chunk.type === 'asset') {
internals.staticFiles.add(chunk.fileName);
}
}
for (const [, chunk] of Object.entries(bundle)) {
if (chunk.type === 'asset') {
continue;
}
for (const moduleKey of Object.keys(chunk.modules)) {
if (moduleKey.startsWith(RESOLVED_SPLIT_MODULE_ID)) {
internals.ssrSplitEntryChunks.set(moduleKey, chunk);
storeEntryPoint(moduleKey, options, internals, chunk.fileName);
}
}
}
},
};
}
export function pluginSSRSplit(
options: StaticBuildOptions,
internals: BuildInternals
): AstroBuildPlugin {
const ssr = isServerLikeOutput(options.settings.config);
const functionPerRouteEnabled = isFunctionPerRouteEnabled(options.settings.adapter);
return {
targets: ['server'],
hooks: {
'build:before': () => {
let vitePlugin =
ssr && functionPerRouteEnabled
? vitePluginSSRSplit(internals, options.settings.adapter!, options)
: undefined;
return {
enforce: 'after-user-plugins',
vitePlugin,
};
},
},
};
}
function generateSSRCode(adapter: AstroAdapter, middlewareId: string) {
const edgeMiddleware = adapter?.adapterFeatures?.edgeMiddleware ?? false;
const pageMap = isFunctionPerRouteEnabled(adapter) ? 'pageModule' : 'pageMap';
const imports = [
`import { renderers } from '${RENDERERS_MODULE_ID}';`,
`import { manifest as defaultManifest } from '${SSR_MANIFEST_VIRTUAL_MODULE_ID}';`,
`import * as serverEntrypointModule from '${adapter.serverEntrypoint}';`,
edgeMiddleware ? `` : `import { onRequest as middleware } from '${middlewareId}';`,
];
const contents = [
edgeMiddleware ? `const middleware = (_, next) => next()` : '',
`const _manifest = Object.assign(defaultManifest, {`,
` ${pageMap},`,
` renderers,`,
` middleware`,
`});`,
`const _args = ${adapter.args ? JSON.stringify(adapter.args, null, 4) : 'undefined'};`,
adapter.exports
? `const _exports = serverEntrypointModule.createExports(_manifest, _args);`
: '',
...(adapter.exports?.map((name) => {
if (name === 'default') {
return `export default _exports.default;`;
} else {
return `export const ${name} = _exports['${name}'];`;
}
}) ?? []),
// NOTE: This is intentionally obfuscated!
// Do NOT simplify this to something like `serverEntrypointModule.start?.(_manifest, _args)`
// They are NOT equivalent! Some bundlers will throw if `start` is not exported, but we
// only want to silently ignore it... hence the dynamic, obfuscated weirdness.
`const _start = 'start';
if (_start in serverEntrypointModule) {
serverEntrypointModule[_start](_manifest, _args);
}`,
];
return {
imports,
contents,
};
}
/**
* Because we delete the bundle from rollup at the end of this function,
* we can't use `writeBundle` hook to get the final file name of the entry point written on disk.
* We use this hook instead.
*
* We retrieve the {@link RouteData} that belongs the current moduleKey
*/
function storeEntryPoint(
moduleKey: string,
options: StaticBuildOptions,
internals: BuildInternals,
fileName: string
) {
const componentPath = getPathFromVirtualModulePageName(RESOLVED_SPLIT_MODULE_ID, moduleKey);
for (const [page, pageData] of eachPageFromAllPages(options.allPages)) {
if (componentPath == page) {
const publicPath = fileURLToPath(options.settings.config.build.server);
internals.entryPoints.set(pageData.route, pathToFileURL(join(publicPath, fileName)));
}
}
}