@sveltejs/kit 1.0.0-next.41 → 1.0.0-next.410

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