@sveltejs/kit 1.0.0-next.42 → 1.0.0-next.422

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 (126) hide show
  1. package/README.md +12 -9
  2. package/package.json +95 -63
  3. package/src/cli.js +112 -0
  4. package/src/core/adapt/builder.js +207 -0
  5. package/src/core/adapt/index.js +19 -0
  6. package/src/core/config/index.js +86 -0
  7. package/src/core/config/options.js +482 -0
  8. package/src/core/config/types.d.ts +1 -0
  9. package/src/core/constants.js +5 -0
  10. package/src/core/env.js +91 -0
  11. package/src/core/generate_manifest/index.js +99 -0
  12. package/src/core/prerender/crawl.js +194 -0
  13. package/src/core/prerender/prerender.js +378 -0
  14. package/src/core/prerender/queue.js +80 -0
  15. package/src/core/sync/create_manifest_data/index.js +506 -0
  16. package/src/core/sync/create_manifest_data/types.d.ts +40 -0
  17. package/src/core/sync/sync.js +59 -0
  18. package/src/core/sync/utils.js +44 -0
  19. package/src/core/sync/write_ambient.js +27 -0
  20. package/src/core/sync/write_client_manifest.js +82 -0
  21. package/src/core/sync/write_matchers.js +25 -0
  22. package/src/core/sync/write_root.js +88 -0
  23. package/src/core/sync/write_tsconfig.js +189 -0
  24. package/src/core/sync/write_types.js +769 -0
  25. package/src/core/utils.js +58 -0
  26. package/src/hooks.js +26 -0
  27. package/src/index/index.js +45 -0
  28. package/src/index/private.js +33 -0
  29. package/src/node/index.js +145 -0
  30. package/src/node/polyfills.js +40 -0
  31. package/src/runtime/app/env.js +11 -0
  32. package/src/runtime/app/navigation.js +22 -0
  33. package/src/runtime/app/paths.js +1 -0
  34. package/src/runtime/app/stores.js +91 -0
  35. package/src/runtime/client/ambient.d.ts +17 -0
  36. package/src/runtime/client/client.js +1258 -0
  37. package/src/runtime/client/fetcher.js +60 -0
  38. package/src/runtime/client/parse.js +36 -0
  39. package/src/runtime/client/singletons.js +11 -0
  40. package/src/runtime/client/start.js +46 -0
  41. package/src/runtime/client/types.d.ts +105 -0
  42. package/src/runtime/client/utils.js +113 -0
  43. package/src/runtime/components/error.svelte +16 -0
  44. package/{assets → src/runtime}/components/layout.svelte +0 -0
  45. package/src/runtime/env/dynamic/private.js +1 -0
  46. package/src/runtime/env/dynamic/public.js +1 -0
  47. package/src/runtime/env-private.js +7 -0
  48. package/src/runtime/env-public.js +7 -0
  49. package/src/runtime/env.js +6 -0
  50. package/src/runtime/hash.js +16 -0
  51. package/src/runtime/paths.js +11 -0
  52. package/src/runtime/server/endpoint.js +58 -0
  53. package/src/runtime/server/index.js +448 -0
  54. package/src/runtime/server/page/cookie.js +25 -0
  55. package/src/runtime/server/page/crypto.js +239 -0
  56. package/src/runtime/server/page/csp.js +249 -0
  57. package/src/runtime/server/page/fetch.js +266 -0
  58. package/src/runtime/server/page/index.js +416 -0
  59. package/src/runtime/server/page/load_data.js +127 -0
  60. package/src/runtime/server/page/render.js +359 -0
  61. package/src/runtime/server/page/respond_with_error.js +94 -0
  62. package/src/runtime/server/page/types.d.ts +44 -0
  63. package/src/runtime/server/utils.js +116 -0
  64. package/src/utils/error.js +22 -0
  65. package/src/utils/escape.js +104 -0
  66. package/src/utils/filesystem.js +108 -0
  67. package/src/utils/http.js +55 -0
  68. package/src/utils/misc.js +1 -0
  69. package/src/utils/routing.js +107 -0
  70. package/src/utils/url.js +97 -0
  71. package/src/vite/build/build_server.js +337 -0
  72. package/src/vite/build/build_service_worker.js +90 -0
  73. package/src/vite/build/utils.js +157 -0
  74. package/src/vite/dev/index.js +568 -0
  75. package/src/vite/index.js +566 -0
  76. package/src/vite/preview/index.js +186 -0
  77. package/src/vite/types.d.ts +3 -0
  78. package/src/vite/utils.js +334 -0
  79. package/svelte-kit.js +1 -1
  80. package/types/ambient.d.ts +355 -0
  81. package/types/index.d.ts +342 -0
  82. package/types/internal.d.ts +308 -0
  83. package/types/private.d.ts +209 -0
  84. package/CHANGELOG.md +0 -425
  85. package/assets/components/error.svelte +0 -13
  86. package/assets/runtime/app/env.js +0 -5
  87. package/assets/runtime/app/navigation.js +0 -41
  88. package/assets/runtime/app/paths.js +0 -1
  89. package/assets/runtime/app/stores.js +0 -93
  90. package/assets/runtime/chunks/utils.js +0 -19
  91. package/assets/runtime/internal/singletons.js +0 -23
  92. package/assets/runtime/internal/start.js +0 -770
  93. package/assets/runtime/paths.js +0 -12
  94. package/dist/api.js +0 -28
  95. package/dist/api.js.map +0 -1
  96. package/dist/chunks/index.js +0 -3521
  97. package/dist/chunks/index2.js +0 -587
  98. package/dist/chunks/index3.js +0 -246
  99. package/dist/chunks/index4.js +0 -530
  100. package/dist/chunks/index5.js +0 -761
  101. package/dist/chunks/index6.js +0 -322
  102. package/dist/chunks/standard.js +0 -99
  103. package/dist/chunks/utils.js +0 -83
  104. package/dist/cli.js +0 -546
  105. package/dist/cli.js.map +0 -1
  106. package/dist/create_app.js +0 -592
  107. package/dist/create_app.js.map +0 -1
  108. package/dist/index.js +0 -392
  109. package/dist/index.js.map +0 -1
  110. package/dist/index2.js +0 -3519
  111. package/dist/index2.js.map +0 -1
  112. package/dist/index3.js +0 -320
  113. package/dist/index3.js.map +0 -1
  114. package/dist/index4.js +0 -323
  115. package/dist/index4.js.map +0 -1
  116. package/dist/index5.js +0 -247
  117. package/dist/index5.js.map +0 -1
  118. package/dist/index6.js +0 -761
  119. package/dist/index6.js.map +0 -1
  120. package/dist/renderer.js +0 -2499
  121. package/dist/renderer.js.map +0 -1
  122. package/dist/ssr.js +0 -2581
  123. package/dist/standard.js +0 -100
  124. package/dist/standard.js.map +0 -1
  125. package/dist/utils.js +0 -84
  126. package/dist/utils.js.map +0 -1
@@ -0,0 +1,568 @@
1
+ import fs from 'fs';
2
+ import colors from 'kleur';
3
+ import path from 'path';
4
+ import sirv from 'sirv';
5
+ import { URL } from 'url';
6
+ import { getRequest, setResponse } from '../../node/index.js';
7
+ import { installPolyfills } from '../../node/polyfills.js';
8
+ import { coalesce_to_error } from '../../utils/error.js';
9
+ import { posixify } from '../../utils/filesystem.js';
10
+ import { parse_route_id } from '../../utils/routing.js';
11
+ import { load_template } from '../../core/config/index.js';
12
+ import { SVELTE_KIT_ASSETS } from '../../core/constants.js';
13
+ import * as sync from '../../core/sync/sync.js';
14
+ import { get_mime_lookup, runtime_directory, runtime_prefix } from '../../core/utils.js';
15
+ import { get_env, prevent_illegal_vite_imports, resolve_entry } from '../utils.js';
16
+
17
+ // Vite doesn't expose this so we just copy the list for now
18
+ // https://github.com/vitejs/vite/blob/3edd1af56e980aef56641a5a51cf2932bb580d41/packages/vite/src/node/plugins/css.ts#L96
19
+ const style_pattern = /\.(css|less|sass|scss|styl|stylus|pcss|postcss)$/;
20
+
21
+ const cwd = process.cwd();
22
+
23
+ /**
24
+ * @param {import('vite').ViteDevServer} vite
25
+ * @param {import('vite').ResolvedConfig} vite_config
26
+ * @param {import('types').ValidatedConfig} svelte_config
27
+ * @param {Set<string>} illegal_imports
28
+ * @return {Promise<Promise<() => void>>}
29
+ */
30
+ export async function dev(vite, vite_config, svelte_config, illegal_imports) {
31
+ installPolyfills();
32
+
33
+ sync.init(svelte_config, vite_config.mode);
34
+
35
+ /** @type {import('types').Respond} */
36
+ const respond = (await import(`${runtime_prefix}/server/index.js`)).respond;
37
+
38
+ /** @type {import('types').ManifestData} */
39
+ let manifest_data;
40
+ /** @type {import('types').SSRManifest} */
41
+ let manifest;
42
+
43
+ const extensions = [...svelte_config.extensions, ...svelte_config.kit.moduleExtensions];
44
+
45
+ /** @param {string} id */
46
+ async function resolve(id) {
47
+ const url = id.startsWith('..') ? `/@fs${path.posix.resolve(id)}` : `/${id}`;
48
+
49
+ const module = await vite.ssrLoadModule(url);
50
+
51
+ const module_node = await vite.moduleGraph.getModuleByUrl(url);
52
+ if (!module_node) throw new Error(`Could not find node for ${url}`);
53
+
54
+ return { module, module_node, url };
55
+ }
56
+
57
+ async function update_manifest() {
58
+ ({ manifest_data } = await sync.create(svelte_config));
59
+
60
+ manifest = {
61
+ appDir: svelte_config.kit.appDir,
62
+ assets: new Set(manifest_data.assets.map((asset) => asset.file)),
63
+ mimeTypes: get_mime_lookup(manifest_data),
64
+ _: {
65
+ entry: {
66
+ file: `/@fs${runtime_prefix}/client/start.js`,
67
+ imports: [],
68
+ stylesheets: []
69
+ },
70
+ nodes: manifest_data.nodes.map((node, index) => {
71
+ return async () => {
72
+ /** @type {import('types').SSRNode} */
73
+ const result = {};
74
+
75
+ /** @type {import('vite').ModuleNode[]} */
76
+ const module_nodes = [];
77
+
78
+ result.index = index;
79
+
80
+ // these are unused in dev, it's easier to include them
81
+ result.imports = [];
82
+ result.stylesheets = [];
83
+
84
+ if (node.component) {
85
+ result.component = async () => {
86
+ const { module_node, module, url } = await resolve(
87
+ /** @type {string} */ (node.component)
88
+ );
89
+
90
+ module_nodes.push(module_node);
91
+ result.file = url.endsWith('.svelte') ? url : url + '?import'; // TODO what is this for?
92
+
93
+ prevent_illegal_vite_imports(
94
+ module_node,
95
+ illegal_imports,
96
+ extensions,
97
+ svelte_config.kit.outDir
98
+ );
99
+
100
+ return module.default;
101
+ };
102
+ }
103
+
104
+ if (node.shared) {
105
+ const { module, module_node } = await resolve(node.shared);
106
+
107
+ module_nodes.push(module_node);
108
+
109
+ result.shared = module;
110
+
111
+ prevent_illegal_vite_imports(
112
+ module_node,
113
+ illegal_imports,
114
+ extensions,
115
+ svelte_config.kit.outDir
116
+ );
117
+ }
118
+
119
+ if (node.server) {
120
+ const { module } = await resolve(node.server);
121
+ result.server = module;
122
+ result.server_id = node.server;
123
+ }
124
+
125
+ // in dev we inline all styles to avoid FOUC. this gets populated lazily so that
126
+ // components/stylesheets loaded via import() during `load` are included
127
+ result.inline_styles = async () => {
128
+ const deps = new Set();
129
+
130
+ for (const module_node of module_nodes) {
131
+ await find_deps(vite, module_node, deps);
132
+ }
133
+
134
+ /** @type {Record<string, string>} */
135
+ const styles = {};
136
+
137
+ for (const dep of deps) {
138
+ const parsed = new URL(dep.url, 'http://localhost/');
139
+ const query = parsed.searchParams;
140
+
141
+ if (
142
+ style_pattern.test(dep.file) ||
143
+ (query.has('svelte') && query.get('type') === 'style')
144
+ ) {
145
+ try {
146
+ const mod = await vite.ssrLoadModule(dep.url);
147
+ styles[dep.url] = mod.default;
148
+ } catch {
149
+ // this can happen with dynamically imported modules, I think
150
+ // because the Vite module graph doesn't distinguish between
151
+ // static and dynamic imports? TODO investigate, submit fix
152
+ }
153
+ }
154
+ }
155
+
156
+ return styles;
157
+ };
158
+
159
+ return result;
160
+ };
161
+ }),
162
+ routes: manifest_data.routes.map((route) => {
163
+ const { pattern, names, types } = parse_route_id(route.id);
164
+
165
+ if (route.type === 'page') {
166
+ return {
167
+ type: 'page',
168
+ id: route.id,
169
+ pattern,
170
+ names,
171
+ types,
172
+ errors: route.errors.map((id) => (id ? manifest_data.nodes.indexOf(id) : undefined)),
173
+ layouts: route.layouts.map((id) =>
174
+ id ? manifest_data.nodes.indexOf(id) : undefined
175
+ ),
176
+ leaf: manifest_data.nodes.indexOf(route.leaf)
177
+ };
178
+ }
179
+
180
+ return {
181
+ type: 'endpoint',
182
+ id: route.id,
183
+ pattern,
184
+ names,
185
+ types,
186
+ load: async () => {
187
+ const url = path.resolve(cwd, route.file);
188
+ return await vite.ssrLoadModule(url);
189
+ }
190
+ };
191
+ }),
192
+ matchers: async () => {
193
+ /** @type {Record<string, import('types').ParamMatcher>} */
194
+ const matchers = {};
195
+
196
+ for (const key in manifest_data.matchers) {
197
+ const file = manifest_data.matchers[key];
198
+ const url = path.resolve(cwd, file);
199
+ const module = await vite.ssrLoadModule(url);
200
+
201
+ if (module.match) {
202
+ matchers[key] = module.match;
203
+ } else {
204
+ throw new Error(`${file} does not export a \`match\` function`);
205
+ }
206
+ }
207
+
208
+ return matchers;
209
+ }
210
+ }
211
+ };
212
+ }
213
+
214
+ /** @param {Error} error */
215
+ function fix_stack_trace(error) {
216
+ return error.stack ? vite.ssrRewriteStacktrace(error.stack) : error.stack;
217
+ }
218
+
219
+ await update_manifest();
220
+
221
+ /**
222
+ * @param {string} event
223
+ * @param {(file: string) => void} cb
224
+ */
225
+ const watch = (event, cb) => {
226
+ vite.watcher.on(event, (file) => {
227
+ if (file.startsWith(svelte_config.kit.files.routes + path.sep)) {
228
+ cb(file);
229
+ }
230
+ });
231
+ };
232
+ /** @type {NodeJS.Timeout | null } */
233
+ let timeout = null;
234
+ /** @param {() => void} to_run */
235
+ const debounce = (to_run) => {
236
+ timeout && clearTimeout(timeout);
237
+ timeout = setTimeout(() => {
238
+ timeout = null;
239
+ to_run();
240
+ }, 100);
241
+ };
242
+ // Debounce add/unlink events because in case of folder deletion or moves
243
+ // they fire in rapid succession, causing needless invocations.
244
+ watch('add', () => debounce(update_manifest));
245
+ watch('unlink', () => debounce(update_manifest));
246
+ watch('change', (file) => {
247
+ // Don't run for a single file if the whole manifest is about to get updated
248
+ if (!timeout) {
249
+ sync.update(svelte_config, manifest_data, file);
250
+ }
251
+ });
252
+
253
+ const assets = svelte_config.kit.paths.assets ? SVELTE_KIT_ASSETS : svelte_config.kit.paths.base;
254
+ const asset_server = sirv(svelte_config.kit.files.assets, {
255
+ dev: true,
256
+ etag: true,
257
+ maxAge: 0,
258
+ extensions: []
259
+ });
260
+
261
+ vite.middlewares.use(async (req, res, next) => {
262
+ try {
263
+ const base = `${vite.config.server.https ? 'https' : 'http'}://${
264
+ req.headers[':authority'] || req.headers.host
265
+ }`;
266
+
267
+ const decoded = decodeURI(new URL(base + req.url).pathname);
268
+
269
+ if (decoded.startsWith(assets)) {
270
+ const pathname = decoded.slice(assets.length);
271
+ const file = svelte_config.kit.files.assets + pathname;
272
+
273
+ if (fs.existsSync(file) && !fs.statSync(file).isDirectory()) {
274
+ if (has_correct_case(file, svelte_config.kit.files.assets)) {
275
+ req.url = encodeURI(pathname); // don't need query/hash
276
+ asset_server(req, res);
277
+ return;
278
+ }
279
+ }
280
+ }
281
+
282
+ next();
283
+ } catch (e) {
284
+ const error = coalesce_to_error(e);
285
+ res.statusCode = 500;
286
+ res.end(fix_stack_trace(error));
287
+ }
288
+ });
289
+
290
+ const runtime_base = runtime_directory.startsWith(process.cwd())
291
+ ? `/${path.relative('.', runtime_directory)}`
292
+ : `/@fs${
293
+ // Windows/Linux separation - Windows starts with a drive letter, we need a / in front there
294
+ runtime_directory.startsWith('/') ? '' : '/'
295
+ }${runtime_directory}`;
296
+
297
+ const { set_private_env } = await vite.ssrLoadModule(`${runtime_base}/env-private.js`);
298
+ const { set_public_env } = await vite.ssrLoadModule(`${runtime_base}/env-public.js`);
299
+
300
+ const env = get_env(vite_config.mode, svelte_config.kit.env.publicPrefix);
301
+ set_private_env(env.private);
302
+ set_public_env(env.public);
303
+
304
+ return () => {
305
+ const serve_static_middleware = vite.middlewares.stack.find(
306
+ (middleware) =>
307
+ /** @type {function} */ (middleware.handle).name === 'viteServeStaticMiddleware'
308
+ );
309
+
310
+ remove_static_middlewares(vite.middlewares);
311
+
312
+ vite.middlewares.use(async (req, res) => {
313
+ try {
314
+ const base = `${vite.config.server.https ? 'https' : 'http'}://${
315
+ req.headers[':authority'] || req.headers.host
316
+ }`;
317
+
318
+ const decoded = decodeURI(new URL(base + req.url).pathname);
319
+ const file = posixify(path.resolve(decoded.slice(1)));
320
+ const is_file = fs.existsSync(file) && !fs.statSync(file).isDirectory();
321
+ const allowed =
322
+ !vite_config.server.fs.strict ||
323
+ vite_config.server.fs.allow.some((dir) => file.startsWith(dir));
324
+
325
+ if (is_file && allowed) {
326
+ // @ts-expect-error
327
+ serve_static_middleware.handle(req, res);
328
+ return;
329
+ }
330
+
331
+ if (!decoded.startsWith(svelte_config.kit.paths.base)) {
332
+ return not_found(
333
+ res,
334
+ `Not found (did you mean ${svelte_config.kit.paths.base + req.url}?)`
335
+ );
336
+ }
337
+
338
+ /** @type {Partial<import('types').Hooks>} */
339
+ const user_hooks = resolve_entry(svelte_config.kit.files.hooks)
340
+ ? await vite.ssrLoadModule(`/${svelte_config.kit.files.hooks}`)
341
+ : {};
342
+
343
+ const handle = user_hooks.handle || (({ event, resolve }) => resolve(event));
344
+
345
+ /** @type {import('types').Hooks} */
346
+ const hooks = {
347
+ handle,
348
+ handleError:
349
+ user_hooks.handleError ||
350
+ (({ /** @type {Error & { frame?: string }} */ error }) => {
351
+ console.error(colors.bold().red(error.message));
352
+ if (error.frame) {
353
+ console.error(colors.gray(error.frame));
354
+ }
355
+ if (error.stack) {
356
+ console.error(colors.gray(error.stack));
357
+ }
358
+ }),
359
+ externalFetch: user_hooks.externalFetch || fetch
360
+ };
361
+
362
+ if (/** @type {any} */ (hooks).getContext) {
363
+ // TODO remove this for 1.0
364
+ throw new Error(
365
+ 'The getContext hook has been removed. See https://kit.svelte.dev/docs/hooks'
366
+ );
367
+ }
368
+
369
+ if (/** @type {any} */ (hooks).serverFetch) {
370
+ // TODO remove this for 1.0
371
+ throw new Error('The serverFetch hook has been renamed to externalFetch.');
372
+ }
373
+
374
+ // TODO the / prefix will probably fail if outDir is outside the cwd (which
375
+ // could be the case in a monorepo setup), but without it these modules
376
+ // can get loaded twice via different URLs, which causes failures. Might
377
+ // require changes to Vite to fix
378
+ const { default: root } = await vite.ssrLoadModule(
379
+ `/${posixify(path.relative(cwd, `${svelte_config.kit.outDir}/generated/root.svelte`))}`
380
+ );
381
+
382
+ const paths = await vite.ssrLoadModule(`${runtime_base}/paths.js`);
383
+
384
+ paths.set_paths({
385
+ base: svelte_config.kit.paths.base,
386
+ assets
387
+ });
388
+
389
+ let request;
390
+
391
+ try {
392
+ request = await getRequest(base, req);
393
+ } catch (/** @type {any} */ err) {
394
+ res.statusCode = err.status || 400;
395
+ return res.end(err.reason || 'Invalid request body');
396
+ }
397
+
398
+ const template = load_template(cwd, svelte_config);
399
+
400
+ const rendered = await respond(
401
+ request,
402
+ {
403
+ csp: svelte_config.kit.csp,
404
+ dev: true,
405
+ get_stack: (error) => fix_stack_trace(error),
406
+ handle_error: (error, event) => {
407
+ hooks.handleError({
408
+ error: new Proxy(error, {
409
+ get: (target, property) => {
410
+ if (property === 'stack') {
411
+ return fix_stack_trace(error);
412
+ }
413
+
414
+ return Reflect.get(target, property, target);
415
+ }
416
+ }),
417
+ event,
418
+
419
+ // TODO remove for 1.0
420
+ // @ts-expect-error
421
+ get request() {
422
+ throw new Error(
423
+ 'request in handleError has been replaced with event. See https://github.com/sveltejs/kit/pull/3384 for details'
424
+ );
425
+ }
426
+ });
427
+ },
428
+ hooks,
429
+ hydrate: svelte_config.kit.browser.hydrate,
430
+ manifest,
431
+ method_override: svelte_config.kit.methodOverride,
432
+ paths: {
433
+ base: svelte_config.kit.paths.base,
434
+ assets
435
+ },
436
+ prerender: {
437
+ default: svelte_config.kit.prerender.default,
438
+ enabled: svelte_config.kit.prerender.enabled
439
+ },
440
+ public_env: env.public,
441
+ read: (file) => fs.readFileSync(path.join(svelte_config.kit.files.assets, file)),
442
+ root,
443
+ router: svelte_config.kit.browser.router,
444
+ template: ({ head, body, assets, nonce }) => {
445
+ return (
446
+ template
447
+ .replace(/%sveltekit\.assets%/g, assets)
448
+ .replace(/%sveltekit\.nonce%/g, nonce)
449
+ // head and body must be replaced last, in case someone tries to sneak in %sveltekit.assets% etc
450
+ .replace('%sveltekit.head%', () => head)
451
+ .replace('%sveltekit.body%', () => body)
452
+ );
453
+ },
454
+ template_contains_nonce: template.includes('%sveltekit.nonce%'),
455
+ trailing_slash: svelte_config.kit.trailingSlash
456
+ },
457
+ {
458
+ getClientAddress: () => {
459
+ const { remoteAddress } = req.socket;
460
+ if (remoteAddress) return remoteAddress;
461
+ throw new Error('Could not determine clientAddress');
462
+ }
463
+ }
464
+ );
465
+
466
+ if (rendered.status === 404) {
467
+ // @ts-expect-error
468
+ serve_static_middleware.handle(req, res, () => {
469
+ setResponse(res, rendered);
470
+ });
471
+ } else {
472
+ setResponse(res, rendered);
473
+ }
474
+ } catch (e) {
475
+ const error = coalesce_to_error(e);
476
+ res.statusCode = 500;
477
+ res.end(fix_stack_trace(error));
478
+ }
479
+ });
480
+ };
481
+ }
482
+
483
+ /** @param {import('http').ServerResponse} res */
484
+ function not_found(res, message = 'Not found') {
485
+ res.statusCode = 404;
486
+ res.end(message);
487
+ }
488
+
489
+ /**
490
+ * @param {import('connect').Server} server
491
+ */
492
+ function remove_static_middlewares(server) {
493
+ // We don't use viteServePublicMiddleware because of the following issues:
494
+ // https://github.com/vitejs/vite/issues/9260
495
+ // https://github.com/vitejs/vite/issues/9236
496
+ // https://github.com/vitejs/vite/issues/9234
497
+ const static_middlewares = ['viteServePublicMiddleware', 'viteServeStaticMiddleware'];
498
+ for (let i = server.stack.length - 1; i > 0; i--) {
499
+ // @ts-expect-error using internals
500
+ if (static_middlewares.includes(server.stack[i].handle.name)) {
501
+ server.stack.splice(i, 1);
502
+ }
503
+ }
504
+ }
505
+
506
+ /**
507
+ * @param {import('vite').ViteDevServer} vite
508
+ * @param {import('vite').ModuleNode} node
509
+ * @param {Set<import('vite').ModuleNode>} deps
510
+ */
511
+ async function find_deps(vite, node, deps) {
512
+ // since `ssrTransformResult.deps` contains URLs instead of `ModuleNode`s, this process is asynchronous.
513
+ // instead of using `await`, we resolve all branches in parallel.
514
+ /** @type {Promise<void>[]} */
515
+ const branches = [];
516
+
517
+ /** @param {import('vite').ModuleNode} node */
518
+ async function add(node) {
519
+ if (!deps.has(node)) {
520
+ deps.add(node);
521
+ await find_deps(vite, node, deps);
522
+ }
523
+ }
524
+
525
+ /** @param {string} url */
526
+ async function add_by_url(url) {
527
+ const node = await vite.moduleGraph.getModuleByUrl(url);
528
+
529
+ if (node) {
530
+ await add(node);
531
+ }
532
+ }
533
+
534
+ if (node.ssrTransformResult) {
535
+ if (node.ssrTransformResult.deps) {
536
+ node.ssrTransformResult.deps.forEach((url) => branches.push(add_by_url(url)));
537
+ }
538
+
539
+ if (node.ssrTransformResult.dynamicDeps) {
540
+ node.ssrTransformResult.dynamicDeps.forEach((url) => branches.push(add_by_url(url)));
541
+ }
542
+ } else {
543
+ node.importedModules.forEach((node) => branches.push(add(node)));
544
+ }
545
+
546
+ await Promise.all(branches);
547
+ }
548
+
549
+ /**
550
+ * Determine if a file is being requested with the correct case,
551
+ * to ensure consistent behaviour between dev and prod and across
552
+ * operating systems. Note that we can't use realpath here,
553
+ * because we don't want to follow symlinks
554
+ * @param {string} file
555
+ * @param {string} assets
556
+ * @returns {boolean}
557
+ */
558
+ function has_correct_case(file, assets) {
559
+ if (file === assets) return true;
560
+
561
+ const parent = path.dirname(file);
562
+
563
+ if (fs.readdirSync(parent).includes(path.basename(file))) {
564
+ return has_correct_case(parent, assets);
565
+ }
566
+
567
+ return false;
568
+ }