@sveltejs/kit 1.0.0-next.405 → 1.0.0-next.406

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/package.json +23 -25
  2. package/{dist → src}/cli.js +19 -18
  3. package/{dist/chunks/index3.js → src/core/adapt/builder.js} +6 -59
  4. package/src/core/adapt/index.js +19 -0
  5. package/src/core/config/index.js +86 -0
  6. package/{dist/chunks/index.js → src/core/config/options.js} +7 -194
  7. package/src/core/config/types.d.ts +1 -0
  8. package/src/core/constants.js +3 -0
  9. package/src/core/generate_manifest/index.js +99 -0
  10. package/src/core/prerender/crawl.js +194 -0
  11. package/src/core/prerender/prerender.js +378 -0
  12. package/src/core/prerender/queue.js +80 -0
  13. package/src/core/sync/create_manifest_data/index.js +492 -0
  14. package/src/core/sync/create_manifest_data/types.d.ts +40 -0
  15. package/src/core/sync/sync.js +59 -0
  16. package/src/core/sync/utils.js +97 -0
  17. package/src/core/sync/write_ambient.js +87 -0
  18. package/src/core/sync/write_client_manifest.js +82 -0
  19. package/src/core/sync/write_matchers.js +25 -0
  20. package/src/core/sync/write_root.js +88 -0
  21. package/{dist/chunks → src/core/sync}/write_tsconfig.js +24 -108
  22. package/src/core/sync/write_types.js +738 -0
  23. package/src/core/utils.js +58 -0
  24. package/{dist → src}/hooks.js +1 -3
  25. package/src/index/index.js +45 -0
  26. package/src/index/private.js +31 -0
  27. package/src/node/index.js +145 -0
  28. package/src/node/polyfills.js +40 -0
  29. package/src/packaging/index.js +218 -0
  30. package/src/packaging/types.d.ts +8 -0
  31. package/src/packaging/typescript.js +150 -0
  32. package/src/packaging/utils.js +138 -0
  33. package/{assets → src/runtime}/app/env.js +3 -5
  34. package/src/runtime/app/navigation.js +22 -0
  35. package/src/runtime/app/paths.js +1 -0
  36. package/{assets → src/runtime}/app/stores.js +6 -9
  37. package/src/runtime/client/ambient.d.ts +17 -0
  38. package/{assets/client/start.js → src/runtime/client/client.js} +302 -878
  39. package/src/runtime/client/fetcher.js +60 -0
  40. package/src/runtime/client/parse.js +36 -0
  41. package/{assets → src/runtime}/client/singletons.js +2 -4
  42. package/src/runtime/client/start.js +48 -0
  43. package/src/runtime/client/types.d.ts +106 -0
  44. package/src/runtime/client/utils.js +113 -0
  45. package/src/runtime/components/error.svelte +16 -0
  46. package/{assets → src/runtime}/components/layout.svelte +0 -0
  47. package/{assets → src/runtime}/env/dynamic/private.js +0 -0
  48. package/{assets → src/runtime}/env/dynamic/public.js +0 -0
  49. package/{assets → src/runtime}/env-private.js +2 -4
  50. package/{assets → src/runtime}/env-public.js +2 -4
  51. package/src/runtime/env.js +6 -0
  52. package/src/runtime/hash.js +16 -0
  53. package/{assets → src/runtime}/paths.js +3 -5
  54. package/src/runtime/server/endpoint.js +42 -0
  55. package/src/runtime/server/index.js +434 -0
  56. package/src/runtime/server/page/cookie.js +25 -0
  57. package/src/runtime/server/page/crypto.js +239 -0
  58. package/src/runtime/server/page/csp.js +249 -0
  59. package/src/runtime/server/page/fetch.js +265 -0
  60. package/src/runtime/server/page/index.js +423 -0
  61. package/src/runtime/server/page/load_data.js +94 -0
  62. package/src/runtime/server/page/render.js +357 -0
  63. package/src/runtime/server/page/respond_with_error.js +105 -0
  64. package/src/runtime/server/page/types.d.ts +44 -0
  65. package/src/runtime/server/utils.js +116 -0
  66. package/src/utils/error.js +22 -0
  67. package/src/utils/escape.js +104 -0
  68. package/{dist/chunks → src/utils}/filesystem.js +22 -24
  69. package/src/utils/http.js +55 -0
  70. package/src/utils/misc.js +1 -0
  71. package/src/utils/routing.js +107 -0
  72. package/src/utils/url.js +97 -0
  73. package/src/vite/build/build_server.js +333 -0
  74. package/src/vite/build/build_service_worker.js +90 -0
  75. package/src/vite/build/utils.js +152 -0
  76. package/src/vite/dev/index.js +565 -0
  77. package/src/vite/index.js +536 -0
  78. package/src/vite/preview/index.js +186 -0
  79. package/src/vite/types.d.ts +3 -0
  80. package/src/vite/utils.js +335 -0
  81. package/svelte-kit.js +1 -10
  82. package/types/ambient.d.ts +5 -12
  83. package/types/index.d.ts +86 -44
  84. package/types/internal.d.ts +50 -72
  85. package/types/private.d.ts +2 -1
  86. package/assets/app/navigation.js +0 -24
  87. package/assets/app/paths.js +0 -1
  88. package/assets/components/error.svelte +0 -29
  89. package/assets/env.js +0 -8
  90. package/assets/server/index.js +0 -3589
  91. package/dist/chunks/error.js +0 -12
  92. package/dist/chunks/index2.js +0 -15745
  93. package/dist/chunks/multipart-parser.js +0 -458
  94. package/dist/chunks/sync.js +0 -1366
  95. package/dist/chunks/utils.js +0 -66
  96. package/dist/node/polyfills.js +0 -17928
  97. package/dist/node.js +0 -348
  98. package/dist/prerender.js +0 -788
  99. package/dist/vite.js +0 -2513
package/dist/vite.js DELETED
@@ -1,2513 +0,0 @@
1
- import { fork } from 'node:child_process';
2
- import fs$1 from 'node:fs';
3
- import path from 'node:path';
4
- import { a as load_template, $, l as load_config } from './chunks/index.js';
5
- import { svelte } from '@sveltejs/vite-plugin-svelte';
6
- import * as vite from 'vite';
7
- import { loadEnv } from 'vite';
8
- import { p as posixify, m as mkdirp, r as rimraf } from './chunks/filesystem.js';
9
- import { g as get_aliases, r as resolve_entry, s, m as merge_vite_configs, a as get_vite_config, i as init, b as get_env, u as update, p as prevent_illegal_vite_imports, c as parse_route_id, d as all, e as prevent_illegal_rollup_imports } from './chunks/sync.js';
10
- import * as fs from 'fs';
11
- import fs__default, { readdirSync, statSync } from 'fs';
12
- import path__default, { resolve, join, normalize } from 'path';
13
- import { g as get_runtime_directory, a as get_runtime_prefix, b as get_mime_lookup, l as logger } from './chunks/utils.js';
14
- import * as qs from 'querystring';
15
- import { URL as URL$1, pathToFileURL } from 'url';
16
- import { getRequest, setResponse } from './node.js';
17
- import { installPolyfills } from './node/polyfills.js';
18
- import { c as coalesce_to_error } from './chunks/error.js';
19
- import { fileURLToPath } from 'node:url';
20
- import './chunks/write_tsconfig.js';
21
- import 'assert';
22
- import 'net';
23
- import 'http';
24
- import 'stream';
25
- import 'buffer';
26
- import 'util';
27
- import 'stream/web';
28
- import 'perf_hooks';
29
- import 'util/types';
30
- import 'events';
31
- import 'tls';
32
- import 'async_hooks';
33
- import 'console';
34
- import 'zlib';
35
- import 'node:http';
36
- import 'node:https';
37
- import 'node:zlib';
38
- import 'node:stream';
39
- import 'node:buffer';
40
- import 'node:util';
41
- import 'node:net';
42
- import 'crypto';
43
-
44
- /**
45
- * @typedef {import('rollup').RollupOutput} RollupOutput
46
- * @typedef {import('rollup').OutputChunk} OutputChunk
47
- * @typedef {import('rollup').OutputAsset} OutputAsset
48
- */
49
-
50
- /**
51
- * Invokes Vite.
52
- * @param {import('vite').UserConfig} config
53
- */
54
- async function create_build(config) {
55
- const { output } = /** @type {RollupOutput} */ (
56
- await vite.build({ ...config, configFile: false })
57
- );
58
-
59
- const chunks = output.filter(
60
- /** @returns {output is OutputChunk} */ (output) => output.type === 'chunk'
61
- );
62
-
63
- const assets = output.filter(
64
- /** @returns {output is OutputAsset} */ (output) => output.type === 'asset'
65
- );
66
-
67
- return { chunks, assets };
68
- }
69
-
70
- /**
71
- * Adds transitive JS and CSS dependencies to the js and css inputs.
72
- * @param {import('vite').Manifest} manifest
73
- * @param {string} entry
74
- * @param {boolean} add_dynamic_css
75
- */
76
- function find_deps$1(manifest, entry, add_dynamic_css) {
77
- /** @type {Set<string>} */
78
- const seen = new Set();
79
-
80
- /** @type {Set<string>} */
81
- const imports = new Set();
82
-
83
- /** @type {Set<string>} */
84
- const stylesheets = new Set();
85
-
86
- /**
87
- * @param {string} file
88
- * @param {boolean} add_js
89
- */
90
- function traverse(file, add_js) {
91
- if (seen.has(file)) return;
92
- seen.add(file);
93
-
94
- const chunk = manifest[file];
95
-
96
- if (add_js) imports.add(chunk.file);
97
-
98
- if (chunk.css) {
99
- chunk.css.forEach((file) => stylesheets.add(file));
100
- }
101
-
102
- if (chunk.imports) {
103
- chunk.imports.forEach((file) => traverse(file, add_js));
104
- }
105
-
106
- if (add_dynamic_css && chunk.dynamicImports) {
107
- chunk.dynamicImports.forEach((file) => traverse(file, false));
108
- }
109
- }
110
-
111
- traverse(entry, true);
112
-
113
- return {
114
- file: manifest[entry].file,
115
- imports: Array.from(imports),
116
- stylesheets: Array.from(stylesheets)
117
- };
118
- }
119
-
120
- /**
121
- * The Vite configuration that we use by default.
122
- * @param {{
123
- * config: import('types').ValidatedConfig;
124
- * input: Record<string, string>;
125
- * ssr: boolean;
126
- * outDir: string;
127
- * }} options
128
- * @return {import('vite').UserConfig}
129
- */
130
- const get_default_config = function ({ config, input, ssr, outDir }) {
131
- return {
132
- appType: 'custom',
133
- base: assets_base(config.kit),
134
- build: {
135
- cssCodeSplit: true,
136
- manifest: true,
137
- outDir,
138
- polyfillModulePreload: false,
139
- rollupOptions: {
140
- input,
141
- output: {
142
- format: 'esm',
143
- entryFileNames: ssr ? '[name].js' : `${config.kit.appDir}/immutable/[name]-[hash].js`,
144
- chunkFileNames: `${config.kit.appDir}/immutable/chunks/[name]-[hash].js`,
145
- assetFileNames: `${config.kit.appDir}/immutable/assets/[name]-[hash][extname]`
146
- },
147
- preserveEntrySignatures: 'strict'
148
- },
149
- ssr,
150
- target: ssr ? 'node14.8' : undefined
151
- },
152
- define: {
153
- __SVELTEKIT_ADAPTER_NAME__: JSON.stringify(config.kit.adapter?.name),
154
- __SVELTEKIT_APP_VERSION__: JSON.stringify(config.kit.version.name),
155
- __SVELTEKIT_APP_VERSION_FILE__: JSON.stringify(`${config.kit.appDir}/version.json`),
156
- __SVELTEKIT_APP_VERSION_POLL_INTERVAL__: JSON.stringify(config.kit.version.pollInterval),
157
- __SVELTEKIT_DEV__: 'false'
158
- },
159
- publicDir: ssr ? false : config.kit.files.assets,
160
- resolve: {
161
- alias: get_aliases(config.kit)
162
- },
163
- ssr: {
164
- // when developing against the Kit src code, we want to ensure that
165
- // our dependencies are bundled so that apps don't need to install
166
- // them as peerDependencies
167
- noExternal: []
168
-
169
- }
170
- };
171
- };
172
-
173
- /**
174
- * @param {import('types').ValidatedKitConfig} config
175
- * @returns {string}
176
- */
177
- function assets_base(config) {
178
- // TODO this is so that Vite's preloading works. Unfortunately, it fails
179
- // during `svelte-kit preview`, because we use a local asset path. This
180
- // may be fixed in Vite 3: https://github.com/vitejs/vite/issues/2009
181
- const { base, assets } = config.paths;
182
- return `${assets || base}/`;
183
- }
184
-
185
- const method_names = new Set(['GET', 'HEAD', 'PUT', 'POST', 'DELETE', 'PATCH']);
186
-
187
- // If we'd written this in TypeScript, it could be easy...
188
- /**
189
- * @param {string} str
190
- * @returns {str is import('types').HttpMethod}
191
- */
192
- function is_http_method(str) {
193
- return method_names.has(str);
194
- }
195
-
196
- /**
197
- * @param {{
198
- * hooks: string;
199
- * config: import('types').ValidatedConfig;
200
- * has_service_worker: boolean;
201
- * runtime: string;
202
- * template: string;
203
- * }} opts
204
- */
205
- const server_template = ({ config, hooks, has_service_worker, runtime, template }) => `
206
- import root from '__GENERATED__/root.svelte';
207
- import { respond } from '${runtime}/server/index.js';
208
- import { set_paths, assets, base } from '${runtime}/paths.js';
209
- import { set_prerendering } from '${runtime}/env.js';
210
- import { set_private_env } from '${runtime}/env-private.js';
211
- import { set_public_env } from '${runtime}/env-public.js';
212
-
213
- const template = ({ head, body, assets, nonce }) => ${s(template)
214
- .replace('%sveltekit.head%', '" + head + "')
215
- .replace('%sveltekit.body%', '" + body + "')
216
- .replace(/%sveltekit\.assets%/g, '" + assets + "')
217
- .replace(/%sveltekit\.nonce%/g, '" + nonce + "')};
218
-
219
- let read = null;
220
-
221
- set_paths(${s(config.kit.paths)});
222
-
223
- let default_protocol = 'https';
224
-
225
- // allow paths to be globally overridden
226
- // in svelte-kit preview and in prerendering
227
- export function override(settings) {
228
- default_protocol = settings.protocol || default_protocol;
229
- set_paths(settings.paths);
230
- set_prerendering(settings.prerendering);
231
- read = settings.read;
232
- }
233
-
234
- export class Server {
235
- constructor(manifest) {
236
- this.options = {
237
- csp: ${s(config.kit.csp)},
238
- dev: false,
239
- get_stack: error => String(error), // for security
240
- handle_error: (error, event) => {
241
- this.options.hooks.handleError({
242
- error,
243
- event,
244
-
245
- // TODO remove for 1.0
246
- // @ts-expect-error
247
- get request() {
248
- throw new Error('request in handleError has been replaced with event. See https://github.com/sveltejs/kit/pull/3384 for details');
249
- }
250
- });
251
- error.stack = this.options.get_stack(error);
252
- },
253
- hooks: null,
254
- hydrate: ${s(config.kit.browser.hydrate)},
255
- manifest,
256
- method_override: ${s(config.kit.methodOverride)},
257
- paths: { base, assets },
258
- prefix: assets + '/',
259
- prerender: {
260
- default: ${config.kit.prerender.default},
261
- enabled: ${config.kit.prerender.enabled}
262
- },
263
- public_env: {},
264
- read,
265
- root,
266
- service_worker: ${has_service_worker ? "base + '/service-worker.js'" : 'null'},
267
- router: ${s(config.kit.browser.router)},
268
- template,
269
- template_contains_nonce: ${template.includes('%sveltekit.nonce%')},
270
- trailing_slash: ${s(config.kit.trailingSlash)}
271
- };
272
- }
273
-
274
- init({ env }) {
275
- const entries = Object.entries(env);
276
-
277
- const prv = Object.fromEntries(entries.filter(([k]) => !k.startsWith('${
278
- config.kit.env.publicPrefix
279
- }')));
280
-
281
- const pub = Object.fromEntries(entries.filter(([k]) => k.startsWith('${
282
- config.kit.env.publicPrefix
283
- }')));
284
-
285
- set_private_env(prv);
286
- set_public_env(pub);
287
-
288
- this.options.public_env = pub;
289
- }
290
-
291
- async respond(request, options = {}) {
292
- if (!(request instanceof Request)) {
293
- throw new Error('The first argument to server.respond must be a Request object. See https://github.com/sveltejs/kit/pull/3384 for details');
294
- }
295
-
296
- if (!this.options.hooks) {
297
- const module = await import(${s(hooks)});
298
- this.options.hooks = {
299
- getSession: module.getSession || (() => ({})),
300
- handle: module.handle || (({ event, resolve }) => resolve(event)),
301
- handleError: module.handleError || (({ error }) => console.error(error.stack)),
302
- externalFetch: module.externalFetch || fetch
303
- };
304
- }
305
-
306
- return respond(request, this.options, options);
307
- }
308
- }
309
- `;
310
-
311
- /**
312
- * @param {{
313
- * cwd: string;
314
- * config: import('types').ValidatedConfig;
315
- * vite_config: import('vite').ResolvedConfig;
316
- * vite_config_env: import('vite').ConfigEnv;
317
- * manifest_data: import('types').ManifestData;
318
- * build_dir: string;
319
- * output_dir: string;
320
- * service_worker_entry_file: string | null;
321
- * }} options
322
- * @param {{ vite_manifest: import('vite').Manifest, assets: import('rollup').OutputAsset[] }} client
323
- */
324
- async function build_server(options, client) {
325
- const {
326
- cwd,
327
- config,
328
- vite_config,
329
- vite_config_env,
330
- manifest_data,
331
- build_dir,
332
- output_dir,
333
- service_worker_entry_file
334
- } = options;
335
-
336
- let hooks_file = resolve_entry(config.kit.files.hooks);
337
- if (!hooks_file || !fs__default.existsSync(hooks_file)) {
338
- hooks_file = path__default.join(config.kit.outDir, 'build/hooks.js');
339
- fs__default.writeFileSync(hooks_file, '');
340
- }
341
-
342
- /** @type {Record<string, string>} */
343
- const input = {
344
- index: `${build_dir}/index.js`
345
- };
346
-
347
- // add entry points for every endpoint...
348
- manifest_data.routes.forEach((route) => {
349
- const file = route.type === 'endpoint' ? route.file : route.shadow;
350
-
351
- if (file) {
352
- const resolved = path__default.resolve(cwd, file);
353
- const relative = decodeURIComponent(path__default.relative(config.kit.files.routes, resolved));
354
- const name = posixify(path__default.join('entries/endpoints', relative.replace(/\.js$/, '')));
355
- input[name] = resolved;
356
- }
357
- });
358
-
359
- // ...and every component used by pages...
360
- manifest_data.components.forEach((file) => {
361
- const resolved = path__default.resolve(cwd, file);
362
- const relative = decodeURIComponent(path__default.relative(config.kit.files.routes, resolved));
363
-
364
- const name = relative.startsWith('..')
365
- ? posixify(path__default.join('entries/fallbacks', path__default.basename(file)))
366
- : posixify(path__default.join('entries/pages', relative));
367
- input[name] = resolved;
368
- });
369
-
370
- // ...and every matcher
371
- Object.entries(manifest_data.matchers).forEach(([key, file]) => {
372
- const name = posixify(path__default.join('entries/matchers', key));
373
- input[name] = path__default.resolve(cwd, file);
374
- });
375
-
376
- /** @type {(file: string) => string} */
377
- const app_relative = (file) => {
378
- const relative_file = path__default.relative(build_dir, path__default.resolve(cwd, file));
379
- return relative_file[0] === '.' ? relative_file : `./${relative_file}`;
380
- };
381
-
382
- fs__default.writeFileSync(
383
- input.index,
384
- server_template({
385
- config,
386
- hooks: app_relative(hooks_file),
387
- has_service_worker: config.kit.serviceWorker.register && !!service_worker_entry_file,
388
- runtime: posixify(path__default.relative(build_dir, get_runtime_directory(config.kit))),
389
- template: load_template(cwd, config)
390
- })
391
- );
392
-
393
- const merged_config = merge_vite_configs(
394
- get_default_config({ config, input, ssr: true, outDir: `${output_dir}/server` }),
395
- await get_vite_config(vite_config, vite_config_env)
396
- );
397
-
398
- const { chunks } = await create_build(merged_config);
399
-
400
- /** @type {import('vite').Manifest} */
401
- const vite_manifest = JSON.parse(fs__default.readFileSync(`${output_dir}/server/manifest.json`, 'utf-8'));
402
-
403
- mkdirp(`${output_dir}/server/nodes`);
404
- mkdirp(`${output_dir}/server/stylesheets`);
405
-
406
- const stylesheet_lookup = new Map();
407
-
408
- client.assets.forEach((asset) => {
409
- if (asset.fileName.endsWith('.css')) {
410
- if (asset.source.length < config.kit.inlineStyleThreshold) {
411
- const index = stylesheet_lookup.size;
412
- const file = `${output_dir}/server/stylesheets/${index}.js`;
413
-
414
- fs__default.writeFileSync(file, `// ${asset.fileName}\nexport default ${s(asset.source)};`);
415
- stylesheet_lookup.set(asset.fileName, index);
416
- }
417
- }
418
- });
419
-
420
- manifest_data.components.forEach((component, i) => {
421
- const entry = find_deps$1(client.vite_manifest, component, true);
422
-
423
- const imports = [`import * as module from '../${vite_manifest[component].file}';`];
424
-
425
- const exports = [
426
- 'export { module };',
427
- `export const index = ${i};`,
428
- `export const file = '${entry.file}';`,
429
- `export const imports = ${s(entry.imports)};`,
430
- `export const stylesheets = ${s(entry.stylesheets)};`
431
- ];
432
-
433
- /** @type {string[]} */
434
- const styles = [];
435
-
436
- entry.stylesheets.forEach((file) => {
437
- if (stylesheet_lookup.has(file)) {
438
- const index = stylesheet_lookup.get(file);
439
- const name = `stylesheet_${index}`;
440
- imports.push(`import ${name} from '../stylesheets/${index}.js';`);
441
- styles.push(`\t${s(file)}: ${name}`);
442
- }
443
- });
444
-
445
- if (styles.length > 0) {
446
- exports.push(`export const inline_styles = () => ({\n${styles.join(',\n')}\n});`);
447
- }
448
-
449
- const out = `${output_dir}/server/nodes/${i}.js`;
450
- fs__default.writeFileSync(out, `${imports.join('\n')}\n\n${exports.join('\n')}\n`);
451
- });
452
-
453
- return {
454
- chunks,
455
- vite_manifest,
456
- methods: get_methods(cwd, chunks, manifest_data)
457
- };
458
- }
459
-
460
- /**
461
- * @param {string} cwd
462
- * @param {import('rollup').OutputChunk[]} output
463
- * @param {import('types').ManifestData} manifest_data
464
- */
465
- function get_methods(cwd, output, manifest_data) {
466
- /** @type {Record<string, string[]>} */
467
- const lookup = {};
468
- output.forEach((chunk) => {
469
- if (!chunk.facadeModuleId) return;
470
- const id = chunk.facadeModuleId.slice(cwd.length + 1);
471
- lookup[id] = chunk.exports;
472
- });
473
-
474
- /** @type {Record<string, import('types').HttpMethod[]>} */
475
- const methods = {};
476
- manifest_data.routes.forEach((route) => {
477
- const file = route.type === 'endpoint' ? route.file : route.shadow;
478
-
479
- if (file && lookup[file]) {
480
- methods[file] = lookup[file].filter(is_http_method);
481
- }
482
- });
483
-
484
- return methods;
485
- }
486
-
487
- /**
488
- * @param {{
489
- * config: import('types').ValidatedConfig;
490
- * vite_config: import('vite').ResolvedConfig;
491
- * vite_config_env: import('vite').ConfigEnv;
492
- * manifest_data: import('types').ManifestData;
493
- * output_dir: string;
494
- * service_worker_entry_file: string | null;
495
- * }} options
496
- * @param {import('types').Prerendered} prerendered
497
- * @param {import('vite').Manifest} client_manifest
498
- */
499
- async function build_service_worker(
500
- { config, manifest_data, output_dir, service_worker_entry_file },
501
- prerendered,
502
- client_manifest
503
- ) {
504
- const build = new Set();
505
- for (const key in client_manifest) {
506
- const { file, css = [], assets = [] } = client_manifest[key];
507
- build.add(file);
508
- css.forEach((file) => build.add(file));
509
- assets.forEach((file) => build.add(file));
510
- }
511
-
512
- const service_worker = `${config.kit.outDir}/generated/service-worker.js`;
513
-
514
- fs__default.writeFileSync(
515
- service_worker,
516
- `
517
- // TODO remove for 1.0
518
- export const timestamp = {
519
- toString: () => {
520
- throw new Error('\`timestamp\` has been removed from $service-worker. Use \`version\` instead');
521
- }
522
- };
523
-
524
- export const build = [
525
- ${Array.from(build)
526
- .map((file) => `${s(`${config.kit.paths.base}/${file}`)}`)
527
- .join(',\n\t\t\t\t')}
528
- ];
529
-
530
- export const files = [
531
- ${manifest_data.assets
532
- .filter((asset) => config.kit.serviceWorker.files(asset.file))
533
- .map((asset) => `${s(`${config.kit.paths.base}/${asset.file}`)}`)
534
- .join(',\n\t\t\t\t')}
535
- ];
536
-
537
- export const prerendered = [
538
- ${prerendered.paths.map((path) => s(path)).join(',\n\t\t\t\t')}
539
- ];
540
-
541
- export const version = ${s(config.kit.version.name)};
542
- `
543
- .replace(/^\t{3}/gm, '')
544
- .trim()
545
- );
546
-
547
- await vite.build({
548
- base: assets_base(config.kit),
549
- build: {
550
- lib: {
551
- entry: /** @type {string} */ (service_worker_entry_file),
552
- name: 'app',
553
- formats: ['es']
554
- },
555
- rollupOptions: {
556
- output: {
557
- entryFileNames: 'service-worker.js'
558
- }
559
- },
560
- outDir: `${output_dir}/client`,
561
- emptyOutDir: false
562
- },
563
- configFile: false,
564
- resolve: {
565
- alias: {
566
- '$service-worker': service_worker,
567
- $lib: config.kit.files.lib
568
- }
569
- }
570
- });
571
- }
572
-
573
- function totalist(dir, callback, pre='') {
574
- dir = resolve('.', dir);
575
- let arr = readdirSync(dir);
576
- let i=0, abs, stats;
577
- for (; i < arr.length; i++) {
578
- abs = join(dir, arr[i]);
579
- stats = statSync(abs);
580
- stats.isDirectory()
581
- ? totalist(abs, callback, join(pre, arr[i]))
582
- : callback(join(pre, arr[i]), abs, stats);
583
- }
584
- }
585
-
586
- /**
587
- * @typedef ParsedURL
588
- * @type {import('.').ParsedURL}
589
- */
590
-
591
- /**
592
- * @typedef Request
593
- * @property {string} url
594
- * @property {ParsedURL} _parsedUrl
595
- */
596
-
597
- /**
598
- * @param {Request} req
599
- * @returns {ParsedURL|void}
600
- */
601
- function parse(req) {
602
- let raw = req.url;
603
- if (raw == null) return;
604
-
605
- let prev = req._parsedUrl;
606
- if (prev && prev.raw === raw) return prev;
607
-
608
- let pathname=raw, search='', query;
609
-
610
- if (raw.length > 1) {
611
- let idx = raw.indexOf('?', 1);
612
-
613
- if (idx !== -1) {
614
- search = raw.substring(idx);
615
- pathname = raw.substring(0, idx);
616
- if (search.length > 1) {
617
- query = qs.parse(search.substring(1));
618
- }
619
- }
620
- }
621
-
622
- return req._parsedUrl = { pathname, search, query, raw };
623
- }
624
-
625
- const mimes = {
626
- "ez": "application/andrew-inset",
627
- "aw": "application/applixware",
628
- "atom": "application/atom+xml",
629
- "atomcat": "application/atomcat+xml",
630
- "atomdeleted": "application/atomdeleted+xml",
631
- "atomsvc": "application/atomsvc+xml",
632
- "dwd": "application/atsc-dwd+xml",
633
- "held": "application/atsc-held+xml",
634
- "rsat": "application/atsc-rsat+xml",
635
- "bdoc": "application/bdoc",
636
- "xcs": "application/calendar+xml",
637
- "ccxml": "application/ccxml+xml",
638
- "cdfx": "application/cdfx+xml",
639
- "cdmia": "application/cdmi-capability",
640
- "cdmic": "application/cdmi-container",
641
- "cdmid": "application/cdmi-domain",
642
- "cdmio": "application/cdmi-object",
643
- "cdmiq": "application/cdmi-queue",
644
- "cu": "application/cu-seeme",
645
- "mpd": "application/dash+xml",
646
- "davmount": "application/davmount+xml",
647
- "dbk": "application/docbook+xml",
648
- "dssc": "application/dssc+der",
649
- "xdssc": "application/dssc+xml",
650
- "es": "application/ecmascript",
651
- "ecma": "application/ecmascript",
652
- "emma": "application/emma+xml",
653
- "emotionml": "application/emotionml+xml",
654
- "epub": "application/epub+zip",
655
- "exi": "application/exi",
656
- "fdt": "application/fdt+xml",
657
- "pfr": "application/font-tdpfr",
658
- "geojson": "application/geo+json",
659
- "gml": "application/gml+xml",
660
- "gpx": "application/gpx+xml",
661
- "gxf": "application/gxf",
662
- "gz": "application/gzip",
663
- "hjson": "application/hjson",
664
- "stk": "application/hyperstudio",
665
- "ink": "application/inkml+xml",
666
- "inkml": "application/inkml+xml",
667
- "ipfix": "application/ipfix",
668
- "its": "application/its+xml",
669
- "jar": "application/java-archive",
670
- "war": "application/java-archive",
671
- "ear": "application/java-archive",
672
- "ser": "application/java-serialized-object",
673
- "class": "application/java-vm",
674
- "js": "application/javascript",
675
- "mjs": "application/javascript",
676
- "json": "application/json",
677
- "map": "application/json",
678
- "json5": "application/json5",
679
- "jsonml": "application/jsonml+json",
680
- "jsonld": "application/ld+json",
681
- "lgr": "application/lgr+xml",
682
- "lostxml": "application/lost+xml",
683
- "hqx": "application/mac-binhex40",
684
- "cpt": "application/mac-compactpro",
685
- "mads": "application/mads+xml",
686
- "webmanifest": "application/manifest+json",
687
- "mrc": "application/marc",
688
- "mrcx": "application/marcxml+xml",
689
- "ma": "application/mathematica",
690
- "nb": "application/mathematica",
691
- "mb": "application/mathematica",
692
- "mathml": "application/mathml+xml",
693
- "mbox": "application/mbox",
694
- "mscml": "application/mediaservercontrol+xml",
695
- "metalink": "application/metalink+xml",
696
- "meta4": "application/metalink4+xml",
697
- "mets": "application/mets+xml",
698
- "maei": "application/mmt-aei+xml",
699
- "musd": "application/mmt-usd+xml",
700
- "mods": "application/mods+xml",
701
- "m21": "application/mp21",
702
- "mp21": "application/mp21",
703
- "mp4s": "application/mp4",
704
- "m4p": "application/mp4",
705
- "doc": "application/msword",
706
- "dot": "application/msword",
707
- "mxf": "application/mxf",
708
- "nq": "application/n-quads",
709
- "nt": "application/n-triples",
710
- "cjs": "application/node",
711
- "bin": "application/octet-stream",
712
- "dms": "application/octet-stream",
713
- "lrf": "application/octet-stream",
714
- "mar": "application/octet-stream",
715
- "so": "application/octet-stream",
716
- "dist": "application/octet-stream",
717
- "distz": "application/octet-stream",
718
- "pkg": "application/octet-stream",
719
- "bpk": "application/octet-stream",
720
- "dump": "application/octet-stream",
721
- "elc": "application/octet-stream",
722
- "deploy": "application/octet-stream",
723
- "exe": "application/octet-stream",
724
- "dll": "application/octet-stream",
725
- "deb": "application/octet-stream",
726
- "dmg": "application/octet-stream",
727
- "iso": "application/octet-stream",
728
- "img": "application/octet-stream",
729
- "msi": "application/octet-stream",
730
- "msp": "application/octet-stream",
731
- "msm": "application/octet-stream",
732
- "buffer": "application/octet-stream",
733
- "oda": "application/oda",
734
- "opf": "application/oebps-package+xml",
735
- "ogx": "application/ogg",
736
- "omdoc": "application/omdoc+xml",
737
- "onetoc": "application/onenote",
738
- "onetoc2": "application/onenote",
739
- "onetmp": "application/onenote",
740
- "onepkg": "application/onenote",
741
- "oxps": "application/oxps",
742
- "relo": "application/p2p-overlay+xml",
743
- "xer": "application/patch-ops-error+xml",
744
- "pdf": "application/pdf",
745
- "pgp": "application/pgp-encrypted",
746
- "asc": "application/pgp-signature",
747
- "sig": "application/pgp-signature",
748
- "prf": "application/pics-rules",
749
- "p10": "application/pkcs10",
750
- "p7m": "application/pkcs7-mime",
751
- "p7c": "application/pkcs7-mime",
752
- "p7s": "application/pkcs7-signature",
753
- "p8": "application/pkcs8",
754
- "ac": "application/pkix-attr-cert",
755
- "cer": "application/pkix-cert",
756
- "crl": "application/pkix-crl",
757
- "pkipath": "application/pkix-pkipath",
758
- "pki": "application/pkixcmp",
759
- "pls": "application/pls+xml",
760
- "ai": "application/postscript",
761
- "eps": "application/postscript",
762
- "ps": "application/postscript",
763
- "provx": "application/provenance+xml",
764
- "cww": "application/prs.cww",
765
- "pskcxml": "application/pskc+xml",
766
- "raml": "application/raml+yaml",
767
- "rdf": "application/rdf+xml",
768
- "owl": "application/rdf+xml",
769
- "rif": "application/reginfo+xml",
770
- "rnc": "application/relax-ng-compact-syntax",
771
- "rl": "application/resource-lists+xml",
772
- "rld": "application/resource-lists-diff+xml",
773
- "rs": "application/rls-services+xml",
774
- "rapd": "application/route-apd+xml",
775
- "sls": "application/route-s-tsid+xml",
776
- "rusd": "application/route-usd+xml",
777
- "gbr": "application/rpki-ghostbusters",
778
- "mft": "application/rpki-manifest",
779
- "roa": "application/rpki-roa",
780
- "rsd": "application/rsd+xml",
781
- "rss": "application/rss+xml",
782
- "rtf": "application/rtf",
783
- "sbml": "application/sbml+xml",
784
- "scq": "application/scvp-cv-request",
785
- "scs": "application/scvp-cv-response",
786
- "spq": "application/scvp-vp-request",
787
- "spp": "application/scvp-vp-response",
788
- "sdp": "application/sdp",
789
- "senmlx": "application/senml+xml",
790
- "sensmlx": "application/sensml+xml",
791
- "setpay": "application/set-payment-initiation",
792
- "setreg": "application/set-registration-initiation",
793
- "shf": "application/shf+xml",
794
- "siv": "application/sieve",
795
- "sieve": "application/sieve",
796
- "smi": "application/smil+xml",
797
- "smil": "application/smil+xml",
798
- "rq": "application/sparql-query",
799
- "srx": "application/sparql-results+xml",
800
- "gram": "application/srgs",
801
- "grxml": "application/srgs+xml",
802
- "sru": "application/sru+xml",
803
- "ssdl": "application/ssdl+xml",
804
- "ssml": "application/ssml+xml",
805
- "swidtag": "application/swid+xml",
806
- "tei": "application/tei+xml",
807
- "teicorpus": "application/tei+xml",
808
- "tfi": "application/thraud+xml",
809
- "tsd": "application/timestamped-data",
810
- "toml": "application/toml",
811
- "trig": "application/trig",
812
- "ttml": "application/ttml+xml",
813
- "ubj": "application/ubjson",
814
- "rsheet": "application/urc-ressheet+xml",
815
- "td": "application/urc-targetdesc+xml",
816
- "vxml": "application/voicexml+xml",
817
- "wasm": "application/wasm",
818
- "wgt": "application/widget",
819
- "hlp": "application/winhlp",
820
- "wsdl": "application/wsdl+xml",
821
- "wspolicy": "application/wspolicy+xml",
822
- "xaml": "application/xaml+xml",
823
- "xav": "application/xcap-att+xml",
824
- "xca": "application/xcap-caps+xml",
825
- "xdf": "application/xcap-diff+xml",
826
- "xel": "application/xcap-el+xml",
827
- "xns": "application/xcap-ns+xml",
828
- "xenc": "application/xenc+xml",
829
- "xhtml": "application/xhtml+xml",
830
- "xht": "application/xhtml+xml",
831
- "xlf": "application/xliff+xml",
832
- "xml": "application/xml",
833
- "xsl": "application/xml",
834
- "xsd": "application/xml",
835
- "rng": "application/xml",
836
- "dtd": "application/xml-dtd",
837
- "xop": "application/xop+xml",
838
- "xpl": "application/xproc+xml",
839
- "xslt": "application/xml",
840
- "xspf": "application/xspf+xml",
841
- "mxml": "application/xv+xml",
842
- "xhvml": "application/xv+xml",
843
- "xvml": "application/xv+xml",
844
- "xvm": "application/xv+xml",
845
- "yang": "application/yang",
846
- "yin": "application/yin+xml",
847
- "zip": "application/zip",
848
- "3gpp": "video/3gpp",
849
- "adp": "audio/adpcm",
850
- "amr": "audio/amr",
851
- "au": "audio/basic",
852
- "snd": "audio/basic",
853
- "mid": "audio/midi",
854
- "midi": "audio/midi",
855
- "kar": "audio/midi",
856
- "rmi": "audio/midi",
857
- "mxmf": "audio/mobile-xmf",
858
- "mp3": "audio/mpeg",
859
- "m4a": "audio/mp4",
860
- "mp4a": "audio/mp4",
861
- "mpga": "audio/mpeg",
862
- "mp2": "audio/mpeg",
863
- "mp2a": "audio/mpeg",
864
- "m2a": "audio/mpeg",
865
- "m3a": "audio/mpeg",
866
- "oga": "audio/ogg",
867
- "ogg": "audio/ogg",
868
- "spx": "audio/ogg",
869
- "opus": "audio/ogg",
870
- "s3m": "audio/s3m",
871
- "sil": "audio/silk",
872
- "wav": "audio/wav",
873
- "weba": "audio/webm",
874
- "xm": "audio/xm",
875
- "ttc": "font/collection",
876
- "otf": "font/otf",
877
- "ttf": "font/ttf",
878
- "woff": "font/woff",
879
- "woff2": "font/woff2",
880
- "exr": "image/aces",
881
- "apng": "image/apng",
882
- "avif": "image/avif",
883
- "bmp": "image/bmp",
884
- "cgm": "image/cgm",
885
- "drle": "image/dicom-rle",
886
- "emf": "image/emf",
887
- "fits": "image/fits",
888
- "g3": "image/g3fax",
889
- "gif": "image/gif",
890
- "heic": "image/heic",
891
- "heics": "image/heic-sequence",
892
- "heif": "image/heif",
893
- "heifs": "image/heif-sequence",
894
- "hej2": "image/hej2k",
895
- "hsj2": "image/hsj2",
896
- "ief": "image/ief",
897
- "jls": "image/jls",
898
- "jp2": "image/jp2",
899
- "jpg2": "image/jp2",
900
- "jpeg": "image/jpeg",
901
- "jpg": "image/jpeg",
902
- "jpe": "image/jpeg",
903
- "jph": "image/jph",
904
- "jhc": "image/jphc",
905
- "jpm": "image/jpm",
906
- "jpx": "image/jpx",
907
- "jpf": "image/jpx",
908
- "jxr": "image/jxr",
909
- "jxra": "image/jxra",
910
- "jxrs": "image/jxrs",
911
- "jxs": "image/jxs",
912
- "jxsc": "image/jxsc",
913
- "jxsi": "image/jxsi",
914
- "jxss": "image/jxss",
915
- "ktx": "image/ktx",
916
- "ktx2": "image/ktx2",
917
- "png": "image/png",
918
- "btif": "image/prs.btif",
919
- "pti": "image/prs.pti",
920
- "sgi": "image/sgi",
921
- "svg": "image/svg+xml",
922
- "svgz": "image/svg+xml",
923
- "t38": "image/t38",
924
- "tif": "image/tiff",
925
- "tiff": "image/tiff",
926
- "tfx": "image/tiff-fx",
927
- "webp": "image/webp",
928
- "wmf": "image/wmf",
929
- "disposition-notification": "message/disposition-notification",
930
- "u8msg": "message/global",
931
- "u8dsn": "message/global-delivery-status",
932
- "u8mdn": "message/global-disposition-notification",
933
- "u8hdr": "message/global-headers",
934
- "eml": "message/rfc822",
935
- "mime": "message/rfc822",
936
- "3mf": "model/3mf",
937
- "gltf": "model/gltf+json",
938
- "glb": "model/gltf-binary",
939
- "igs": "model/iges",
940
- "iges": "model/iges",
941
- "msh": "model/mesh",
942
- "mesh": "model/mesh",
943
- "silo": "model/mesh",
944
- "mtl": "model/mtl",
945
- "obj": "model/obj",
946
- "stpz": "model/step+zip",
947
- "stpxz": "model/step-xml+zip",
948
- "stl": "model/stl",
949
- "wrl": "model/vrml",
950
- "vrml": "model/vrml",
951
- "x3db": "model/x3d+fastinfoset",
952
- "x3dbz": "model/x3d+binary",
953
- "x3dv": "model/x3d-vrml",
954
- "x3dvz": "model/x3d+vrml",
955
- "x3d": "model/x3d+xml",
956
- "x3dz": "model/x3d+xml",
957
- "appcache": "text/cache-manifest",
958
- "manifest": "text/cache-manifest",
959
- "ics": "text/calendar",
960
- "ifb": "text/calendar",
961
- "coffee": "text/coffeescript",
962
- "litcoffee": "text/coffeescript",
963
- "css": "text/css",
964
- "csv": "text/csv",
965
- "html": "text/html",
966
- "htm": "text/html",
967
- "shtml": "text/html",
968
- "jade": "text/jade",
969
- "jsx": "text/jsx",
970
- "less": "text/less",
971
- "markdown": "text/markdown",
972
- "md": "text/markdown",
973
- "mml": "text/mathml",
974
- "mdx": "text/mdx",
975
- "n3": "text/n3",
976
- "txt": "text/plain",
977
- "text": "text/plain",
978
- "conf": "text/plain",
979
- "def": "text/plain",
980
- "list": "text/plain",
981
- "log": "text/plain",
982
- "in": "text/plain",
983
- "ini": "text/plain",
984
- "dsc": "text/prs.lines.tag",
985
- "rtx": "text/richtext",
986
- "sgml": "text/sgml",
987
- "sgm": "text/sgml",
988
- "shex": "text/shex",
989
- "slim": "text/slim",
990
- "slm": "text/slim",
991
- "spdx": "text/spdx",
992
- "stylus": "text/stylus",
993
- "styl": "text/stylus",
994
- "tsv": "text/tab-separated-values",
995
- "t": "text/troff",
996
- "tr": "text/troff",
997
- "roff": "text/troff",
998
- "man": "text/troff",
999
- "me": "text/troff",
1000
- "ms": "text/troff",
1001
- "ttl": "text/turtle",
1002
- "uri": "text/uri-list",
1003
- "uris": "text/uri-list",
1004
- "urls": "text/uri-list",
1005
- "vcard": "text/vcard",
1006
- "vtt": "text/vtt",
1007
- "yaml": "text/yaml",
1008
- "yml": "text/yaml",
1009
- "3gp": "video/3gpp",
1010
- "3g2": "video/3gpp2",
1011
- "h261": "video/h261",
1012
- "h263": "video/h263",
1013
- "h264": "video/h264",
1014
- "m4s": "video/iso.segment",
1015
- "jpgv": "video/jpeg",
1016
- "jpgm": "image/jpm",
1017
- "mj2": "video/mj2",
1018
- "mjp2": "video/mj2",
1019
- "ts": "video/mp2t",
1020
- "mp4": "video/mp4",
1021
- "mp4v": "video/mp4",
1022
- "mpg4": "video/mp4",
1023
- "mpeg": "video/mpeg",
1024
- "mpg": "video/mpeg",
1025
- "mpe": "video/mpeg",
1026
- "m1v": "video/mpeg",
1027
- "m2v": "video/mpeg",
1028
- "ogv": "video/ogg",
1029
- "qt": "video/quicktime",
1030
- "mov": "video/quicktime",
1031
- "webm": "video/webm"
1032
- };
1033
-
1034
- function lookup(extn) {
1035
- let tmp = ('' + extn).trim().toLowerCase();
1036
- let idx = tmp.lastIndexOf('.');
1037
- return mimes[!~idx ? tmp : tmp.substring(++idx)];
1038
- }
1039
-
1040
- const noop = () => {};
1041
-
1042
- function isMatch(uri, arr) {
1043
- for (let i=0; i < arr.length; i++) {
1044
- if (arr[i].test(uri)) return true;
1045
- }
1046
- }
1047
-
1048
- function toAssume(uri, extns) {
1049
- let i=0, x, len=uri.length - 1;
1050
- if (uri.charCodeAt(len) === 47) {
1051
- uri = uri.substring(0, len);
1052
- }
1053
-
1054
- let arr=[], tmp=`${uri}/index`;
1055
- for (; i < extns.length; i++) {
1056
- x = extns[i] ? `.${extns[i]}` : '';
1057
- if (uri) arr.push(uri + x);
1058
- arr.push(tmp + x);
1059
- }
1060
-
1061
- return arr;
1062
- }
1063
-
1064
- function viaCache(cache, uri, extns) {
1065
- let i=0, data, arr=toAssume(uri, extns);
1066
- for (; i < arr.length; i++) {
1067
- if (data = cache[arr[i]]) return data;
1068
- }
1069
- }
1070
-
1071
- function viaLocal(dir, isEtag, uri, extns) {
1072
- let i=0, arr=toAssume(uri, extns);
1073
- let abs, stats, name, headers;
1074
- for (; i < arr.length; i++) {
1075
- abs = normalize(join(dir, name=arr[i]));
1076
- if (abs.startsWith(dir) && fs.existsSync(abs)) {
1077
- stats = fs.statSync(abs);
1078
- if (stats.isDirectory()) continue;
1079
- headers = toHeaders(name, stats, isEtag);
1080
- headers['Cache-Control'] = isEtag ? 'no-cache' : 'no-store';
1081
- return { abs, stats, headers };
1082
- }
1083
- }
1084
- }
1085
-
1086
- function is404(req, res) {
1087
- return (res.statusCode=404,res.end());
1088
- }
1089
-
1090
- function send(req, res, file, stats, headers) {
1091
- let code=200, tmp, opts={};
1092
- headers = { ...headers };
1093
-
1094
- for (let key in headers) {
1095
- tmp = res.getHeader(key);
1096
- if (tmp) headers[key] = tmp;
1097
- }
1098
-
1099
- if (tmp = res.getHeader('content-type')) {
1100
- headers['Content-Type'] = tmp;
1101
- }
1102
-
1103
- if (req.headers.range) {
1104
- code = 206;
1105
- let [x, y] = req.headers.range.replace('bytes=', '').split('-');
1106
- let end = opts.end = parseInt(y, 10) || stats.size - 1;
1107
- let start = opts.start = parseInt(x, 10) || 0;
1108
-
1109
- if (start >= stats.size || end >= stats.size) {
1110
- res.setHeader('Content-Range', `bytes */${stats.size}`);
1111
- res.statusCode = 416;
1112
- return res.end();
1113
- }
1114
-
1115
- headers['Content-Range'] = `bytes ${start}-${end}/${stats.size}`;
1116
- headers['Content-Length'] = (end - start + 1);
1117
- headers['Accept-Ranges'] = 'bytes';
1118
- }
1119
-
1120
- res.writeHead(code, headers);
1121
- fs.createReadStream(file, opts).pipe(res);
1122
- }
1123
-
1124
- const ENCODING = {
1125
- '.br': 'br',
1126
- '.gz': 'gzip',
1127
- };
1128
-
1129
- function toHeaders(name, stats, isEtag) {
1130
- let enc = ENCODING[name.slice(-3)];
1131
-
1132
- let ctype = lookup(name.slice(0, enc && -3)) || '';
1133
- if (ctype === 'text/html') ctype += ';charset=utf-8';
1134
-
1135
- let headers = {
1136
- 'Content-Length': stats.size,
1137
- 'Content-Type': ctype,
1138
- 'Last-Modified': stats.mtime.toUTCString(),
1139
- };
1140
-
1141
- if (enc) headers['Content-Encoding'] = enc;
1142
- if (isEtag) headers['ETag'] = `W/"${stats.size}-${stats.mtime.getTime()}"`;
1143
-
1144
- return headers;
1145
- }
1146
-
1147
- function sirv (dir, opts={}) {
1148
- dir = resolve(dir || '.');
1149
-
1150
- let isNotFound = opts.onNoMatch || is404;
1151
- let setHeaders = opts.setHeaders || noop;
1152
-
1153
- let extensions = opts.extensions || ['html', 'htm'];
1154
- let gzips = opts.gzip && extensions.map(x => `${x}.gz`).concat('gz');
1155
- let brots = opts.brotli && extensions.map(x => `${x}.br`).concat('br');
1156
-
1157
- const FILES = {};
1158
-
1159
- let fallback = '/';
1160
- let isEtag = !!opts.etag;
1161
- let isSPA = !!opts.single;
1162
- if (typeof opts.single === 'string') {
1163
- let idx = opts.single.lastIndexOf('.');
1164
- fallback += !!~idx ? opts.single.substring(0, idx) : opts.single;
1165
- }
1166
-
1167
- let ignores = [];
1168
- if (opts.ignores !== false) {
1169
- ignores.push(/[/]([A-Za-z\s\d~$._-]+\.\w+){1,}$/); // any extn
1170
- if (opts.dotfiles) ignores.push(/\/\.\w/);
1171
- else ignores.push(/\/\.well-known/);
1172
- [].concat(opts.ignores || []).forEach(x => {
1173
- ignores.push(new RegExp(x, 'i'));
1174
- });
1175
- }
1176
-
1177
- let cc = opts.maxAge != null && `public,max-age=${opts.maxAge}`;
1178
- if (cc && opts.immutable) cc += ',immutable';
1179
- else if (cc && opts.maxAge === 0) cc += ',must-revalidate';
1180
-
1181
- if (!opts.dev) {
1182
- totalist(dir, (name, abs, stats) => {
1183
- if (/\.well-known[\\+\/]/.test(name)) ; // keep
1184
- else if (!opts.dotfiles && /(^\.|[\\+|\/+]\.)/.test(name)) return;
1185
-
1186
- let headers = toHeaders(name, stats, isEtag);
1187
- if (cc) headers['Cache-Control'] = cc;
1188
-
1189
- FILES['/' + name.normalize().replace(/\\+/g, '/')] = { abs, stats, headers };
1190
- });
1191
- }
1192
-
1193
- let lookup = opts.dev ? viaLocal.bind(0, dir, isEtag) : viaCache.bind(0, FILES);
1194
-
1195
- return function (req, res, next) {
1196
- let extns = [''];
1197
- let pathname = parse(req).pathname;
1198
- let val = req.headers['accept-encoding'] || '';
1199
- if (gzips && val.includes('gzip')) extns.unshift(...gzips);
1200
- if (brots && /(br|brotli)/i.test(val)) extns.unshift(...brots);
1201
- extns.push(...extensions); // [...br, ...gz, orig, ...exts]
1202
-
1203
- if (pathname.indexOf('%') !== -1) {
1204
- try { pathname = decodeURIComponent(pathname); }
1205
- catch (err) { /* malform uri */ }
1206
- }
1207
-
1208
- let data = lookup(pathname, extns) || isSPA && !isMatch(pathname, ignores) && lookup(fallback, extns);
1209
- if (!data) return next ? next() : isNotFound(req, res);
1210
-
1211
- if (isEtag && req.headers['if-none-match'] === data.headers['ETag']) {
1212
- res.writeHead(304);
1213
- return res.end();
1214
- }
1215
-
1216
- if (gzips || brots) {
1217
- res.setHeader('Vary', 'Accept-Encoding');
1218
- }
1219
-
1220
- setHeaders(res, pathname, data.stats);
1221
- send(req, res, data.abs, data.stats, data.headers);
1222
- };
1223
- }
1224
-
1225
- // in `vite dev` and `vite preview`, we use a fake asset path so that we can
1226
- // serve local assets while verifying that requests are correctly prefixed
1227
- const SVELTE_KIT_ASSETS = '/_svelte_kit_assets';
1228
-
1229
- // Vite doesn't expose this so we just copy the list for now
1230
- // https://github.com/vitejs/vite/blob/3edd1af56e980aef56641a5a51cf2932bb580d41/packages/vite/src/node/plugins/css.ts#L96
1231
- const style_pattern = /\.(css|less|sass|scss|styl|stylus|pcss|postcss)$/;
1232
-
1233
- const cwd$1 = process.cwd();
1234
-
1235
- /**
1236
- * @param {import('vite').ViteDevServer} vite
1237
- * @param {import('vite').ResolvedConfig} vite_config
1238
- * @param {import('types').ValidatedConfig} svelte_config
1239
- * @param {Set<string>} illegal_imports
1240
- * @return {Promise<Promise<() => void>>}
1241
- */
1242
- async function dev(vite, vite_config, svelte_config, illegal_imports) {
1243
- installPolyfills();
1244
-
1245
- init(svelte_config, vite_config.mode);
1246
-
1247
- const runtime = get_runtime_prefix(svelte_config.kit);
1248
-
1249
- /** @type {import('types').Respond} */
1250
- const respond = (await import(`${runtime}/server/index.js`)).respond;
1251
-
1252
- /** @type {import('types').SSRManifest} */
1253
- let manifest;
1254
-
1255
- function update_manifest() {
1256
- const { manifest_data } = update(svelte_config);
1257
-
1258
- manifest = {
1259
- appDir: svelte_config.kit.appDir,
1260
- assets: new Set(manifest_data.assets.map((asset) => asset.file)),
1261
- mimeTypes: get_mime_lookup(manifest_data),
1262
- _: {
1263
- entry: {
1264
- file: `/@fs${runtime}/client/start.js`,
1265
- imports: [],
1266
- stylesheets: []
1267
- },
1268
- nodes: manifest_data.components.map((id, index) => {
1269
- return async () => {
1270
- const url = id.startsWith('..') ? `/@fs${path__default.posix.resolve(id)}` : `/${id}`;
1271
-
1272
- const module = /** @type {import('types').SSRComponent} */ (
1273
- await vite.ssrLoadModule(url)
1274
- );
1275
-
1276
- const node = await vite.moduleGraph.getModuleByUrl(url);
1277
- if (!node) throw new Error(`Could not find node for ${url}`);
1278
-
1279
- prevent_illegal_vite_imports(
1280
- node,
1281
- illegal_imports,
1282
- [...svelte_config.extensions, ...svelte_config.kit.moduleExtensions],
1283
- svelte_config.kit.outDir
1284
- );
1285
-
1286
- return {
1287
- module,
1288
- index,
1289
- file: url.endsWith('.svelte') ? url : url + '?import',
1290
- imports: [],
1291
- stylesheets: [],
1292
- // in dev we inline all styles to avoid FOUC
1293
- inline_styles: async () => {
1294
- const deps = new Set();
1295
- await find_deps(vite, node, deps);
1296
-
1297
- /** @type {Record<string, string>} */
1298
- const styles = {};
1299
-
1300
- for (const dep of deps) {
1301
- const parsed = new URL$1(dep.url, 'http://localhost/');
1302
- const query = parsed.searchParams;
1303
-
1304
- if (
1305
- style_pattern.test(dep.file) ||
1306
- (query.has('svelte') && query.get('type') === 'style')
1307
- ) {
1308
- try {
1309
- const mod = await vite.ssrLoadModule(dep.url);
1310
- styles[dep.url] = mod.default;
1311
- } catch {
1312
- // this can happen with dynamically imported modules, I think
1313
- // because the Vite module graph doesn't distinguish between
1314
- // static and dynamic imports? TODO investigate, submit fix
1315
- }
1316
- }
1317
- }
1318
-
1319
- return styles;
1320
- }
1321
- };
1322
- };
1323
- }),
1324
- routes: manifest_data.routes.map((route) => {
1325
- const { pattern, names, types } = parse_route_id(route.id);
1326
-
1327
- if (route.type === 'page') {
1328
- return {
1329
- type: 'page',
1330
- id: route.id,
1331
- pattern,
1332
- names,
1333
- types,
1334
- shadow: route.shadow
1335
- ? async () => {
1336
- const url = path__default.resolve(cwd$1, /** @type {string} */ (route.shadow));
1337
- return await vite.ssrLoadModule(url);
1338
- }
1339
- : null,
1340
- a: route.a.map((id) => (id ? manifest_data.components.indexOf(id) : undefined)),
1341
- b: route.b.map((id) => (id ? manifest_data.components.indexOf(id) : undefined))
1342
- };
1343
- }
1344
-
1345
- return {
1346
- type: 'endpoint',
1347
- id: route.id,
1348
- pattern,
1349
- names,
1350
- types,
1351
- load: async () => {
1352
- const url = path__default.resolve(cwd$1, route.file);
1353
- return await vite.ssrLoadModule(url);
1354
- }
1355
- };
1356
- }),
1357
- matchers: async () => {
1358
- /** @type {Record<string, import('types').ParamMatcher>} */
1359
- const matchers = {};
1360
-
1361
- for (const key in manifest_data.matchers) {
1362
- const file = manifest_data.matchers[key];
1363
- const url = path__default.resolve(cwd$1, file);
1364
- const module = await vite.ssrLoadModule(url);
1365
-
1366
- if (module.match) {
1367
- matchers[key] = module.match;
1368
- } else {
1369
- throw new Error(`${file} does not export a \`match\` function`);
1370
- }
1371
- }
1372
-
1373
- return matchers;
1374
- }
1375
- }
1376
- };
1377
- }
1378
-
1379
- /** @param {Error} error */
1380
- function fix_stack_trace(error) {
1381
- return error.stack ? vite.ssrRewriteStacktrace(error.stack) : error.stack;
1382
- }
1383
-
1384
- update_manifest();
1385
-
1386
- for (const event of ['add', 'unlink']) {
1387
- vite.watcher.on(event, (file) => {
1388
- if (file.startsWith(svelte_config.kit.files.routes + path__default.sep)) {
1389
- update_manifest();
1390
- }
1391
- });
1392
- }
1393
-
1394
- const assets = svelte_config.kit.paths.assets ? SVELTE_KIT_ASSETS : svelte_config.kit.paths.base;
1395
- const asset_server = sirv(svelte_config.kit.files.assets, {
1396
- dev: true,
1397
- etag: true,
1398
- maxAge: 0,
1399
- extensions: []
1400
- });
1401
-
1402
- vite.middlewares.use(async (req, res, next) => {
1403
- try {
1404
- const base = `${vite.config.server.https ? 'https' : 'http'}://${
1405
- req.headers[':authority'] || req.headers.host
1406
- }`;
1407
-
1408
- const decoded = decodeURI(new URL$1(base + req.url).pathname);
1409
-
1410
- if (decoded.startsWith(assets)) {
1411
- const pathname = decoded.slice(assets.length);
1412
- const file = svelte_config.kit.files.assets + pathname;
1413
-
1414
- if (fs__default.existsSync(file) && !fs__default.statSync(file).isDirectory()) {
1415
- if (has_correct_case(file, svelte_config.kit.files.assets)) {
1416
- req.url = encodeURI(pathname); // don't need query/hash
1417
- asset_server(req, res);
1418
- return;
1419
- }
1420
- }
1421
- }
1422
-
1423
- next();
1424
- } catch (e) {
1425
- const error = coalesce_to_error(e);
1426
- res.statusCode = 500;
1427
- res.end(fix_stack_trace(error));
1428
- }
1429
- });
1430
-
1431
- return () => {
1432
- const serve_static_middleware = vite.middlewares.stack.find(
1433
- (middleware) =>
1434
- /** @type {function} */ (middleware.handle).name === 'viteServeStaticMiddleware'
1435
- );
1436
-
1437
- remove_static_middlewares(vite.middlewares);
1438
-
1439
- vite.middlewares.use(async (req, res) => {
1440
- try {
1441
- const base = `${vite.config.server.https ? 'https' : 'http'}://${
1442
- req.headers[':authority'] || req.headers.host
1443
- }`;
1444
-
1445
- const decoded = decodeURI(new URL$1(base + req.url).pathname);
1446
- const file = posixify(path__default.resolve(decoded.slice(1)));
1447
- const is_file = fs__default.existsSync(file) && !fs__default.statSync(file).isDirectory();
1448
- const allowed =
1449
- !vite_config.server.fs.strict ||
1450
- vite_config.server.fs.allow.some((dir) => file.startsWith(dir));
1451
-
1452
- if (is_file && allowed) {
1453
- // @ts-expect-error
1454
- serve_static_middleware.handle(req, res);
1455
- return;
1456
- }
1457
-
1458
- if (!decoded.startsWith(svelte_config.kit.paths.base)) {
1459
- return not_found(
1460
- res,
1461
- `Not found (did you mean ${svelte_config.kit.paths.base + req.url}?)`
1462
- );
1463
- }
1464
-
1465
- const runtime_base = true
1466
- ? `/${posixify(path__default.relative(cwd$1, `${svelte_config.kit.outDir}/runtime`))}`
1467
- : `/@fs${runtime}`;
1468
-
1469
- const { set_private_env } = await vite.ssrLoadModule(`${runtime_base}/env-private.js`);
1470
- const { set_public_env } = await vite.ssrLoadModule(`${runtime_base}/env-public.js`);
1471
-
1472
- const env = get_env(vite_config.mode, svelte_config.kit.env.publicPrefix);
1473
- set_private_env(env.private);
1474
- set_public_env(env.public);
1475
-
1476
- /** @type {Partial<import('types').Hooks>} */
1477
- const user_hooks = resolve_entry(svelte_config.kit.files.hooks)
1478
- ? await vite.ssrLoadModule(`/${svelte_config.kit.files.hooks}`)
1479
- : {};
1480
-
1481
- const handle = user_hooks.handle || (({ event, resolve }) => resolve(event));
1482
-
1483
- /** @type {import('types').Hooks} */
1484
- const hooks = {
1485
- getSession: user_hooks.getSession || (() => ({})),
1486
- handle,
1487
- handleError:
1488
- user_hooks.handleError ||
1489
- (({ /** @type {Error & { frame?: string }} */ error }) => {
1490
- console.error($.bold().red(error.message));
1491
- if (error.frame) {
1492
- console.error($.gray(error.frame));
1493
- }
1494
- if (error.stack) {
1495
- console.error($.gray(error.stack));
1496
- }
1497
- }),
1498
- externalFetch: user_hooks.externalFetch || fetch
1499
- };
1500
-
1501
- if (/** @type {any} */ (hooks).getContext) {
1502
- // TODO remove this for 1.0
1503
- throw new Error(
1504
- 'The getContext hook has been removed. See https://kit.svelte.dev/docs/hooks'
1505
- );
1506
- }
1507
-
1508
- if (/** @type {any} */ (hooks).serverFetch) {
1509
- // TODO remove this for 1.0
1510
- throw new Error('The serverFetch hook has been renamed to externalFetch.');
1511
- }
1512
-
1513
- // TODO the / prefix will probably fail if outDir is outside the cwd (which
1514
- // could be the case in a monorepo setup), but without it these modules
1515
- // can get loaded twice via different URLs, which causes failures. Might
1516
- // require changes to Vite to fix
1517
- const { default: root } = await vite.ssrLoadModule(
1518
- `/${posixify(path__default.relative(cwd$1, `${svelte_config.kit.outDir}/generated/root.svelte`))}`
1519
- );
1520
-
1521
- const paths = await vite.ssrLoadModule(`${runtime_base}/paths.js`);
1522
-
1523
- paths.set_paths({
1524
- base: svelte_config.kit.paths.base,
1525
- assets
1526
- });
1527
-
1528
- let request;
1529
-
1530
- try {
1531
- request = await getRequest(base, req);
1532
- } catch (/** @type {any} */ err) {
1533
- res.statusCode = err.status || 400;
1534
- return res.end(err.reason || 'Invalid request body');
1535
- }
1536
-
1537
- const template = load_template(cwd$1, svelte_config);
1538
-
1539
- const rendered = await respond(
1540
- request,
1541
- {
1542
- csp: svelte_config.kit.csp,
1543
- dev: true,
1544
- get_stack: (error) => fix_stack_trace(error),
1545
- handle_error: (error, event) => {
1546
- hooks.handleError({
1547
- error: new Proxy(error, {
1548
- get: (target, property) => {
1549
- if (property === 'stack') {
1550
- return fix_stack_trace(error);
1551
- }
1552
-
1553
- return Reflect.get(target, property, target);
1554
- }
1555
- }),
1556
- event,
1557
-
1558
- // TODO remove for 1.0
1559
- // @ts-expect-error
1560
- get request() {
1561
- throw new Error(
1562
- 'request in handleError has been replaced with event. See https://github.com/sveltejs/kit/pull/3384 for details'
1563
- );
1564
- }
1565
- });
1566
- },
1567
- hooks,
1568
- hydrate: svelte_config.kit.browser.hydrate,
1569
- manifest,
1570
- method_override: svelte_config.kit.methodOverride,
1571
- paths: {
1572
- base: svelte_config.kit.paths.base,
1573
- assets
1574
- },
1575
- prefix: '',
1576
- prerender: {
1577
- default: svelte_config.kit.prerender.default,
1578
- enabled: svelte_config.kit.prerender.enabled
1579
- },
1580
- public_env: env.public,
1581
- read: (file) => fs__default.readFileSync(path__default.join(svelte_config.kit.files.assets, file)),
1582
- root,
1583
- router: svelte_config.kit.browser.router,
1584
- template: ({ head, body, assets, nonce }) => {
1585
- return (
1586
- template
1587
- .replace(/%sveltekit\.assets%/g, assets)
1588
- .replace(/%sveltekit\.nonce%/g, nonce)
1589
- // head and body must be replaced last, in case someone tries to sneak in %sveltekit.assets% etc
1590
- .replace('%sveltekit.head%', () => head)
1591
- .replace('%sveltekit.body%', () => body)
1592
- );
1593
- },
1594
- template_contains_nonce: template.includes('%sveltekit.nonce%'),
1595
- trailing_slash: svelte_config.kit.trailingSlash
1596
- },
1597
- {
1598
- getClientAddress: () => {
1599
- const { remoteAddress } = req.socket;
1600
- if (remoteAddress) return remoteAddress;
1601
- throw new Error('Could not determine clientAddress');
1602
- }
1603
- }
1604
- );
1605
-
1606
- if (rendered.status === 404) {
1607
- // @ts-expect-error
1608
- serve_static_middleware.handle(req, res, () => {
1609
- setResponse(res, rendered);
1610
- });
1611
- } else {
1612
- setResponse(res, rendered);
1613
- }
1614
- } catch (e) {
1615
- const error = coalesce_to_error(e);
1616
- res.statusCode = 500;
1617
- res.end(fix_stack_trace(error));
1618
- }
1619
- });
1620
- };
1621
- }
1622
-
1623
- /** @param {import('http').ServerResponse} res */
1624
- function not_found(res, message = 'Not found') {
1625
- res.statusCode = 404;
1626
- res.end(message);
1627
- }
1628
-
1629
- /**
1630
- * @param {import('connect').Server} server
1631
- */
1632
- function remove_static_middlewares(server) {
1633
- // We don't use viteServePublicMiddleware because of the following issues:
1634
- // https://github.com/vitejs/vite/issues/9260
1635
- // https://github.com/vitejs/vite/issues/9236
1636
- // https://github.com/vitejs/vite/issues/9234
1637
- const static_middlewares = ['viteServePublicMiddleware', 'viteServeStaticMiddleware'];
1638
- for (let i = server.stack.length - 1; i > 0; i--) {
1639
- // @ts-expect-error using internals
1640
- if (static_middlewares.includes(server.stack[i].handle.name)) {
1641
- server.stack.splice(i, 1);
1642
- }
1643
- }
1644
- }
1645
-
1646
- /**
1647
- * @param {import('vite').ViteDevServer} vite
1648
- * @param {import('vite').ModuleNode} node
1649
- * @param {Set<import('vite').ModuleNode>} deps
1650
- */
1651
- async function find_deps(vite, node, deps) {
1652
- // since `ssrTransformResult.deps` contains URLs instead of `ModuleNode`s, this process is asynchronous.
1653
- // instead of using `await`, we resolve all branches in parallel.
1654
- /** @type {Promise<void>[]} */
1655
- const branches = [];
1656
-
1657
- /** @param {import('vite').ModuleNode} node */
1658
- async function add(node) {
1659
- if (!deps.has(node)) {
1660
- deps.add(node);
1661
- await find_deps(vite, node, deps);
1662
- }
1663
- }
1664
-
1665
- /** @param {string} url */
1666
- async function add_by_url(url) {
1667
- const node = await vite.moduleGraph.getModuleByUrl(url);
1668
-
1669
- if (node) {
1670
- await add(node);
1671
- }
1672
- }
1673
-
1674
- if (node.ssrTransformResult) {
1675
- if (node.ssrTransformResult.deps) {
1676
- node.ssrTransformResult.deps.forEach((url) => branches.push(add_by_url(url)));
1677
- }
1678
-
1679
- if (node.ssrTransformResult.dynamicDeps) {
1680
- node.ssrTransformResult.dynamicDeps.forEach((url) => branches.push(add_by_url(url)));
1681
- }
1682
- } else {
1683
- node.importedModules.forEach((node) => branches.push(add(node)));
1684
- }
1685
-
1686
- await Promise.all(branches);
1687
- }
1688
-
1689
- /**
1690
- * Determine if a file is being requested with the correct case,
1691
- * to ensure consistent behaviour between dev and prod and across
1692
- * operating systems. Note that we can't use realpath here,
1693
- * because we don't want to follow symlinks
1694
- * @param {string} file
1695
- * @param {string} assets
1696
- * @returns {boolean}
1697
- */
1698
- function has_correct_case(file, assets) {
1699
- if (file === assets) return true;
1700
-
1701
- const parent = path__default.dirname(file);
1702
-
1703
- if (fs__default.readdirSync(parent).includes(path__default.basename(file))) {
1704
- return has_correct_case(parent, assets);
1705
- }
1706
-
1707
- return false;
1708
- }
1709
-
1710
- /**
1711
- * Generates the data used to write the server-side manifest.js file. This data is used in the Vite
1712
- * build process, to power routing, etc.
1713
- * @param {{
1714
- * build_data: import('types').BuildData;
1715
- * relative_path: string;
1716
- * routes: import('types').RouteData[];
1717
- * format?: 'esm' | 'cjs'
1718
- * }} opts
1719
- */
1720
- function generate_manifest({ build_data, relative_path, routes, format = 'esm' }) {
1721
- /** @typedef {{ index: number, path: string }} LookupEntry */
1722
- /** @type {Map<string, LookupEntry>} */
1723
- const bundled_nodes = new Map();
1724
-
1725
- // 0 and 1 are special, they correspond to the root layout and root error nodes
1726
- bundled_nodes.set(build_data.manifest_data.components[0], {
1727
- path: `${relative_path}/nodes/0.js`,
1728
- index: 0
1729
- });
1730
-
1731
- bundled_nodes.set(build_data.manifest_data.components[1], {
1732
- path: `${relative_path}/nodes/1.js`,
1733
- index: 1
1734
- });
1735
-
1736
- routes.forEach((route) => {
1737
- if (route.type === 'page') {
1738
- [...route.a, ...route.b].forEach((component) => {
1739
- if (component && !bundled_nodes.has(component)) {
1740
- const i = build_data.manifest_data.components.indexOf(component);
1741
-
1742
- bundled_nodes.set(component, {
1743
- path: `${relative_path}/nodes/${i}.js`,
1744
- index: bundled_nodes.size
1745
- });
1746
- }
1747
- });
1748
- }
1749
- });
1750
-
1751
- /** @type {(path: string) => string} */
1752
- const load =
1753
- format === 'esm'
1754
- ? (path) => `import('${path}')`
1755
- : (path) => `Promise.resolve().then(() => require('${path}'))`;
1756
-
1757
- /** @type {(path: string) => string} */
1758
- const loader = (path) => `() => ${load(path)}`;
1759
-
1760
- const assets = build_data.manifest_data.assets.map((asset) => asset.file);
1761
- if (build_data.service_worker) {
1762
- assets.push(build_data.service_worker);
1763
- }
1764
-
1765
- /** @param {string | undefined} id */
1766
- const get_index = (id) => id && /** @type {LookupEntry} */ (bundled_nodes.get(id)).index;
1767
-
1768
- const matchers = new Set();
1769
-
1770
- // prettier-ignore
1771
- return `{
1772
- appDir: ${s(build_data.app_dir)},
1773
- assets: new Set(${s(assets)}),
1774
- mimeTypes: ${s(get_mime_lookup(build_data.manifest_data))},
1775
- _: {
1776
- entry: ${s(build_data.client.entry)},
1777
- nodes: [
1778
- ${Array.from(bundled_nodes.values()).map(node => loader(node.path)).join(',\n\t\t\t\t')}
1779
- ],
1780
- routes: [
1781
- ${routes.map(route => {
1782
- const { pattern, names, types } = parse_route_id(route.id);
1783
-
1784
- types.forEach(type => {
1785
- if (type) matchers.add(type);
1786
- });
1787
-
1788
- if (route.type === 'page') {
1789
- return `{
1790
- type: 'page',
1791
- id: ${s(route.id)},
1792
- pattern: ${pattern},
1793
- names: ${s(names)},
1794
- types: ${s(types)},
1795
- path: ${route.path ? s(route.path) : null},
1796
- shadow: ${route.shadow ? loader(`${relative_path}/${build_data.server.vite_manifest[route.shadow].file}`) : null},
1797
- a: ${s(route.a.map(get_index))},
1798
- b: ${s(route.b.map(get_index))}
1799
- }`.replace(/^\t\t/gm, '');
1800
- } else {
1801
- if (!build_data.server.vite_manifest[route.file]) {
1802
- // this is necessary in cases where a .css file snuck in —
1803
- // perhaps it would be better to disallow these (and others?)
1804
- return null;
1805
- }
1806
-
1807
- return `{
1808
- type: 'endpoint',
1809
- id: ${s(route.id)},
1810
- pattern: ${pattern},
1811
- names: ${s(names)},
1812
- types: ${s(types)},
1813
- load: ${loader(`${relative_path}/${build_data.server.vite_manifest[route.file].file}`)}
1814
- }`.replace(/^\t\t/gm, '');
1815
- }
1816
- }).filter(Boolean).join(',\n\t\t\t\t')}
1817
- ],
1818
- matchers: async () => {
1819
- ${Array.from(matchers).map(type => `const { match: ${type} } = await ${load(`${relative_path}/entries/matchers/${type}.js`)}`).join('\n\t\t\t\t')}
1820
- return { ${Array.from(matchers).join(', ')} };
1821
- }
1822
- }
1823
- }`.replace(/^\t/gm, '');
1824
- }
1825
-
1826
- /** @typedef {import('http').IncomingMessage} Req */
1827
- /** @typedef {import('http').ServerResponse} Res */
1828
- /** @typedef {(req: Req, res: Res, next: () => void) => void} Handler */
1829
-
1830
- /**
1831
- * @param {{
1832
- * middlewares: import('connect').Server;
1833
- * httpServer: import('http').Server;
1834
- * }} vite
1835
- * @param {import('vite').ResolvedConfig} vite_config
1836
- * @param {import('types').ValidatedConfig} svelte_config
1837
- */
1838
- async function preview(vite, vite_config, svelte_config) {
1839
- installPolyfills();
1840
-
1841
- const { paths } = svelte_config.kit;
1842
- const base = paths.base;
1843
- const assets = paths.assets ? SVELTE_KIT_ASSETS : paths.base;
1844
-
1845
- const protocol = vite_config.preview.https ? 'https' : 'http';
1846
-
1847
- const etag = `"${Date.now()}"`;
1848
-
1849
- const index_file = join(svelte_config.kit.outDir, 'output/server/index.js');
1850
- const manifest_file = join(svelte_config.kit.outDir, 'output/server/manifest.js');
1851
-
1852
- /** @type {import('types').ServerModule} */
1853
- const { Server, override } = await import(pathToFileURL(index_file).href);
1854
- const { manifest } = await import(pathToFileURL(manifest_file).href);
1855
-
1856
- override({
1857
- paths: { base, assets },
1858
- prerendering: false,
1859
- protocol,
1860
- read: (file) => fs__default.readFileSync(join(svelte_config.kit.files.assets, file))
1861
- });
1862
-
1863
- const server = new Server(manifest);
1864
- server.init({
1865
- env: loadEnv(vite_config.mode, process.cwd(), '')
1866
- });
1867
-
1868
- return () => {
1869
- // generated client assets and the contents of `static`
1870
- vite.middlewares.use(
1871
- scoped(
1872
- assets,
1873
- sirv(join(svelte_config.kit.outDir, 'output/client'), {
1874
- setHeaders: (res, pathname) => {
1875
- // only apply to immutable directory, not e.g. version.json
1876
- if (pathname.startsWith(`/${svelte_config.kit.appDir}/immutable`)) {
1877
- res.setHeader('cache-control', 'public,max-age=31536000,immutable');
1878
- }
1879
- }
1880
- })
1881
- )
1882
- );
1883
-
1884
- vite.middlewares.use((req, res, next) => {
1885
- const original_url = /** @type {string} */ (req.url);
1886
- const { pathname } = new URL(original_url, 'http://dummy');
1887
-
1888
- if (pathname.startsWith(base)) {
1889
- next();
1890
- } else {
1891
- res.statusCode = 404;
1892
- res.end(`Not found (did you mean ${base + pathname}?)`);
1893
- }
1894
- });
1895
-
1896
- // prerendered dependencies
1897
- vite.middlewares.use(
1898
- scoped(base, mutable(join(svelte_config.kit.outDir, 'output/prerendered/dependencies')))
1899
- );
1900
-
1901
- // prerendered pages (we can't just use sirv because we need to
1902
- // preserve the correct trailingSlash behaviour)
1903
- vite.middlewares.use(
1904
- scoped(base, (req, res, next) => {
1905
- let if_none_match_value = req.headers['if-none-match'];
1906
-
1907
- if (if_none_match_value?.startsWith('W/"')) {
1908
- if_none_match_value = if_none_match_value.substring(2);
1909
- }
1910
-
1911
- if (if_none_match_value === etag) {
1912
- res.statusCode = 304;
1913
- res.end();
1914
- return;
1915
- }
1916
-
1917
- const { pathname } = new URL(/** @type {string} */ (req.url), 'http://dummy');
1918
-
1919
- // only treat this as a page if it doesn't include an extension
1920
- if (pathname === '/' || /\/[^./]+\/?$/.test(pathname)) {
1921
- const file = join(
1922
- svelte_config.kit.outDir,
1923
- 'output/prerendered/pages' +
1924
- pathname +
1925
- (pathname.endsWith('/') ? 'index.html' : '.html')
1926
- );
1927
-
1928
- if (fs__default.existsSync(file)) {
1929
- res.writeHead(200, {
1930
- 'content-type': 'text/html',
1931
- etag
1932
- });
1933
-
1934
- fs__default.createReadStream(file).pipe(res);
1935
- return;
1936
- }
1937
- }
1938
-
1939
- next();
1940
- })
1941
- );
1942
-
1943
- // SSR
1944
- vite.middlewares.use(async (req, res) => {
1945
- const host = req.headers['host'];
1946
-
1947
- let request;
1948
-
1949
- try {
1950
- request = await getRequest(`${protocol}://${host}`, req);
1951
- } catch (/** @type {any} */ err) {
1952
- res.statusCode = err.status || 400;
1953
- return res.end(err.reason || 'Invalid request body');
1954
- }
1955
-
1956
- setResponse(
1957
- res,
1958
- await server.respond(request, {
1959
- getClientAddress: () => {
1960
- const { remoteAddress } = req.socket;
1961
- if (remoteAddress) return remoteAddress;
1962
- throw new Error('Could not determine clientAddress');
1963
- }
1964
- })
1965
- );
1966
- });
1967
- };
1968
- }
1969
-
1970
- /**
1971
- * @param {string} dir
1972
- * @returns {Handler}
1973
- */
1974
- const mutable = (dir) =>
1975
- fs__default.existsSync(dir)
1976
- ? sirv(dir, {
1977
- etag: true,
1978
- maxAge: 0
1979
- })
1980
- : (_req, _res, next) => next();
1981
-
1982
- /**
1983
- * @param {string} scope
1984
- * @param {Handler} handler
1985
- * @returns {Handler}
1986
- */
1987
- function scoped(scope, handler) {
1988
- if (scope === '') return handler;
1989
-
1990
- return (req, res, next) => {
1991
- if (req.url?.startsWith(scope)) {
1992
- const original_url = req.url;
1993
- req.url = req.url.slice(scope.length);
1994
- handler(req, res, () => {
1995
- req.url = original_url;
1996
- next();
1997
- });
1998
- } else {
1999
- next();
2000
- }
2001
- };
2002
- }
2003
-
2004
- const cwd = process.cwd();
2005
-
2006
- /** @type {import('./types').EnforcedConfig} */
2007
- const enforced_config = {
2008
- appType: true,
2009
- base: true,
2010
- build: {
2011
- cssCodeSplit: true,
2012
- emptyOutDir: true,
2013
- lib: {
2014
- entry: true,
2015
- name: true,
2016
- formats: true
2017
- },
2018
- manifest: true,
2019
- outDir: true,
2020
- polyfillModulePreload: true,
2021
- rollupOptions: {
2022
- input: true,
2023
- output: {
2024
- format: true,
2025
- entryFileNames: true,
2026
- chunkFileNames: true,
2027
- assetFileNames: true
2028
- },
2029
- preserveEntrySignatures: true
2030
- },
2031
- ssr: true
2032
- },
2033
- publicDir: true,
2034
- resolve: {
2035
- alias: {
2036
- $app: true,
2037
- $lib: true,
2038
- '$service-worker': true
2039
- }
2040
- },
2041
- root: true
2042
- };
2043
-
2044
- /**
2045
- * @return {import('vite').Plugin[]}
2046
- */
2047
- function sveltekit() {
2048
- return [...svelte(), kit()];
2049
- }
2050
-
2051
- /**
2052
- * Returns the SvelteKit Vite plugin. Vite executes Rollup hooks as well as some of its own.
2053
- * Background reading is available at:
2054
- * - https://vitejs.dev/guide/api-plugin.html
2055
- * - https://rollupjs.org/guide/en/#plugin-development
2056
- *
2057
- * You can get an idea of the lifecycle by looking at the flow charts here:
2058
- * - https://rollupjs.org/guide/en/#build-hooks
2059
- * - https://rollupjs.org/guide/en/#output-generation-hooks
2060
- *
2061
- * @return {import('vite').Plugin}
2062
- */
2063
- function kit() {
2064
- /** @type {import('types').ValidatedConfig} */
2065
- let svelte_config;
2066
-
2067
- /** @type {import('vite').ResolvedConfig} */
2068
- let vite_config;
2069
-
2070
- /** @type {import('vite').ConfigEnv} */
2071
- let vite_config_env;
2072
-
2073
- /** @type {import('types').ManifestData} */
2074
- let manifest_data;
2075
-
2076
- /** @type {boolean} */
2077
- let is_build;
2078
-
2079
- /** @type {import('types').Logger} */
2080
- let log;
2081
-
2082
- /** @type {import('types').Prerendered} */
2083
- let prerendered;
2084
-
2085
- /** @type {import('types').BuildData} */
2086
- let build_data;
2087
-
2088
- /** @type {Set<string>} */
2089
- let illegal_imports;
2090
-
2091
- /** @type {string | undefined} */
2092
- let deferred_warning;
2093
-
2094
- /**
2095
- * @type {{
2096
- * build_dir: string;
2097
- * output_dir: string;
2098
- * client_out_dir: string;
2099
- * }}
2100
- */
2101
- let paths;
2102
-
2103
- let completed_build = false;
2104
-
2105
- function vite_client_build_config() {
2106
- /** @type {Record<string, string>} */
2107
- const input = {
2108
- // Put unchanging assets in immutable directory. We don't set that in the
2109
- // outDir so that other plugins can add mutable assets to the bundle
2110
- start: `${get_runtime_directory(svelte_config.kit)}/client/start.js`
2111
- };
2112
-
2113
- // This step is optional — Vite/Rollup will create the necessary chunks
2114
- // for everything regardless — but it means that entry chunks reflect
2115
- // their location in the source code, which is helpful for debugging
2116
- manifest_data.components.forEach((file) => {
2117
- const resolved = path.resolve(cwd, file);
2118
- const relative = decodeURIComponent(path.relative(svelte_config.kit.files.routes, resolved));
2119
-
2120
- const name = relative.startsWith('..')
2121
- ? path.basename(file)
2122
- : posixify(path.join('pages', relative));
2123
- input[name] = resolved;
2124
- });
2125
-
2126
- return get_default_config({
2127
- config: svelte_config,
2128
- input,
2129
- ssr: false,
2130
- outDir: `${paths.client_out_dir}`
2131
- });
2132
- }
2133
-
2134
- /**
2135
- * @param {import('rollup').OutputAsset[]} assets
2136
- * @param {import('rollup').OutputChunk[]} chunks
2137
- */
2138
- function client_build_info(assets, chunks) {
2139
- /** @type {import('vite').Manifest} */
2140
- const vite_manifest = JSON.parse(
2141
- fs$1.readFileSync(`${paths.client_out_dir}/manifest.json`, 'utf-8')
2142
- );
2143
-
2144
- const entry_id = posixify(
2145
- path.relative(cwd, `${get_runtime_directory(svelte_config.kit)}/client/start.js`)
2146
- );
2147
-
2148
- return {
2149
- assets,
2150
- chunks,
2151
- entry: find_deps$1(vite_manifest, entry_id, false),
2152
- vite_manifest
2153
- };
2154
- }
2155
-
2156
- // TODO remove this for 1.0
2157
- check_vite_version();
2158
-
2159
- return {
2160
- name: 'vite-plugin-svelte-kit',
2161
-
2162
- /**
2163
- * Build the SvelteKit-provided Vite config to be merged with the user's vite.config.js file.
2164
- * @see https://vitejs.dev/guide/api-plugin.html#config
2165
- */
2166
- async config(config, config_env) {
2167
- // The config is created in build_server for SSR mode and passed inline
2168
- if (config.build?.ssr) {
2169
- return;
2170
- }
2171
-
2172
- vite_config_env = config_env;
2173
- svelte_config = await load_config();
2174
- is_build = config_env.command === 'build';
2175
-
2176
- paths = {
2177
- build_dir: `${svelte_config.kit.outDir}/build`,
2178
- output_dir: `${svelte_config.kit.outDir}/output`,
2179
- client_out_dir: `${svelte_config.kit.outDir}/output/client/`
2180
- };
2181
-
2182
- illegal_imports = new Set([
2183
- vite.normalizePath(`${svelte_config.kit.outDir}/runtime/env/dynamic/private.js`),
2184
- vite.normalizePath(`${svelte_config.kit.outDir}/runtime/env/static/private.js`)
2185
- ]);
2186
-
2187
- if (is_build) {
2188
- manifest_data = all(svelte_config, config_env.mode).manifest_data;
2189
-
2190
- const new_config = vite_client_build_config();
2191
-
2192
- const warning = warn_overridden_config(config, new_config);
2193
- if (warning) console.error(warning + '\n');
2194
-
2195
- return new_config;
2196
- }
2197
-
2198
- // dev and preview config can be shared
2199
- /** @type {import('vite').UserConfig} */
2200
- const result = {
2201
- appType: 'custom',
2202
- base: '/',
2203
- build: {
2204
- rollupOptions: {
2205
- // Vite dependency crawler needs an explicit JS entry point
2206
- // eventhough server otherwise works without it
2207
- input: `${get_runtime_directory(svelte_config.kit)}/client/start.js`
2208
- }
2209
- },
2210
- define: {
2211
- __SVELTEKIT_DEV__: 'true',
2212
- __SVELTEKIT_APP_VERSION_POLL_INTERVAL__: '0'
2213
- },
2214
- publicDir: svelte_config.kit.files.assets,
2215
- resolve: {
2216
- alias: get_aliases(svelte_config.kit)
2217
- },
2218
- root: cwd,
2219
- server: {
2220
- fs: {
2221
- allow: [
2222
- ...new Set([
2223
- svelte_config.kit.files.lib,
2224
- svelte_config.kit.files.routes,
2225
- svelte_config.kit.outDir,
2226
- path.resolve(cwd, 'src'),
2227
- path.resolve(cwd, 'node_modules'),
2228
- path.resolve(vite.searchForWorkspaceRoot(cwd), 'node_modules')
2229
- ])
2230
- ]
2231
- },
2232
- watch: {
2233
- ignored: [
2234
- // Ignore all siblings of config.kit.outDir/generated
2235
- `${posixify(svelte_config.kit.outDir)}/!(generated)`
2236
- ]
2237
- }
2238
- }
2239
- };
2240
-
2241
- deferred_warning = warn_overridden_config(config, result);
2242
- return result;
2243
- },
2244
-
2245
- /**
2246
- * Stores the final config.
2247
- */
2248
- configResolved(config) {
2249
- vite_config = config;
2250
- },
2251
-
2252
- /**
2253
- * Clears the output directories.
2254
- */
2255
- buildStart() {
2256
- if (vite_config.build.ssr) {
2257
- return;
2258
- }
2259
-
2260
- // Reset for new build. Goes here because `build --watch` calls buildStart but not config
2261
- completed_build = false;
2262
-
2263
- if (is_build) {
2264
- rimraf(paths.build_dir);
2265
- mkdirp(paths.build_dir);
2266
-
2267
- rimraf(paths.output_dir);
2268
- mkdirp(paths.output_dir);
2269
- }
2270
- },
2271
-
2272
- /**
2273
- * Vite builds a single bundle. We need three bundles: client, server, and service worker.
2274
- * The user's package.json scripts will invoke the Vite CLI to execute the client build. We
2275
- * then use this hook to kick off builds for the server and service worker.
2276
- */
2277
- async writeBundle(_options, bundle) {
2278
- if (vite_config.build.ssr) {
2279
- return;
2280
- }
2281
-
2282
- for (const file of manifest_data.components) {
2283
- const id = vite.normalizePath(path.resolve(file));
2284
- const node = this.getModuleInfo(id);
2285
-
2286
- if (node) {
2287
- prevent_illegal_rollup_imports(
2288
- this.getModuleInfo.bind(this),
2289
- node,
2290
- illegal_imports,
2291
- svelte_config.kit.outDir
2292
- );
2293
- }
2294
- }
2295
-
2296
- const verbose = vite_config.logLevel === 'info';
2297
- log = logger({
2298
- verbose
2299
- });
2300
-
2301
- fs$1.writeFileSync(
2302
- `${paths.client_out_dir}/${svelte_config.kit.appDir}/version.json`,
2303
- JSON.stringify({ version: svelte_config.kit.version.name })
2304
- );
2305
-
2306
- const { assets, chunks } = collect_output(bundle);
2307
- log.info(`Client build completed. Wrote ${chunks.length} chunks and ${assets.length} assets`);
2308
-
2309
- log.info('Building server');
2310
- const options = {
2311
- cwd,
2312
- config: svelte_config,
2313
- vite_config,
2314
- vite_config_env,
2315
- build_dir: paths.build_dir, // TODO just pass `paths`
2316
- manifest_data,
2317
- output_dir: paths.output_dir,
2318
- service_worker_entry_file: resolve_entry(svelte_config.kit.files.serviceWorker)
2319
- };
2320
- const client = client_build_info(assets, chunks);
2321
- const server = await build_server(options, client);
2322
-
2323
- /** @type {import('types').BuildData} */
2324
- build_data = {
2325
- app_dir: svelte_config.kit.appDir,
2326
- manifest_data,
2327
- service_worker: options.service_worker_entry_file ? 'service-worker.js' : null, // TODO make file configurable?
2328
- client,
2329
- server
2330
- };
2331
-
2332
- const manifest_path = `${paths.output_dir}/server/manifest.js`;
2333
- fs$1.writeFileSync(
2334
- manifest_path,
2335
- `export const manifest = ${generate_manifest({
2336
- build_data,
2337
- relative_path: '.',
2338
- routes: manifest_data.routes
2339
- })};\n`
2340
- );
2341
-
2342
- log.info('Prerendering');
2343
- await new Promise((fulfil, reject) => {
2344
- const results_path = `${svelte_config.kit.outDir}/generated/prerendered.json`;
2345
-
2346
- // do prerendering in a subprocess so any dangling stuff gets killed upon completion
2347
- const script = fileURLToPath(
2348
- new URL(
2349
- './prerender.js' ,
2350
- import.meta.url
2351
- )
2352
- );
2353
-
2354
- const child = fork(
2355
- script,
2356
- [vite_config.build.outDir, results_path, manifest_path, '' + verbose],
2357
- {
2358
- stdio: 'inherit'
2359
- }
2360
- );
2361
-
2362
- child.on('exit', (code) => {
2363
- if (code) {
2364
- reject(new Error(`Prerendering failed with code ${code}`));
2365
- } else {
2366
- prerendered = JSON.parse(fs$1.readFileSync(results_path, 'utf8'), (key, value) => {
2367
- if (key === 'pages' || key === 'assets' || key === 'redirects') {
2368
- return new Map(value);
2369
- }
2370
- return value;
2371
- });
2372
- fulfil(undefined);
2373
- }
2374
- });
2375
- });
2376
-
2377
- if (options.service_worker_entry_file) {
2378
- if (svelte_config.kit.paths.assets) {
2379
- throw new Error('Cannot use service worker alongside config.kit.paths.assets');
2380
- }
2381
-
2382
- log.info('Building service worker');
2383
-
2384
- await build_service_worker(options, prerendered, client.vite_manifest);
2385
- }
2386
-
2387
- console.log(
2388
- `\nRun ${$.bold().cyan('npm run preview')} to preview your production build locally.`
2389
- );
2390
-
2391
- completed_build = true;
2392
- },
2393
-
2394
- /**
2395
- * Runs the adapter.
2396
- */
2397
- async closeBundle() {
2398
- // vite calls closeBundle when dev-server restarts, ignore that,
2399
- // and only adapt when build successfully completes.
2400
- const is_restart = !completed_build;
2401
- if (vite_config.build.ssr || is_restart) {
2402
- return;
2403
- }
2404
-
2405
- if (svelte_config.kit.adapter) {
2406
- const { adapt } = await import('./chunks/index3.js');
2407
- await adapt(svelte_config, build_data, prerendered, { log });
2408
- } else {
2409
- console.log($.bold().yellow('\nNo adapter specified'));
2410
- // prettier-ignore
2411
- console.log(
2412
- `See ${$.bold().cyan('https://kit.svelte.dev/docs/adapters')} to learn how to configure your app to run on the platform of your choosing`
2413
- );
2414
- }
2415
- },
2416
-
2417
- /**
2418
- * Adds the SvelteKit middleware to do SSR in dev mode.
2419
- * @see https://vitejs.dev/guide/api-plugin.html#configureserver
2420
- */
2421
- async configureServer(vite) {
2422
- // This method is called by Vite after clearing the screen.
2423
- // This patch ensures we can log any important messages afterwards for the user to see.
2424
- const print_urls = vite.printUrls;
2425
- vite.printUrls = function () {
2426
- print_urls.apply(this);
2427
- if (deferred_warning) console.error('\n' + deferred_warning);
2428
- };
2429
-
2430
- return await dev(vite, vite_config, svelte_config, illegal_imports);
2431
- },
2432
-
2433
- /**
2434
- * Adds the SvelteKit middleware to do SSR in preview mode.
2435
- * @see https://vitejs.dev/guide/api-plugin.html#configurepreviewserver
2436
- */
2437
- configurePreviewServer(vite) {
2438
- return preview(vite, vite_config, svelte_config);
2439
- }
2440
- };
2441
- }
2442
-
2443
- function check_vite_version() {
2444
- // TODO parse from kit peer deps and maybe do a full semver compare if we ever require feature releases a min
2445
- const min_required_vite_major = 3;
2446
- const vite_version = vite.version ?? '2.x'; // vite started exporting it's version in 3.0
2447
- const current_vite_major = parseInt(vite_version.split('.')[0], 10);
2448
-
2449
- if (current_vite_major < min_required_vite_major) {
2450
- throw new Error(
2451
- `Vite version ${current_vite_major} is no longer supported. Please upgrade to version ${min_required_vite_major}`
2452
- );
2453
- }
2454
- }
2455
-
2456
- /** @param {import('rollup').OutputBundle} bundle */
2457
- function collect_output(bundle) {
2458
- /** @type {import('rollup').OutputChunk[]} */
2459
- const chunks = [];
2460
- /** @type {import('rollup').OutputAsset[]} */
2461
- const assets = [];
2462
- for (const value of Object.values(bundle)) {
2463
- // collect asset and output chunks
2464
- if (value.type === 'asset') {
2465
- assets.push(value);
2466
- } else {
2467
- chunks.push(value);
2468
- }
2469
- }
2470
- return { assets, chunks };
2471
- }
2472
-
2473
- /**
2474
- * @param {Record<string, any>} config
2475
- * @param {Record<string, any>} resolved_config
2476
- */
2477
- function warn_overridden_config(config, resolved_config) {
2478
- const overridden = find_overridden_config(config, resolved_config, enforced_config, '', []);
2479
-
2480
- if (overridden.length > 0) {
2481
- return (
2482
- $.bold().red('The following Vite config options will be overridden by SvelteKit:') +
2483
- overridden.map((key) => `\n - ${key}`).join('')
2484
- );
2485
- }
2486
- }
2487
-
2488
- /**
2489
- * @param {Record<string, any>} config
2490
- * @param {Record<string, any>} resolved_config
2491
- * @param {import('./types').EnforcedConfig} enforced_config
2492
- * @param {string} path
2493
- * @param {string[]} out used locally to compute the return value
2494
- */
2495
- function find_overridden_config(config, resolved_config, enforced_config, path, out) {
2496
- for (const key in enforced_config) {
2497
- if (typeof config === 'object' && config !== null && key in config) {
2498
- const enforced = enforced_config[key];
2499
-
2500
- if (enforced === true) {
2501
- if (config[key] !== resolved_config[key]) {
2502
- out.push(path + key);
2503
- }
2504
- } else {
2505
- find_overridden_config(config[key], resolved_config[key], enforced, path + key + '.', out);
2506
- }
2507
- }
2508
- }
2509
-
2510
- return out;
2511
- }
2512
-
2513
- export { generate_manifest as g, sveltekit };