@sveltejs/kit 1.0.0-next.29 → 1.0.0-next.292

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/README.md +12 -9
  2. package/assets/app/env.js +20 -0
  3. package/assets/app/navigation.js +24 -0
  4. package/assets/app/paths.js +1 -0
  5. package/assets/app/stores.js +97 -0
  6. package/assets/client/singletons.js +13 -0
  7. package/assets/client/start.js +1523 -0
  8. package/assets/components/error.svelte +18 -2
  9. package/assets/env.js +8 -0
  10. package/assets/paths.js +13 -0
  11. package/assets/server/index.js +2797 -0
  12. package/dist/chunks/amp_hook.js +56 -0
  13. package/dist/chunks/cert.js +28154 -0
  14. package/dist/chunks/constants.js +663 -0
  15. package/dist/chunks/filesystem.js +110 -0
  16. package/dist/chunks/index.js +508 -0
  17. package/dist/chunks/index2.js +1307 -0
  18. package/dist/chunks/index3.js +118 -0
  19. package/dist/chunks/index4.js +196 -0
  20. package/dist/chunks/index5.js +242 -0
  21. package/dist/chunks/index6.js +15585 -0
  22. package/dist/chunks/index7.js +4207 -0
  23. package/dist/chunks/misc.js +3 -0
  24. package/dist/chunks/multipart-parser.js +449 -0
  25. package/dist/chunks/object.js +83 -0
  26. package/dist/chunks/sync.js +999 -0
  27. package/dist/chunks/url.js +56 -0
  28. package/dist/cli.js +1018 -85
  29. package/dist/hooks.js +28 -0
  30. package/dist/install-fetch.js +6518 -0
  31. package/dist/node.js +94 -0
  32. package/package.json +92 -54
  33. package/svelte-kit.js +2 -0
  34. package/types/ambient.d.ts +303 -0
  35. package/types/index.d.ts +166 -0
  36. package/types/internal.d.ts +318 -0
  37. package/types/private.d.ts +357 -0
  38. package/CHANGELOG.md +0 -332
  39. package/assets/runtime/app/navigation.js +0 -23
  40. package/assets/runtime/app/navigation.js.map +0 -1
  41. package/assets/runtime/app/paths.js +0 -2
  42. package/assets/runtime/app/paths.js.map +0 -1
  43. package/assets/runtime/app/stores.js +0 -78
  44. package/assets/runtime/app/stores.js.map +0 -1
  45. package/assets/runtime/internal/singletons.js +0 -15
  46. package/assets/runtime/internal/singletons.js.map +0 -1
  47. package/assets/runtime/internal/start.js +0 -591
  48. package/assets/runtime/internal/start.js.map +0 -1
  49. package/assets/runtime/utils-85ebcc60.js +0 -18
  50. package/assets/runtime/utils-85ebcc60.js.map +0 -1
  51. package/dist/api.js +0 -44
  52. package/dist/api.js.map +0 -1
  53. package/dist/build.js +0 -246
  54. package/dist/build.js.map +0 -1
  55. package/dist/cli.js.map +0 -1
  56. package/dist/colors.js +0 -37
  57. package/dist/colors.js.map +0 -1
  58. package/dist/create_app.js +0 -580
  59. package/dist/create_app.js.map +0 -1
  60. package/dist/index.js +0 -368
  61. package/dist/index.js.map +0 -1
  62. package/dist/index2.js +0 -12035
  63. package/dist/index2.js.map +0 -1
  64. package/dist/index3.js +0 -549
  65. package/dist/index3.js.map +0 -1
  66. package/dist/index4.js +0 -74
  67. package/dist/index4.js.map +0 -1
  68. package/dist/index5.js +0 -464
  69. package/dist/index5.js.map +0 -1
  70. package/dist/index6.js +0 -735
  71. package/dist/index6.js.map +0 -1
  72. package/dist/logging.js +0 -43
  73. package/dist/logging.js.map +0 -1
  74. package/dist/package.js +0 -432
  75. package/dist/package.js.map +0 -1
  76. package/dist/renderer.js +0 -2425
  77. package/dist/renderer.js.map +0 -1
  78. package/dist/standard.js +0 -101
  79. package/dist/standard.js.map +0 -1
  80. package/dist/utils.js +0 -58
  81. package/dist/utils.js.map +0 -1
  82. package/svelte-kit +0 -3
@@ -0,0 +1,1307 @@
1
+ import fs__default, { readFileSync, writeFileSync } from 'fs';
2
+ import path__default, { join, dirname } from 'path';
3
+ import { p as posixify, m as mkdirp, r as rimraf } from './filesystem.js';
4
+ import { all } from './sync.js';
5
+ import { p as print_config_conflicts, b as get_aliases, r as resolve_entry, g as get_runtime_path, l as load_template } from '../cli.js';
6
+ import { g as generate_manifest } from './index3.js';
7
+ import vite from 'vite';
8
+ import { s } from './misc.js';
9
+ import { d as deep_merge } from './object.js';
10
+ import { n as normalize_path, r as resolve, i as is_root_relative } from './url.js';
11
+ import { svelte } from '@sveltejs/vite-plugin-svelte';
12
+ import { pathToFileURL, URL } from 'url';
13
+ import { installFetch } from '../install-fetch.js';
14
+ import 'sade';
15
+ import 'child_process';
16
+ import 'net';
17
+ import 'os';
18
+ import 'node:http';
19
+ import 'node:https';
20
+ import 'node:zlib';
21
+ import 'node:stream';
22
+ import 'node:util';
23
+ import 'node:url';
24
+
25
+ /**
26
+ * @param {{
27
+ * cwd: string;
28
+ * assets_base: string;
29
+ * config: import('types').ValidatedConfig;
30
+ * manifest_data: import('types').ManifestData;
31
+ * output_dir: string;
32
+ * service_worker_entry_file: string | null;
33
+ * }} options
34
+ * @param {import('types').Prerendered} prerendered
35
+ * @param {import('vite').Manifest} client_manifest
36
+ */
37
+ async function build_service_worker(
38
+ { cwd, assets_base, config, manifest_data, output_dir, service_worker_entry_file },
39
+ prerendered,
40
+ client_manifest
41
+ ) {
42
+ // TODO add any assets referenced in template .html file, e.g. favicon?
43
+ const app_files = new Set();
44
+ for (const key in client_manifest) {
45
+ const { file, css } = client_manifest[key];
46
+ app_files.add(file);
47
+ if (css) {
48
+ css.forEach((file) => {
49
+ app_files.add(file);
50
+ });
51
+ }
52
+ }
53
+
54
+ const service_worker = `${config.kit.outDir}/generated/service-worker.js`;
55
+
56
+ fs__default.writeFileSync(
57
+ service_worker,
58
+ `
59
+ export const timestamp = ${Date.now()};
60
+
61
+ export const build = [
62
+ ${Array.from(app_files)
63
+ .map((file) => `${s(`${config.kit.paths.base}/${config.kit.appDir}/${file}`)}`)
64
+ .join(',\n\t\t\t\t')}
65
+ ];
66
+
67
+ export const files = [
68
+ ${manifest_data.assets
69
+ .map((asset) => `${s(`${config.kit.paths.base}/${asset.file}`)}`)
70
+ .join(',\n\t\t\t\t')}
71
+ ];
72
+
73
+ export const prerendered = [
74
+ ${prerendered.paths
75
+ .map((path) => s(normalize_path(path, config.kit.trailingSlash)))
76
+ .join(',\n\t\t\t\t')}
77
+ ];
78
+ `
79
+ .replace(/^\t{3}/gm, '')
80
+ .trim()
81
+ );
82
+
83
+ /** @type {[any, string[]]} */
84
+ const [merged_config, conflicts] = deep_merge(await config.kit.vite(), {
85
+ configFile: false,
86
+ root: cwd,
87
+ base: assets_base,
88
+ build: {
89
+ lib: {
90
+ entry: service_worker_entry_file,
91
+ name: 'app',
92
+ formats: ['es']
93
+ },
94
+ rollupOptions: {
95
+ output: {
96
+ entryFileNames: 'service-worker.js'
97
+ }
98
+ },
99
+ outDir: `${output_dir}/client`,
100
+ emptyOutDir: false
101
+ },
102
+ resolve: {
103
+ alias: {
104
+ '$service-worker': service_worker,
105
+ $lib: config.kit.files.lib
106
+ }
107
+ }
108
+ });
109
+
110
+ print_config_conflicts(conflicts, 'kit.vite.', 'build_service_worker');
111
+
112
+ await vite.build(merged_config);
113
+ }
114
+
115
+ /**
116
+ * @typedef {import('rollup').RollupOutput} RollupOutput
117
+ * @typedef {import('rollup').OutputChunk} OutputChunk
118
+ * @typedef {import('rollup').OutputAsset} OutputAsset
119
+ */
120
+
121
+ /** @param {import('vite').UserConfig} config */
122
+ async function create_build(config) {
123
+ const { output } = /** @type {RollupOutput} */ (await vite.build(config));
124
+
125
+ const chunks = output.filter(
126
+ /** @returns {output is OutputChunk} */ (output) => output.type === 'chunk'
127
+ );
128
+
129
+ const assets = output.filter(
130
+ /** @returns {output is OutputAsset} */ (output) => output.type === 'asset'
131
+ );
132
+
133
+ return { chunks, assets };
134
+ }
135
+
136
+ /**
137
+ * @param {string} file
138
+ * @param {import('vite').Manifest} manifest
139
+ * @param {Set<string>} css
140
+ * @param {Set<string>} js
141
+ * @returns
142
+ */
143
+ function find_deps(file, manifest, js, css) {
144
+ const chunk = manifest[file];
145
+
146
+ if (js.has(chunk.file)) return;
147
+ js.add(chunk.file);
148
+
149
+ if (chunk.css) {
150
+ chunk.css.forEach((file) => css.add(file));
151
+ }
152
+
153
+ if (chunk.imports) {
154
+ chunk.imports.forEach((file) => find_deps(file, manifest, js, css));
155
+ }
156
+ }
157
+
158
+ /**
159
+ * @param {{
160
+ * cwd: string;
161
+ * assets_base: string;
162
+ * config: import('types').ValidatedConfig
163
+ * manifest_data: import('types').ManifestData
164
+ * output_dir: string;
165
+ * client_entry_file: string;
166
+ * service_worker_entry_file: string | null;
167
+ * service_worker_register: boolean;
168
+ * }} options
169
+ */
170
+ async function build_client({
171
+ cwd,
172
+ assets_base,
173
+ config,
174
+ manifest_data,
175
+ output_dir,
176
+ client_entry_file
177
+ }) {
178
+ process.env.VITE_SVELTEKIT_APP_VERSION = config.kit.version.name;
179
+ process.env.VITE_SVELTEKIT_APP_VERSION_FILE = `${config.kit.appDir}/version.json`;
180
+ process.env.VITE_SVELTEKIT_APP_VERSION_POLL_INTERVAL = `${config.kit.version.pollInterval}`;
181
+
182
+ process.env.VITE_SVELTEKIT_AMP = config.kit.amp ? 'true' : '';
183
+
184
+ const client_out_dir = `${output_dir}/client/${config.kit.appDir}`;
185
+
186
+ /** @type {Record<string, string>} */
187
+ const input = {
188
+ start: path__default.resolve(cwd, client_entry_file)
189
+ };
190
+
191
+ // This step is optional — Vite/Rollup will create the necessary chunks
192
+ // for everything regardless — but it means that entry chunks reflect
193
+ // their location in the source code, which is helpful for debugging
194
+ manifest_data.components.forEach((file) => {
195
+ const resolved = path__default.resolve(cwd, file);
196
+ const relative = path__default.relative(config.kit.files.routes, resolved);
197
+
198
+ const name = relative.startsWith('..')
199
+ ? path__default.basename(file)
200
+ : posixify(path__default.join('pages', relative));
201
+ input[name] = resolved;
202
+ });
203
+
204
+ /** @type {[any, string[]]} */
205
+ const [merged_config, conflicts] = deep_merge(await config.kit.vite(), {
206
+ configFile: false,
207
+ root: cwd,
208
+ base: assets_base,
209
+ build: {
210
+ cssCodeSplit: true,
211
+ manifest: true,
212
+ outDir: client_out_dir,
213
+ polyfillDynamicImport: false,
214
+ rollupOptions: {
215
+ input,
216
+ output: {
217
+ entryFileNames: '[name]-[hash].js',
218
+ chunkFileNames: 'chunks/[name]-[hash].js',
219
+ assetFileNames: 'assets/[name]-[hash][extname]'
220
+ },
221
+ preserveEntrySignatures: 'strict'
222
+ }
223
+ },
224
+ resolve: {
225
+ alias: get_aliases(config)
226
+ },
227
+ plugins: [
228
+ svelte({
229
+ extensions: config.extensions,
230
+ // In AMP mode, we know that there are no conditional component imports. In that case, we
231
+ // don't need to include CSS for components that are imported but unused, so we can just
232
+ // include rendered CSS.
233
+ // This would also apply if hydrate and router are both false, but we don't know if one
234
+ // has been enabled at the page level, so we don't do anything there.
235
+ emitCss: !config.kit.amp,
236
+ compilerOptions: {
237
+ hydratable: !!config.kit.browser.hydrate
238
+ }
239
+ })
240
+ ],
241
+ // prevent Vite copying the contents of `config.kit.files.assets`,
242
+ // if it happens to be 'public' instead of 'static'
243
+ publicDir: false
244
+ });
245
+
246
+ print_config_conflicts(conflicts, 'kit.vite.', 'build_client');
247
+
248
+ const { chunks, assets } = await create_build(merged_config);
249
+
250
+ /** @type {import('vite').Manifest} */
251
+ const vite_manifest = JSON.parse(fs__default.readFileSync(`${client_out_dir}/manifest.json`, 'utf-8'));
252
+
253
+ const entry = posixify(client_entry_file);
254
+ const entry_js = new Set();
255
+ const entry_css = new Set();
256
+ find_deps(entry, vite_manifest, entry_js, entry_css);
257
+
258
+ fs__default.writeFileSync(
259
+ `${client_out_dir}/version.json`,
260
+ JSON.stringify({ version: process.env.VITE_SVELTEKIT_APP_VERSION })
261
+ );
262
+
263
+ return {
264
+ assets,
265
+ chunks,
266
+ entry: {
267
+ file: vite_manifest[entry].file,
268
+ js: Array.from(entry_js),
269
+ css: Array.from(entry_css)
270
+ },
271
+ vite_manifest
272
+ };
273
+ }
274
+
275
+ /**
276
+ * @param {{
277
+ * hooks: string;
278
+ * config: import('types').ValidatedConfig;
279
+ * has_service_worker: boolean;
280
+ * runtime: string;
281
+ * template: string;
282
+ * }} opts
283
+ * @returns
284
+ */
285
+ const server_template = ({ config, hooks, has_service_worker, runtime, template }) => `
286
+ import root from '__GENERATED__/root.svelte';
287
+ import { respond } from '${runtime}/server/index.js';
288
+ import { set_paths, assets, base } from '${runtime}/paths.js';
289
+ import { set_prerendering } from '${runtime}/env.js';
290
+ import * as user_hooks from ${s(hooks)};
291
+
292
+ const template = ({ head, body, assets, nonce }) => ${s(template)
293
+ .replace('%svelte.head%', '" + head + "')
294
+ .replace('%svelte.body%', '" + body + "')
295
+ .replace(/%svelte\.assets%/g, '" + assets + "')
296
+ .replace(/%svelte\.nonce%/g, '" + nonce + "')};
297
+
298
+ let read = null;
299
+
300
+ set_paths(${s(config.kit.paths)});
301
+
302
+ // this looks redundant, but the indirection allows us to access
303
+ // named imports without triggering Rollup's missing import detection
304
+ const get_hooks = hooks => ({
305
+ getSession: hooks.getSession || (() => ({})),
306
+ handle: hooks.handle || (({ event, resolve }) => resolve(event)),
307
+ handleError: hooks.handleError || (({ error }) => console.error(error.stack)),
308
+ externalFetch: hooks.externalFetch || fetch
309
+ });
310
+
311
+ let default_protocol = 'https';
312
+
313
+ // allow paths to be globally overridden
314
+ // in svelte-kit preview and in prerendering
315
+ export function override(settings) {
316
+ default_protocol = settings.protocol || default_protocol;
317
+ set_paths(settings.paths);
318
+ set_prerendering(settings.prerendering);
319
+ read = settings.read;
320
+ }
321
+
322
+ export class Server {
323
+ constructor(manifest) {
324
+ const hooks = get_hooks(user_hooks);
325
+
326
+ this.options = {
327
+ amp: ${config.kit.amp},
328
+ csp: ${s(config.kit.csp)},
329
+ dev: false,
330
+ floc: ${config.kit.floc},
331
+ get_stack: error => String(error), // for security
332
+ handle_error: (error, event) => {
333
+ hooks.handleError({
334
+ error,
335
+ event,
336
+
337
+ // TODO remove for 1.0
338
+ // @ts-expect-error
339
+ get request() {
340
+ throw new Error('request in handleError has been replaced with event. See https://github.com/sveltejs/kit/pull/3384 for details');
341
+ }
342
+ });
343
+ error.stack = this.options.get_stack(error);
344
+ },
345
+ hooks,
346
+ hydrate: ${s(config.kit.browser.hydrate)},
347
+ manifest,
348
+ method_override: ${s(config.kit.methodOverride)},
349
+ paths: { base, assets },
350
+ prefix: assets + '/${config.kit.appDir}/',
351
+ prerender: ${config.kit.prerender.enabled},
352
+ read,
353
+ root,
354
+ service_worker: ${has_service_worker ? "base + '/service-worker.js'" : 'null'},
355
+ router: ${s(config.kit.browser.router)},
356
+ template,
357
+ template_contains_nonce: ${template.includes('%svelte.nonce%')},
358
+ trailing_slash: ${s(config.kit.trailingSlash)}
359
+ };
360
+ }
361
+
362
+ respond(request, options = {}) {
363
+ if (!(request instanceof Request)) {
364
+ throw new Error('The first argument to app.render must be a Request object. See https://github.com/sveltejs/kit/pull/3384 for details');
365
+ }
366
+
367
+ return respond(request, this.options, options);
368
+ }
369
+ }
370
+ `;
371
+
372
+ /**
373
+ * @param {{
374
+ * cwd: string;
375
+ * assets_base: string;
376
+ * config: import('types').ValidatedConfig
377
+ * manifest_data: import('types').ManifestData
378
+ * build_dir: string;
379
+ * output_dir: string;
380
+ * service_worker_entry_file: string | null;
381
+ * service_worker_register: boolean;
382
+ * }} options
383
+ * @param {{ vite_manifest: import('vite').Manifest, assets: import('rollup').OutputAsset[] }} client
384
+ */
385
+ async function build_server(
386
+ {
387
+ cwd,
388
+ assets_base,
389
+ config,
390
+ manifest_data,
391
+ build_dir,
392
+ output_dir,
393
+ service_worker_entry_file,
394
+ service_worker_register
395
+ },
396
+ client
397
+ ) {
398
+ let hooks_file = resolve_entry(config.kit.files.hooks);
399
+ if (!hooks_file || !fs__default.existsSync(hooks_file)) {
400
+ hooks_file = path__default.join(config.kit.outDir, 'build/hooks.js');
401
+ fs__default.writeFileSync(hooks_file, '');
402
+ }
403
+
404
+ /** @type {Record<string, string>} */
405
+ const input = {
406
+ index: `${build_dir}/index.js`
407
+ };
408
+
409
+ // add entry points for every endpoint...
410
+ manifest_data.routes.forEach((route) => {
411
+ const file = route.type === 'endpoint' ? route.file : route.shadow;
412
+
413
+ if (file) {
414
+ const resolved = path__default.resolve(cwd, file);
415
+ const relative = path__default.relative(config.kit.files.routes, resolved);
416
+ const name = posixify(path__default.join('entries/endpoints', relative.replace(/\.js$/, '')));
417
+ input[name] = resolved;
418
+ }
419
+ });
420
+
421
+ // ...and every component used by pages
422
+ manifest_data.components.forEach((file) => {
423
+ const resolved = path__default.resolve(cwd, file);
424
+ const relative = path__default.relative(config.kit.files.routes, resolved);
425
+
426
+ const name = relative.startsWith('..')
427
+ ? posixify(path__default.join('entries/pages', path__default.basename(file)))
428
+ : posixify(path__default.join('entries/pages', relative));
429
+ input[name] = resolved;
430
+ });
431
+
432
+ /** @type {(file: string) => string} */
433
+ const app_relative = (file) => {
434
+ const relative_file = path__default.relative(build_dir, path__default.resolve(cwd, file));
435
+ return relative_file[0] === '.' ? relative_file : `./${relative_file}`;
436
+ };
437
+
438
+ fs__default.writeFileSync(
439
+ input.index,
440
+ server_template({
441
+ config,
442
+ hooks: app_relative(hooks_file),
443
+ has_service_worker: service_worker_register && !!service_worker_entry_file,
444
+ runtime: get_runtime_path(config),
445
+ template: load_template(cwd, config)
446
+ })
447
+ );
448
+
449
+ /** @type {import('vite').UserConfig} */
450
+ const vite_config = await config.kit.vite();
451
+
452
+ const default_config = {
453
+ build: {
454
+ target: 'es2020'
455
+ }
456
+ };
457
+
458
+ // don't warn on overriding defaults
459
+ const [modified_vite_config] = deep_merge(default_config, vite_config);
460
+
461
+ /** @type {[any, string[]]} */
462
+ const [merged_config, conflicts] = deep_merge(modified_vite_config, {
463
+ configFile: false,
464
+ root: cwd,
465
+ base: assets_base,
466
+ build: {
467
+ ssr: true,
468
+ outDir: `${output_dir}/server`,
469
+ manifest: true,
470
+ polyfillDynamicImport: false,
471
+ rollupOptions: {
472
+ input,
473
+ output: {
474
+ format: 'esm',
475
+ entryFileNames: '[name].js',
476
+ chunkFileNames: 'chunks/[name]-[hash].js',
477
+ assetFileNames: 'assets/[name]-[hash][extname]'
478
+ },
479
+ preserveEntrySignatures: 'strict'
480
+ }
481
+ },
482
+ plugins: [
483
+ svelte({
484
+ extensions: config.extensions,
485
+ compilerOptions: {
486
+ hydratable: !!config.kit.browser.hydrate
487
+ }
488
+ })
489
+ ],
490
+ resolve: {
491
+ alias: get_aliases(config)
492
+ }
493
+ });
494
+
495
+ print_config_conflicts(conflicts, 'kit.vite.', 'build_server');
496
+
497
+ const { chunks } = await create_build(merged_config);
498
+
499
+ /** @type {import('vite').Manifest} */
500
+ const vite_manifest = JSON.parse(fs__default.readFileSync(`${output_dir}/server/manifest.json`, 'utf-8'));
501
+
502
+ mkdirp(`${output_dir}/server/nodes`);
503
+ mkdirp(`${output_dir}/server/stylesheets`);
504
+
505
+ const stylesheet_lookup = new Map();
506
+
507
+ client.assets.forEach((asset) => {
508
+ if (asset.fileName.endsWith('.css')) {
509
+ if (config.kit.amp || asset.source.length < config.kit.inlineStyleThreshold) {
510
+ const index = stylesheet_lookup.size;
511
+ const file = `${output_dir}/server/stylesheets/${index}.js`;
512
+
513
+ fs__default.writeFileSync(file, `// ${asset.fileName}\nexport default ${s(asset.source)};`);
514
+ stylesheet_lookup.set(asset.fileName, index);
515
+ }
516
+ }
517
+ });
518
+
519
+ manifest_data.components.forEach((component, i) => {
520
+ const file = `${output_dir}/server/nodes/${i}.js`;
521
+
522
+ const js = new Set();
523
+ const css = new Set();
524
+ find_deps(component, client.vite_manifest, js, css);
525
+
526
+ const imports = [`import * as module from '../${vite_manifest[component].file}';`];
527
+
528
+ const exports = [
529
+ 'export { module };',
530
+ `export const entry = '${client.vite_manifest[component].file}';`,
531
+ `export const js = ${s(Array.from(js))};`,
532
+ `export const css = ${s(Array.from(css))};`
533
+ ];
534
+
535
+ /** @type {string[]} */
536
+ const styles = [];
537
+
538
+ css.forEach((file) => {
539
+ if (stylesheet_lookup.has(file)) {
540
+ const index = stylesheet_lookup.get(file);
541
+ const name = `stylesheet_${index}`;
542
+ imports.push(`import ${name} from '../stylesheets/${index}.js';`);
543
+ styles.push(`\t${s(file)}: ${name}`);
544
+ }
545
+ });
546
+
547
+ if (styles.length > 0) {
548
+ exports.push(`export const styles = {\n${styles.join(',\n')}\n};`);
549
+ }
550
+
551
+ fs__default.writeFileSync(file, `${imports.join('\n')}\n\n${exports.join('\n')}\n`);
552
+ });
553
+
554
+ return {
555
+ chunks,
556
+ vite_manifest,
557
+ methods: get_methods(cwd, chunks, manifest_data)
558
+ };
559
+ }
560
+
561
+ /** @type {Record<string, string>} */
562
+ const method_names = {
563
+ get: 'get',
564
+ head: 'head',
565
+ post: 'post',
566
+ put: 'put',
567
+ del: 'delete',
568
+ patch: 'patch'
569
+ };
570
+
571
+ /**
572
+ *
573
+ * @param {string} cwd
574
+ * @param {import('rollup').OutputChunk[]} output
575
+ * @param {import('types').ManifestData} manifest_data
576
+ */
577
+ function get_methods(cwd, output, manifest_data) {
578
+ /** @type {Record<string, string[]>} */
579
+ const lookup = {};
580
+ output.forEach((chunk) => {
581
+ if (!chunk.facadeModuleId) return;
582
+ const id = chunk.facadeModuleId.slice(cwd.length + 1);
583
+ lookup[id] = chunk.exports;
584
+ });
585
+
586
+ /** @type {Record<string, import('types').HttpMethod[]>} */
587
+ const methods = {};
588
+ manifest_data.routes.forEach((route) => {
589
+ const file = route.type === 'endpoint' ? route.file : route.shadow;
590
+
591
+ if (file && lookup[file]) {
592
+ methods[file] = lookup[file]
593
+ .map((x) => /** @type {import('types').HttpMethod} */ (method_names[x]))
594
+ .filter(Boolean);
595
+ }
596
+ });
597
+
598
+ return methods;
599
+ }
600
+
601
+ /** @typedef {{
602
+ * fn: () => Promise<any>,
603
+ * fulfil: (value: any) => void,
604
+ * reject: (error: Error) => void
605
+ * }} Task */
606
+
607
+ /** @param {number} concurrency */
608
+ function queue(concurrency) {
609
+ /** @type {Task[]} */
610
+ const tasks = [];
611
+
612
+ let current = 0;
613
+
614
+ /** @type {(value?: any) => void} */
615
+ let fulfil;
616
+
617
+ /** @type {(error: Error) => void} */
618
+ let reject;
619
+
620
+ let closed = false;
621
+
622
+ const done = new Promise((f, r) => {
623
+ fulfil = f;
624
+ reject = r;
625
+ });
626
+
627
+ done.catch(() => {
628
+ // this is necessary in case a catch handler is never added
629
+ // to the done promise by the user
630
+ });
631
+
632
+ function dequeue() {
633
+ if (current < concurrency) {
634
+ const task = tasks.shift();
635
+
636
+ if (task) {
637
+ current += 1;
638
+ const promise = Promise.resolve(task.fn());
639
+
640
+ promise
641
+ .then(task.fulfil, (err) => {
642
+ task.reject(err);
643
+ reject(err);
644
+ })
645
+ .then(() => {
646
+ current -= 1;
647
+ dequeue();
648
+ });
649
+ } else if (current === 0) {
650
+ closed = true;
651
+ fulfil();
652
+ }
653
+ }
654
+ }
655
+
656
+ return {
657
+ /** @param {() => any} fn */
658
+ add: (fn) => {
659
+ if (closed) throw new Error('Cannot add tasks to a queue that has ended');
660
+
661
+ const promise = new Promise((fulfil, reject) => {
662
+ tasks.push({ fn, fulfil, reject });
663
+ });
664
+
665
+ dequeue();
666
+ return promise;
667
+ },
668
+
669
+ done: () => {
670
+ if (current === 0) {
671
+ closed = true;
672
+ fulfil();
673
+ }
674
+
675
+ return done;
676
+ }
677
+ };
678
+ }
679
+
680
+ const DOCTYPE = 'DOCTYPE';
681
+ const CDATA_OPEN = '[CDATA[';
682
+ const CDATA_CLOSE = ']]>';
683
+ const COMMENT_OPEN = '--';
684
+ const COMMENT_CLOSE = '-->';
685
+
686
+ const TAG_OPEN = /[a-zA-Z]/;
687
+ const TAG_CHAR = /[a-zA-Z0-9]/;
688
+ const ATTRIBUTE_NAME = /[^\t\n\f />"'=]/;
689
+
690
+ const WHITESPACE = /[\s\n\r]/;
691
+
692
+ /** @param {string} html */
693
+ function crawl(html) {
694
+ /** @type {string[]} */
695
+ const hrefs = [];
696
+
697
+ let i = 0;
698
+ main: while (i < html.length) {
699
+ const char = html[i];
700
+
701
+ if (char === '<') {
702
+ if (html[i + 1] === '!') {
703
+ i += 2;
704
+
705
+ if (html.substr(i, DOCTYPE.length).toUpperCase() === DOCTYPE) {
706
+ i += DOCTYPE.length;
707
+ while (i < html.length) {
708
+ if (html[i++] === '>') {
709
+ continue main;
710
+ }
711
+ }
712
+ }
713
+
714
+ // skip cdata
715
+ if (html.substr(i, CDATA_OPEN.length) === CDATA_OPEN) {
716
+ i += CDATA_OPEN.length;
717
+ while (i < html.length) {
718
+ if (html.substr(i, CDATA_CLOSE.length) === CDATA_CLOSE) {
719
+ i += CDATA_CLOSE.length;
720
+ continue main;
721
+ }
722
+
723
+ i += 1;
724
+ }
725
+ }
726
+
727
+ // skip comments
728
+ if (html.substr(i, COMMENT_OPEN.length) === COMMENT_OPEN) {
729
+ i += COMMENT_OPEN.length;
730
+ while (i < html.length) {
731
+ if (html.substr(i, COMMENT_CLOSE.length) === COMMENT_CLOSE) {
732
+ i += COMMENT_CLOSE.length;
733
+ continue main;
734
+ }
735
+
736
+ i += 1;
737
+ }
738
+ }
739
+ }
740
+
741
+ // parse opening tags
742
+ const start = ++i;
743
+ if (TAG_OPEN.test(html[start])) {
744
+ while (i < html.length) {
745
+ if (!TAG_CHAR.test(html[i])) {
746
+ break;
747
+ }
748
+
749
+ i += 1;
750
+ }
751
+
752
+ const tag = html.slice(start, i).toUpperCase();
753
+
754
+ if (tag === 'SCRIPT' || tag === 'STYLE') {
755
+ while (i < html.length) {
756
+ if (
757
+ html[i] === '<' &&
758
+ html[i + 1] === '/' &&
759
+ html.substr(i + 2, tag.length).toUpperCase() === tag
760
+ ) {
761
+ continue main;
762
+ }
763
+
764
+ i += 1;
765
+ }
766
+ }
767
+
768
+ let href = '';
769
+
770
+ while (i < html.length) {
771
+ const start = i;
772
+
773
+ const char = html[start];
774
+ if (char === '>') break;
775
+
776
+ if (ATTRIBUTE_NAME.test(char)) {
777
+ i += 1;
778
+
779
+ while (i < html.length) {
780
+ if (!ATTRIBUTE_NAME.test(html[i])) {
781
+ break;
782
+ }
783
+
784
+ i += 1;
785
+ }
786
+
787
+ const name = html.slice(start, i).toLowerCase();
788
+
789
+ while (WHITESPACE.test(html[i])) i += 1;
790
+
791
+ if (html[i] === '=') {
792
+ i += 1;
793
+ while (WHITESPACE.test(html[i])) i += 1;
794
+
795
+ let value;
796
+
797
+ if (html[i] === "'" || html[i] === '"') {
798
+ const quote = html[i++];
799
+
800
+ const start = i;
801
+ let escaped = false;
802
+
803
+ while (i < html.length) {
804
+ if (!escaped) {
805
+ const char = html[i];
806
+
807
+ if (html[i] === quote) {
808
+ break;
809
+ }
810
+
811
+ if (char === '\\') {
812
+ escaped = true;
813
+ }
814
+ }
815
+
816
+ i += 1;
817
+ }
818
+
819
+ value = html.slice(start, i);
820
+ } else {
821
+ const start = i;
822
+ while (html[i] !== '>' && !WHITESPACE.test(html[i])) i += 1;
823
+ value = html.slice(start, i);
824
+
825
+ i -= 1;
826
+ }
827
+
828
+ if (name === 'href') {
829
+ href = value;
830
+ } else if (name === 'src') {
831
+ hrefs.push(value);
832
+ } else if (name === 'srcset') {
833
+ const candidates = [];
834
+ let insideURL = true;
835
+ value = value.trim();
836
+ for (let i = 0; i < value.length; i++) {
837
+ if (value[i] === ',' && (!insideURL || (insideURL && value[i + 1] === ' '))) {
838
+ candidates.push(value.slice(0, i));
839
+ value = value.substring(i + 1).trim();
840
+ i = 0;
841
+ insideURL = true;
842
+ } else if (value[i] === ' ') {
843
+ insideURL = false;
844
+ }
845
+ }
846
+ candidates.push(value);
847
+ for (const candidate of candidates) {
848
+ const src = candidate.split(WHITESPACE)[0];
849
+ hrefs.push(src);
850
+ }
851
+ }
852
+ } else {
853
+ i -= 1;
854
+ }
855
+ }
856
+
857
+ i += 1;
858
+ }
859
+
860
+ if (href) {
861
+ hrefs.push(href);
862
+ }
863
+ }
864
+ }
865
+
866
+ i += 1;
867
+ }
868
+
869
+ return hrefs;
870
+ }
871
+
872
+ /**
873
+ * Inside a script element, only `</script` and `<!--` hold special meaning to the HTML parser.
874
+ *
875
+ * The first closes the script element, so everything after is treated as raw HTML.
876
+ * The second disables further parsing until `-->`, so the script element might be unexpectedly
877
+ * kept open until until an unrelated HTML comment in the page.
878
+ *
879
+ * U+2028 LINE SEPARATOR and U+2029 PARAGRAPH SEPARATOR are escaped for the sake of pre-2018
880
+ * browsers.
881
+ *
882
+ * @see tests for unsafe parsing examples.
883
+ * @see https://html.spec.whatwg.org/multipage/scripting.html#restrictions-for-contents-of-script-elements
884
+ * @see https://html.spec.whatwg.org/multipage/syntax.html#cdata-rcdata-restrictions
885
+ * @see https://html.spec.whatwg.org/multipage/parsing.html#script-data-state
886
+ * @see https://html.spec.whatwg.org/multipage/parsing.html#script-data-double-escaped-state
887
+ * @see https://github.com/tc39/proposal-json-superset
888
+ * @type {Record<string, string>}
889
+ */
890
+ const render_json_payload_script_dict = {
891
+ '<': '\\u003C',
892
+ '\u2028': '\\u2028',
893
+ '\u2029': '\\u2029'
894
+ };
895
+
896
+ new RegExp(
897
+ `[${Object.keys(render_json_payload_script_dict).join('')}]`,
898
+ 'g'
899
+ );
900
+
901
+ /**
902
+ * When inside a double-quoted attribute value, only `&` and `"` hold special meaning.
903
+ * @see https://html.spec.whatwg.org/multipage/parsing.html#attribute-value-(double-quoted)-state
904
+ * @type {Record<string, string>}
905
+ */
906
+ const escape_html_attr_dict = {
907
+ '&': '&amp;',
908
+ '"': '&quot;'
909
+ };
910
+
911
+ const escape_html_attr_regex = new RegExp(
912
+ // special characters
913
+ `[${Object.keys(escape_html_attr_dict).join('')}]|` +
914
+ // high surrogate without paired low surrogate
915
+ '[\\ud800-\\udbff](?![\\udc00-\\udfff])|' +
916
+ // a valid surrogate pair, the only match with 2 code units
917
+ // we match it so that we can match unpaired low surrogates in the same pass
918
+ // TODO: use lookbehind assertions once they are widely supported: (?<![\ud800-udbff])[\udc00-\udfff]
919
+ '[\\ud800-\\udbff][\\udc00-\\udfff]|' +
920
+ // unpaired low surrogate (see previous match)
921
+ '[\\udc00-\\udfff]',
922
+ 'g'
923
+ );
924
+
925
+ /**
926
+ * Formats a string to be used as an attribute's value in raw HTML.
927
+ *
928
+ * It escapes unpaired surrogates (which are allowed in js strings but invalid in HTML), escapes
929
+ * characters that are special in attributes, and surrounds the whole string in double-quotes.
930
+ *
931
+ * @param {string} str
932
+ * @returns {string} Escaped string surrounded by double-quotes.
933
+ * @example const html = `<tag data-value=${escape_html_attr('value')}>...</tag>`;
934
+ */
935
+ function escape_html_attr(str) {
936
+ const escaped_str = str.replace(escape_html_attr_regex, (match) => {
937
+ if (match.length === 2) {
938
+ // valid surrogate pair
939
+ return match;
940
+ }
941
+
942
+ return escape_html_attr_dict[match] ?? `&#${match.charCodeAt(0)};`;
943
+ });
944
+
945
+ return `"${escaped_str}"`;
946
+ }
947
+
948
+ /**
949
+ * @typedef {import('types').PrerenderErrorHandler} PrerenderErrorHandler
950
+ * @typedef {import('types').PrerenderOnErrorValue} OnError
951
+ * @typedef {import('types').Logger} Logger
952
+ */
953
+
954
+ /** @type {(details: Parameters<PrerenderErrorHandler>[0] ) => string} */
955
+ function format_error({ status, path, referrer, referenceType }) {
956
+ return `${status} ${path}${referrer ? ` (${referenceType} from ${referrer})` : ''}`;
957
+ }
958
+
959
+ /** @type {(log: Logger, onError: OnError) => PrerenderErrorHandler} */
960
+ function normalise_error_handler(log, onError) {
961
+ switch (onError) {
962
+ case 'continue':
963
+ return (details) => {
964
+ log.error(format_error(details));
965
+ };
966
+ case 'fail':
967
+ return (details) => {
968
+ throw new Error(format_error(details));
969
+ };
970
+ default:
971
+ return onError;
972
+ }
973
+ }
974
+
975
+ const OK = 2;
976
+ const REDIRECT = 3;
977
+
978
+ /**
979
+ * @param {{
980
+ * config: import('types').ValidatedConfig;
981
+ * entries: string[];
982
+ * files: Set<string>;
983
+ * log: Logger;
984
+ * }} opts
985
+ */
986
+ async function prerender({ config, entries, files, log }) {
987
+ /** @type {import('types').Prerendered} */
988
+ const prerendered = {
989
+ pages: new Map(),
990
+ assets: new Map(),
991
+ redirects: new Map(),
992
+ paths: []
993
+ };
994
+
995
+ if (!config.kit.prerender.enabled) {
996
+ return prerendered;
997
+ }
998
+
999
+ installFetch();
1000
+
1001
+ const server_root = join(config.kit.outDir, 'output');
1002
+
1003
+ /** @type {import('types').ServerModule} */
1004
+ const { Server, override } = await import(pathToFileURL(`${server_root}/server/index.js`).href);
1005
+ const { manifest } = await import(pathToFileURL(`${server_root}/server/manifest.js`).href);
1006
+
1007
+ override({
1008
+ paths: config.kit.paths,
1009
+ prerendering: true,
1010
+ read: (file) => readFileSync(join(config.kit.files.assets, file))
1011
+ });
1012
+
1013
+ const server = new Server(manifest);
1014
+
1015
+ const error = normalise_error_handler(log, config.kit.prerender.onError);
1016
+
1017
+ const q = queue(config.kit.prerender.concurrency);
1018
+
1019
+ /**
1020
+ * @param {string} path
1021
+ * @param {boolean} is_html
1022
+ */
1023
+ function output_filename(path, is_html) {
1024
+ const file = path.slice(config.kit.paths.base.length + 1);
1025
+
1026
+ if (file === '') {
1027
+ return 'index.html';
1028
+ }
1029
+
1030
+ if (is_html && !file.endsWith('.html')) {
1031
+ return file + (config.kit.trailingSlash === 'always' ? 'index.html' : '.html');
1032
+ }
1033
+
1034
+ return file;
1035
+ }
1036
+
1037
+ const seen = new Set();
1038
+ const written = new Set();
1039
+
1040
+ /**
1041
+ * @param {string | null} referrer
1042
+ * @param {string} decoded
1043
+ * @param {string} [encoded]
1044
+ */
1045
+ function enqueue(referrer, decoded, encoded) {
1046
+ if (seen.has(decoded)) return;
1047
+ seen.add(decoded);
1048
+
1049
+ const file = decoded.slice(config.kit.paths.base.length + 1);
1050
+ if (files.has(file)) return;
1051
+
1052
+ return q.add(() => visit(decoded, encoded || encodeURI(decoded), referrer));
1053
+ }
1054
+
1055
+ /**
1056
+ * @param {string} decoded
1057
+ * @param {string} encoded
1058
+ * @param {string?} referrer
1059
+ */
1060
+ async function visit(decoded, encoded, referrer) {
1061
+ if (!decoded.startsWith(config.kit.paths.base)) {
1062
+ error({ status: 404, path: decoded, referrer, referenceType: 'linked' });
1063
+ return;
1064
+ }
1065
+
1066
+ /** @type {Map<string, import('types').PrerenderDependency>} */
1067
+ const dependencies = new Map();
1068
+
1069
+ const response = await server.respond(new Request(`http://sveltekit-prerender${encoded}`), {
1070
+ prerender: {
1071
+ default: config.kit.prerender.default,
1072
+ dependencies
1073
+ }
1074
+ });
1075
+
1076
+ const text = await response.text();
1077
+
1078
+ save('pages', response, text, decoded, encoded, referrer, 'linked');
1079
+
1080
+ for (const [dependency_path, result] of dependencies) {
1081
+ // this seems circuitous, but using new URL allows us to not care
1082
+ // whether dependency_path is encoded or not
1083
+ const encoded_dependency_path = new URL(dependency_path, 'http://localhost').pathname;
1084
+ const decoded_dependency_path = decodeURI(encoded_dependency_path);
1085
+
1086
+ const body = result.body ?? new Uint8Array(await result.response.arrayBuffer());
1087
+ save(
1088
+ 'dependencies',
1089
+ result.response,
1090
+ body,
1091
+ decoded_dependency_path,
1092
+ encoded_dependency_path,
1093
+ decoded,
1094
+ 'fetched'
1095
+ );
1096
+ }
1097
+
1098
+ if (config.kit.prerender.crawl && response.headers.get('content-type') === 'text/html') {
1099
+ for (const href of crawl(text)) {
1100
+ if (href.startsWith('data:') || href.startsWith('#')) continue;
1101
+
1102
+ const resolved = resolve(encoded, href);
1103
+ if (!is_root_relative(resolved)) continue;
1104
+
1105
+ const parsed = new URL(resolved, 'http://localhost');
1106
+
1107
+ if (parsed.search) ;
1108
+
1109
+ const pathname = normalize_path(parsed.pathname, config.kit.trailingSlash);
1110
+ enqueue(decoded, decodeURI(pathname), pathname);
1111
+ }
1112
+ }
1113
+ }
1114
+
1115
+ /**
1116
+ * @param {'pages' | 'dependencies'} category
1117
+ * @param {Response} response
1118
+ * @param {string | Uint8Array} body
1119
+ * @param {string} decoded
1120
+ * @param {string} encoded
1121
+ * @param {string | null} referrer
1122
+ * @param {'linked' | 'fetched'} referenceType
1123
+ */
1124
+ function save(category, response, body, decoded, encoded, referrer, referenceType) {
1125
+ const response_type = Math.floor(response.status / 100);
1126
+ const type = /** @type {string} */ (response.headers.get('content-type'));
1127
+ const is_html = response_type === REDIRECT || type === 'text/html';
1128
+
1129
+ const file = output_filename(decoded, is_html);
1130
+ const dest = `${config.kit.outDir}/output/prerendered/${category}/${file}`;
1131
+
1132
+ if (written.has(file)) return;
1133
+ written.add(file);
1134
+
1135
+ if (response_type === REDIRECT) {
1136
+ const location = response.headers.get('location');
1137
+
1138
+ if (location) {
1139
+ mkdirp(dirname(dest));
1140
+
1141
+ log.warn(`${response.status} ${decoded} -> ${location}`);
1142
+
1143
+ writeFileSync(
1144
+ dest,
1145
+ `<meta http-equiv="refresh" content=${escape_html_attr(`0;url=${location}`)}>`
1146
+ );
1147
+
1148
+ let resolved = resolve(encoded, location);
1149
+ if (is_root_relative(resolved)) {
1150
+ resolved = normalize_path(resolved, config.kit.trailingSlash);
1151
+ enqueue(decoded, decodeURI(resolved), resolved);
1152
+ }
1153
+
1154
+ if (!prerendered.redirects.has(decoded)) {
1155
+ prerendered.redirects.set(decoded, {
1156
+ status: response.status,
1157
+ location: resolved
1158
+ });
1159
+
1160
+ prerendered.paths.push(normalize_path(decoded, 'never'));
1161
+ }
1162
+ } else {
1163
+ log.warn(`location header missing on redirect received from ${decoded}`);
1164
+ }
1165
+
1166
+ return;
1167
+ }
1168
+
1169
+ if (response.status === 200) {
1170
+ mkdirp(dirname(dest));
1171
+
1172
+ log.info(`${response.status} ${decoded}`);
1173
+ writeFileSync(dest, body);
1174
+
1175
+ if (is_html) {
1176
+ prerendered.pages.set(decoded, {
1177
+ file
1178
+ });
1179
+ } else {
1180
+ prerendered.assets.set(decoded, {
1181
+ type
1182
+ });
1183
+ }
1184
+
1185
+ prerendered.paths.push(normalize_path(decoded, 'never'));
1186
+ } else if (response_type !== OK) {
1187
+ error({ status: response.status, path: decoded, referrer, referenceType });
1188
+ }
1189
+ }
1190
+
1191
+ if (config.kit.prerender.enabled) {
1192
+ for (const entry of config.kit.prerender.entries) {
1193
+ if (entry === '*') {
1194
+ for (const entry of entries) {
1195
+ enqueue(null, normalize_path(config.kit.paths.base + entry, config.kit.trailingSlash)); // TODO can we pre-normalize these?
1196
+ }
1197
+ } else {
1198
+ enqueue(null, normalize_path(config.kit.paths.base + entry, config.kit.trailingSlash));
1199
+ }
1200
+ }
1201
+
1202
+ await q.done();
1203
+ }
1204
+
1205
+ const rendered = await server.respond(new Request('http://sveltekit-prerender/[fallback]'), {
1206
+ prerender: {
1207
+ fallback: true,
1208
+ default: false,
1209
+ dependencies: new Map()
1210
+ }
1211
+ });
1212
+
1213
+ const file = `${config.kit.outDir}/output/prerendered/fallback.html`;
1214
+ mkdirp(dirname(file));
1215
+ writeFileSync(file, await rendered.text());
1216
+
1217
+ return prerendered;
1218
+ }
1219
+
1220
+ /**
1221
+ * @param {import('types').ValidatedConfig} config
1222
+ * @param {{ log: import('types').Logger }} opts
1223
+ */
1224
+ async function build(config, { log }) {
1225
+ const cwd = process.cwd(); // TODO is this necessary?
1226
+
1227
+ const build_dir = path__default.join(config.kit.outDir, 'build');
1228
+ rimraf(build_dir);
1229
+ mkdirp(build_dir);
1230
+
1231
+ const output_dir = path__default.join(config.kit.outDir, 'output');
1232
+ rimraf(output_dir);
1233
+ mkdirp(output_dir);
1234
+
1235
+ const { manifest_data } = all(config);
1236
+
1237
+ const options = {
1238
+ cwd,
1239
+ config,
1240
+ build_dir,
1241
+ // TODO this is so that Vite's preloading works. Unfortunately, it fails
1242
+ // during `svelte-kit preview`, because we use a local asset path. If Vite
1243
+ // used relative paths, I _think_ this could get fixed. Issue here:
1244
+ // https://github.com/vitejs/vite/issues/2009
1245
+ assets_base: `${config.kit.paths.assets || config.kit.paths.base}/${config.kit.appDir}/`,
1246
+ manifest_data,
1247
+ output_dir,
1248
+ client_entry_file: path__default.relative(cwd, `${get_runtime_path(config)}/client/start.js`),
1249
+ service_worker_entry_file: resolve_entry(config.kit.files.serviceWorker),
1250
+ service_worker_register: config.kit.serviceWorker.register
1251
+ };
1252
+
1253
+ const client = await build_client(options);
1254
+ const server = await build_server(options, client);
1255
+
1256
+ /** @type {import('types').BuildData} */
1257
+ const build_data = {
1258
+ app_dir: config.kit.appDir,
1259
+ manifest_data: options.manifest_data,
1260
+ service_worker: options.service_worker_entry_file ? 'service-worker.js' : null, // TODO make file configurable?
1261
+ client,
1262
+ server
1263
+ };
1264
+
1265
+ const manifest = `export const manifest = ${generate_manifest({
1266
+ build_data,
1267
+ relative_path: '.',
1268
+ routes: options.manifest_data.routes
1269
+ })};\n`;
1270
+ fs__default.writeFileSync(`${output_dir}/server/manifest.js`, manifest);
1271
+
1272
+ const static_files = options.manifest_data.assets.map((asset) => posixify(asset.file));
1273
+
1274
+ const files = new Set([
1275
+ ...static_files,
1276
+ ...client.chunks.map((chunk) => `${config.kit.appDir}/${chunk.fileName}`),
1277
+ ...client.assets.map((chunk) => `${config.kit.appDir}/${chunk.fileName}`)
1278
+ ]);
1279
+
1280
+ // TODO is this right?
1281
+ static_files.forEach((file) => {
1282
+ if (file.endsWith('/index.html')) {
1283
+ files.add(file.slice(0, -11));
1284
+ }
1285
+ });
1286
+
1287
+ const prerendered = await prerender({
1288
+ config,
1289
+ entries: options.manifest_data.routes
1290
+ .map((route) => (route.type === 'page' ? route.path : ''))
1291
+ .filter(Boolean),
1292
+ files,
1293
+ log
1294
+ });
1295
+
1296
+ if (options.service_worker_entry_file) {
1297
+ if (config.kit.paths.assets) {
1298
+ throw new Error('Cannot use service worker alongside config.kit.paths.assets');
1299
+ }
1300
+
1301
+ await build_service_worker(options, prerendered, client.vite_manifest);
1302
+ }
1303
+
1304
+ return { build_data, prerendered };
1305
+ }
1306
+
1307
+ export { build };