@sveltejs/kit 1.0.0-next.31 → 1.0.0-next.312

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