@sveltejs/kit 1.0.0-next.47 → 1.0.0-next.472

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