@sveltejs/kit 1.0.0-next.46 → 1.0.0-next.460

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 (115) hide show
  1. package/README.md +12 -9
  2. package/package.json +93 -65
  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 +498 -0
  15. package/src/core/config/types.d.ts +1 -0
  16. package/src/core/env.js +112 -0
  17. package/src/core/generate_manifest/index.js +78 -0
  18. package/src/core/prerender/crawl.js +194 -0
  19. package/src/core/prerender/prerender.js +425 -0
  20. package/src/core/prerender/queue.js +80 -0
  21. package/src/core/sync/create_manifest_data/index.js +452 -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 +595 -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 +45 -0
  35. package/src/exports/node/index.js +145 -0
  36. package/src/exports/node/polyfills.js +40 -0
  37. package/src/exports/vite/build/build_server.js +349 -0
  38. package/src/exports/vite/build/build_service_worker.js +90 -0
  39. package/src/exports/vite/build/utils.js +160 -0
  40. package/src/exports/vite/dev/index.js +543 -0
  41. package/src/exports/vite/index.js +595 -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 +345 -0
  45. package/src/runtime/app/env.js +1 -0
  46. package/src/runtime/app/environment.js +11 -0
  47. package/src/runtime/app/navigation.js +22 -0
  48. package/src/runtime/app/paths.js +1 -0
  49. package/src/runtime/app/stores.js +102 -0
  50. package/src/runtime/client/ambient.d.ts +24 -0
  51. package/src/runtime/client/client.js +1387 -0
  52. package/src/runtime/client/fetcher.js +60 -0
  53. package/src/runtime/client/parse.js +60 -0
  54. package/src/runtime/client/singletons.js +21 -0
  55. package/src/runtime/client/start.js +45 -0
  56. package/src/runtime/client/types.d.ts +88 -0
  57. package/src/runtime/client/utils.js +140 -0
  58. package/src/runtime/components/error.svelte +16 -0
  59. package/{assets → src/runtime}/components/layout.svelte +0 -0
  60. package/src/runtime/control.js +33 -0
  61. package/src/runtime/env/dynamic/private.js +1 -0
  62. package/src/runtime/env/dynamic/public.js +1 -0
  63. package/src/runtime/env-private.js +6 -0
  64. package/src/runtime/env-public.js +6 -0
  65. package/src/runtime/env.js +6 -0
  66. package/src/runtime/hash.js +16 -0
  67. package/src/runtime/paths.js +11 -0
  68. package/src/runtime/server/data/index.js +146 -0
  69. package/src/runtime/server/endpoint.js +63 -0
  70. package/src/runtime/server/index.js +339 -0
  71. package/src/runtime/server/page/cookie.js +25 -0
  72. package/src/runtime/server/page/crypto.js +239 -0
  73. package/src/runtime/server/page/csp.js +249 -0
  74. package/src/runtime/server/page/fetch.js +269 -0
  75. package/src/runtime/server/page/index.js +404 -0
  76. package/src/runtime/server/page/load_data.js +124 -0
  77. package/src/runtime/server/page/render.js +358 -0
  78. package/src/runtime/server/page/respond_with_error.js +92 -0
  79. package/src/runtime/server/page/serialize_data.js +58 -0
  80. package/src/runtime/server/page/types.d.ts +44 -0
  81. package/src/runtime/server/utils.js +209 -0
  82. package/src/utils/array.js +9 -0
  83. package/src/utils/error.js +22 -0
  84. package/src/utils/escape.js +46 -0
  85. package/src/utils/filesystem.js +108 -0
  86. package/src/utils/functions.js +16 -0
  87. package/src/utils/http.js +55 -0
  88. package/src/utils/misc.js +1 -0
  89. package/src/utils/routing.js +137 -0
  90. package/src/utils/url.js +142 -0
  91. package/svelte-kit.js +1 -1
  92. package/types/ambient.d.ts +332 -0
  93. package/types/index.d.ts +343 -0
  94. package/types/internal.d.ts +383 -0
  95. package/types/private.d.ts +213 -0
  96. package/CHANGELOG.md +0 -456
  97. package/assets/components/error.svelte +0 -13
  98. package/assets/runtime/app/env.js +0 -5
  99. package/assets/runtime/app/navigation.js +0 -44
  100. package/assets/runtime/app/paths.js +0 -1
  101. package/assets/runtime/app/stores.js +0 -93
  102. package/assets/runtime/chunks/utils.js +0 -22
  103. package/assets/runtime/internal/singletons.js +0 -23
  104. package/assets/runtime/internal/start.js +0 -771
  105. package/assets/runtime/paths.js +0 -12
  106. package/dist/chunks/index.js +0 -3522
  107. package/dist/chunks/index2.js +0 -587
  108. package/dist/chunks/index3.js +0 -246
  109. package/dist/chunks/index4.js +0 -539
  110. package/dist/chunks/index5.js +0 -763
  111. package/dist/chunks/index6.js +0 -322
  112. package/dist/chunks/standard.js +0 -99
  113. package/dist/chunks/utils.js +0 -83
  114. package/dist/cli.js +0 -546
  115. package/dist/ssr.js +0 -2581
@@ -0,0 +1,595 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import MagicString from 'magic-string';
4
+ import { posixify, rimraf, walk } from '../../../utils/filesystem.js';
5
+ import { compact } from '../../../utils/array.js';
6
+
7
+ /**
8
+ * @typedef {{
9
+ * modified: boolean;
10
+ * code: string;
11
+ * exports: any[];
12
+ * } | null} Proxy
13
+ */
14
+
15
+ /** @type {import('typescript')} */
16
+ // @ts-ignore
17
+ let ts = undefined;
18
+ try {
19
+ ts = (await import('typescript')).default;
20
+ } catch {}
21
+
22
+ const cwd = process.cwd();
23
+
24
+ const shared_names = new Set(['load']);
25
+ const server_names = new Set(['load', 'POST', 'PUT', 'PATCH', 'DELETE']); // TODO replace with a single `action`
26
+
27
+ /**
28
+ * Creates types for the whole manifest
29
+ * @param {import('types').ValidatedConfig} config
30
+ * @param {import('types').ManifestData} manifest_data
31
+ */
32
+ export async function write_all_types(config, manifest_data) {
33
+ if (!ts) return;
34
+
35
+ const types_dir = `${config.kit.outDir}/types`;
36
+
37
+ // empty out files that no longer need to exist
38
+ const routes_dir = path.relative('.', config.kit.files.routes);
39
+ const expected_directories = new Set(
40
+ manifest_data.routes.map((route) => path.join(routes_dir, route.id))
41
+ );
42
+
43
+ if (fs.existsSync(types_dir)) {
44
+ for (const file of walk(types_dir)) {
45
+ const dir = path.dirname(file);
46
+ if (!expected_directories.has(dir)) {
47
+ rimraf(file);
48
+ }
49
+ }
50
+ }
51
+
52
+ const routes_map = create_routes_map(manifest_data);
53
+ // For each directory, write $types.d.ts
54
+ for (const route of manifest_data.routes) {
55
+ update_types(config, routes_map, route);
56
+ }
57
+ }
58
+
59
+ /**
60
+ * Creates types related to the given file. This should only be called
61
+ * if the file in question was edited, not if it was created/deleted/moved.
62
+ * @param {import('types').ValidatedConfig} config
63
+ * @param {import('types').ManifestData} manifest_data
64
+ * @param {string} file
65
+ */
66
+ export async function write_types(config, manifest_data, file) {
67
+ if (!ts) return;
68
+
69
+ if (!path.basename(file).startsWith('+')) {
70
+ // Not a route file
71
+ return;
72
+ }
73
+
74
+ const id = path.relative(config.kit.files.routes, path.dirname(file));
75
+
76
+ const route = manifest_data.routes.find((route) => route.id === id);
77
+ if (!route) return; // this shouldn't ever happen
78
+
79
+ update_types(config, create_routes_map(manifest_data), route);
80
+ }
81
+
82
+ /**
83
+ * Collect all leafs into a leaf -> route map
84
+ * @param {import('types').ManifestData} manifest_data
85
+ */
86
+ function create_routes_map(manifest_data) {
87
+ /** @type {Map<import('types').PageNode, import('types').RouteData>} */
88
+ const map = new Map();
89
+ for (const route of manifest_data.routes) {
90
+ if (route.leaf) {
91
+ map.set(route.leaf, route);
92
+ }
93
+ }
94
+ return map;
95
+ }
96
+
97
+ /**
98
+ * Update types for a specific route
99
+ * @param {import('types').ValidatedConfig} config
100
+ * @param {Map<import('types').PageNode, import('types').RouteData>} routes
101
+ * @param {import('types').RouteData} route
102
+ */
103
+ function update_types(config, routes, route) {
104
+ if (!route.leaf && !route.layout && !route.endpoint) return; // nothing to do
105
+
106
+ const routes_dir = posixify(path.relative('.', config.kit.files.routes));
107
+ const outdir = path.join(config.kit.outDir, 'types', routes_dir, route.id);
108
+
109
+ // first, check if the types are out of date
110
+ const input_files = [];
111
+
112
+ /** @type {import('types').PageNode | null} */
113
+ let node = route.leaf;
114
+ while (node) {
115
+ if (node.shared) input_files.push(node.shared);
116
+ if (node.server) input_files.push(node.server);
117
+ node = node.parent ?? null;
118
+ }
119
+
120
+ /** @type {import('types').PageNode | null} */
121
+ node = route.layout;
122
+ while (node) {
123
+ if (node.shared) input_files.push(node.shared);
124
+ if (node.server) input_files.push(node.server);
125
+ node = node.parent ?? null;
126
+ }
127
+
128
+ if (route.endpoint) {
129
+ input_files.push(route.endpoint.file);
130
+ }
131
+
132
+ try {
133
+ fs.mkdirSync(outdir, { recursive: true });
134
+ } catch {}
135
+
136
+ const output_files = compact(
137
+ fs.readdirSync(outdir).map((name) => {
138
+ const stats = fs.statSync(path.join(outdir, name));
139
+ if (stats.isDirectory()) return;
140
+ return {
141
+ name,
142
+ updated: stats.mtimeMs
143
+ };
144
+ })
145
+ );
146
+
147
+ const source_last_updated = Math.max(...input_files.map((file) => fs.statSync(file).mtimeMs));
148
+ const types_last_updated = Math.max(...output_files.map((file) => file?.updated));
149
+
150
+ // types were generated more recently than the source files, so don't regenerate
151
+ if (types_last_updated > source_last_updated) return;
152
+
153
+ // track which old files end up being surplus to requirements
154
+ const to_delete = new Set(output_files.map((file) => file.name));
155
+
156
+ // now generate new types
157
+ const imports = [`import type * as Kit from '@sveltejs/kit';`];
158
+
159
+ /** @type {string[]} */
160
+ const declarations = [];
161
+
162
+ /** @type {string[]} */
163
+ const exports = [];
164
+
165
+ declarations.push(
166
+ `type RouteParams = { ${route.names.map((param) => `${param}: string`).join('; ')} }`
167
+ );
168
+
169
+ // These could also be placed in our public types, but it would bloat them unnecessarily and we may want to change these in the future
170
+ if (route.layout || route.leaf) {
171
+ // If T extends the empty object, void is also allowed as a return type
172
+ declarations.push(`type MaybeWithVoid<T> = {} extends T ? T | void : T;`);
173
+ // Returns the key of the object whose values are required.
174
+ declarations.push(
175
+ `export type RequiredKeys<T> = { [K in keyof T]-?: {} extends { [P in K]: T[K] } ? never : K; }[keyof T];`
176
+ );
177
+ // Helper type to get the correct output type for load functions. It should be passed the parent type to check what types from App.PageData are still required.
178
+ // If none, void is also allowed as a return type.
179
+ declarations.push(
180
+ `type OutputDataShape<T> = MaybeWithVoid<Omit<App.PageData, RequiredKeys<T>> & Partial<Pick<App.PageData, keyof T & keyof App.PageData>> & Record<string, any>>`
181
+ );
182
+ // null & {} == null, we need to prevent that in some situations
183
+ declarations.push(`type EnsureParentData<T> = T extends null | undefined ? {} : T;`);
184
+ }
185
+
186
+ if (route.leaf) {
187
+ const { declarations: d, exports: e, written_proxies } = process_node(route.leaf, outdir, true);
188
+
189
+ exports.push(...e);
190
+ declarations.push(...d);
191
+
192
+ for (const file of written_proxies) to_delete.delete(file);
193
+
194
+ if (route.leaf.server) {
195
+ exports.push(`export type Action = Kit.Action<RouteParams>`);
196
+ }
197
+ }
198
+
199
+ if (route.layout) {
200
+ let all_pages_have_load = true;
201
+ const layout_params = new Set();
202
+ route.layout.child_pages?.forEach((page) => {
203
+ const leaf = routes.get(page);
204
+ if (leaf) {
205
+ for (const name of leaf.names) {
206
+ layout_params.add(name);
207
+ }
208
+ }
209
+ if (!page.server && !page.shared) {
210
+ all_pages_have_load = false;
211
+ }
212
+ });
213
+
214
+ declarations.push(
215
+ `type LayoutParams = RouteParams & { ${Array.from(layout_params).map(
216
+ (param) => `${param}?: string`
217
+ )} }`
218
+ );
219
+
220
+ const {
221
+ exports: e,
222
+ declarations: d,
223
+ written_proxies
224
+ } = process_node(route.layout, outdir, false, all_pages_have_load);
225
+
226
+ exports.push(...e);
227
+ declarations.push(...d);
228
+
229
+ for (const file of written_proxies) to_delete.delete(file);
230
+ }
231
+
232
+ if (route.endpoint) {
233
+ exports.push(`export type RequestHandler = Kit.RequestHandler<RouteParams>;`);
234
+ exports.push(`export type RequestEvent = Kit.RequestEvent<RouteParams>;`);
235
+ }
236
+
237
+ const output = [imports.join('\n'), declarations.join('\n'), exports.join('\n')]
238
+ .filter(Boolean)
239
+ .join('\n\n');
240
+
241
+ fs.writeFileSync(`${outdir}/$types.d.ts`, output);
242
+ to_delete.delete('$types.d.ts');
243
+
244
+ for (const file of to_delete) {
245
+ fs.unlinkSync(path.join(outdir, file));
246
+ }
247
+ }
248
+
249
+ /**
250
+ * @param {import('types').PageNode} node
251
+ * @param {string} outdir
252
+ * @param {boolean} is_page
253
+ * @param {boolean} [all_pages_have_load]
254
+ */
255
+ function process_node(node, outdir, is_page, all_pages_have_load = true) {
256
+ const params = `${is_page ? 'Route' : 'Layout'}Params`;
257
+ const prefix = is_page ? 'Page' : 'Layout';
258
+
259
+ /** @type {string[]} */
260
+ let written_proxies = [];
261
+ /** @type {string[]} */
262
+ const declarations = [];
263
+ /** @type {string[]} */
264
+ const exports = [];
265
+
266
+ /** @type {string} */
267
+ let server_data;
268
+ /** @type {string} */
269
+ let data;
270
+
271
+ if (node.server) {
272
+ const content = fs.readFileSync(node.server, 'utf8');
273
+ const proxy = tweak_types(content, server_names);
274
+ const basename = path.basename(node.server);
275
+ if (proxy?.modified) {
276
+ fs.writeFileSync(`${outdir}/proxy${basename}`, proxy.code);
277
+ written_proxies.push(`proxy${basename}`);
278
+ }
279
+
280
+ server_data = get_data_type(node.server, 'null', proxy);
281
+
282
+ const parent_type = `${prefix}ServerParentData`;
283
+
284
+ declarations.push(`type ${parent_type} = ${get_parent_type(node, 'LayoutServerData')};`);
285
+
286
+ // +page.js load present -> server can return all-optional data
287
+ const output_data_shape =
288
+ node.shared || (!is_page && all_pages_have_load)
289
+ ? `Partial<App.PageData> & Record<string, any> | void`
290
+ : `OutputDataShape<${parent_type}>`;
291
+ exports.push(
292
+ `export type ${prefix}ServerLoad<OutputData extends ${output_data_shape} = ${output_data_shape}> = Kit.ServerLoad<${params}, ${parent_type}, OutputData>;`
293
+ );
294
+
295
+ exports.push(`export type ${prefix}ServerLoadEvent = Parameters<${prefix}ServerLoad>[0];`);
296
+
297
+ if (is_page) {
298
+ let errors = 'unknown';
299
+ if (proxy) {
300
+ const types = [];
301
+ for (const method of ['POST', 'PUT', 'PATCH', 'DELETE']) {
302
+ if (proxy.exports.includes(method)) {
303
+ // If the file wasn't tweaked, we can use the return type of the original file.
304
+ // The advantage is that type updates are reflected without saving.
305
+ const from = proxy.modified
306
+ ? `./proxy${replace_ext_with_js(basename)}`
307
+ : path_to_original(outdir, node.server);
308
+
309
+ types.push(`Kit.AwaitedErrors<typeof import('${from}').${method}>`);
310
+ }
311
+ }
312
+ errors = types.length ? types.join(' | ') : 'null';
313
+ }
314
+ exports.push(`export type Errors = ${errors};`);
315
+ }
316
+ } else {
317
+ server_data = 'null';
318
+ }
319
+ exports.push(`export type ${prefix}ServerData = ${server_data};`);
320
+
321
+ const parent_type = `${prefix}ParentData`;
322
+ declarations.push(`type ${parent_type} = ${get_parent_type(node, 'LayoutData')};`);
323
+
324
+ if (node.shared) {
325
+ const content = fs.readFileSync(node.shared, 'utf8');
326
+ const proxy = tweak_types(content, shared_names);
327
+ if (proxy?.modified) {
328
+ fs.writeFileSync(`${outdir}/proxy${path.basename(node.shared)}`, proxy.code);
329
+ written_proxies.push(`proxy${path.basename(node.shared)}`);
330
+ }
331
+
332
+ const type = get_data_type(node.shared, `${parent_type} & ${prefix}ServerData`, proxy);
333
+
334
+ data = `Omit<${parent_type}, keyof ${type}> & ${type}`;
335
+
336
+ const output_data_shape =
337
+ !is_page && all_pages_have_load
338
+ ? `Partial<App.PageData> & Record<string, any> | void`
339
+ : `OutputDataShape<${parent_type}>`;
340
+ exports.push(
341
+ `export type ${prefix}Load<OutputData extends ${output_data_shape} = ${output_data_shape}> = Kit.Load<${params}, ${prefix}ServerData, ${parent_type}, OutputData>;`
342
+ );
343
+
344
+ exports.push(`export type ${prefix}LoadEvent = Parameters<${prefix}Load>[0];`);
345
+ } else if (server_data === 'null') {
346
+ data = parent_type;
347
+ } else {
348
+ data = `Omit<${parent_type}, keyof ${prefix}ServerData> & ${prefix}ServerData`;
349
+ }
350
+
351
+ exports.push(`export type ${prefix}Data = ${data};`);
352
+
353
+ return { declarations, exports, written_proxies };
354
+
355
+ /**
356
+ * @param {string} file_path
357
+ * @param {string} fallback
358
+ * @param {Proxy} proxy
359
+ */
360
+ function get_data_type(file_path, fallback, proxy) {
361
+ if (proxy) {
362
+ if (proxy.exports.includes('load')) {
363
+ // If the file wasn't tweaked, we can use the return type of the original file.
364
+ // The advantage is that type updates are reflected without saving.
365
+ const from = proxy.modified
366
+ ? `./proxy${replace_ext_with_js(path.basename(file_path))}`
367
+ : path_to_original(outdir, file_path);
368
+ return `Kit.AwaitedProperties<Awaited<ReturnType<typeof import('${from}').load>>>`;
369
+ } else {
370
+ return fallback;
371
+ }
372
+ } else {
373
+ return 'unknown';
374
+ }
375
+ }
376
+ }
377
+
378
+ /**
379
+ * Get the parent type string by recursively looking up the parent layout and accumulate them to one type.
380
+ * @param {import('types').PageNode} node
381
+ * @param {string} type
382
+ */
383
+ function get_parent_type(node, type) {
384
+ const parent_imports = [];
385
+
386
+ let parent = node.parent;
387
+
388
+ while (parent) {
389
+ const d = node.depth - parent.depth;
390
+ // unshift because we need it the other way round for the import string
391
+ parent_imports.unshift(
392
+ `${d === 0 ? '' : `import('${'../'.repeat(d)}${'$types.js'}').`}${type}`
393
+ );
394
+ parent = parent.parent;
395
+ }
396
+
397
+ let parent_str = `EnsureParentData<${parent_imports[0] || '{}'}>`;
398
+ for (let i = 1; i < parent_imports.length; i++) {
399
+ // Omit is necessary because a parent could have a property with the same key which would
400
+ // cause a type conflict. At runtime the child overwrites the parent property in this case,
401
+ // so reflect that in the type definition.
402
+ // EnsureParentData is necessary because {something: string} & null becomes null.
403
+ // Output types of server loads can be null but when passed in through the `parent` parameter they are the empty object instead.
404
+ parent_str = `Omit<${parent_str}, keyof ${parent_imports[i]}> & EnsureParentData<${parent_imports[i]}>`;
405
+ }
406
+ return parent_str;
407
+ }
408
+
409
+ /**
410
+ * @param {string} outdir
411
+ * @param {string} file_path
412
+ */
413
+ function path_to_original(outdir, file_path) {
414
+ return posixify(path.relative(outdir, path.join(cwd, replace_ext_with_js(file_path))));
415
+ }
416
+
417
+ /**
418
+ * @param {string} file_path
419
+ */
420
+ function replace_ext_with_js(file_path) {
421
+ // Another extension than `.js` (or nothing, but that fails with node16 moduleResolution)
422
+ // will result in TS failing to lookup the file
423
+ const ext = path.extname(file_path);
424
+ return file_path.slice(0, -ext.length) + '.js';
425
+ }
426
+
427
+ /**
428
+ * @param {string} content
429
+ * @param {Set<string>} names
430
+ * @returns {Proxy}
431
+ */
432
+ export function tweak_types(content, names) {
433
+ try {
434
+ let modified = false;
435
+
436
+ const ast = ts.createSourceFile(
437
+ 'filename.ts',
438
+ content,
439
+ ts.ScriptTarget.Latest,
440
+ false,
441
+ ts.ScriptKind.TS
442
+ );
443
+
444
+ const code = new MagicString(content);
445
+
446
+ const exports = new Map();
447
+
448
+ ast.forEachChild((node) => {
449
+ if (
450
+ ts.isExportDeclaration(node) &&
451
+ node.exportClause &&
452
+ ts.isNamedExports(node.exportClause)
453
+ ) {
454
+ node.exportClause.elements.forEach((element) => {
455
+ const exported = element.name;
456
+ if (names.has(element.name.text)) {
457
+ const local = element.propertyName || element.name;
458
+ exports.set(exported.text, local.text);
459
+ }
460
+ });
461
+ }
462
+
463
+ if (node.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword)) {
464
+ if (ts.isFunctionDeclaration(node) && node.name?.text && names.has(node.name?.text)) {
465
+ exports.set(node.name.text, node.name.text);
466
+ }
467
+
468
+ if (ts.isVariableStatement(node)) {
469
+ node.declarationList.declarations.forEach((declaration) => {
470
+ if (ts.isIdentifier(declaration.name) && names.has(declaration.name.text)) {
471
+ exports.set(declaration.name.text, declaration.name.text);
472
+ }
473
+ });
474
+ }
475
+ }
476
+ });
477
+
478
+ /**
479
+ * @param {import('typescript').Node} node
480
+ * @param {import('typescript').Node} value
481
+ */
482
+ function replace_jsdoc_type_tags(node, value) {
483
+ // @ts-ignore
484
+ if (node.jsDoc) {
485
+ // @ts-ignore
486
+ for (const comment of node.jsDoc) {
487
+ for (const tag of comment.tags) {
488
+ if (ts.isJSDocTypeTag(tag)) {
489
+ const is_fn =
490
+ ts.isFunctionDeclaration(value) ||
491
+ ts.isFunctionExpression(value) ||
492
+ ts.isArrowFunction(value);
493
+
494
+ if (is_fn && value.parameters?.length > 0) {
495
+ code.overwrite(tag.tagName.pos, tag.tagName.end, 'param');
496
+ code.prependRight(tag.typeExpression.pos + 1, 'Parameters<');
497
+ code.appendLeft(tag.typeExpression.end - 1, '>[0]');
498
+ code.appendLeft(tag.typeExpression.end, ' event');
499
+ } else {
500
+ code.overwrite(tag.pos, tag.end, '');
501
+ }
502
+ modified = true;
503
+ }
504
+ }
505
+ }
506
+ }
507
+ }
508
+
509
+ ast.forEachChild((node) => {
510
+ if (ts.isFunctionDeclaration(node) && node.name?.text && names.has(node.name?.text)) {
511
+ // remove JSDoc comment above `export function load ...`
512
+ replace_jsdoc_type_tags(node, node);
513
+ }
514
+
515
+ if (ts.isVariableStatement(node)) {
516
+ // remove JSDoc comment above `export const load = ...`
517
+ if (
518
+ ts.isIdentifier(node.declarationList.declarations[0].name) &&
519
+ names.has(node.declarationList.declarations[0].name.text) &&
520
+ node.declarationList.declarations[0].initializer
521
+ ) {
522
+ replace_jsdoc_type_tags(node, node.declarationList.declarations[0].initializer);
523
+ }
524
+
525
+ for (const declaration of node.declarationList.declarations) {
526
+ if (
527
+ ts.isIdentifier(declaration.name) &&
528
+ names.has(declaration.name.text) &&
529
+ declaration.initializer
530
+ ) {
531
+ // edge case — remove JSDoc comment above individual export
532
+ replace_jsdoc_type_tags(declaration, declaration.initializer);
533
+
534
+ // remove type from `export const load: Load ...`
535
+ if (declaration.type) {
536
+ let a = declaration.type.pos;
537
+ let b = declaration.type.end;
538
+ while (/\s/.test(content[a])) a += 1;
539
+
540
+ const type = content.slice(a, b);
541
+ code.remove(declaration.name.end, declaration.type.end);
542
+
543
+ const rhs = declaration.initializer;
544
+
545
+ if (
546
+ rhs &&
547
+ (ts.isArrowFunction(rhs) || ts.isFunctionExpression(rhs)) &&
548
+ rhs.parameters.length
549
+ ) {
550
+ const arg = rhs.parameters[0];
551
+
552
+ const add_parens = content[arg.pos - 1] !== '(';
553
+
554
+ if (add_parens) code.prependRight(arg.pos, '(');
555
+
556
+ if (arg && !arg.type) {
557
+ code.appendLeft(
558
+ arg.name.end,
559
+ `: Parameters<${type}>[0]` + (add_parens ? ')' : '')
560
+ );
561
+ } else {
562
+ // prevent "type X is imported but not used" (isn't silenced by @ts-nocheck) when svelte-check runs
563
+ code.append(`;null as any as ${type};`);
564
+ }
565
+ } else {
566
+ // prevent "type X is imported but not used" (isn't silenced by @ts-nocheck) when svelte-check runs
567
+ code.append(`;null as any as ${type};`);
568
+ }
569
+
570
+ modified = true;
571
+ }
572
+ }
573
+ }
574
+ }
575
+ });
576
+
577
+ if (modified) {
578
+ // Ignore all type errors so they don't show up twice when svelte-check runs
579
+ // Account for possible @ts-check which would overwrite @ts-nocheck
580
+ if (code.original.startsWith('// @ts-check')) {
581
+ code.prependLeft('// @ts-check'.length, '\n// @ts-nocheck\n');
582
+ } else {
583
+ code.prepend('// @ts-nocheck\n');
584
+ }
585
+ }
586
+
587
+ return {
588
+ modified,
589
+ code: code.toString(),
590
+ exports: Array.from(exports.keys())
591
+ };
592
+ } catch {
593
+ return null;
594
+ }
595
+ }
@@ -0,0 +1,70 @@
1
+ import path from 'path';
2
+ import colors from 'kleur';
3
+ import { fileURLToPath } from 'url';
4
+ import { posixify } from '../utils/filesystem.js';
5
+
6
+ /**
7
+ * Resolved path of the `runtime` directory
8
+ *
9
+ * TODO Windows issue:
10
+ * Vite or sth else somehow sets the driver letter inconsistently to lower or upper case depending on the run environment.
11
+ * In playwright debug mode run through VS Code this a root-to-lowercase conversion is needed in order for the tests to run.
12
+ * If we do this conversion in other cases it has the opposite effect though and fails.
13
+ */
14
+ export const runtime_directory = posixify(fileURLToPath(new URL('../runtime', import.meta.url)));
15
+
16
+ /** Prefix for the `runtime` directory, for use with import declarations */
17
+ export const runtime_prefix = posixify_path(runtime_directory);
18
+
19
+ /**
20
+ * This allows us to import SvelteKit internals that aren't exposed via `pkg.exports` in a
21
+ * way that works whether `@sveltejs/kit` is installed inside the project's `node_modules`
22
+ * or in a workspace root
23
+ */
24
+ export const runtime_base = runtime_directory.startsWith(process.cwd())
25
+ ? `/${path.relative('.', runtime_directory)}`
26
+ : `/@fs${
27
+ // Windows/Linux separation - Windows starts with a drive letter, we need a / in front there
28
+ runtime_directory.startsWith('/') ? '' : '/'
29
+ }${runtime_directory}`;
30
+
31
+ /** @param {string} str */
32
+ function posixify_path(str) {
33
+ const parsed = path.parse(str);
34
+ return `/${parsed.dir.slice(parsed.root.length).split(path.sep).join('/')}/${parsed.base}`;
35
+ }
36
+
37
+ function noop() {}
38
+
39
+ /** @param {{ verbose: boolean }} opts */
40
+ export function logger({ verbose }) {
41
+ /** @type {import('types').Logger} */
42
+ const log = (msg) => console.log(msg.replace(/^/gm, ' '));
43
+
44
+ /** @param {string} msg */
45
+ const err = (msg) => console.error(msg.replace(/^/gm, ' '));
46
+
47
+ log.success = (msg) => log(colors.green(`✔ ${msg}`));
48
+ log.error = (msg) => err(colors.bold().red(msg));
49
+ log.warn = (msg) => log(colors.bold().yellow(msg));
50
+
51
+ log.minor = verbose ? (msg) => log(colors.grey(msg)) : noop;
52
+ log.info = verbose ? log : noop;
53
+
54
+ return log;
55
+ }
56
+
57
+ /** @param {import('types').ManifestData} manifest_data */
58
+ export function get_mime_lookup(manifest_data) {
59
+ /** @type {Record<string, string>} */
60
+ const mime = {};
61
+
62
+ manifest_data.assets.forEach((asset) => {
63
+ if (asset.type) {
64
+ const ext = path.extname(asset.file);
65
+ mime[ext] = asset.type;
66
+ }
67
+ });
68
+
69
+ return mime;
70
+ }
@@ -0,0 +1 @@
1
+ export { sequence } from './sequence.js';
@@ -0,0 +1,44 @@
1
+ /**
2
+ * @param {...import('types').Handle} handlers
3
+ * @returns {import('types').Handle}
4
+ */
5
+ export function sequence(...handlers) {
6
+ const length = handlers.length;
7
+ if (!length) return ({ event, resolve }) => resolve(event);
8
+
9
+ return ({ event, resolve }) => {
10
+ return apply_handle(0, event, {});
11
+
12
+ /**
13
+ * @param {number} i
14
+ * @param {import('types').RequestEvent} event
15
+ * @param {import('types').ResolveOptions | undefined} parent_options
16
+ * @returns {import('types').MaybePromise<Response>}
17
+ */
18
+ function apply_handle(i, event, parent_options) {
19
+ const handle = handlers[i];
20
+
21
+ return handle({
22
+ event,
23
+ resolve: (event, options) => {
24
+ /** @param {{ html: string, done: boolean }} opts */
25
+ const transformPageChunk = async ({ html, done }) => {
26
+ if (options?.transformPageChunk) {
27
+ html = (await options.transformPageChunk({ html, done })) ?? '';
28
+ }
29
+
30
+ if (parent_options?.transformPageChunk) {
31
+ html = (await parent_options.transformPageChunk({ html, done })) ?? '';
32
+ }
33
+
34
+ return html;
35
+ };
36
+
37
+ return i < length - 1
38
+ ? apply_handle(i + 1, event, { transformPageChunk })
39
+ : resolve(event, { transformPageChunk });
40
+ }
41
+ });
42
+ }
43
+ };
44
+ }