@sveltejs/kit 1.0.0-next.34 → 1.0.0-next.342

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