@sveltejs/kit 1.0.0-next.38 → 1.0.0-next.380

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 (42) hide show
  1. package/README.md +12 -9
  2. package/assets/app/env.js +28 -0
  3. package/assets/app/navigation.js +24 -0
  4. package/assets/app/paths.js +1 -0
  5. package/assets/{runtime/app → app}/stores.js +33 -29
  6. package/assets/client/singletons.js +13 -0
  7. package/assets/client/start.js +1803 -0
  8. package/assets/components/error.svelte +18 -2
  9. package/assets/env.js +8 -0
  10. package/assets/{runtime/chunks/paths.js → paths.js} +4 -3
  11. package/assets/server/index.js +3563 -0
  12. package/dist/chunks/_commonjsHelpers.js +3 -0
  13. package/dist/chunks/error.js +664 -0
  14. package/dist/chunks/index.js +15292 -3067
  15. package/dist/chunks/index2.js +186 -555
  16. package/dist/chunks/multipart-parser.js +445 -0
  17. package/dist/chunks/sync.js +1007 -0
  18. package/dist/chunks/write_tsconfig.js +274 -0
  19. package/dist/cli.js +66 -514
  20. package/dist/hooks.js +28 -0
  21. package/dist/node/polyfills.js +12240 -0
  22. package/dist/node.js +5883 -0
  23. package/dist/vite.js +3243 -0
  24. package/package.json +97 -64
  25. package/types/ambient.d.ts +345 -0
  26. package/types/index.d.ts +289 -0
  27. package/types/internal.d.ts +326 -0
  28. package/types/private.d.ts +235 -0
  29. package/CHANGELOG.md +0 -399
  30. package/assets/runtime/app/env.js +0 -5
  31. package/assets/runtime/app/navigation.js +0 -41
  32. package/assets/runtime/app/paths.js +0 -1
  33. package/assets/runtime/chunks/utils.js +0 -19
  34. package/assets/runtime/internal/singletons.js +0 -23
  35. package/assets/runtime/internal/start.js +0 -770
  36. package/dist/chunks/index3.js +0 -246
  37. package/dist/chunks/index4.js +0 -511
  38. package/dist/chunks/index5.js +0 -761
  39. package/dist/chunks/index6.js +0 -322
  40. package/dist/chunks/standard.js +0 -99
  41. package/dist/chunks/utils.js +0 -83
  42. package/dist/ssr.js +0 -2523
package/dist/vite.js ADDED
@@ -0,0 +1,3243 @@
1
+ import * as fs from 'fs';
2
+ import fs__default, { readFileSync, writeFileSync, readdirSync, statSync } from 'fs';
3
+ import path__default, { join, dirname, resolve as resolve$1, normalize } from 'path';
4
+ import { a as load_template, $, c as coalesce_to_error, l as load_config } from './chunks/error.js';
5
+ import { svelte } from '@sveltejs/vite-plugin-svelte';
6
+ import * as vite from 'vite';
7
+ import { loadConfigFromFile } from 'vite';
8
+ import { p as posixify, m as mkdirp, r as rimraf } from './chunks/write_tsconfig.js';
9
+ import { g as get_runtime_directory, s, i as init, a as get_runtime_prefix, u as update, b as get_mime_lookup, p as parse_route_id, c as all, l as logger } from './chunks/sync.js';
10
+ import { pathToFileURL, URL as URL$1 } from 'url';
11
+ import { installPolyfills } from './node/polyfills.js';
12
+ import * as qs from 'querystring';
13
+ import { getRequest, setResponse } from './node.js';
14
+ import 'assert';
15
+ import 'net';
16
+ import 'http';
17
+ import 'stream';
18
+ import 'buffer';
19
+ import 'util';
20
+ import 'stream/web';
21
+ import 'perf_hooks';
22
+ import 'util/types';
23
+ import 'events';
24
+ import 'tls';
25
+ import './chunks/_commonjsHelpers.js';
26
+ import 'async_hooks';
27
+ import 'console';
28
+ import 'zlib';
29
+ import 'crypto';
30
+ import 'node:http';
31
+ import 'node:https';
32
+ import 'node:zlib';
33
+ import 'node:stream';
34
+ import 'node:buffer';
35
+ import 'node:util';
36
+ import 'node:url';
37
+ import 'node:net';
38
+ import 'node:fs';
39
+ import 'node:path';
40
+
41
+ /**
42
+ * @param {import('vite').ConfigEnv} config_env
43
+ * @return {Promise<import('vite').UserConfig>}
44
+ */
45
+ async function get_vite_config(config_env) {
46
+ const config = (await loadConfigFromFile(config_env))?.config;
47
+ if (!config) {
48
+ throw new Error('Could not load Vite config');
49
+ }
50
+ return config;
51
+ }
52
+
53
+ /**
54
+ * @param {...import('vite').UserConfig} configs
55
+ * @returns {import('vite').UserConfig}
56
+ */
57
+ function merge_vite_configs(...configs) {
58
+ return deep_merge(
59
+ ...configs.map((config) => ({
60
+ ...config,
61
+ resolve: {
62
+ ...config.resolve,
63
+ alias: normalize_alias(config.resolve?.alias || {})
64
+ }
65
+ }))
66
+ );
67
+ }
68
+
69
+ /**
70
+ * Takes zero or more objects and returns a new object that has all the values
71
+ * deeply merged together. None of the original objects will be mutated at any
72
+ * level, and the returned object will have no references to the original
73
+ * objects at any depth. If there's a conflict the last one wins, except for
74
+ * arrays which will be combined.
75
+ * @param {...Object} objects
76
+ * @returns {Record<string, any>} the merged object
77
+ */
78
+ function deep_merge(...objects) {
79
+ const result = {};
80
+ /** @type {string[]} */
81
+ objects.forEach((o) => merge_into(result, o));
82
+ return result;
83
+ }
84
+
85
+ /**
86
+ * normalize kit.vite.resolve.alias as an array
87
+ * @param {import('vite').AliasOptions} o
88
+ * @returns {import('vite').Alias[]}
89
+ */
90
+ function normalize_alias(o) {
91
+ if (Array.isArray(o)) return o;
92
+ return Object.entries(o).map(([find, replacement]) => ({ find, replacement }));
93
+ }
94
+
95
+ /**
96
+ * Merges b into a, recursively, mutating a.
97
+ * @param {Record<string, any>} a
98
+ * @param {Record<string, any>} b
99
+ */
100
+ function merge_into(a, b) {
101
+ /**
102
+ * Checks for "plain old Javascript object", typically made as an object
103
+ * literal. Excludes Arrays and built-in types like Buffer.
104
+ * @param {any} x
105
+ */
106
+ const is_plain_object = (x) => typeof x === 'object' && x.constructor === Object;
107
+
108
+ for (const prop in b) {
109
+ if (is_plain_object(b[prop])) {
110
+ if (!is_plain_object(a[prop])) {
111
+ a[prop] = {};
112
+ }
113
+ merge_into(a[prop], b[prop]);
114
+ } else if (Array.isArray(b[prop])) {
115
+ if (!Array.isArray(a[prop])) {
116
+ a[prop] = [];
117
+ }
118
+ a[prop].push(...b[prop]);
119
+ } else {
120
+ a[prop] = b[prop];
121
+ }
122
+ }
123
+ }
124
+
125
+ /** @param {import('types').ValidatedKitConfig} config */
126
+ function get_aliases(config) {
127
+ /** @type {Record<string, string>} */
128
+ const alias = {
129
+ __GENERATED__: path__default.posix.join(config.outDir, 'generated'),
130
+ $app: `${get_runtime_directory(config)}/app`,
131
+
132
+ // For now, we handle `$lib` specially here rather than make it a default value for
133
+ // `config.kit.alias` since it has special meaning for packaging, etc.
134
+ $lib: config.files.lib
135
+ };
136
+
137
+ for (const [key, value] of Object.entries(config.alias)) {
138
+ alias[key] = path__default.resolve(value);
139
+ }
140
+
141
+ return alias;
142
+ }
143
+
144
+ /**
145
+ * Given an entry point like [cwd]/src/hooks, returns a filename like [cwd]/src/hooks.js or [cwd]/src/hooks/index.js
146
+ * @param {string} entry
147
+ * @returns {string|null}
148
+ */
149
+ function resolve_entry(entry) {
150
+ if (fs__default.existsSync(entry)) {
151
+ const stats = fs__default.statSync(entry);
152
+ if (stats.isDirectory()) {
153
+ return resolve_entry(path__default.join(entry, 'index'));
154
+ }
155
+
156
+ return entry;
157
+ } else {
158
+ const dir = path__default.dirname(entry);
159
+
160
+ if (fs__default.existsSync(dir)) {
161
+ const base = path__default.basename(entry);
162
+ const files = fs__default.readdirSync(dir);
163
+
164
+ const found = files.find((file) => file.replace(/\.[^.]+$/, '') === base);
165
+
166
+ if (found) return path__default.join(dir, found);
167
+ }
168
+ }
169
+
170
+ return null;
171
+ }
172
+
173
+ /**
174
+ * @typedef {import('rollup').RollupOutput} RollupOutput
175
+ * @typedef {import('rollup').OutputChunk} OutputChunk
176
+ * @typedef {import('rollup').OutputAsset} OutputAsset
177
+ */
178
+
179
+ /**
180
+ * Invokes Vite.
181
+ * @param {import('vite').UserConfig} config
182
+ */
183
+ async function create_build(config) {
184
+ const { output } = /** @type {RollupOutput} */ (
185
+ await vite.build({ ...config, configFile: false })
186
+ );
187
+
188
+ const chunks = output.filter(
189
+ /** @returns {output is OutputChunk} */ (output) => output.type === 'chunk'
190
+ );
191
+
192
+ const assets = output.filter(
193
+ /** @returns {output is OutputAsset} */ (output) => output.type === 'asset'
194
+ );
195
+
196
+ return { chunks, assets };
197
+ }
198
+
199
+ /**
200
+ * Adds transitive JS and CSS dependencies to the js and css inputs.
201
+ * @param {import('vite').Manifest} manifest
202
+ * @param {string} entry
203
+ * @param {boolean} add_dynamic_css
204
+ */
205
+ function find_deps$1(manifest, entry, add_dynamic_css) {
206
+ /** @type {Set<string>} */
207
+ const seen = new Set();
208
+
209
+ /** @type {Set<string>} */
210
+ const imports = new Set();
211
+
212
+ /** @type {Set<string>} */
213
+ const stylesheets = new Set();
214
+
215
+ /**
216
+ * @param {string} file
217
+ * @param {boolean} add_js
218
+ */
219
+ function traverse(file, add_js) {
220
+ if (seen.has(file)) return;
221
+ seen.add(file);
222
+
223
+ const chunk = manifest[file];
224
+
225
+ if (add_js) imports.add(chunk.file);
226
+
227
+ if (chunk.css) {
228
+ chunk.css.forEach((file) => stylesheets.add(file));
229
+ }
230
+
231
+ if (chunk.imports) {
232
+ chunk.imports.forEach((file) => traverse(file, add_js));
233
+ }
234
+
235
+ if (add_dynamic_css && chunk.dynamicImports) {
236
+ chunk.dynamicImports.forEach((file) => traverse(file, false));
237
+ }
238
+ }
239
+
240
+ traverse(entry, true);
241
+
242
+ return {
243
+ file: manifest[entry].file,
244
+ imports: Array.from(imports),
245
+ stylesheets: Array.from(stylesheets)
246
+ };
247
+ }
248
+
249
+ /**
250
+ * The Vite configuration that we use by default.
251
+ * @param {{
252
+ * config: import('types').ValidatedConfig;
253
+ * input: Record<string, string>;
254
+ * ssr: boolean;
255
+ * outDir: string;
256
+ * }} options
257
+ * @return {import('vite').UserConfig}
258
+ */
259
+ const get_default_config = function ({ config, input, ssr, outDir }) {
260
+ return {
261
+ appType: 'custom',
262
+ base: assets_base(config.kit),
263
+ build: {
264
+ cssCodeSplit: true,
265
+ manifest: true,
266
+ outDir,
267
+ polyfillModulePreload: false,
268
+ rollupOptions: {
269
+ input,
270
+ output: {
271
+ format: 'esm',
272
+ entryFileNames: ssr ? '[name].js' : 'immutable/[name]-[hash].js',
273
+ chunkFileNames: 'immutable/chunks/[name]-[hash].js',
274
+ assetFileNames: 'immutable/assets/[name]-[hash][extname]'
275
+ },
276
+ preserveEntrySignatures: 'strict'
277
+ },
278
+ ssr,
279
+ target: ssr ? 'node14.8' : undefined
280
+ },
281
+ define: {
282
+ __SVELTEKIT_ADAPTER_NAME__: JSON.stringify(config.kit.adapter?.name),
283
+ __SVELTEKIT_APP_VERSION__: JSON.stringify(config.kit.version.name),
284
+ __SVELTEKIT_APP_VERSION_FILE__: JSON.stringify(`${config.kit.appDir}/version.json`),
285
+ __SVELTEKIT_APP_VERSION_POLL_INTERVAL__: JSON.stringify(config.kit.version.pollInterval)
286
+ },
287
+ // prevent Vite copying the contents of `config.kit.files.assets`,
288
+ // if it happens to be 'public' instead of 'static'
289
+ publicDir: false,
290
+ resolve: {
291
+ alias: get_aliases(config.kit)
292
+ },
293
+ ssr: {
294
+ // when developing against the Kit src code, we want to ensure that
295
+ // our dependencies are bundled so that apps don't need to install
296
+ // them as peerDependencies
297
+ noExternal: []
298
+
299
+ }
300
+ };
301
+ };
302
+
303
+ /**
304
+ * @param {import('types').ValidatedKitConfig} config
305
+ * @returns {string}
306
+ */
307
+ function assets_base(config) {
308
+ // TODO this is so that Vite's preloading works. Unfortunately, it fails
309
+ // during `svelte-kit preview`, because we use a local asset path. This
310
+ // may be fixed in Vite 3: https://github.com/vitejs/vite/issues/2009
311
+ const { base, assets } = config.paths;
312
+ return `${assets || base}/${config.appDir}/`;
313
+ }
314
+
315
+ /**
316
+ * vite.config.js will contain vite-plugin-svelte-kit, which kicks off the server and service
317
+ * worker builds in a hook. When running the server and service worker builds we must remove
318
+ * the SvelteKit plugin so that we do not kick off additional instances of these builds.
319
+ * @param {import('vite').UserConfig} config
320
+ */
321
+ function remove_svelte_kit(config) {
322
+ // TODO i feel like there's a more elegant way to do this
323
+ // @ts-expect-error - it can't handle infinite type expansion
324
+ config.plugins = (config.plugins || [])
325
+ .flat(Infinity)
326
+ .filter((plugin) => plugin.name !== 'vite-plugin-svelte-kit');
327
+ }
328
+
329
+ const method_names = new Set(['GET', 'HEAD', 'PUT', 'POST', 'DELETE', 'PATCH']);
330
+
331
+ // If we'd written this in TypeScript, it could be easy...
332
+ /**
333
+ * @param {string} str
334
+ * @returns {str is import('types').HttpMethod}
335
+ */
336
+ function is_http_method(str) {
337
+ return method_names.has(str);
338
+ }
339
+
340
+ /**
341
+ * @param {{
342
+ * hooks: string;
343
+ * config: import('types').ValidatedConfig;
344
+ * has_service_worker: boolean;
345
+ * runtime: string;
346
+ * template: string;
347
+ * }} opts
348
+ */
349
+ const server_template = ({ config, hooks, has_service_worker, runtime, template }) => `
350
+ import root from '__GENERATED__/root.svelte';
351
+ import { respond } from '${runtime}/server/index.js';
352
+ import { set_paths, assets, base } from '${runtime}/paths.js';
353
+ import { set_prerendering } from '${runtime}/env.js';
354
+
355
+ const template = ({ head, body, assets, nonce }) => ${s(template)
356
+ .replace('%sveltekit.head%', '" + head + "')
357
+ .replace('%sveltekit.body%', '" + body + "')
358
+ .replace(/%sveltekit\.assets%/g, '" + assets + "')
359
+ .replace(/%sveltekit\.nonce%/g, '" + nonce + "')};
360
+
361
+ let read = null;
362
+
363
+ set_paths(${s(config.kit.paths)});
364
+
365
+ let default_protocol = 'https';
366
+
367
+ // allow paths to be globally overridden
368
+ // in svelte-kit preview and in prerendering
369
+ export function override(settings) {
370
+ default_protocol = settings.protocol || default_protocol;
371
+ set_paths(settings.paths);
372
+ set_prerendering(settings.prerendering);
373
+ read = settings.read;
374
+ }
375
+
376
+ export class Server {
377
+ constructor(manifest) {
378
+ this.options = {
379
+ csp: ${s(config.kit.csp)},
380
+ dev: false,
381
+ get_stack: error => String(error), // for security
382
+ handle_error: (error, event) => {
383
+ this.options.hooks.handleError({
384
+ error,
385
+ event,
386
+
387
+ // TODO remove for 1.0
388
+ // @ts-expect-error
389
+ get request() {
390
+ throw new Error('request in handleError has been replaced with event. See https://github.com/sveltejs/kit/pull/3384 for details');
391
+ }
392
+ });
393
+ error.stack = this.options.get_stack(error);
394
+ },
395
+ hooks: null,
396
+ hydrate: ${s(config.kit.browser.hydrate)},
397
+ manifest,
398
+ method_override: ${s(config.kit.methodOverride)},
399
+ paths: { base, assets },
400
+ prefix: assets + '/${config.kit.appDir}/',
401
+ prerender: {
402
+ default: ${config.kit.prerender.default},
403
+ enabled: ${config.kit.prerender.enabled}
404
+ },
405
+ read,
406
+ root,
407
+ service_worker: ${has_service_worker ? "base + '/service-worker.js'" : 'null'},
408
+ router: ${s(config.kit.browser.router)},
409
+ template,
410
+ template_contains_nonce: ${template.includes('%sveltekit.nonce%')},
411
+ trailing_slash: ${s(config.kit.trailingSlash)}
412
+ };
413
+ }
414
+
415
+ async respond(request, options = {}) {
416
+ if (!(request instanceof Request)) {
417
+ throw new Error('The first argument to server.respond must be a Request object. See https://github.com/sveltejs/kit/pull/3384 for details');
418
+ }
419
+
420
+ if (!this.options.hooks) {
421
+ const module = await import(${s(hooks)});
422
+ this.options.hooks = {
423
+ getSession: module.getSession || (() => ({})),
424
+ handle: module.handle || (({ event, resolve }) => resolve(event)),
425
+ handleError: module.handleError || (({ error }) => console.error(error.stack)),
426
+ externalFetch: module.externalFetch || fetch
427
+ };
428
+ }
429
+
430
+ return respond(request, this.options, options);
431
+ }
432
+ }
433
+ `;
434
+
435
+ /**
436
+ * @param {{
437
+ * cwd: string;
438
+ * config: import('types').ValidatedConfig
439
+ * vite_config_env: import('vite').ConfigEnv
440
+ * manifest_data: import('types').ManifestData
441
+ * build_dir: string;
442
+ * output_dir: string;
443
+ * service_worker_entry_file: string | null;
444
+ * }} options
445
+ * @param {{ vite_manifest: import('vite').Manifest, assets: import('rollup').OutputAsset[] }} client
446
+ */
447
+ async function build_server(options, client) {
448
+ const {
449
+ cwd,
450
+ config,
451
+ vite_config_env,
452
+ manifest_data,
453
+ build_dir,
454
+ output_dir,
455
+ service_worker_entry_file
456
+ } = options;
457
+
458
+ let hooks_file = resolve_entry(config.kit.files.hooks);
459
+ if (!hooks_file || !fs__default.existsSync(hooks_file)) {
460
+ hooks_file = path__default.join(config.kit.outDir, 'build/hooks.js');
461
+ fs__default.writeFileSync(hooks_file, '');
462
+ }
463
+
464
+ /** @type {Record<string, string>} */
465
+ const input = {
466
+ index: `${build_dir}/index.js`
467
+ };
468
+
469
+ // add entry points for every endpoint...
470
+ manifest_data.routes.forEach((route) => {
471
+ const file = route.type === 'endpoint' ? route.file : route.shadow;
472
+
473
+ if (file) {
474
+ const resolved = path__default.resolve(cwd, file);
475
+ const relative = decodeURIComponent(path__default.relative(config.kit.files.routes, resolved));
476
+ const name = posixify(path__default.join('entries/endpoints', relative.replace(/\.js$/, '')));
477
+ input[name] = resolved;
478
+ }
479
+ });
480
+
481
+ // ...and every component used by pages...
482
+ manifest_data.components.forEach((file) => {
483
+ const resolved = path__default.resolve(cwd, file);
484
+ const relative = decodeURIComponent(path__default.relative(config.kit.files.routes, resolved));
485
+
486
+ const name = relative.startsWith('..')
487
+ ? posixify(path__default.join('entries/fallbacks', path__default.basename(file)))
488
+ : posixify(path__default.join('entries/pages', relative));
489
+ input[name] = resolved;
490
+ });
491
+
492
+ // ...and every matcher
493
+ Object.entries(manifest_data.matchers).forEach(([key, file]) => {
494
+ const name = posixify(path__default.join('entries/matchers', key));
495
+ input[name] = path__default.resolve(cwd, file);
496
+ });
497
+
498
+ /** @type {(file: string) => string} */
499
+ const app_relative = (file) => {
500
+ const relative_file = path__default.relative(build_dir, path__default.resolve(cwd, file));
501
+ return relative_file[0] === '.' ? relative_file : `./${relative_file}`;
502
+ };
503
+
504
+ fs__default.writeFileSync(
505
+ input.index,
506
+ server_template({
507
+ config,
508
+ hooks: app_relative(hooks_file),
509
+ has_service_worker: config.kit.serviceWorker.register && !!service_worker_entry_file,
510
+ runtime: posixify(path__default.relative(build_dir, get_runtime_directory(config.kit))),
511
+ template: load_template(cwd, config)
512
+ })
513
+ );
514
+
515
+ const vite_config = await get_vite_config(vite_config_env);
516
+
517
+ const merged_config = merge_vite_configs(
518
+ get_default_config({ config, input, ssr: true, outDir: `${output_dir}/server` }),
519
+ vite_config
520
+ );
521
+
522
+ remove_svelte_kit(merged_config);
523
+
524
+ const { chunks } = await create_build(merged_config);
525
+
526
+ /** @type {import('vite').Manifest} */
527
+ const vite_manifest = JSON.parse(fs__default.readFileSync(`${output_dir}/server/manifest.json`, 'utf-8'));
528
+
529
+ mkdirp(`${output_dir}/server/nodes`);
530
+ mkdirp(`${output_dir}/server/stylesheets`);
531
+
532
+ const stylesheet_lookup = new Map();
533
+
534
+ client.assets.forEach((asset) => {
535
+ if (asset.fileName.endsWith('.css')) {
536
+ if (asset.source.length < config.kit.inlineStyleThreshold) {
537
+ const index = stylesheet_lookup.size;
538
+ const file = `${output_dir}/server/stylesheets/${index}.js`;
539
+
540
+ fs__default.writeFileSync(file, `// ${asset.fileName}\nexport default ${s(asset.source)};`);
541
+ stylesheet_lookup.set(asset.fileName, index);
542
+ }
543
+ }
544
+ });
545
+
546
+ manifest_data.components.forEach((component, i) => {
547
+ const entry = find_deps$1(client.vite_manifest, component, true);
548
+
549
+ const imports = [`import * as module from '../${vite_manifest[component].file}';`];
550
+
551
+ const exports = [
552
+ 'export { module };',
553
+ `export const index = ${i};`,
554
+ `export const file = '${entry.file}';`,
555
+ `export const imports = ${s(entry.imports)};`,
556
+ `export const stylesheets = ${s(entry.stylesheets)};`
557
+ ];
558
+
559
+ /** @type {string[]} */
560
+ const styles = [];
561
+
562
+ entry.stylesheets.forEach((file) => {
563
+ if (stylesheet_lookup.has(file)) {
564
+ const index = stylesheet_lookup.get(file);
565
+ const name = `stylesheet_${index}`;
566
+ imports.push(`import ${name} from '../stylesheets/${index}.js';`);
567
+ styles.push(`\t${s(file)}: ${name}`);
568
+ }
569
+ });
570
+
571
+ if (styles.length > 0) {
572
+ exports.push(`export const inline_styles = () => ({\n${styles.join(',\n')}\n});`);
573
+ }
574
+
575
+ const out = `${output_dir}/server/nodes/${i}.js`;
576
+ fs__default.writeFileSync(out, `${imports.join('\n')}\n\n${exports.join('\n')}\n`);
577
+ });
578
+
579
+ return {
580
+ chunks,
581
+ vite_manifest,
582
+ methods: get_methods(cwd, chunks, manifest_data)
583
+ };
584
+ }
585
+
586
+ /**
587
+ * @param {string} cwd
588
+ * @param {import('rollup').OutputChunk[]} output
589
+ * @param {import('types').ManifestData} manifest_data
590
+ */
591
+ function get_methods(cwd, output, manifest_data) {
592
+ /** @type {Record<string, string[]>} */
593
+ const lookup = {};
594
+ output.forEach((chunk) => {
595
+ if (!chunk.facadeModuleId) return;
596
+ const id = chunk.facadeModuleId.slice(cwd.length + 1);
597
+ lookup[id] = chunk.exports;
598
+ });
599
+
600
+ /** @type {Record<string, import('types').HttpMethod[]>} */
601
+ const methods = {};
602
+ manifest_data.routes.forEach((route) => {
603
+ const file = route.type === 'endpoint' ? route.file : route.shadow;
604
+
605
+ if (file && lookup[file]) {
606
+ methods[file] = lookup[file].filter(is_http_method);
607
+ }
608
+ });
609
+
610
+ return methods;
611
+ }
612
+
613
+ const absolute = /^([a-z]+:)?\/?\//;
614
+ const scheme = /^[a-z]+:/;
615
+
616
+ /**
617
+ * @param {string} base
618
+ * @param {string} path
619
+ */
620
+ function resolve(base, path) {
621
+ if (scheme.test(path)) return path;
622
+
623
+ const base_match = absolute.exec(base);
624
+ const path_match = absolute.exec(path);
625
+
626
+ if (!base_match) {
627
+ throw new Error(`bad base path: "${base}"`);
628
+ }
629
+
630
+ const baseparts = path_match ? [] : base.slice(base_match[0].length).split('/');
631
+ const pathparts = path_match ? path.slice(path_match[0].length).split('/') : path.split('/');
632
+
633
+ baseparts.pop();
634
+
635
+ for (let i = 0; i < pathparts.length; i += 1) {
636
+ const part = pathparts[i];
637
+ if (part === '.') continue;
638
+ else if (part === '..') baseparts.pop();
639
+ else baseparts.push(part);
640
+ }
641
+
642
+ const prefix = (path_match && path_match[0]) || (base_match && base_match[0]) || '';
643
+
644
+ return `${prefix}${baseparts.join('/')}`;
645
+ }
646
+
647
+ /** @param {string} path */
648
+ function is_root_relative(path) {
649
+ return path[0] === '/' && path[1] !== '/';
650
+ }
651
+
652
+ /**
653
+ * @param {string} path
654
+ * @param {import('types').TrailingSlash} trailing_slash
655
+ */
656
+ function normalize_path(path, trailing_slash) {
657
+ if (path === '/' || trailing_slash === 'ignore') return path;
658
+
659
+ if (trailing_slash === 'never') {
660
+ return path.endsWith('/') ? path.slice(0, -1) : path;
661
+ } else if (trailing_slash === 'always' && !path.endsWith('/')) {
662
+ return path + '/';
663
+ }
664
+
665
+ return path;
666
+ }
667
+
668
+ /**
669
+ * @param {{
670
+ * config: import('types').ValidatedConfig;
671
+ * vite_config_env: import('vite').ConfigEnv;
672
+ * manifest_data: import('types').ManifestData;
673
+ * output_dir: string;
674
+ * service_worker_entry_file: string | null;
675
+ * }} options
676
+ * @param {import('types').Prerendered} prerendered
677
+ * @param {import('vite').Manifest} client_manifest
678
+ */
679
+ async function build_service_worker(
680
+ { config, vite_config_env, manifest_data, output_dir, service_worker_entry_file },
681
+ prerendered,
682
+ client_manifest
683
+ ) {
684
+ const build = new Set();
685
+ for (const key in client_manifest) {
686
+ const { file, css = [], assets = [] } = client_manifest[key];
687
+ build.add(file);
688
+ css.forEach((file) => build.add(file));
689
+ assets.forEach((file) => build.add(file));
690
+ }
691
+
692
+ const service_worker = `${config.kit.outDir}/generated/service-worker.js`;
693
+
694
+ fs__default.writeFileSync(
695
+ service_worker,
696
+ `
697
+ // TODO remove for 1.0
698
+ export const timestamp = {
699
+ toString: () => {
700
+ throw new Error('\`timestamp\` has been removed from $service-worker. Use \`version\` instead');
701
+ }
702
+ };
703
+
704
+ export const build = [
705
+ ${Array.from(build)
706
+ .map((file) => `${s(`${config.kit.paths.base}/${config.kit.appDir}/${file}`)}`)
707
+ .join(',\n\t\t\t\t')}
708
+ ];
709
+
710
+ export const files = [
711
+ ${manifest_data.assets
712
+ .filter((asset) => config.kit.serviceWorker.files(asset.file))
713
+ .map((asset) => `${s(`${config.kit.paths.base}/${asset.file}`)}`)
714
+ .join(',\n\t\t\t\t')}
715
+ ];
716
+
717
+ export const prerendered = [
718
+ ${prerendered.paths
719
+ .map((path) => s(normalize_path(path, config.kit.trailingSlash)))
720
+ .join(',\n\t\t\t\t')}
721
+ ];
722
+
723
+ export const version = ${s(config.kit.version.name)};
724
+ `
725
+ .replace(/^\t{3}/gm, '')
726
+ .trim()
727
+ );
728
+
729
+ const vite_config = await get_vite_config(vite_config_env);
730
+ const merged_config = merge_vite_configs(vite_config, {
731
+ base: assets_base(config.kit),
732
+ build: {
733
+ lib: {
734
+ entry: /** @type {string} */ (service_worker_entry_file),
735
+ name: 'app',
736
+ formats: ['es']
737
+ },
738
+ rollupOptions: {
739
+ output: {
740
+ entryFileNames: 'service-worker.js'
741
+ }
742
+ },
743
+ outDir: `${output_dir}/client`,
744
+ emptyOutDir: false
745
+ },
746
+ // @ts-expect-error
747
+ configFile: false,
748
+ resolve: {
749
+ alias: {
750
+ '$service-worker': service_worker,
751
+ $lib: config.kit.files.lib
752
+ }
753
+ }
754
+ });
755
+
756
+ remove_svelte_kit(merged_config);
757
+
758
+ await vite.build(merged_config);
759
+ }
760
+
761
+ /**
762
+ * @typedef {{
763
+ * fn: () => Promise<any>,
764
+ * fulfil: (value: any) => void,
765
+ * reject: (error: Error) => void
766
+ * }} Task
767
+ */
768
+
769
+ /** @param {number} concurrency */
770
+ function queue(concurrency) {
771
+ /** @type {Task[]} */
772
+ const tasks = [];
773
+
774
+ let current = 0;
775
+
776
+ /** @type {(value?: any) => void} */
777
+ let fulfil;
778
+
779
+ /** @type {(error: Error) => void} */
780
+ let reject;
781
+
782
+ let closed = false;
783
+
784
+ const done = new Promise((f, r) => {
785
+ fulfil = f;
786
+ reject = r;
787
+ });
788
+
789
+ done.catch(() => {
790
+ // this is necessary in case a catch handler is never added
791
+ // to the done promise by the user
792
+ });
793
+
794
+ function dequeue() {
795
+ if (current < concurrency) {
796
+ const task = tasks.shift();
797
+
798
+ if (task) {
799
+ current += 1;
800
+ const promise = Promise.resolve(task.fn());
801
+
802
+ promise
803
+ .then(task.fulfil, (err) => {
804
+ task.reject(err);
805
+ reject(err);
806
+ })
807
+ .then(() => {
808
+ current -= 1;
809
+ dequeue();
810
+ });
811
+ } else if (current === 0) {
812
+ closed = true;
813
+ fulfil();
814
+ }
815
+ }
816
+ }
817
+
818
+ return {
819
+ /** @param {() => any} fn */
820
+ add: (fn) => {
821
+ if (closed) throw new Error('Cannot add tasks to a queue that has ended');
822
+
823
+ const promise = new Promise((fulfil, reject) => {
824
+ tasks.push({ fn, fulfil, reject });
825
+ });
826
+
827
+ dequeue();
828
+ return promise;
829
+ },
830
+
831
+ done: () => {
832
+ if (current === 0) {
833
+ closed = true;
834
+ fulfil();
835
+ }
836
+
837
+ return done;
838
+ }
839
+ };
840
+ }
841
+
842
+ const DOCTYPE = 'DOCTYPE';
843
+ const CDATA_OPEN = '[CDATA[';
844
+ const CDATA_CLOSE = ']]>';
845
+ const COMMENT_OPEN = '--';
846
+ const COMMENT_CLOSE = '-->';
847
+
848
+ const TAG_OPEN = /[a-zA-Z]/;
849
+ const TAG_CHAR = /[a-zA-Z0-9]/;
850
+ const ATTRIBUTE_NAME = /[^\t\n\f />"'=]/;
851
+
852
+ const WHITESPACE = /[\s\n\r]/;
853
+
854
+ /** @param {string} html */
855
+ function crawl(html) {
856
+ /** @type {string[]} */
857
+ const hrefs = [];
858
+
859
+ let i = 0;
860
+ main: while (i < html.length) {
861
+ const char = html[i];
862
+
863
+ if (char === '<') {
864
+ if (html[i + 1] === '!') {
865
+ i += 2;
866
+
867
+ if (html.slice(i, i + DOCTYPE.length).toUpperCase() === DOCTYPE) {
868
+ i += DOCTYPE.length;
869
+ while (i < html.length) {
870
+ if (html[i++] === '>') {
871
+ continue main;
872
+ }
873
+ }
874
+ }
875
+
876
+ // skip cdata
877
+ if (html.slice(i, i + CDATA_OPEN.length) === CDATA_OPEN) {
878
+ i += CDATA_OPEN.length;
879
+ while (i < html.length) {
880
+ if (html.slice(i, i + CDATA_CLOSE.length) === CDATA_CLOSE) {
881
+ i += CDATA_CLOSE.length;
882
+ continue main;
883
+ }
884
+
885
+ i += 1;
886
+ }
887
+ }
888
+
889
+ // skip comments
890
+ if (html.slice(i, i + COMMENT_OPEN.length) === COMMENT_OPEN) {
891
+ i += COMMENT_OPEN.length;
892
+ while (i < html.length) {
893
+ if (html.slice(i, i + COMMENT_CLOSE.length) === COMMENT_CLOSE) {
894
+ i += COMMENT_CLOSE.length;
895
+ continue main;
896
+ }
897
+
898
+ i += 1;
899
+ }
900
+ }
901
+ }
902
+
903
+ // parse opening tags
904
+ const start = ++i;
905
+ if (TAG_OPEN.test(html[start])) {
906
+ while (i < html.length) {
907
+ if (!TAG_CHAR.test(html[i])) {
908
+ break;
909
+ }
910
+
911
+ i += 1;
912
+ }
913
+
914
+ const tag = html.slice(start, i).toUpperCase();
915
+
916
+ if (tag === 'SCRIPT' || tag === 'STYLE') {
917
+ while (i < html.length) {
918
+ if (
919
+ html[i] === '<' &&
920
+ html[i + 1] === '/' &&
921
+ html.slice(i + 2, i + 2 + tag.length).toUpperCase() === tag
922
+ ) {
923
+ continue main;
924
+ }
925
+
926
+ i += 1;
927
+ }
928
+ }
929
+
930
+ let href = '';
931
+ let rel = '';
932
+
933
+ while (i < html.length) {
934
+ const start = i;
935
+
936
+ const char = html[start];
937
+ if (char === '>') break;
938
+
939
+ if (ATTRIBUTE_NAME.test(char)) {
940
+ i += 1;
941
+
942
+ while (i < html.length) {
943
+ if (!ATTRIBUTE_NAME.test(html[i])) {
944
+ break;
945
+ }
946
+
947
+ i += 1;
948
+ }
949
+
950
+ const name = html.slice(start, i).toLowerCase();
951
+
952
+ while (WHITESPACE.test(html[i])) i += 1;
953
+
954
+ if (html[i] === '=') {
955
+ i += 1;
956
+ while (WHITESPACE.test(html[i])) i += 1;
957
+
958
+ let value;
959
+
960
+ if (html[i] === "'" || html[i] === '"') {
961
+ const quote = html[i++];
962
+
963
+ const start = i;
964
+ let escaped = false;
965
+
966
+ while (i < html.length) {
967
+ if (!escaped) {
968
+ const char = html[i];
969
+
970
+ if (html[i] === quote) {
971
+ break;
972
+ }
973
+
974
+ if (char === '\\') {
975
+ escaped = true;
976
+ }
977
+ }
978
+
979
+ i += 1;
980
+ }
981
+
982
+ value = html.slice(start, i);
983
+ } else {
984
+ const start = i;
985
+ while (html[i] !== '>' && !WHITESPACE.test(html[i])) i += 1;
986
+ value = html.slice(start, i);
987
+
988
+ i -= 1;
989
+ }
990
+
991
+ if (name === 'href') {
992
+ href = value;
993
+ } else if (name === 'rel') {
994
+ rel = value;
995
+ } else if (name === 'src') {
996
+ hrefs.push(value);
997
+ } else if (name === 'srcset') {
998
+ const candidates = [];
999
+ let insideURL = true;
1000
+ value = value.trim();
1001
+ for (let i = 0; i < value.length; i++) {
1002
+ if (value[i] === ',' && (!insideURL || (insideURL && value[i + 1] === ' '))) {
1003
+ candidates.push(value.slice(0, i));
1004
+ value = value.substring(i + 1).trim();
1005
+ i = 0;
1006
+ insideURL = true;
1007
+ } else if (value[i] === ' ') {
1008
+ insideURL = false;
1009
+ }
1010
+ }
1011
+ candidates.push(value);
1012
+ for (const candidate of candidates) {
1013
+ const src = candidate.split(WHITESPACE)[0];
1014
+ hrefs.push(src);
1015
+ }
1016
+ }
1017
+ } else {
1018
+ i -= 1;
1019
+ }
1020
+ }
1021
+
1022
+ i += 1;
1023
+ }
1024
+
1025
+ if (href && !/\bexternal\b/i.test(rel)) {
1026
+ hrefs.push(href);
1027
+ }
1028
+ }
1029
+ }
1030
+
1031
+ i += 1;
1032
+ }
1033
+
1034
+ return hrefs;
1035
+ }
1036
+
1037
+ /**
1038
+ * Inside a script element, only `</script` and `<!--` hold special meaning to the HTML parser.
1039
+ *
1040
+ * The first closes the script element, so everything after is treated as raw HTML.
1041
+ * The second disables further parsing until `-->`, so the script element might be unexpectedly
1042
+ * kept open until until an unrelated HTML comment in the page.
1043
+ *
1044
+ * U+2028 LINE SEPARATOR and U+2029 PARAGRAPH SEPARATOR are escaped for the sake of pre-2018
1045
+ * browsers.
1046
+ *
1047
+ * @see tests for unsafe parsing examples.
1048
+ * @see https://html.spec.whatwg.org/multipage/scripting.html#restrictions-for-contents-of-script-elements
1049
+ * @see https://html.spec.whatwg.org/multipage/syntax.html#cdata-rcdata-restrictions
1050
+ * @see https://html.spec.whatwg.org/multipage/parsing.html#script-data-state
1051
+ * @see https://html.spec.whatwg.org/multipage/parsing.html#script-data-double-escaped-state
1052
+ * @see https://github.com/tc39/proposal-json-superset
1053
+ * @type {Record<string, string>}
1054
+ */
1055
+ const render_json_payload_script_dict = {
1056
+ '<': '\\u003C',
1057
+ '\u2028': '\\u2028',
1058
+ '\u2029': '\\u2029'
1059
+ };
1060
+
1061
+ new RegExp(
1062
+ `[${Object.keys(render_json_payload_script_dict).join('')}]`,
1063
+ 'g'
1064
+ );
1065
+
1066
+ /**
1067
+ * When inside a double-quoted attribute value, only `&` and `"` hold special meaning.
1068
+ * @see https://html.spec.whatwg.org/multipage/parsing.html#attribute-value-(double-quoted)-state
1069
+ * @type {Record<string, string>}
1070
+ */
1071
+ const escape_html_attr_dict = {
1072
+ '&': '&amp;',
1073
+ '"': '&quot;'
1074
+ };
1075
+
1076
+ const escape_html_attr_regex = new RegExp(
1077
+ // special characters
1078
+ `[${Object.keys(escape_html_attr_dict).join('')}]|` +
1079
+ // high surrogate without paired low surrogate
1080
+ '[\\ud800-\\udbff](?![\\udc00-\\udfff])|' +
1081
+ // a valid surrogate pair, the only match with 2 code units
1082
+ // we match it so that we can match unpaired low surrogates in the same pass
1083
+ // TODO: use lookbehind assertions once they are widely supported: (?<![\ud800-udbff])[\udc00-\udfff]
1084
+ '[\\ud800-\\udbff][\\udc00-\\udfff]|' +
1085
+ // unpaired low surrogate (see previous match)
1086
+ '[\\udc00-\\udfff]',
1087
+ 'g'
1088
+ );
1089
+
1090
+ /**
1091
+ * Formats a string to be used as an attribute's value in raw HTML.
1092
+ *
1093
+ * It escapes unpaired surrogates (which are allowed in js strings but invalid in HTML), escapes
1094
+ * characters that are special in attributes, and surrounds the whole string in double-quotes.
1095
+ *
1096
+ * @param {string} str
1097
+ * @returns {string} Escaped string surrounded by double-quotes.
1098
+ * @example const html = `<tag data-value=${escape_html_attr('value')}>...</tag>`;
1099
+ */
1100
+ function escape_html_attr(str) {
1101
+ const escaped_str = str.replace(escape_html_attr_regex, (match) => {
1102
+ if (match.length === 2) {
1103
+ // valid surrogate pair
1104
+ return match;
1105
+ }
1106
+
1107
+ return escape_html_attr_dict[match] ?? `&#${match.charCodeAt(0)};`;
1108
+ });
1109
+
1110
+ return `"${escaped_str}"`;
1111
+ }
1112
+
1113
+ /**
1114
+ * @typedef {import('types').PrerenderErrorHandler} PrerenderErrorHandler
1115
+ * @typedef {import('types').PrerenderOnErrorValue} OnError
1116
+ * @typedef {import('types').Logger} Logger
1117
+ */
1118
+
1119
+ /** @type {(details: Parameters<PrerenderErrorHandler>[0] ) => string} */
1120
+ function format_error({ status, path, referrer, referenceType }) {
1121
+ return `${status} ${path}${referrer ? ` (${referenceType} from ${referrer})` : ''}`;
1122
+ }
1123
+
1124
+ /** @type {(log: Logger, onError: OnError) => PrerenderErrorHandler} */
1125
+ function normalise_error_handler(log, onError) {
1126
+ switch (onError) {
1127
+ case 'continue':
1128
+ return (details) => {
1129
+ log.error(format_error(details));
1130
+ };
1131
+ case 'fail':
1132
+ return (details) => {
1133
+ throw new Error(format_error(details));
1134
+ };
1135
+ default:
1136
+ return onError;
1137
+ }
1138
+ }
1139
+
1140
+ const OK = 2;
1141
+ const REDIRECT = 3;
1142
+
1143
+ /**
1144
+ * @param {{
1145
+ * config: import('types').ValidatedKitConfig;
1146
+ * entries: string[];
1147
+ * files: Set<string>;
1148
+ * log: Logger;
1149
+ * }} opts
1150
+ */
1151
+ async function prerender({ config, entries, files, log }) {
1152
+ /** @type {import('types').Prerendered} */
1153
+ const prerendered = {
1154
+ pages: new Map(),
1155
+ assets: new Map(),
1156
+ redirects: new Map(),
1157
+ paths: []
1158
+ };
1159
+
1160
+ if (!config.prerender.enabled) {
1161
+ return prerendered;
1162
+ }
1163
+
1164
+ installPolyfills();
1165
+
1166
+ const server_root = join(config.outDir, 'output');
1167
+
1168
+ /** @type {import('types').ServerModule} */
1169
+ const { Server, override } = await import(pathToFileURL(`${server_root}/server/index.js`).href);
1170
+ const { manifest } = await import(pathToFileURL(`${server_root}/server/manifest.js`).href);
1171
+
1172
+ override({
1173
+ paths: config.paths,
1174
+ prerendering: true,
1175
+ read: (file) => readFileSync(join(config.files.assets, file))
1176
+ });
1177
+
1178
+ const server = new Server(manifest);
1179
+
1180
+ const error = normalise_error_handler(log, config.prerender.onError);
1181
+
1182
+ const q = queue(config.prerender.concurrency);
1183
+
1184
+ /**
1185
+ * @param {string} path
1186
+ * @param {boolean} is_html
1187
+ */
1188
+ function output_filename(path, is_html) {
1189
+ const file = path.slice(config.paths.base.length + 1);
1190
+
1191
+ if (file === '') {
1192
+ return 'index.html';
1193
+ }
1194
+
1195
+ if (is_html && !file.endsWith('.html')) {
1196
+ return file + (file.endsWith('/') ? 'index.html' : '.html');
1197
+ }
1198
+
1199
+ return file;
1200
+ }
1201
+
1202
+ const seen = new Set();
1203
+ const written = new Set();
1204
+
1205
+ /**
1206
+ * @param {string | null} referrer
1207
+ * @param {string} decoded
1208
+ * @param {string} [encoded]
1209
+ */
1210
+ function enqueue(referrer, decoded, encoded) {
1211
+ if (seen.has(decoded)) return;
1212
+ seen.add(decoded);
1213
+
1214
+ const file = decoded.slice(config.paths.base.length + 1);
1215
+ if (files.has(file)) return;
1216
+
1217
+ return q.add(() => visit(decoded, encoded || encodeURI(decoded), referrer));
1218
+ }
1219
+
1220
+ /**
1221
+ * @param {string} decoded
1222
+ * @param {string} encoded
1223
+ * @param {string?} referrer
1224
+ */
1225
+ async function visit(decoded, encoded, referrer) {
1226
+ if (!decoded.startsWith(config.paths.base)) {
1227
+ error({ status: 404, path: decoded, referrer, referenceType: 'linked' });
1228
+ return;
1229
+ }
1230
+
1231
+ /** @type {Map<string, import('types').PrerenderDependency>} */
1232
+ const dependencies = new Map();
1233
+
1234
+ const response = await server.respond(new Request(`http://sveltekit-prerender${encoded}`), {
1235
+ getClientAddress,
1236
+ prerendering: {
1237
+ dependencies
1238
+ }
1239
+ });
1240
+
1241
+ const body = Buffer.from(await response.arrayBuffer());
1242
+
1243
+ save('pages', response, body, decoded, encoded, referrer, 'linked');
1244
+
1245
+ for (const [dependency_path, result] of dependencies) {
1246
+ // this seems circuitous, but using new URL allows us to not care
1247
+ // whether dependency_path is encoded or not
1248
+ const encoded_dependency_path = new URL$1(dependency_path, 'http://localhost').pathname;
1249
+ const decoded_dependency_path = decodeURI(encoded_dependency_path);
1250
+
1251
+ const body = result.body ?? new Uint8Array(await result.response.arrayBuffer());
1252
+ save(
1253
+ 'dependencies',
1254
+ result.response,
1255
+ body,
1256
+ decoded_dependency_path,
1257
+ encoded_dependency_path,
1258
+ decoded,
1259
+ 'fetched'
1260
+ );
1261
+ }
1262
+
1263
+ if (config.prerender.crawl && response.headers.get('content-type') === 'text/html') {
1264
+ for (const href of crawl(body.toString())) {
1265
+ if (href.startsWith('data:') || href.startsWith('#')) continue;
1266
+
1267
+ const resolved = resolve(encoded, href);
1268
+ if (!is_root_relative(resolved)) continue;
1269
+
1270
+ const { pathname, search } = new URL$1(resolved, 'http://localhost');
1271
+
1272
+ enqueue(decoded, decodeURI(pathname), pathname);
1273
+ }
1274
+ }
1275
+ }
1276
+
1277
+ /**
1278
+ * @param {'pages' | 'dependencies'} category
1279
+ * @param {Response} response
1280
+ * @param {string | Uint8Array} body
1281
+ * @param {string} decoded
1282
+ * @param {string} encoded
1283
+ * @param {string | null} referrer
1284
+ * @param {'linked' | 'fetched'} referenceType
1285
+ */
1286
+ function save(category, response, body, decoded, encoded, referrer, referenceType) {
1287
+ const response_type = Math.floor(response.status / 100);
1288
+ const type = /** @type {string} */ (response.headers.get('content-type'));
1289
+ const is_html = response_type === REDIRECT || type === 'text/html';
1290
+
1291
+ const file = output_filename(decoded, is_html);
1292
+ const dest = `${config.outDir}/output/prerendered/${category}/${file}`;
1293
+
1294
+ if (written.has(file)) return;
1295
+
1296
+ if (response_type === REDIRECT) {
1297
+ const location = response.headers.get('location');
1298
+
1299
+ if (location) {
1300
+ const resolved = resolve(encoded, location);
1301
+ if (is_root_relative(resolved)) {
1302
+ enqueue(decoded, decodeURI(resolved), resolved);
1303
+ }
1304
+
1305
+ if (!response.headers.get('x-sveltekit-normalize')) {
1306
+ mkdirp(dirname(dest));
1307
+
1308
+ log.warn(`${response.status} ${decoded} -> ${location}`);
1309
+
1310
+ writeFileSync(
1311
+ dest,
1312
+ `<meta http-equiv="refresh" content=${escape_html_attr(`0;url=${location}`)}>`
1313
+ );
1314
+
1315
+ written.add(file);
1316
+
1317
+ if (!prerendered.redirects.has(decoded)) {
1318
+ prerendered.redirects.set(decoded, {
1319
+ status: response.status,
1320
+ location: resolved
1321
+ });
1322
+
1323
+ prerendered.paths.push(normalize_path(decoded, 'never'));
1324
+ }
1325
+ }
1326
+ } else {
1327
+ log.warn(`location header missing on redirect received from ${decoded}`);
1328
+ }
1329
+
1330
+ return;
1331
+ }
1332
+
1333
+ if (response.status === 200) {
1334
+ mkdirp(dirname(dest));
1335
+
1336
+ log.info(`${response.status} ${decoded}`);
1337
+ writeFileSync(dest, body);
1338
+ written.add(file);
1339
+
1340
+ if (is_html) {
1341
+ prerendered.pages.set(decoded, {
1342
+ file
1343
+ });
1344
+ } else {
1345
+ prerendered.assets.set(decoded, {
1346
+ type
1347
+ });
1348
+ }
1349
+
1350
+ prerendered.paths.push(normalize_path(decoded, 'never'));
1351
+ } else if (response_type !== OK) {
1352
+ error({ status: response.status, path: decoded, referrer, referenceType });
1353
+ }
1354
+ }
1355
+
1356
+ if (config.prerender.enabled) {
1357
+ for (const entry of config.prerender.entries) {
1358
+ if (entry === '*') {
1359
+ for (const entry of entries) {
1360
+ enqueue(null, config.paths.base + entry); // TODO can we pre-normalize these?
1361
+ }
1362
+ } else {
1363
+ enqueue(null, config.paths.base + entry);
1364
+ }
1365
+ }
1366
+
1367
+ await q.done();
1368
+ }
1369
+
1370
+ const rendered = await server.respond(new Request('http://sveltekit-prerender/[fallback]'), {
1371
+ getClientAddress,
1372
+ prerendering: {
1373
+ fallback: true,
1374
+ dependencies: new Map()
1375
+ }
1376
+ });
1377
+
1378
+ const file = `${config.outDir}/output/prerendered/fallback.html`;
1379
+ mkdirp(dirname(file));
1380
+ writeFileSync(file, await rendered.text());
1381
+
1382
+ return prerendered;
1383
+ }
1384
+
1385
+ /** @return {string} */
1386
+ function getClientAddress() {
1387
+ throw new Error('Cannot read clientAddress during prerendering');
1388
+ }
1389
+
1390
+ function totalist(dir, callback, pre='') {
1391
+ dir = resolve$1('.', dir);
1392
+ let arr = readdirSync(dir);
1393
+ let i=0, abs, stats;
1394
+ for (; i < arr.length; i++) {
1395
+ abs = join(dir, arr[i]);
1396
+ stats = statSync(abs);
1397
+ stats.isDirectory()
1398
+ ? totalist(abs, callback, join(pre, arr[i]))
1399
+ : callback(join(pre, arr[i]), abs, stats);
1400
+ }
1401
+ }
1402
+
1403
+ /**
1404
+ * @typedef ParsedURL
1405
+ * @type {import('.').ParsedURL}
1406
+ */
1407
+
1408
+ /**
1409
+ * @typedef Request
1410
+ * @property {string} url
1411
+ * @property {ParsedURL} _parsedUrl
1412
+ */
1413
+
1414
+ /**
1415
+ * @param {Request} req
1416
+ * @returns {ParsedURL|void}
1417
+ */
1418
+ function parse(req) {
1419
+ let raw = req.url;
1420
+ if (raw == null) return;
1421
+
1422
+ let prev = req._parsedUrl;
1423
+ if (prev && prev.raw === raw) return prev;
1424
+
1425
+ let pathname=raw, search='', query;
1426
+
1427
+ if (raw.length > 1) {
1428
+ let idx = raw.indexOf('?', 1);
1429
+
1430
+ if (idx !== -1) {
1431
+ search = raw.substring(idx);
1432
+ pathname = raw.substring(0, idx);
1433
+ if (search.length > 1) {
1434
+ query = qs.parse(search.substring(1));
1435
+ }
1436
+ }
1437
+ }
1438
+
1439
+ return req._parsedUrl = { pathname, search, query, raw };
1440
+ }
1441
+
1442
+ const mimes = {
1443
+ "ez": "application/andrew-inset",
1444
+ "aw": "application/applixware",
1445
+ "atom": "application/atom+xml",
1446
+ "atomcat": "application/atomcat+xml",
1447
+ "atomdeleted": "application/atomdeleted+xml",
1448
+ "atomsvc": "application/atomsvc+xml",
1449
+ "dwd": "application/atsc-dwd+xml",
1450
+ "held": "application/atsc-held+xml",
1451
+ "rsat": "application/atsc-rsat+xml",
1452
+ "bdoc": "application/bdoc",
1453
+ "xcs": "application/calendar+xml",
1454
+ "ccxml": "application/ccxml+xml",
1455
+ "cdfx": "application/cdfx+xml",
1456
+ "cdmia": "application/cdmi-capability",
1457
+ "cdmic": "application/cdmi-container",
1458
+ "cdmid": "application/cdmi-domain",
1459
+ "cdmio": "application/cdmi-object",
1460
+ "cdmiq": "application/cdmi-queue",
1461
+ "cu": "application/cu-seeme",
1462
+ "mpd": "application/dash+xml",
1463
+ "davmount": "application/davmount+xml",
1464
+ "dbk": "application/docbook+xml",
1465
+ "dssc": "application/dssc+der",
1466
+ "xdssc": "application/dssc+xml",
1467
+ "es": "application/ecmascript",
1468
+ "ecma": "application/ecmascript",
1469
+ "emma": "application/emma+xml",
1470
+ "emotionml": "application/emotionml+xml",
1471
+ "epub": "application/epub+zip",
1472
+ "exi": "application/exi",
1473
+ "fdt": "application/fdt+xml",
1474
+ "pfr": "application/font-tdpfr",
1475
+ "geojson": "application/geo+json",
1476
+ "gml": "application/gml+xml",
1477
+ "gpx": "application/gpx+xml",
1478
+ "gxf": "application/gxf",
1479
+ "gz": "application/gzip",
1480
+ "hjson": "application/hjson",
1481
+ "stk": "application/hyperstudio",
1482
+ "ink": "application/inkml+xml",
1483
+ "inkml": "application/inkml+xml",
1484
+ "ipfix": "application/ipfix",
1485
+ "its": "application/its+xml",
1486
+ "jar": "application/java-archive",
1487
+ "war": "application/java-archive",
1488
+ "ear": "application/java-archive",
1489
+ "ser": "application/java-serialized-object",
1490
+ "class": "application/java-vm",
1491
+ "js": "application/javascript",
1492
+ "mjs": "application/javascript",
1493
+ "json": "application/json",
1494
+ "map": "application/json",
1495
+ "json5": "application/json5",
1496
+ "jsonml": "application/jsonml+json",
1497
+ "jsonld": "application/ld+json",
1498
+ "lgr": "application/lgr+xml",
1499
+ "lostxml": "application/lost+xml",
1500
+ "hqx": "application/mac-binhex40",
1501
+ "cpt": "application/mac-compactpro",
1502
+ "mads": "application/mads+xml",
1503
+ "webmanifest": "application/manifest+json",
1504
+ "mrc": "application/marc",
1505
+ "mrcx": "application/marcxml+xml",
1506
+ "ma": "application/mathematica",
1507
+ "nb": "application/mathematica",
1508
+ "mb": "application/mathematica",
1509
+ "mathml": "application/mathml+xml",
1510
+ "mbox": "application/mbox",
1511
+ "mscml": "application/mediaservercontrol+xml",
1512
+ "metalink": "application/metalink+xml",
1513
+ "meta4": "application/metalink4+xml",
1514
+ "mets": "application/mets+xml",
1515
+ "maei": "application/mmt-aei+xml",
1516
+ "musd": "application/mmt-usd+xml",
1517
+ "mods": "application/mods+xml",
1518
+ "m21": "application/mp21",
1519
+ "mp21": "application/mp21",
1520
+ "mp4s": "application/mp4",
1521
+ "m4p": "application/mp4",
1522
+ "doc": "application/msword",
1523
+ "dot": "application/msword",
1524
+ "mxf": "application/mxf",
1525
+ "nq": "application/n-quads",
1526
+ "nt": "application/n-triples",
1527
+ "cjs": "application/node",
1528
+ "bin": "application/octet-stream",
1529
+ "dms": "application/octet-stream",
1530
+ "lrf": "application/octet-stream",
1531
+ "mar": "application/octet-stream",
1532
+ "so": "application/octet-stream",
1533
+ "dist": "application/octet-stream",
1534
+ "distz": "application/octet-stream",
1535
+ "pkg": "application/octet-stream",
1536
+ "bpk": "application/octet-stream",
1537
+ "dump": "application/octet-stream",
1538
+ "elc": "application/octet-stream",
1539
+ "deploy": "application/octet-stream",
1540
+ "exe": "application/octet-stream",
1541
+ "dll": "application/octet-stream",
1542
+ "deb": "application/octet-stream",
1543
+ "dmg": "application/octet-stream",
1544
+ "iso": "application/octet-stream",
1545
+ "img": "application/octet-stream",
1546
+ "msi": "application/octet-stream",
1547
+ "msp": "application/octet-stream",
1548
+ "msm": "application/octet-stream",
1549
+ "buffer": "application/octet-stream",
1550
+ "oda": "application/oda",
1551
+ "opf": "application/oebps-package+xml",
1552
+ "ogx": "application/ogg",
1553
+ "omdoc": "application/omdoc+xml",
1554
+ "onetoc": "application/onenote",
1555
+ "onetoc2": "application/onenote",
1556
+ "onetmp": "application/onenote",
1557
+ "onepkg": "application/onenote",
1558
+ "oxps": "application/oxps",
1559
+ "relo": "application/p2p-overlay+xml",
1560
+ "xer": "application/patch-ops-error+xml",
1561
+ "pdf": "application/pdf",
1562
+ "pgp": "application/pgp-encrypted",
1563
+ "asc": "application/pgp-signature",
1564
+ "sig": "application/pgp-signature",
1565
+ "prf": "application/pics-rules",
1566
+ "p10": "application/pkcs10",
1567
+ "p7m": "application/pkcs7-mime",
1568
+ "p7c": "application/pkcs7-mime",
1569
+ "p7s": "application/pkcs7-signature",
1570
+ "p8": "application/pkcs8",
1571
+ "ac": "application/pkix-attr-cert",
1572
+ "cer": "application/pkix-cert",
1573
+ "crl": "application/pkix-crl",
1574
+ "pkipath": "application/pkix-pkipath",
1575
+ "pki": "application/pkixcmp",
1576
+ "pls": "application/pls+xml",
1577
+ "ai": "application/postscript",
1578
+ "eps": "application/postscript",
1579
+ "ps": "application/postscript",
1580
+ "provx": "application/provenance+xml",
1581
+ "cww": "application/prs.cww",
1582
+ "pskcxml": "application/pskc+xml",
1583
+ "raml": "application/raml+yaml",
1584
+ "rdf": "application/rdf+xml",
1585
+ "owl": "application/rdf+xml",
1586
+ "rif": "application/reginfo+xml",
1587
+ "rnc": "application/relax-ng-compact-syntax",
1588
+ "rl": "application/resource-lists+xml",
1589
+ "rld": "application/resource-lists-diff+xml",
1590
+ "rs": "application/rls-services+xml",
1591
+ "rapd": "application/route-apd+xml",
1592
+ "sls": "application/route-s-tsid+xml",
1593
+ "rusd": "application/route-usd+xml",
1594
+ "gbr": "application/rpki-ghostbusters",
1595
+ "mft": "application/rpki-manifest",
1596
+ "roa": "application/rpki-roa",
1597
+ "rsd": "application/rsd+xml",
1598
+ "rss": "application/rss+xml",
1599
+ "rtf": "application/rtf",
1600
+ "sbml": "application/sbml+xml",
1601
+ "scq": "application/scvp-cv-request",
1602
+ "scs": "application/scvp-cv-response",
1603
+ "spq": "application/scvp-vp-request",
1604
+ "spp": "application/scvp-vp-response",
1605
+ "sdp": "application/sdp",
1606
+ "senmlx": "application/senml+xml",
1607
+ "sensmlx": "application/sensml+xml",
1608
+ "setpay": "application/set-payment-initiation",
1609
+ "setreg": "application/set-registration-initiation",
1610
+ "shf": "application/shf+xml",
1611
+ "siv": "application/sieve",
1612
+ "sieve": "application/sieve",
1613
+ "smi": "application/smil+xml",
1614
+ "smil": "application/smil+xml",
1615
+ "rq": "application/sparql-query",
1616
+ "srx": "application/sparql-results+xml",
1617
+ "gram": "application/srgs",
1618
+ "grxml": "application/srgs+xml",
1619
+ "sru": "application/sru+xml",
1620
+ "ssdl": "application/ssdl+xml",
1621
+ "ssml": "application/ssml+xml",
1622
+ "swidtag": "application/swid+xml",
1623
+ "tei": "application/tei+xml",
1624
+ "teicorpus": "application/tei+xml",
1625
+ "tfi": "application/thraud+xml",
1626
+ "tsd": "application/timestamped-data",
1627
+ "toml": "application/toml",
1628
+ "trig": "application/trig",
1629
+ "ttml": "application/ttml+xml",
1630
+ "ubj": "application/ubjson",
1631
+ "rsheet": "application/urc-ressheet+xml",
1632
+ "td": "application/urc-targetdesc+xml",
1633
+ "vxml": "application/voicexml+xml",
1634
+ "wasm": "application/wasm",
1635
+ "wgt": "application/widget",
1636
+ "hlp": "application/winhlp",
1637
+ "wsdl": "application/wsdl+xml",
1638
+ "wspolicy": "application/wspolicy+xml",
1639
+ "xaml": "application/xaml+xml",
1640
+ "xav": "application/xcap-att+xml",
1641
+ "xca": "application/xcap-caps+xml",
1642
+ "xdf": "application/xcap-diff+xml",
1643
+ "xel": "application/xcap-el+xml",
1644
+ "xns": "application/xcap-ns+xml",
1645
+ "xenc": "application/xenc+xml",
1646
+ "xhtml": "application/xhtml+xml",
1647
+ "xht": "application/xhtml+xml",
1648
+ "xlf": "application/xliff+xml",
1649
+ "xml": "application/xml",
1650
+ "xsl": "application/xml",
1651
+ "xsd": "application/xml",
1652
+ "rng": "application/xml",
1653
+ "dtd": "application/xml-dtd",
1654
+ "xop": "application/xop+xml",
1655
+ "xpl": "application/xproc+xml",
1656
+ "xslt": "application/xml",
1657
+ "xspf": "application/xspf+xml",
1658
+ "mxml": "application/xv+xml",
1659
+ "xhvml": "application/xv+xml",
1660
+ "xvml": "application/xv+xml",
1661
+ "xvm": "application/xv+xml",
1662
+ "yang": "application/yang",
1663
+ "yin": "application/yin+xml",
1664
+ "zip": "application/zip",
1665
+ "3gpp": "video/3gpp",
1666
+ "adp": "audio/adpcm",
1667
+ "amr": "audio/amr",
1668
+ "au": "audio/basic",
1669
+ "snd": "audio/basic",
1670
+ "mid": "audio/midi",
1671
+ "midi": "audio/midi",
1672
+ "kar": "audio/midi",
1673
+ "rmi": "audio/midi",
1674
+ "mxmf": "audio/mobile-xmf",
1675
+ "mp3": "audio/mpeg",
1676
+ "m4a": "audio/mp4",
1677
+ "mp4a": "audio/mp4",
1678
+ "mpga": "audio/mpeg",
1679
+ "mp2": "audio/mpeg",
1680
+ "mp2a": "audio/mpeg",
1681
+ "m2a": "audio/mpeg",
1682
+ "m3a": "audio/mpeg",
1683
+ "oga": "audio/ogg",
1684
+ "ogg": "audio/ogg",
1685
+ "spx": "audio/ogg",
1686
+ "opus": "audio/ogg",
1687
+ "s3m": "audio/s3m",
1688
+ "sil": "audio/silk",
1689
+ "wav": "audio/wav",
1690
+ "weba": "audio/webm",
1691
+ "xm": "audio/xm",
1692
+ "ttc": "font/collection",
1693
+ "otf": "font/otf",
1694
+ "ttf": "font/ttf",
1695
+ "woff": "font/woff",
1696
+ "woff2": "font/woff2",
1697
+ "exr": "image/aces",
1698
+ "apng": "image/apng",
1699
+ "avif": "image/avif",
1700
+ "bmp": "image/bmp",
1701
+ "cgm": "image/cgm",
1702
+ "drle": "image/dicom-rle",
1703
+ "emf": "image/emf",
1704
+ "fits": "image/fits",
1705
+ "g3": "image/g3fax",
1706
+ "gif": "image/gif",
1707
+ "heic": "image/heic",
1708
+ "heics": "image/heic-sequence",
1709
+ "heif": "image/heif",
1710
+ "heifs": "image/heif-sequence",
1711
+ "hej2": "image/hej2k",
1712
+ "hsj2": "image/hsj2",
1713
+ "ief": "image/ief",
1714
+ "jls": "image/jls",
1715
+ "jp2": "image/jp2",
1716
+ "jpg2": "image/jp2",
1717
+ "jpeg": "image/jpeg",
1718
+ "jpg": "image/jpeg",
1719
+ "jpe": "image/jpeg",
1720
+ "jph": "image/jph",
1721
+ "jhc": "image/jphc",
1722
+ "jpm": "image/jpm",
1723
+ "jpx": "image/jpx",
1724
+ "jpf": "image/jpx",
1725
+ "jxr": "image/jxr",
1726
+ "jxra": "image/jxra",
1727
+ "jxrs": "image/jxrs",
1728
+ "jxs": "image/jxs",
1729
+ "jxsc": "image/jxsc",
1730
+ "jxsi": "image/jxsi",
1731
+ "jxss": "image/jxss",
1732
+ "ktx": "image/ktx",
1733
+ "ktx2": "image/ktx2",
1734
+ "png": "image/png",
1735
+ "btif": "image/prs.btif",
1736
+ "pti": "image/prs.pti",
1737
+ "sgi": "image/sgi",
1738
+ "svg": "image/svg+xml",
1739
+ "svgz": "image/svg+xml",
1740
+ "t38": "image/t38",
1741
+ "tif": "image/tiff",
1742
+ "tiff": "image/tiff",
1743
+ "tfx": "image/tiff-fx",
1744
+ "webp": "image/webp",
1745
+ "wmf": "image/wmf",
1746
+ "disposition-notification": "message/disposition-notification",
1747
+ "u8msg": "message/global",
1748
+ "u8dsn": "message/global-delivery-status",
1749
+ "u8mdn": "message/global-disposition-notification",
1750
+ "u8hdr": "message/global-headers",
1751
+ "eml": "message/rfc822",
1752
+ "mime": "message/rfc822",
1753
+ "3mf": "model/3mf",
1754
+ "gltf": "model/gltf+json",
1755
+ "glb": "model/gltf-binary",
1756
+ "igs": "model/iges",
1757
+ "iges": "model/iges",
1758
+ "msh": "model/mesh",
1759
+ "mesh": "model/mesh",
1760
+ "silo": "model/mesh",
1761
+ "mtl": "model/mtl",
1762
+ "obj": "model/obj",
1763
+ "stpz": "model/step+zip",
1764
+ "stpxz": "model/step-xml+zip",
1765
+ "stl": "model/stl",
1766
+ "wrl": "model/vrml",
1767
+ "vrml": "model/vrml",
1768
+ "x3db": "model/x3d+fastinfoset",
1769
+ "x3dbz": "model/x3d+binary",
1770
+ "x3dv": "model/x3d-vrml",
1771
+ "x3dvz": "model/x3d+vrml",
1772
+ "x3d": "model/x3d+xml",
1773
+ "x3dz": "model/x3d+xml",
1774
+ "appcache": "text/cache-manifest",
1775
+ "manifest": "text/cache-manifest",
1776
+ "ics": "text/calendar",
1777
+ "ifb": "text/calendar",
1778
+ "coffee": "text/coffeescript",
1779
+ "litcoffee": "text/coffeescript",
1780
+ "css": "text/css",
1781
+ "csv": "text/csv",
1782
+ "html": "text/html",
1783
+ "htm": "text/html",
1784
+ "shtml": "text/html",
1785
+ "jade": "text/jade",
1786
+ "jsx": "text/jsx",
1787
+ "less": "text/less",
1788
+ "markdown": "text/markdown",
1789
+ "md": "text/markdown",
1790
+ "mml": "text/mathml",
1791
+ "mdx": "text/mdx",
1792
+ "n3": "text/n3",
1793
+ "txt": "text/plain",
1794
+ "text": "text/plain",
1795
+ "conf": "text/plain",
1796
+ "def": "text/plain",
1797
+ "list": "text/plain",
1798
+ "log": "text/plain",
1799
+ "in": "text/plain",
1800
+ "ini": "text/plain",
1801
+ "dsc": "text/prs.lines.tag",
1802
+ "rtx": "text/richtext",
1803
+ "sgml": "text/sgml",
1804
+ "sgm": "text/sgml",
1805
+ "shex": "text/shex",
1806
+ "slim": "text/slim",
1807
+ "slm": "text/slim",
1808
+ "spdx": "text/spdx",
1809
+ "stylus": "text/stylus",
1810
+ "styl": "text/stylus",
1811
+ "tsv": "text/tab-separated-values",
1812
+ "t": "text/troff",
1813
+ "tr": "text/troff",
1814
+ "roff": "text/troff",
1815
+ "man": "text/troff",
1816
+ "me": "text/troff",
1817
+ "ms": "text/troff",
1818
+ "ttl": "text/turtle",
1819
+ "uri": "text/uri-list",
1820
+ "uris": "text/uri-list",
1821
+ "urls": "text/uri-list",
1822
+ "vcard": "text/vcard",
1823
+ "vtt": "text/vtt",
1824
+ "yaml": "text/yaml",
1825
+ "yml": "text/yaml",
1826
+ "3gp": "video/3gpp",
1827
+ "3g2": "video/3gpp2",
1828
+ "h261": "video/h261",
1829
+ "h263": "video/h263",
1830
+ "h264": "video/h264",
1831
+ "m4s": "video/iso.segment",
1832
+ "jpgv": "video/jpeg",
1833
+ "jpgm": "image/jpm",
1834
+ "mj2": "video/mj2",
1835
+ "mjp2": "video/mj2",
1836
+ "ts": "video/mp2t",
1837
+ "mp4": "video/mp4",
1838
+ "mp4v": "video/mp4",
1839
+ "mpg4": "video/mp4",
1840
+ "mpeg": "video/mpeg",
1841
+ "mpg": "video/mpeg",
1842
+ "mpe": "video/mpeg",
1843
+ "m1v": "video/mpeg",
1844
+ "m2v": "video/mpeg",
1845
+ "ogv": "video/ogg",
1846
+ "qt": "video/quicktime",
1847
+ "mov": "video/quicktime",
1848
+ "webm": "video/webm"
1849
+ };
1850
+
1851
+ function lookup(extn) {
1852
+ let tmp = ('' + extn).trim().toLowerCase();
1853
+ let idx = tmp.lastIndexOf('.');
1854
+ return mimes[!~idx ? tmp : tmp.substring(++idx)];
1855
+ }
1856
+
1857
+ const noop = () => {};
1858
+
1859
+ function isMatch(uri, arr) {
1860
+ for (let i=0; i < arr.length; i++) {
1861
+ if (arr[i].test(uri)) return true;
1862
+ }
1863
+ }
1864
+
1865
+ function toAssume(uri, extns) {
1866
+ let i=0, x, len=uri.length - 1;
1867
+ if (uri.charCodeAt(len) === 47) {
1868
+ uri = uri.substring(0, len);
1869
+ }
1870
+
1871
+ let arr=[], tmp=`${uri}/index`;
1872
+ for (; i < extns.length; i++) {
1873
+ x = extns[i] ? `.${extns[i]}` : '';
1874
+ if (uri) arr.push(uri + x);
1875
+ arr.push(tmp + x);
1876
+ }
1877
+
1878
+ return arr;
1879
+ }
1880
+
1881
+ function viaCache(cache, uri, extns) {
1882
+ let i=0, data, arr=toAssume(uri, extns);
1883
+ for (; i < arr.length; i++) {
1884
+ if (data = cache[arr[i]]) return data;
1885
+ }
1886
+ }
1887
+
1888
+ function viaLocal(dir, isEtag, uri, extns) {
1889
+ let i=0, arr=toAssume(uri, extns);
1890
+ let abs, stats, name, headers;
1891
+ for (; i < arr.length; i++) {
1892
+ abs = normalize(join(dir, name=arr[i]));
1893
+ if (abs.startsWith(dir) && fs.existsSync(abs)) {
1894
+ stats = fs.statSync(abs);
1895
+ if (stats.isDirectory()) continue;
1896
+ headers = toHeaders(name, stats, isEtag);
1897
+ headers['Cache-Control'] = isEtag ? 'no-cache' : 'no-store';
1898
+ return { abs, stats, headers };
1899
+ }
1900
+ }
1901
+ }
1902
+
1903
+ function is404(req, res) {
1904
+ return (res.statusCode=404,res.end());
1905
+ }
1906
+
1907
+ function send(req, res, file, stats, headers) {
1908
+ let code=200, tmp, opts={};
1909
+ headers = { ...headers };
1910
+
1911
+ for (let key in headers) {
1912
+ tmp = res.getHeader(key);
1913
+ if (tmp) headers[key] = tmp;
1914
+ }
1915
+
1916
+ if (tmp = res.getHeader('content-type')) {
1917
+ headers['Content-Type'] = tmp;
1918
+ }
1919
+
1920
+ if (req.headers.range) {
1921
+ code = 206;
1922
+ let [x, y] = req.headers.range.replace('bytes=', '').split('-');
1923
+ let end = opts.end = parseInt(y, 10) || stats.size - 1;
1924
+ let start = opts.start = parseInt(x, 10) || 0;
1925
+
1926
+ if (start >= stats.size || end >= stats.size) {
1927
+ res.setHeader('Content-Range', `bytes */${stats.size}`);
1928
+ res.statusCode = 416;
1929
+ return res.end();
1930
+ }
1931
+
1932
+ headers['Content-Range'] = `bytes ${start}-${end}/${stats.size}`;
1933
+ headers['Content-Length'] = (end - start + 1);
1934
+ headers['Accept-Ranges'] = 'bytes';
1935
+ }
1936
+
1937
+ res.writeHead(code, headers);
1938
+ fs.createReadStream(file, opts).pipe(res);
1939
+ }
1940
+
1941
+ const ENCODING = {
1942
+ '.br': 'br',
1943
+ '.gz': 'gzip',
1944
+ };
1945
+
1946
+ function toHeaders(name, stats, isEtag) {
1947
+ let enc = ENCODING[name.slice(-3)];
1948
+
1949
+ let ctype = lookup(name.slice(0, enc && -3)) || '';
1950
+ if (ctype === 'text/html') ctype += ';charset=utf-8';
1951
+
1952
+ let headers = {
1953
+ 'Content-Length': stats.size,
1954
+ 'Content-Type': ctype,
1955
+ 'Last-Modified': stats.mtime.toUTCString(),
1956
+ };
1957
+
1958
+ if (enc) headers['Content-Encoding'] = enc;
1959
+ if (isEtag) headers['ETag'] = `W/"${stats.size}-${stats.mtime.getTime()}"`;
1960
+
1961
+ return headers;
1962
+ }
1963
+
1964
+ function sirv (dir, opts={}) {
1965
+ dir = resolve$1(dir || '.');
1966
+
1967
+ let isNotFound = opts.onNoMatch || is404;
1968
+ let setHeaders = opts.setHeaders || noop;
1969
+
1970
+ let extensions = opts.extensions || ['html', 'htm'];
1971
+ let gzips = opts.gzip && extensions.map(x => `${x}.gz`).concat('gz');
1972
+ let brots = opts.brotli && extensions.map(x => `${x}.br`).concat('br');
1973
+
1974
+ const FILES = {};
1975
+
1976
+ let fallback = '/';
1977
+ let isEtag = !!opts.etag;
1978
+ let isSPA = !!opts.single;
1979
+ if (typeof opts.single === 'string') {
1980
+ let idx = opts.single.lastIndexOf('.');
1981
+ fallback += !!~idx ? opts.single.substring(0, idx) : opts.single;
1982
+ }
1983
+
1984
+ let ignores = [];
1985
+ if (opts.ignores !== false) {
1986
+ ignores.push(/[/]([A-Za-z\s\d~$._-]+\.\w+){1,}$/); // any extn
1987
+ if (opts.dotfiles) ignores.push(/\/\.\w/);
1988
+ else ignores.push(/\/\.well-known/);
1989
+ [].concat(opts.ignores || []).forEach(x => {
1990
+ ignores.push(new RegExp(x, 'i'));
1991
+ });
1992
+ }
1993
+
1994
+ let cc = opts.maxAge != null && `public,max-age=${opts.maxAge}`;
1995
+ if (cc && opts.immutable) cc += ',immutable';
1996
+ else if (cc && opts.maxAge === 0) cc += ',must-revalidate';
1997
+
1998
+ if (!opts.dev) {
1999
+ totalist(dir, (name, abs, stats) => {
2000
+ if (/\.well-known[\\+\/]/.test(name)) ; // keep
2001
+ else if (!opts.dotfiles && /(^\.|[\\+|\/+]\.)/.test(name)) return;
2002
+
2003
+ let headers = toHeaders(name, stats, isEtag);
2004
+ if (cc) headers['Cache-Control'] = cc;
2005
+
2006
+ FILES['/' + name.normalize().replace(/\\+/g, '/')] = { abs, stats, headers };
2007
+ });
2008
+ }
2009
+
2010
+ let lookup = opts.dev ? viaLocal.bind(0, dir, isEtag) : viaCache.bind(0, FILES);
2011
+
2012
+ return function (req, res, next) {
2013
+ let extns = [''];
2014
+ let pathname = parse(req).pathname;
2015
+ let val = req.headers['accept-encoding'] || '';
2016
+ if (gzips && val.includes('gzip')) extns.unshift(...gzips);
2017
+ if (brots && /(br|brotli)/i.test(val)) extns.unshift(...brots);
2018
+ extns.push(...extensions); // [...br, ...gz, orig, ...exts]
2019
+
2020
+ if (pathname.indexOf('%') !== -1) {
2021
+ try { pathname = decodeURIComponent(pathname); }
2022
+ catch (err) { /* malform uri */ }
2023
+ }
2024
+
2025
+ let data = lookup(pathname, extns) || isSPA && !isMatch(pathname, ignores) && lookup(fallback, extns);
2026
+ if (!data) return next ? next() : isNotFound(req, res);
2027
+
2028
+ if (isEtag && req.headers['if-none-match'] === data.headers['ETag']) {
2029
+ res.writeHead(304);
2030
+ return res.end();
2031
+ }
2032
+
2033
+ if (gzips || brots) {
2034
+ res.setHeader('Vary', 'Accept-Encoding');
2035
+ }
2036
+
2037
+ setHeaders(res, pathname, data.stats);
2038
+ send(req, res, data.abs, data.stats, data.headers);
2039
+ };
2040
+ }
2041
+
2042
+ // in `vite dev` and `vite preview`, we use a fake asset path so that we can
2043
+ // serve local assets while verifying that requests are correctly prefixed
2044
+ const SVELTE_KIT_ASSETS = '/_svelte_kit_assets';
2045
+
2046
+ // Vite doesn't expose this so we just copy the list for now
2047
+ // https://github.com/vitejs/vite/blob/3edd1af56e980aef56641a5a51cf2932bb580d41/packages/vite/src/node/plugins/css.ts#L96
2048
+ const style_pattern = /\.(css|less|sass|scss|styl|stylus|pcss|postcss)$/;
2049
+
2050
+ const cwd$1 = process.cwd();
2051
+
2052
+ /**
2053
+ * @param {import('vite').ViteDevServer} vite
2054
+ * @param {import('vite').ResolvedConfig} vite_config
2055
+ * @param {import('types').ValidatedConfig} svelte_config
2056
+ * @return {Promise<Promise<() => void>>}
2057
+ */
2058
+ async function dev(vite, vite_config, svelte_config) {
2059
+ installPolyfills();
2060
+
2061
+ init(svelte_config);
2062
+
2063
+ const runtime = get_runtime_prefix(svelte_config.kit);
2064
+
2065
+ /** @type {import('types').Respond} */
2066
+ const respond = (await import(`${runtime}/server/index.js`)).respond;
2067
+
2068
+ /** @type {import('types').SSRManifest} */
2069
+ let manifest;
2070
+
2071
+ function update_manifest() {
2072
+ const { manifest_data } = update(svelte_config);
2073
+
2074
+ manifest = {
2075
+ appDir: svelte_config.kit.appDir,
2076
+ assets: new Set(manifest_data.assets.map((asset) => asset.file)),
2077
+ mimeTypes: get_mime_lookup(manifest_data),
2078
+ _: {
2079
+ entry: {
2080
+ file: `/@fs${runtime}/client/start.js`,
2081
+ imports: [],
2082
+ stylesheets: []
2083
+ },
2084
+ nodes: manifest_data.components.map((id, index) => {
2085
+ return async () => {
2086
+ const url = id.startsWith('..') ? `/@fs${path__default.posix.resolve(id)}` : `/${id}`;
2087
+
2088
+ const module = /** @type {import('types').SSRComponent} */ (
2089
+ await vite.ssrLoadModule(url)
2090
+ );
2091
+
2092
+ return {
2093
+ module,
2094
+ index,
2095
+ file: url.endsWith('.svelte') ? url : url + '?import',
2096
+ imports: [],
2097
+ stylesheets: [],
2098
+ // in dev we inline all styles to avoid FOUC
2099
+ inline_styles: async () => {
2100
+ const node = await vite.moduleGraph.getModuleByUrl(url);
2101
+
2102
+ if (!node) throw new Error(`Could not find node for ${url}`);
2103
+
2104
+ const deps = new Set();
2105
+ await find_deps(vite, node, deps);
2106
+
2107
+ /** @type {Record<string, string>} */
2108
+ const styles = {};
2109
+
2110
+ for (const dep of deps) {
2111
+ const parsed = new URL$1(dep.url, 'http://localhost/');
2112
+ const query = parsed.searchParams;
2113
+
2114
+ if (
2115
+ style_pattern.test(dep.file) ||
2116
+ (query.has('svelte') && query.get('type') === 'style')
2117
+ ) {
2118
+ try {
2119
+ const mod = await vite.ssrLoadModule(dep.url);
2120
+ styles[dep.url] = mod.default;
2121
+ } catch {
2122
+ // this can happen with dynamically imported modules, I think
2123
+ // because the Vite module graph doesn't distinguish between
2124
+ // static and dynamic imports? TODO investigate, submit fix
2125
+ }
2126
+ }
2127
+ }
2128
+
2129
+ return styles;
2130
+ }
2131
+ };
2132
+ };
2133
+ }),
2134
+ routes: manifest_data.routes.map((route) => {
2135
+ const { pattern, names, types } = parse_route_id(route.id);
2136
+
2137
+ if (route.type === 'page') {
2138
+ return {
2139
+ type: 'page',
2140
+ id: route.id,
2141
+ pattern,
2142
+ names,
2143
+ types,
2144
+ shadow: route.shadow
2145
+ ? async () => {
2146
+ const url = path__default.resolve(cwd$1, /** @type {string} */ (route.shadow));
2147
+ return await vite.ssrLoadModule(url);
2148
+ }
2149
+ : null,
2150
+ a: route.a.map((id) => (id ? manifest_data.components.indexOf(id) : undefined)),
2151
+ b: route.b.map((id) => (id ? manifest_data.components.indexOf(id) : undefined))
2152
+ };
2153
+ }
2154
+
2155
+ return {
2156
+ type: 'endpoint',
2157
+ id: route.id,
2158
+ pattern,
2159
+ names,
2160
+ types,
2161
+ load: async () => {
2162
+ const url = path__default.resolve(cwd$1, route.file);
2163
+ return await vite.ssrLoadModule(url);
2164
+ }
2165
+ };
2166
+ }),
2167
+ matchers: async () => {
2168
+ /** @type {Record<string, import('types').ParamMatcher>} */
2169
+ const matchers = {};
2170
+
2171
+ for (const key in manifest_data.matchers) {
2172
+ const file = manifest_data.matchers[key];
2173
+ const url = path__default.resolve(cwd$1, file);
2174
+ const module = await vite.ssrLoadModule(url);
2175
+
2176
+ if (module.match) {
2177
+ matchers[key] = module.match;
2178
+ } else {
2179
+ throw new Error(`${file} does not export a \`match\` function`);
2180
+ }
2181
+ }
2182
+
2183
+ return matchers;
2184
+ }
2185
+ }
2186
+ };
2187
+ }
2188
+
2189
+ /** @param {Error} error */
2190
+ function fix_stack_trace(error) {
2191
+ return error.stack ? vite.ssrRewriteStacktrace(error.stack) : error.stack;
2192
+ }
2193
+
2194
+ update_manifest();
2195
+
2196
+ for (const event of ['add', 'unlink']) {
2197
+ vite.watcher.on(event, (file) => {
2198
+ if (file.startsWith(svelte_config.kit.files.routes + path__default.sep)) {
2199
+ update_manifest();
2200
+ }
2201
+ });
2202
+ }
2203
+
2204
+ const assets = svelte_config.kit.paths.assets ? SVELTE_KIT_ASSETS : svelte_config.kit.paths.base;
2205
+ const asset_server = sirv(svelte_config.kit.files.assets, {
2206
+ dev: true,
2207
+ etag: true,
2208
+ maxAge: 0,
2209
+ extensions: []
2210
+ });
2211
+
2212
+ return () => {
2213
+ const serve_static_middleware = vite.middlewares.stack.find(
2214
+ (middleware) =>
2215
+ /** @type {function} */ (middleware.handle).name === 'viteServeStaticMiddleware'
2216
+ );
2217
+
2218
+ remove_html_middlewares(vite.middlewares);
2219
+
2220
+ vite.middlewares.use(async (req, res) => {
2221
+ try {
2222
+ if (!req.url || !req.method) throw new Error('Incomplete request');
2223
+
2224
+ const base = `${vite.config.server.https ? 'https' : 'http'}://${
2225
+ req.headers[':authority'] || req.headers.host
2226
+ }`;
2227
+
2228
+ const decoded = decodeURI(new URL$1(base + req.url).pathname);
2229
+
2230
+ if (decoded.startsWith(assets)) {
2231
+ const pathname = decoded.slice(assets.length);
2232
+ const file = svelte_config.kit.files.assets + pathname;
2233
+
2234
+ if (fs__default.existsSync(file) && !fs__default.statSync(file).isDirectory()) {
2235
+ if (has_correct_case(file, svelte_config.kit.files.assets)) {
2236
+ req.url = encodeURI(pathname); // don't need query/hash
2237
+ asset_server(req, res);
2238
+ return;
2239
+ }
2240
+ }
2241
+ }
2242
+
2243
+ const file = posixify(path__default.resolve(decoded.slice(1)));
2244
+ const is_file = fs__default.existsSync(file) && !fs__default.statSync(file).isDirectory();
2245
+ const allowed =
2246
+ !vite_config.server.fs.strict ||
2247
+ vite_config.server.fs.allow.some((dir) => file.startsWith(dir));
2248
+
2249
+ if (is_file && allowed) {
2250
+ // @ts-expect-error
2251
+ serve_static_middleware.handle(req, res);
2252
+ return;
2253
+ }
2254
+
2255
+ if (!decoded.startsWith(svelte_config.kit.paths.base)) {
2256
+ return not_found(
2257
+ res,
2258
+ `Not found (did you mean ${svelte_config.kit.paths.base + req.url}?)`
2259
+ );
2260
+ }
2261
+
2262
+ /** @type {Partial<import('types').Hooks>} */
2263
+ const user_hooks = resolve_entry(svelte_config.kit.files.hooks)
2264
+ ? await vite.ssrLoadModule(`/${svelte_config.kit.files.hooks}`)
2265
+ : {};
2266
+
2267
+ const handle = user_hooks.handle || (({ event, resolve }) => resolve(event));
2268
+
2269
+ /** @type {import('types').Hooks} */
2270
+ const hooks = {
2271
+ getSession: user_hooks.getSession || (() => ({})),
2272
+ handle,
2273
+ handleError:
2274
+ user_hooks.handleError ||
2275
+ (({ /** @type {Error & { frame?: string }} */ error }) => {
2276
+ console.error($.bold().red(error.message));
2277
+ if (error.frame) {
2278
+ console.error($.gray(error.frame));
2279
+ }
2280
+ if (error.stack) {
2281
+ console.error($.gray(error.stack));
2282
+ }
2283
+ }),
2284
+ externalFetch: user_hooks.externalFetch || fetch
2285
+ };
2286
+
2287
+ if (/** @type {any} */ (hooks).getContext) {
2288
+ // TODO remove this for 1.0
2289
+ throw new Error(
2290
+ 'The getContext hook has been removed. See https://kit.svelte.dev/docs/hooks'
2291
+ );
2292
+ }
2293
+
2294
+ if (/** @type {any} */ (hooks).serverFetch) {
2295
+ // TODO remove this for 1.0
2296
+ throw new Error('The serverFetch hook has been renamed to externalFetch.');
2297
+ }
2298
+
2299
+ // TODO the / prefix will probably fail if outDir is outside the cwd (which
2300
+ // could be the case in a monorepo setup), but without it these modules
2301
+ // can get loaded twice via different URLs, which causes failures. Might
2302
+ // require changes to Vite to fix
2303
+ const { default: root } = await vite.ssrLoadModule(
2304
+ `/${posixify(path__default.relative(cwd$1, `${svelte_config.kit.outDir}/generated/root.svelte`))}`
2305
+ );
2306
+
2307
+ const paths = await vite.ssrLoadModule(
2308
+ true
2309
+ ? `/${posixify(path__default.relative(cwd$1, `${svelte_config.kit.outDir}/runtime/paths.js`))}`
2310
+ : `/@fs${runtime}/paths.js`
2311
+ );
2312
+
2313
+ paths.set_paths({
2314
+ base: svelte_config.kit.paths.base,
2315
+ assets
2316
+ });
2317
+
2318
+ let request;
2319
+
2320
+ try {
2321
+ request = await getRequest(base, req);
2322
+ } catch (/** @type {any} */ err) {
2323
+ res.statusCode = err.status || 400;
2324
+ return res.end(err.reason || 'Invalid request body');
2325
+ }
2326
+
2327
+ const template = load_template(cwd$1, svelte_config);
2328
+
2329
+ const rendered = await respond(
2330
+ request,
2331
+ {
2332
+ csp: svelte_config.kit.csp,
2333
+ dev: true,
2334
+ get_stack: (error) => {
2335
+ return fix_stack_trace(error);
2336
+ },
2337
+ handle_error: (error, event) => {
2338
+ hooks.handleError({
2339
+ error: new Proxy(error, {
2340
+ get: (target, property) => {
2341
+ if (property === 'stack') {
2342
+ return fix_stack_trace(error);
2343
+ }
2344
+
2345
+ return Reflect.get(target, property, target);
2346
+ }
2347
+ }),
2348
+ event,
2349
+
2350
+ // TODO remove for 1.0
2351
+ // @ts-expect-error
2352
+ get request() {
2353
+ throw new Error(
2354
+ 'request in handleError has been replaced with event. See https://github.com/sveltejs/kit/pull/3384 for details'
2355
+ );
2356
+ }
2357
+ });
2358
+ },
2359
+ hooks,
2360
+ hydrate: svelte_config.kit.browser.hydrate,
2361
+ manifest,
2362
+ method_override: svelte_config.kit.methodOverride,
2363
+ paths: {
2364
+ base: svelte_config.kit.paths.base,
2365
+ assets
2366
+ },
2367
+ prefix: '',
2368
+ prerender: {
2369
+ default: svelte_config.kit.prerender.default,
2370
+ enabled: svelte_config.kit.prerender.enabled
2371
+ },
2372
+ read: (file) => fs__default.readFileSync(path__default.join(svelte_config.kit.files.assets, file)),
2373
+ root,
2374
+ router: svelte_config.kit.browser.router,
2375
+ template: ({ head, body, assets, nonce }) => {
2376
+ return (
2377
+ template
2378
+ .replace(/%sveltekit\.assets%/g, assets)
2379
+ .replace(/%sveltekit\.nonce%/g, nonce)
2380
+ // head and body must be replaced last, in case someone tries to sneak in %sveltekit.assets% etc
2381
+ .replace('%sveltekit.head%', () => head)
2382
+ .replace('%sveltekit.body%', () => body)
2383
+ );
2384
+ },
2385
+ template_contains_nonce: template.includes('%sveltekit.nonce%'),
2386
+ trailing_slash: svelte_config.kit.trailingSlash
2387
+ },
2388
+ {
2389
+ getClientAddress: () => {
2390
+ const { remoteAddress } = req.socket;
2391
+ if (remoteAddress) return remoteAddress;
2392
+ throw new Error('Could not determine clientAddress');
2393
+ }
2394
+ }
2395
+ );
2396
+
2397
+ if (rendered.status === 404) {
2398
+ // @ts-expect-error
2399
+ serve_static_middleware.handle(req, res, () => {
2400
+ setResponse(res, rendered);
2401
+ });
2402
+ } else {
2403
+ setResponse(res, rendered);
2404
+ }
2405
+ } catch (e) {
2406
+ const error = coalesce_to_error(e);
2407
+ vite.ssrFixStacktrace(error);
2408
+ res.statusCode = 500;
2409
+ res.end(error.stack);
2410
+ }
2411
+ });
2412
+ };
2413
+ }
2414
+
2415
+ /** @param {import('http').ServerResponse} res */
2416
+ function not_found(res, message = 'Not found') {
2417
+ res.statusCode = 404;
2418
+ res.end(message);
2419
+ }
2420
+
2421
+ /**
2422
+ * @param {import('connect').Server} server
2423
+ */
2424
+ function remove_html_middlewares(server) {
2425
+ const html_middlewares = ['viteServeStaticMiddleware'];
2426
+ for (let i = server.stack.length - 1; i > 0; i--) {
2427
+ // @ts-expect-error using internals until https://github.com/vitejs/vite/pull/4640 is merged
2428
+ if (html_middlewares.includes(server.stack[i].handle.name)) {
2429
+ server.stack.splice(i, 1);
2430
+ }
2431
+ }
2432
+ }
2433
+
2434
+ /**
2435
+ * @param {import('vite').ViteDevServer} vite
2436
+ * @param {import('vite').ModuleNode} node
2437
+ * @param {Set<import('vite').ModuleNode>} deps
2438
+ */
2439
+ async function find_deps(vite, node, deps) {
2440
+ // since `ssrTransformResult.deps` contains URLs instead of `ModuleNode`s, this process is asynchronous.
2441
+ // instead of using `await`, we resolve all branches in parallel.
2442
+ /** @type {Promise<void>[]} */
2443
+ const branches = [];
2444
+
2445
+ /** @param {import('vite').ModuleNode} node */
2446
+ async function add(node) {
2447
+ if (!deps.has(node)) {
2448
+ deps.add(node);
2449
+ await find_deps(vite, node, deps);
2450
+ }
2451
+ }
2452
+
2453
+ /** @param {string} url */
2454
+ async function add_by_url(url) {
2455
+ const node = await vite.moduleGraph.getModuleByUrl(url);
2456
+
2457
+ if (node) {
2458
+ await add(node);
2459
+ }
2460
+ }
2461
+
2462
+ if (node.ssrTransformResult) {
2463
+ if (node.ssrTransformResult.deps) {
2464
+ node.ssrTransformResult.deps.forEach((url) => branches.push(add_by_url(url)));
2465
+ }
2466
+
2467
+ if (node.ssrTransformResult.dynamicDeps) {
2468
+ node.ssrTransformResult.dynamicDeps.forEach((url) => branches.push(add_by_url(url)));
2469
+ }
2470
+ } else {
2471
+ node.importedModules.forEach((node) => branches.push(add(node)));
2472
+ }
2473
+
2474
+ await Promise.all(branches);
2475
+ }
2476
+
2477
+ /**
2478
+ * Determine if a file is being requested with the correct case,
2479
+ * to ensure consistent behaviour between dev and prod and across
2480
+ * operating systems. Note that we can't use realpath here,
2481
+ * because we don't want to follow symlinks
2482
+ * @param {string} file
2483
+ * @param {string} assets
2484
+ * @returns {boolean}
2485
+ */
2486
+ function has_correct_case(file, assets) {
2487
+ if (file === assets) return true;
2488
+
2489
+ const parent = path__default.dirname(file);
2490
+
2491
+ if (fs__default.readdirSync(parent).includes(path__default.basename(file))) {
2492
+ return has_correct_case(parent, assets);
2493
+ }
2494
+
2495
+ return false;
2496
+ }
2497
+
2498
+ /**
2499
+ * Generates the data used to write the server-side manifest.js file. This data is used in the Vite
2500
+ * build process, to power routing, etc.
2501
+ * @param {{
2502
+ * build_data: import('types').BuildData;
2503
+ * relative_path: string;
2504
+ * routes: import('types').RouteData[];
2505
+ * format?: 'esm' | 'cjs'
2506
+ * }} opts
2507
+ */
2508
+ function generate_manifest({ build_data, relative_path, routes, format = 'esm' }) {
2509
+ /** @typedef {{ index: number, path: string }} LookupEntry */
2510
+ /** @type {Map<string, LookupEntry>} */
2511
+ const bundled_nodes = new Map();
2512
+
2513
+ // 0 and 1 are special, they correspond to the root layout and root error nodes
2514
+ bundled_nodes.set(build_data.manifest_data.components[0], {
2515
+ path: `${relative_path}/nodes/0.js`,
2516
+ index: 0
2517
+ });
2518
+
2519
+ bundled_nodes.set(build_data.manifest_data.components[1], {
2520
+ path: `${relative_path}/nodes/1.js`,
2521
+ index: 1
2522
+ });
2523
+
2524
+ routes.forEach((route) => {
2525
+ if (route.type === 'page') {
2526
+ [...route.a, ...route.b].forEach((component) => {
2527
+ if (component && !bundled_nodes.has(component)) {
2528
+ const i = build_data.manifest_data.components.indexOf(component);
2529
+
2530
+ bundled_nodes.set(component, {
2531
+ path: `${relative_path}/nodes/${i}.js`,
2532
+ index: bundled_nodes.size
2533
+ });
2534
+ }
2535
+ });
2536
+ }
2537
+ });
2538
+
2539
+ /** @type {(path: string) => string} */
2540
+ const load =
2541
+ format === 'esm'
2542
+ ? (path) => `import('${path}')`
2543
+ : (path) => `Promise.resolve().then(() => require('${path}'))`;
2544
+
2545
+ /** @type {(path: string) => string} */
2546
+ const loader = (path) => `() => ${load(path)}`;
2547
+
2548
+ const assets = build_data.manifest_data.assets.map((asset) => asset.file);
2549
+ if (build_data.service_worker) {
2550
+ assets.push(build_data.service_worker);
2551
+ }
2552
+
2553
+ /** @param {string | undefined} id */
2554
+ const get_index = (id) => id && /** @type {LookupEntry} */ (bundled_nodes.get(id)).index;
2555
+
2556
+ const matchers = new Set();
2557
+
2558
+ // prettier-ignore
2559
+ return `{
2560
+ appDir: ${s(build_data.app_dir)},
2561
+ assets: new Set(${s(assets)}),
2562
+ mimeTypes: ${s(get_mime_lookup(build_data.manifest_data))},
2563
+ _: {
2564
+ entry: ${s(build_data.client.entry)},
2565
+ nodes: [
2566
+ ${Array.from(bundled_nodes.values()).map(node => loader(node.path)).join(',\n\t\t\t\t')}
2567
+ ],
2568
+ routes: [
2569
+ ${routes.map(route => {
2570
+ const { pattern, names, types } = parse_route_id(route.id);
2571
+
2572
+ types.forEach(type => {
2573
+ if (type) matchers.add(type);
2574
+ });
2575
+
2576
+ if (route.type === 'page') {
2577
+ return `{
2578
+ type: 'page',
2579
+ id: ${s(route.id)},
2580
+ pattern: ${pattern},
2581
+ names: ${s(names)},
2582
+ types: ${s(types)},
2583
+ path: ${route.path ? s(route.path) : null},
2584
+ shadow: ${route.shadow ? loader(`${relative_path}/${build_data.server.vite_manifest[route.shadow].file}`) : null},
2585
+ a: ${s(route.a.map(get_index))},
2586
+ b: ${s(route.b.map(get_index))}
2587
+ }`.replace(/^\t\t/gm, '');
2588
+ } else {
2589
+ if (!build_data.server.vite_manifest[route.file]) {
2590
+ // this is necessary in cases where a .css file snuck in —
2591
+ // perhaps it would be better to disallow these (and others?)
2592
+ return null;
2593
+ }
2594
+
2595
+ return `{
2596
+ type: 'endpoint',
2597
+ id: ${s(route.id)},
2598
+ pattern: ${pattern},
2599
+ names: ${s(names)},
2600
+ types: ${s(types)},
2601
+ load: ${loader(`${relative_path}/${build_data.server.vite_manifest[route.file].file}`)}
2602
+ }`.replace(/^\t\t/gm, '');
2603
+ }
2604
+ }).filter(Boolean).join(',\n\t\t\t\t')}
2605
+ ],
2606
+ matchers: async () => {
2607
+ ${Array.from(matchers).map(type => `const { match: ${type} } = await ${load(`${relative_path}/entries/matchers/${type}.js`)}`).join('\n\t\t\t\t')}
2608
+ return { ${Array.from(matchers).join(', ')} };
2609
+ }
2610
+ }
2611
+ }`.replace(/^\t/gm, '');
2612
+ }
2613
+
2614
+ /** @typedef {import('http').IncomingMessage} Req */
2615
+ /** @typedef {import('http').ServerResponse} Res */
2616
+ /** @typedef {(req: Req, res: Res, next: () => void) => void} Handler */
2617
+
2618
+ /**
2619
+ * @param {{
2620
+ * middlewares: import('connect').Server;
2621
+ * httpServer: import('http').Server;
2622
+ * }} vite
2623
+ * @param {import('types').ValidatedConfig} config
2624
+ * @param {'http' | 'https'} protocol
2625
+ */
2626
+ async function preview(vite, config, protocol) {
2627
+ installPolyfills();
2628
+
2629
+ const { paths } = config.kit;
2630
+ const base = paths.base;
2631
+ const assets = paths.assets ? SVELTE_KIT_ASSETS : paths.base;
2632
+
2633
+ const etag = `"${Date.now()}"`;
2634
+
2635
+ const index_file = join(config.kit.outDir, 'output/server/index.js');
2636
+ const manifest_file = join(config.kit.outDir, 'output/server/manifest.js');
2637
+
2638
+ /** @type {import('types').ServerModule} */
2639
+ const { Server, override } = await import(pathToFileURL(index_file).href);
2640
+ const { manifest } = await import(pathToFileURL(manifest_file).href);
2641
+
2642
+ override({
2643
+ paths: { base, assets },
2644
+ prerendering: false,
2645
+ protocol,
2646
+ read: (file) => fs__default.readFileSync(join(config.kit.files.assets, file))
2647
+ });
2648
+
2649
+ const server = new Server(manifest);
2650
+
2651
+ return () => {
2652
+ // files in `static`
2653
+ vite.middlewares.use(scoped(assets, mutable(config.kit.files.assets)));
2654
+
2655
+ // immutable generated client assets
2656
+ vite.middlewares.use(
2657
+ scoped(
2658
+ assets,
2659
+ sirv(join(config.kit.outDir, 'output/client'), {
2660
+ setHeaders: (res, pathname) => {
2661
+ // only apply to build directory, not e.g. version.json
2662
+ if (pathname.startsWith(`/${config.kit.appDir}/immutable`)) {
2663
+ res.setHeader('cache-control', 'public,max-age=31536000,immutable');
2664
+ }
2665
+ }
2666
+ })
2667
+ )
2668
+ );
2669
+
2670
+ vite.middlewares.use((req, res, next) => {
2671
+ const original_url = /** @type {string} */ (req.url);
2672
+ const { pathname } = new URL(original_url, 'http://dummy');
2673
+
2674
+ if (pathname.startsWith(base)) {
2675
+ next();
2676
+ } else {
2677
+ res.statusCode = 404;
2678
+ res.end(`Not found (did you mean ${base + pathname}?)`);
2679
+ }
2680
+ });
2681
+
2682
+ // prerendered dependencies
2683
+ vite.middlewares.use(
2684
+ scoped(base, mutable(join(config.kit.outDir, 'output/prerendered/dependencies')))
2685
+ );
2686
+
2687
+ // prerendered pages (we can't just use sirv because we need to
2688
+ // preserve the correct trailingSlash behaviour)
2689
+ vite.middlewares.use(
2690
+ scoped(base, (req, res, next) => {
2691
+ let if_none_match_value = req.headers['if-none-match'];
2692
+
2693
+ if (if_none_match_value?.startsWith('W/"')) {
2694
+ if_none_match_value = if_none_match_value.substring(2);
2695
+ }
2696
+
2697
+ if (if_none_match_value === etag) {
2698
+ res.statusCode = 304;
2699
+ res.end();
2700
+ return;
2701
+ }
2702
+
2703
+ const { pathname } = new URL(/** @type {string} */ (req.url), 'http://dummy');
2704
+
2705
+ // only treat this as a page if it doesn't include an extension
2706
+ if (pathname === '/' || /\/[^./]+\/?$/.test(pathname)) {
2707
+ const file = join(
2708
+ config.kit.outDir,
2709
+ 'output/prerendered/pages' +
2710
+ pathname +
2711
+ (pathname.endsWith('/') ? 'index.html' : '.html')
2712
+ );
2713
+
2714
+ if (fs__default.existsSync(file)) {
2715
+ res.writeHead(200, {
2716
+ 'content-type': 'text/html',
2717
+ etag
2718
+ });
2719
+
2720
+ fs__default.createReadStream(file).pipe(res);
2721
+ return;
2722
+ }
2723
+ }
2724
+
2725
+ next();
2726
+ })
2727
+ );
2728
+
2729
+ // SSR
2730
+ vite.middlewares.use(async (req, res) => {
2731
+ const host = req.headers['host'];
2732
+
2733
+ let request;
2734
+
2735
+ try {
2736
+ request = await getRequest(`${protocol}://${host}`, req);
2737
+ } catch (/** @type {any} */ err) {
2738
+ res.statusCode = err.status || 400;
2739
+ return res.end(err.reason || 'Invalid request body');
2740
+ }
2741
+
2742
+ setResponse(
2743
+ res,
2744
+ await server.respond(request, {
2745
+ getClientAddress: () => {
2746
+ const { remoteAddress } = req.socket;
2747
+ if (remoteAddress) return remoteAddress;
2748
+ throw new Error('Could not determine clientAddress');
2749
+ }
2750
+ })
2751
+ );
2752
+ });
2753
+ };
2754
+ }
2755
+
2756
+ /**
2757
+ * @param {string} dir
2758
+ * @returns {Handler}
2759
+ */
2760
+ const mutable = (dir) =>
2761
+ fs__default.existsSync(dir)
2762
+ ? sirv(dir, {
2763
+ etag: true,
2764
+ maxAge: 0
2765
+ })
2766
+ : (req, res, next) => next();
2767
+
2768
+ /**
2769
+ * @param {string} scope
2770
+ * @param {Handler} handler
2771
+ * @returns {Handler}
2772
+ */
2773
+ function scoped(scope, handler) {
2774
+ if (scope === '') return handler;
2775
+
2776
+ return (req, res, next) => {
2777
+ if (req.url?.startsWith(scope)) {
2778
+ const original_url = req.url;
2779
+ req.url = req.url.slice(scope.length);
2780
+ handler(req, res, () => {
2781
+ req.url = original_url;
2782
+ next();
2783
+ });
2784
+ } else {
2785
+ next();
2786
+ }
2787
+ };
2788
+ }
2789
+
2790
+ const cwd = process.cwd();
2791
+
2792
+ /** @type {import('./types').EnforcedConfig} */
2793
+ const enforced_config = {
2794
+ appType: true,
2795
+ base: true,
2796
+ build: {
2797
+ cssCodeSplit: true,
2798
+ emptyOutDir: true,
2799
+ lib: {
2800
+ entry: true,
2801
+ name: true,
2802
+ formats: true
2803
+ },
2804
+ manifest: true,
2805
+ outDir: true,
2806
+ polyfillModulePreload: true,
2807
+ rollupOptions: {
2808
+ input: true,
2809
+ output: {
2810
+ format: true,
2811
+ entryFileNames: true,
2812
+ chunkFileNames: true,
2813
+ assetFileNames: true
2814
+ },
2815
+ preserveEntrySignatures: true
2816
+ },
2817
+ ssr: true
2818
+ },
2819
+ publicDir: true,
2820
+ resolve: {
2821
+ alias: {
2822
+ $app: true,
2823
+ $lib: true,
2824
+ '$service-worker': true
2825
+ }
2826
+ },
2827
+ root: true
2828
+ };
2829
+
2830
+ /**
2831
+ * @return {import('vite').Plugin[]}
2832
+ */
2833
+ function sveltekit() {
2834
+ return [...svelte(), kit()];
2835
+ }
2836
+
2837
+ /**
2838
+ * Returns the SvelteKit Vite plugin. Vite executes Rollup hooks as well as some of its own.
2839
+ * Background reading is available at:
2840
+ * - https://vitejs.dev/guide/api-plugin.html
2841
+ * - https://rollupjs.org/guide/en/#plugin-development
2842
+ *
2843
+ * You can get an idea of the lifecycle by looking at the flow charts here:
2844
+ * - https://rollupjs.org/guide/en/#build-hooks
2845
+ * - https://rollupjs.org/guide/en/#output-generation-hooks
2846
+ *
2847
+ * @return {import('vite').Plugin}
2848
+ */
2849
+ function kit() {
2850
+ /** @type {import('types').ValidatedConfig} */
2851
+ let svelte_config;
2852
+
2853
+ /** @type {import('vite').ResolvedConfig} */
2854
+ let vite_config;
2855
+
2856
+ /** @type {import('vite').ConfigEnv} */
2857
+ let vite_config_env;
2858
+
2859
+ /** @type {import('types').ManifestData} */
2860
+ let manifest_data;
2861
+
2862
+ /** @type {boolean} */
2863
+ let is_build;
2864
+
2865
+ /** @type {import('types').Logger} */
2866
+ let log;
2867
+
2868
+ /** @type {import('types').Prerendered} */
2869
+ let prerendered;
2870
+
2871
+ /** @type {import('types').BuildData} */
2872
+ let build_data;
2873
+
2874
+ /**
2875
+ * @type {{
2876
+ * build_dir: string;
2877
+ * output_dir: string;
2878
+ * client_out_dir: string;
2879
+ * }}
2880
+ */
2881
+ let paths;
2882
+
2883
+ let completed_build = false;
2884
+
2885
+ function vite_client_build_config() {
2886
+ /** @type {Record<string, string>} */
2887
+ const input = {
2888
+ // Put unchanging assets in immutable directory. We don't set that in the
2889
+ // outDir so that other plugins can add mutable assets to the bundle
2890
+ start: `${get_runtime_directory(svelte_config.kit)}/client/start.js`
2891
+ };
2892
+
2893
+ // This step is optional — Vite/Rollup will create the necessary chunks
2894
+ // for everything regardless — but it means that entry chunks reflect
2895
+ // their location in the source code, which is helpful for debugging
2896
+ manifest_data.components.forEach((file) => {
2897
+ const resolved = path__default.resolve(cwd, file);
2898
+ const relative = decodeURIComponent(path__default.relative(svelte_config.kit.files.routes, resolved));
2899
+
2900
+ const name = relative.startsWith('..')
2901
+ ? path__default.basename(file)
2902
+ : posixify(path__default.join('pages', relative));
2903
+ input[name] = resolved;
2904
+ });
2905
+
2906
+ return get_default_config({
2907
+ config: svelte_config,
2908
+ input,
2909
+ ssr: false,
2910
+ outDir: `${paths.client_out_dir}`
2911
+ });
2912
+ }
2913
+
2914
+ /**
2915
+ * @param {import('rollup').OutputAsset[]} assets
2916
+ * @param {import('rollup').OutputChunk[]} chunks
2917
+ */
2918
+ function client_build_info(assets, chunks) {
2919
+ /** @type {import('vite').Manifest} */
2920
+ const vite_manifest = JSON.parse(
2921
+ fs__default.readFileSync(`${paths.client_out_dir}/manifest.json`, 'utf-8')
2922
+ );
2923
+
2924
+ const entry_id = posixify(
2925
+ path__default.relative(cwd, `${get_runtime_directory(svelte_config.kit)}/client/start.js`)
2926
+ );
2927
+
2928
+ return {
2929
+ assets,
2930
+ chunks,
2931
+ entry: find_deps$1(vite_manifest, entry_id, false),
2932
+ vite_manifest
2933
+ };
2934
+ }
2935
+
2936
+ // TODO remove this for 1.0
2937
+ check_vite_version();
2938
+
2939
+ return {
2940
+ name: 'vite-plugin-svelte-kit',
2941
+
2942
+ /**
2943
+ * Build the SvelteKit-provided Vite config to be merged with the user's vite.config.js file.
2944
+ * @see https://vitejs.dev/guide/api-plugin.html#config
2945
+ */
2946
+ async config(config, config_env) {
2947
+ vite_config_env = config_env;
2948
+ svelte_config = await load_config();
2949
+ is_build = config_env.command === 'build';
2950
+
2951
+ paths = {
2952
+ build_dir: `${svelte_config.kit.outDir}/build`,
2953
+ output_dir: `${svelte_config.kit.outDir}/output`,
2954
+ client_out_dir: `${svelte_config.kit.outDir}/output/client/${svelte_config.kit.appDir}`
2955
+ };
2956
+
2957
+ if (is_build) {
2958
+ manifest_data = all(svelte_config).manifest_data;
2959
+
2960
+ const new_config = vite_client_build_config();
2961
+
2962
+ warn_overridden_config(config, new_config);
2963
+
2964
+ return new_config;
2965
+ }
2966
+
2967
+ // dev and preview config can be shared
2968
+ /** @type {import('vite').UserConfig} */
2969
+ const result = {
2970
+ appType: 'custom',
2971
+ base: '/',
2972
+ build: {
2973
+ rollupOptions: {
2974
+ // Vite dependency crawler needs an explicit JS entry point
2975
+ // eventhough server otherwise works without it
2976
+ input: `${get_runtime_directory(svelte_config.kit)}/client/start.js`
2977
+ }
2978
+ },
2979
+ define: {
2980
+ __SVELTEKIT_APP_VERSION_POLL_INTERVAL__: '0'
2981
+ },
2982
+ resolve: {
2983
+ alias: get_aliases(svelte_config.kit)
2984
+ },
2985
+ root: cwd,
2986
+ server: {
2987
+ fs: {
2988
+ allow: [
2989
+ ...new Set([
2990
+ svelte_config.kit.files.lib,
2991
+ svelte_config.kit.files.routes,
2992
+ svelte_config.kit.outDir,
2993
+ path__default.resolve(cwd, 'src'),
2994
+ path__default.resolve(cwd, 'node_modules'),
2995
+ path__default.resolve(vite.searchForWorkspaceRoot(cwd), 'node_modules')
2996
+ ])
2997
+ ]
2998
+ },
2999
+ watch: {
3000
+ ignored: [
3001
+ // Ignore all siblings of config.kit.outDir/generated
3002
+ `${posixify(svelte_config.kit.outDir)}/!(generated)`
3003
+ ]
3004
+ }
3005
+ }
3006
+ };
3007
+ warn_overridden_config(config, result);
3008
+ return result;
3009
+ },
3010
+
3011
+ /**
3012
+ * Stores the final config.
3013
+ */
3014
+ configResolved(config) {
3015
+ vite_config = config;
3016
+ },
3017
+
3018
+ /**
3019
+ * Clears the output directories.
3020
+ */
3021
+ buildStart() {
3022
+ // Reset for new build. Goes here because `build --watch` calls buildStart but not config
3023
+ completed_build = false;
3024
+
3025
+ if (is_build) {
3026
+ rimraf(paths.build_dir);
3027
+ mkdirp(paths.build_dir);
3028
+
3029
+ rimraf(paths.output_dir);
3030
+ mkdirp(paths.output_dir);
3031
+ }
3032
+ },
3033
+
3034
+ /**
3035
+ * Vite builds a single bundle. We need three bundles: client, server, and service worker.
3036
+ * The user's package.json scripts will invoke the Vite CLI to execute the client build. We
3037
+ * then use this hook to kick off builds for the server and service worker.
3038
+ */
3039
+ async writeBundle(_options, bundle) {
3040
+ log = logger({
3041
+ verbose: vite_config.logLevel === 'info'
3042
+ });
3043
+
3044
+ fs__default.writeFileSync(
3045
+ `${paths.client_out_dir}/version.json`,
3046
+ JSON.stringify({ version: svelte_config.kit.version.name })
3047
+ );
3048
+
3049
+ const { assets, chunks } = collect_output(bundle);
3050
+ log.info(`Client build completed. Wrote ${chunks.length} chunks and ${assets.length} assets`);
3051
+
3052
+ log.info('Building server');
3053
+ const options = {
3054
+ cwd,
3055
+ config: svelte_config,
3056
+ vite_config_env,
3057
+ build_dir: paths.build_dir, // TODO just pass `paths`
3058
+ manifest_data,
3059
+ output_dir: paths.output_dir,
3060
+ service_worker_entry_file: resolve_entry(svelte_config.kit.files.serviceWorker)
3061
+ };
3062
+ const client = client_build_info(assets, chunks);
3063
+ const server = await build_server(options, client);
3064
+
3065
+ /** @type {import('types').BuildData} */
3066
+ build_data = {
3067
+ app_dir: svelte_config.kit.appDir,
3068
+ manifest_data,
3069
+ service_worker: options.service_worker_entry_file ? 'service-worker.js' : null, // TODO make file configurable?
3070
+ client,
3071
+ server
3072
+ };
3073
+
3074
+ fs__default.writeFileSync(
3075
+ `${paths.output_dir}/server/manifest.js`,
3076
+ `export const manifest = ${generate_manifest({
3077
+ build_data,
3078
+ relative_path: '.',
3079
+ routes: manifest_data.routes
3080
+ })};\n`
3081
+ );
3082
+
3083
+ process.env.SVELTEKIT_SERVER_BUILD_COMPLETED = 'true';
3084
+ log.info('Prerendering');
3085
+
3086
+ const static_files = manifest_data.assets.map((asset) => posixify(asset.file));
3087
+
3088
+ const files = new Set([
3089
+ ...static_files,
3090
+ ...chunks.map((chunk) => `${svelte_config.kit.appDir}/${chunk.fileName}`),
3091
+ ...assets.map((chunk) => `${svelte_config.kit.appDir}/${chunk.fileName}`)
3092
+ ]);
3093
+
3094
+ // TODO is this right?
3095
+ static_files.forEach((file) => {
3096
+ if (file.endsWith('/index.html')) {
3097
+ files.add(file.slice(0, -11));
3098
+ }
3099
+ });
3100
+
3101
+ prerendered = await prerender({
3102
+ config: svelte_config.kit,
3103
+ entries: manifest_data.routes
3104
+ .map((route) => (route.type === 'page' ? route.path : ''))
3105
+ .filter(Boolean),
3106
+ files,
3107
+ log
3108
+ });
3109
+
3110
+ if (options.service_worker_entry_file) {
3111
+ if (svelte_config.kit.paths.assets) {
3112
+ throw new Error('Cannot use service worker alongside config.kit.paths.assets');
3113
+ }
3114
+
3115
+ log.info('Building service worker');
3116
+
3117
+ await build_service_worker(options, prerendered, client.vite_manifest);
3118
+ }
3119
+
3120
+ console.log(
3121
+ `\nRun ${$.bold().cyan('npm run preview')} to preview your production build locally.`
3122
+ );
3123
+
3124
+ completed_build = true;
3125
+ },
3126
+
3127
+ /**
3128
+ * Runs the adapter.
3129
+ */
3130
+ async closeBundle() {
3131
+ if (!completed_build) {
3132
+ // vite calls closeBundle when dev-server restarts, ignore that,
3133
+ // and only adapt when build successfully completes.
3134
+ return;
3135
+ }
3136
+
3137
+ if (svelte_config.kit.adapter) {
3138
+ const { adapt } = await import('./chunks/index2.js');
3139
+ await adapt(svelte_config, build_data, prerendered, { log });
3140
+ } else {
3141
+ console.log($.bold().yellow('\nNo adapter specified'));
3142
+ // prettier-ignore
3143
+ console.log(
3144
+ `See ${$.bold().cyan('https://kit.svelte.dev/docs/adapters')} to learn how to configure your app to run on the platform of your choosing`
3145
+ );
3146
+ }
3147
+
3148
+ if (svelte_config.kit.prerender.enabled) {
3149
+ // this is necessary to close any open db connections, etc.
3150
+ // TODO: prerender in a subprocess so we can exit in isolation and then remove this
3151
+ // https://github.com/sveltejs/kit/issues/5306
3152
+ process.exit(0);
3153
+ }
3154
+ },
3155
+
3156
+ /**
3157
+ * Adds the SvelteKit middleware to do SSR in dev mode.
3158
+ * @see https://vitejs.dev/guide/api-plugin.html#configureserver
3159
+ */
3160
+ async configureServer(vite) {
3161
+ return await dev(vite, vite_config, svelte_config);
3162
+ },
3163
+
3164
+ /**
3165
+ * Adds the SvelteKit middleware to do SSR in preview mode.
3166
+ * @see https://vitejs.dev/guide/api-plugin.html#configurepreviewserver
3167
+ */
3168
+ configurePreviewServer(vite) {
3169
+ return preview(vite, svelte_config, vite_config.preview.https ? 'https' : 'http');
3170
+ }
3171
+ };
3172
+ }
3173
+
3174
+ function check_vite_version() {
3175
+ // TODO parse from kit peer deps and maybe do a full semver compare if we ever require feature releases a min
3176
+ const min_required_vite_major = 3;
3177
+ const vite_version = vite.version ?? '2.x'; // vite started exporting it's version in 3.0
3178
+ const current_vite_major = parseInt(vite_version.split('.')[0], 10);
3179
+
3180
+ if (current_vite_major < min_required_vite_major) {
3181
+ throw new Error(
3182
+ `Vite version ${current_vite_major} is no longer supported. Please upgrade to version ${min_required_vite_major}`
3183
+ );
3184
+ }
3185
+ }
3186
+
3187
+ /** @param {import('rollup').OutputBundle} bundle */
3188
+ function collect_output(bundle) {
3189
+ /** @type {import('rollup').OutputChunk[]} */
3190
+ const chunks = [];
3191
+ /** @type {import('rollup').OutputAsset[]} */
3192
+ const assets = [];
3193
+ for (const value of Object.values(bundle)) {
3194
+ // collect asset and output chunks
3195
+ if (value.type === 'asset') {
3196
+ assets.push(value);
3197
+ } else {
3198
+ chunks.push(value);
3199
+ }
3200
+ }
3201
+ return { assets, chunks };
3202
+ }
3203
+
3204
+ /**
3205
+ * @param {Record<string, any>} config
3206
+ * @param {Record<string, any>} resolved_config
3207
+ */
3208
+ function warn_overridden_config(config, resolved_config) {
3209
+ const overridden = find_overridden_config(config, resolved_config, enforced_config, '', []);
3210
+ if (overridden.length > 0) {
3211
+ console.log(
3212
+ $.bold().red('The following Vite config options will be overridden by SvelteKit:')
3213
+ );
3214
+ console.log(overridden.map((key) => ` - ${key}`).join('\n'));
3215
+ }
3216
+ }
3217
+
3218
+ /**
3219
+ * @param {Record<string, any>} config
3220
+ * @param {Record<string, any>} resolved_config
3221
+ * @param {import('./types').EnforcedConfig} enforced_config
3222
+ * @param {string} path
3223
+ * @param {string[]} out used locally to compute the return value
3224
+ */
3225
+ function find_overridden_config(config, resolved_config, enforced_config, path, out) {
3226
+ for (const key in enforced_config) {
3227
+ if (typeof config === 'object' && config !== null && key in config) {
3228
+ const enforced = enforced_config[key];
3229
+
3230
+ if (enforced === true) {
3231
+ if (config[key] !== resolved_config[key]) {
3232
+ out.push(path + key);
3233
+ }
3234
+ } else {
3235
+ find_overridden_config(config[key], resolved_config[key], enforced, path + key + '.', out);
3236
+ }
3237
+ }
3238
+ }
3239
+
3240
+ return out;
3241
+ }
3242
+
3243
+ export { generate_manifest as g, sveltekit };