@sveltejs/kit 1.0.0-next.352 → 1.0.0-next.353

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