@sveltejs/kit 1.0.0-next.55 → 1.0.0-next.550

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 (128) hide show
  1. package/README.md +5 -2
  2. package/package.json +93 -67
  3. package/postinstall.js +47 -0
  4. package/scripts/special-types/$env+dynamic+private.md +10 -0
  5. package/scripts/special-types/$env+dynamic+public.md +8 -0
  6. package/scripts/special-types/$env+static+private.md +19 -0
  7. package/scripts/special-types/$env+static+public.md +7 -0
  8. package/scripts/special-types/$lib.md +5 -0
  9. package/src/cli.js +108 -0
  10. package/src/constants.js +5 -0
  11. package/src/core/adapt/builder.js +212 -0
  12. package/src/core/adapt/index.js +31 -0
  13. package/src/core/config/default-error.html +56 -0
  14. package/src/core/config/index.js +110 -0
  15. package/src/core/config/options.js +516 -0
  16. package/src/core/config/types.d.ts +1 -0
  17. package/src/core/env.js +121 -0
  18. package/src/core/generate_manifest/index.js +125 -0
  19. package/src/core/prerender/crawl.js +207 -0
  20. package/src/core/prerender/entities.js +2252 -0
  21. package/src/core/prerender/prerender.js +460 -0
  22. package/src/core/prerender/queue.js +80 -0
  23. package/src/core/sync/create_manifest_data/conflict.js +0 -0
  24. package/src/core/sync/create_manifest_data/index.js +513 -0
  25. package/src/core/sync/create_manifest_data/sort.js +161 -0
  26. package/src/core/sync/create_manifest_data/types.d.ts +37 -0
  27. package/src/core/sync/sync.js +78 -0
  28. package/src/core/sync/utils.js +33 -0
  29. package/src/core/sync/write_ambient.js +53 -0
  30. package/src/core/sync/write_client_manifest.js +106 -0
  31. package/src/core/sync/write_matchers.js +25 -0
  32. package/src/core/sync/write_root.js +91 -0
  33. package/src/core/sync/write_tsconfig.js +195 -0
  34. package/src/core/sync/write_types/index.js +809 -0
  35. package/src/core/utils.js +67 -0
  36. package/src/exports/hooks/index.js +1 -0
  37. package/src/exports/hooks/sequence.js +44 -0
  38. package/src/exports/index.js +45 -0
  39. package/src/exports/node/index.js +172 -0
  40. package/src/exports/node/polyfills.js +28 -0
  41. package/src/exports/vite/build/build_server.js +384 -0
  42. package/src/exports/vite/build/build_service_worker.js +92 -0
  43. package/src/exports/vite/build/utils.js +195 -0
  44. package/src/exports/vite/dev/index.js +588 -0
  45. package/src/exports/vite/graph_analysis/index.js +107 -0
  46. package/src/exports/vite/graph_analysis/types.d.ts +5 -0
  47. package/src/exports/vite/graph_analysis/utils.js +6 -0
  48. package/src/exports/vite/index.js +651 -0
  49. package/src/exports/vite/preview/index.js +193 -0
  50. package/src/exports/vite/types.d.ts +3 -0
  51. package/src/exports/vite/utils.js +171 -0
  52. package/src/runtime/app/env.js +1 -0
  53. package/src/runtime/app/environment.js +11 -0
  54. package/src/runtime/app/forms.js +141 -0
  55. package/src/runtime/app/navigation.js +23 -0
  56. package/src/runtime/app/paths.js +1 -0
  57. package/src/runtime/app/stores.js +102 -0
  58. package/src/runtime/client/ambient.d.ts +30 -0
  59. package/src/runtime/client/client.js +1726 -0
  60. package/src/runtime/client/fetcher.js +121 -0
  61. package/src/runtime/client/parse.js +60 -0
  62. package/src/runtime/client/singletons.js +21 -0
  63. package/src/runtime/client/start.js +43 -0
  64. package/src/runtime/client/types.d.ts +84 -0
  65. package/src/runtime/client/utils.js +166 -0
  66. package/src/runtime/components/error.svelte +16 -0
  67. package/{assets → src/runtime}/components/layout.svelte +0 -0
  68. package/src/runtime/control.js +98 -0
  69. package/src/runtime/env/dynamic/private.js +1 -0
  70. package/src/runtime/env/dynamic/public.js +1 -0
  71. package/src/runtime/env-private.js +6 -0
  72. package/src/runtime/env-public.js +6 -0
  73. package/src/runtime/env.js +6 -0
  74. package/src/runtime/hash.js +20 -0
  75. package/src/runtime/paths.js +11 -0
  76. package/src/runtime/server/cookie.js +231 -0
  77. package/src/runtime/server/data/index.js +144 -0
  78. package/src/runtime/server/endpoint.js +89 -0
  79. package/src/runtime/server/fetch.js +164 -0
  80. package/src/runtime/server/index.js +375 -0
  81. package/src/runtime/server/page/actions.js +258 -0
  82. package/src/runtime/server/page/crypto.js +239 -0
  83. package/src/runtime/server/page/csp.js +250 -0
  84. package/src/runtime/server/page/index.js +303 -0
  85. package/src/runtime/server/page/load_data.js +258 -0
  86. package/src/runtime/server/page/render.js +391 -0
  87. package/src/runtime/server/page/respond_with_error.js +102 -0
  88. package/src/runtime/server/page/serialize_data.js +87 -0
  89. package/src/runtime/server/page/types.d.ts +35 -0
  90. package/src/runtime/server/utils.js +205 -0
  91. package/src/utils/array.js +9 -0
  92. package/src/utils/error.js +22 -0
  93. package/src/utils/escape.js +46 -0
  94. package/src/utils/filesystem.js +166 -0
  95. package/src/utils/functions.js +16 -0
  96. package/src/utils/http.js +72 -0
  97. package/src/utils/misc.js +1 -0
  98. package/src/utils/promises.js +17 -0
  99. package/src/utils/routing.js +168 -0
  100. package/src/utils/unit_test.js +11 -0
  101. package/src/utils/url.js +159 -0
  102. package/svelte-kit.js +1 -1
  103. package/types/ambient.d.ts +469 -0
  104. package/types/index.d.ts +775 -0
  105. package/types/internal.d.ts +381 -0
  106. package/types/private.d.ts +229 -0
  107. package/CHANGELOG.md +0 -519
  108. package/assets/components/error.svelte +0 -13
  109. package/assets/runtime/app/env.js +0 -5
  110. package/assets/runtime/app/navigation.js +0 -48
  111. package/assets/runtime/app/paths.js +0 -1
  112. package/assets/runtime/app/stores.js +0 -93
  113. package/assets/runtime/chunks/utils.js +0 -22
  114. package/assets/runtime/internal/singletons.js +0 -23
  115. package/assets/runtime/internal/start.js +0 -823
  116. package/assets/runtime/paths.js +0 -12
  117. package/dist/chunks/index.js +0 -3544
  118. package/dist/chunks/index2.js +0 -572
  119. package/dist/chunks/index3.js +0 -246
  120. package/dist/chunks/index4.js +0 -569
  121. package/dist/chunks/index5.js +0 -751
  122. package/dist/chunks/index6.js +0 -323
  123. package/dist/chunks/standard.js +0 -99
  124. package/dist/chunks/utils.js +0 -83
  125. package/dist/cli.js +0 -558
  126. package/dist/ssr.js +0 -2620
  127. package/types.d.ts +0 -74
  128. package/types.internal.d.ts +0 -237
@@ -0,0 +1,809 @@
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
+ * file_name: string;
10
+ * modified: boolean;
11
+ * code: string;
12
+ * exports: any[];
13
+ * } | null} Proxy
14
+ *
15
+ * @typedef {{
16
+ * server: Proxy,
17
+ * shared: Proxy
18
+ * }} Proxies
19
+ *
20
+ * @typedef {Map<import('types').PageNode, {route: import('types').RouteData, proxies: Proxies}>} RoutesMap
21
+ */
22
+
23
+ /** @type {import('typescript')} */
24
+ // @ts-ignore
25
+ let ts = undefined;
26
+ try {
27
+ ts = (await import('typescript')).default;
28
+ } catch {}
29
+
30
+ const cwd = process.cwd();
31
+
32
+ /**
33
+ * Creates types for the whole manifest
34
+ * @param {import('types').ValidatedConfig} config
35
+ * @param {import('types').ManifestData} manifest_data
36
+ */
37
+ export async function write_all_types(config, manifest_data) {
38
+ if (!ts) return;
39
+
40
+ const types_dir = `${config.kit.outDir}/types`;
41
+
42
+ // empty out files that no longer need to exist
43
+ const routes_dir = posixify(path.relative('.', config.kit.files.routes)).replace(/\.\.\//g, '');
44
+ const expected_directories = new Set(
45
+ manifest_data.routes.map((route) => path.join(routes_dir, route.id))
46
+ );
47
+
48
+ if (fs.existsSync(types_dir)) {
49
+ for (const file of walk(types_dir)) {
50
+ const dir = path.dirname(file);
51
+ if (!expected_directories.has(dir)) {
52
+ rimraf(file);
53
+ }
54
+ }
55
+ }
56
+
57
+ // Read/write meta data on each invocation, not once per node process,
58
+ // it could be invoked by another process in the meantime.
59
+ const meta_data_file = `${types_dir}/route_meta_data.json`;
60
+ const has_meta_data = fs.existsSync(meta_data_file);
61
+ let meta_data = has_meta_data
62
+ ? /** @type {Record<string, string[]>} */ (JSON.parse(fs.readFileSync(meta_data_file, 'utf-8')))
63
+ : {};
64
+ const routes_map = create_routes_map(manifest_data);
65
+ // For each directory, write $types.d.ts
66
+ for (const route of manifest_data.routes) {
67
+ if (!route.leaf && !route.layout && !route.endpoint) continue; // nothing to do
68
+
69
+ const outdir = path.join(config.kit.outDir, 'types', routes_dir, route.id);
70
+
71
+ // check if the types are out of date
72
+ /** @type {string[]} */
73
+ const input_files = [];
74
+
75
+ /** @type {import('types').PageNode | null} */
76
+ let node = route.leaf;
77
+ while (node) {
78
+ if (node.shared) input_files.push(node.shared);
79
+ if (node.server) input_files.push(node.server);
80
+ node = node.parent ?? null;
81
+ }
82
+
83
+ /** @type {import('types').PageNode | null} */
84
+ node = route.layout;
85
+ while (node) {
86
+ if (node.shared) input_files.push(node.shared);
87
+ if (node.server) input_files.push(node.server);
88
+ node = node.parent ?? null;
89
+ }
90
+
91
+ if (route.endpoint) {
92
+ input_files.push(route.endpoint.file);
93
+ }
94
+
95
+ try {
96
+ fs.mkdirSync(outdir, { recursive: true });
97
+ } catch {}
98
+
99
+ const output_files = compact(
100
+ fs.readdirSync(outdir).map((name) => {
101
+ const stats = fs.statSync(path.join(outdir, name));
102
+ if (stats.isDirectory()) return;
103
+ return {
104
+ name,
105
+ updated: stats.mtimeMs
106
+ };
107
+ })
108
+ );
109
+
110
+ const source_last_updated = Math.max(
111
+ // ctimeMs includes move operations whereas mtimeMs does not
112
+ ...input_files.map((file) => fs.statSync(file).ctimeMs)
113
+ );
114
+ const types_last_updated = Math.max(...output_files.map((file) => file.updated));
115
+
116
+ const should_generate =
117
+ // source files were generated more recently than the types
118
+ source_last_updated > types_last_updated ||
119
+ // no meta data file exists yet
120
+ !has_meta_data ||
121
+ // some file was deleted
122
+ !meta_data[route.id]?.every((file) => input_files.includes(file));
123
+
124
+ if (should_generate) {
125
+ // track which old files end up being surplus to requirements
126
+ const to_delete = new Set(output_files.map((file) => file.name));
127
+ update_types(config, routes_map, route, to_delete);
128
+ meta_data[route.id] = input_files;
129
+ }
130
+ }
131
+
132
+ fs.writeFileSync(meta_data_file, JSON.stringify(meta_data, null, '\t'));
133
+ }
134
+
135
+ /**
136
+ * Creates types related to the given file. This should only be called
137
+ * if the file in question was edited, not if it was created/deleted/moved.
138
+ * @param {import('types').ValidatedConfig} config
139
+ * @param {import('types').ManifestData} manifest_data
140
+ * @param {string} file
141
+ */
142
+ export async function write_types(config, manifest_data, file) {
143
+ if (!ts) return;
144
+
145
+ if (!path.basename(file).startsWith('+')) {
146
+ // Not a route file
147
+ return;
148
+ }
149
+
150
+ const id = '/' + posixify(path.relative(config.kit.files.routes, path.dirname(file)));
151
+
152
+ const route = manifest_data.routes.find((route) => route.id === id);
153
+ if (!route) return; // this shouldn't ever happen
154
+ if (!route.leaf && !route.layout && !route.endpoint) return; // nothing to do
155
+
156
+ update_types(config, create_routes_map(manifest_data), route);
157
+ }
158
+
159
+ /**
160
+ * Collect all leafs into a leaf -> route map
161
+ * @param {import('types').ManifestData} manifest_data
162
+ */
163
+ function create_routes_map(manifest_data) {
164
+ /** @type {RoutesMap} */
165
+ const map = new Map();
166
+ for (const route of manifest_data.routes) {
167
+ if (route.leaf) {
168
+ map.set(route.leaf, { route, proxies: { server: null, shared: null } });
169
+ }
170
+ }
171
+ return map;
172
+ }
173
+
174
+ /**
175
+ * Update types for a specific route
176
+ * @param {import('types').ValidatedConfig} config
177
+ * @param {RoutesMap} routes
178
+ * @param {import('types').RouteData} route
179
+ * @param {Set<string>} [to_delete]
180
+ */
181
+ function update_types(config, routes, route, to_delete = new Set()) {
182
+ const routes_dir = posixify(path.relative('.', config.kit.files.routes)).replace(/\.\.\//g, '');
183
+ const outdir = path.join(config.kit.outDir, 'types', routes_dir, route.id);
184
+
185
+ // now generate new types
186
+ const imports = [`import type * as Kit from '@sveltejs/kit';`];
187
+
188
+ /** @type {string[]} */
189
+ const declarations = [];
190
+
191
+ /** @type {string[]} */
192
+ const exports = [];
193
+
194
+ // add 'Expand' helper
195
+ // Makes sure a type is "repackaged" and therefore more readable
196
+ declarations.push('type Expand<T> = T extends infer O ? { [K in keyof O]: O[K] } : never;');
197
+ declarations.push(
198
+ `type RouteParams = { ${route.names
199
+ .map((param, idx) => `${param}${route.optional[idx] ? '?' : ''}: string`)
200
+ .join('; ')} }`
201
+ );
202
+
203
+ declarations.push(`type RouteId = '${route.id}';`);
204
+
205
+ // 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
206
+ if (route.layout || route.leaf) {
207
+ // If T extends the empty object, void is also allowed as a return type
208
+ declarations.push(`type MaybeWithVoid<T> = {} extends T ? T | void : T;`);
209
+ // Returns the key of the object whose values are required.
210
+ declarations.push(
211
+ `export type RequiredKeys<T> = { [K in keyof T]-?: {} extends { [P in K]: T[K] } ? never : K; }[keyof T];`
212
+ );
213
+ // 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.
214
+ // If none, void is also allowed as a return type.
215
+ declarations.push(
216
+ `type OutputDataShape<T> = MaybeWithVoid<Omit<App.PageData, RequiredKeys<T>> & Partial<Pick<App.PageData, keyof T & keyof App.PageData>> & Record<string, any>>`
217
+ );
218
+ // null & {} == null, we need to prevent that in some situations
219
+ declarations.push(`type EnsureDefined<T> = T extends null | undefined ? {} : T;`);
220
+ // Takes a union type and returns a union type where each type also has all properties
221
+ // of all possible types (typed as undefined), making accessing them more ergonomic
222
+ declarations.push(
223
+ `type OptionalUnion<U extends Record<string, any>, A extends keyof U = U extends U ? keyof U : never> = U extends unknown ? { [P in Exclude<A, keyof U>]?: never } & U : never;`
224
+ );
225
+ }
226
+
227
+ if (route.leaf) {
228
+ let route_info = routes.get(route.leaf);
229
+ if (!route_info) {
230
+ // This should be defined, but belts and braces
231
+ route_info = { route, proxies: { server: null, shared: null } };
232
+ routes.set(route.leaf, route_info);
233
+ }
234
+
235
+ const {
236
+ declarations: d,
237
+ exports: e,
238
+ proxies
239
+ } = process_node(route.leaf, outdir, true, route_info.proxies);
240
+
241
+ exports.push(...e);
242
+ declarations.push(...d);
243
+
244
+ if (proxies.server) {
245
+ route_info.proxies.server = proxies.server;
246
+ if (proxies.server?.modified) to_delete.delete(proxies.server.file_name);
247
+ }
248
+ if (proxies.shared) {
249
+ route_info.proxies.shared = proxies.shared;
250
+ if (proxies.shared?.modified) to_delete.delete(proxies.shared.file_name);
251
+ }
252
+
253
+ if (route.leaf.server) {
254
+ exports.push(
255
+ `export type Action<OutputData extends Record<string, any> | void = Record<string, any> | void> = Kit.Action<RouteParams, OutputData, RouteId>`
256
+ );
257
+ exports.push(
258
+ `export type Actions<OutputData extends Record<string, any> | void = Record<string, any> | void> = Kit.Actions<RouteParams, OutputData, RouteId>`
259
+ );
260
+ }
261
+ }
262
+
263
+ if (route.layout) {
264
+ let all_pages_have_load = true;
265
+ const layout_params = new Set();
266
+ const ids = ['RouteId'];
267
+
268
+ route.layout.child_pages?.forEach((page) => {
269
+ const leaf = routes.get(page);
270
+ if (leaf) {
271
+ if (leaf.route.page) ids.push(`"${leaf.route.id}"`);
272
+
273
+ for (const name of leaf.route.names) {
274
+ layout_params.add(name);
275
+ }
276
+
277
+ ensureProxies(page, leaf.proxies);
278
+
279
+ if (
280
+ // Be defensive - if a proxy doesn't exist (because it couldn't be created), assume a load function exists.
281
+ // If we didn't and it's a false negative, the user could wrongfully get a type error on layouts.
282
+ (leaf.proxies.server && !leaf.proxies.server.exports.includes('load')) ||
283
+ (leaf.proxies.shared && !leaf.proxies.shared.exports.includes('load'))
284
+ ) {
285
+ all_pages_have_load = false;
286
+ }
287
+ }
288
+ if (!page.server && !page.shared) {
289
+ all_pages_have_load = false;
290
+ }
291
+ });
292
+
293
+ if (route.id === '/') {
294
+ // root layout is used for fallback error page, where ID can be null
295
+ ids.push('null');
296
+ }
297
+
298
+ declarations.push(`type LayoutRouteId = ${ids.join(' | ')}`);
299
+
300
+ declarations.push(
301
+ `type LayoutParams = RouteParams & { ${Array.from(layout_params).map(
302
+ (param) => `${param}?: string`
303
+ )} }`
304
+ );
305
+
306
+ const {
307
+ exports: e,
308
+ declarations: d,
309
+ proxies
310
+ } = process_node(
311
+ route.layout,
312
+ outdir,
313
+ false,
314
+ { server: null, shared: null },
315
+ all_pages_have_load
316
+ );
317
+
318
+ exports.push(...e);
319
+ declarations.push(...d);
320
+
321
+ if (proxies.server?.modified) to_delete.delete(proxies.server.file_name);
322
+ if (proxies.shared?.modified) to_delete.delete(proxies.shared.file_name);
323
+ }
324
+
325
+ if (route.endpoint) {
326
+ exports.push(`export type RequestHandler = Kit.RequestHandler<RouteParams, RouteId>;`);
327
+ }
328
+
329
+ if (route.leaf?.server || route.layout?.server || route.endpoint) {
330
+ exports.push(`export type RequestEvent = Kit.RequestEvent<RouteParams, RouteId>;`);
331
+ }
332
+
333
+ const output = [imports.join('\n'), declarations.join('\n'), exports.join('\n')]
334
+ .filter(Boolean)
335
+ .join('\n\n');
336
+
337
+ fs.writeFileSync(`${outdir}/$types.d.ts`, output);
338
+ to_delete.delete('$types.d.ts');
339
+
340
+ for (const file of to_delete) {
341
+ fs.unlinkSync(path.join(outdir, file));
342
+ }
343
+ }
344
+
345
+ /**
346
+ * @param {import('types').PageNode} node
347
+ * @param {string} outdir
348
+ * @param {boolean} is_page
349
+ * @param {Proxies} proxies
350
+ * @param {boolean} [all_pages_have_load]
351
+ */
352
+ function process_node(node, outdir, is_page, proxies, all_pages_have_load = true) {
353
+ const params = `${is_page ? 'Route' : 'Layout'}Params`;
354
+ const prefix = is_page ? 'Page' : 'Layout';
355
+
356
+ const route_id = is_page ? 'RouteId' : 'LayoutRouteId';
357
+
358
+ /** @type {string[]} */
359
+ const declarations = [];
360
+ /** @type {string[]} */
361
+ const exports = [];
362
+
363
+ /** @type {string} */
364
+ let server_data;
365
+ /** @type {string} */
366
+ let data;
367
+
368
+ ensureProxies(node, proxies);
369
+
370
+ if (node.server) {
371
+ const basename = path.basename(node.server);
372
+ const proxy = proxies.server;
373
+ if (proxy?.modified) {
374
+ fs.writeFileSync(`${outdir}/proxy${basename}`, proxy.code);
375
+ }
376
+
377
+ server_data = get_data_type(node.server, 'null', proxy, true);
378
+
379
+ const parent_type = `${prefix}ServerParentData`;
380
+
381
+ declarations.push(`type ${parent_type} = ${get_parent_type(node, 'LayoutServerData')};`);
382
+
383
+ // +page.js load present -> server can return all-optional data
384
+ const output_data_shape =
385
+ node.shared || (!is_page && all_pages_have_load)
386
+ ? `Partial<App.PageData> & Record<string, any> | void`
387
+ : `OutputDataShape<${parent_type}>`;
388
+ exports.push(
389
+ `export type ${prefix}ServerLoad<OutputData extends ${output_data_shape} = ${output_data_shape}> = Kit.ServerLoad<${params}, ${parent_type}, OutputData, ${route_id}>;`
390
+ );
391
+
392
+ exports.push(`export type ${prefix}ServerLoadEvent = Parameters<${prefix}ServerLoad>[0];`);
393
+
394
+ if (is_page) {
395
+ let type = 'unknown';
396
+ if (proxy) {
397
+ if (proxy.exports.includes('actions')) {
398
+ // If the file wasn't tweaked, we can use the return type of the original file.
399
+ // The advantage is that type updates are reflected without saving.
400
+ const from = proxy.modified
401
+ ? `./proxy${replace_ext_with_js(basename)}`
402
+ : path_to_original(outdir, node.server);
403
+
404
+ type = `Expand<Kit.AwaitedActions<typeof import('${from}').actions>> | undefined`;
405
+ }
406
+ }
407
+ exports.push(`export type ActionData = ${type};`);
408
+ }
409
+ } else {
410
+ server_data = 'null';
411
+ }
412
+ exports.push(`export type ${prefix}ServerData = ${server_data};`);
413
+
414
+ const parent_type = `${prefix}ParentData`;
415
+ declarations.push(`type ${parent_type} = ${get_parent_type(node, 'LayoutData')};`);
416
+
417
+ if (node.shared) {
418
+ const proxy = proxies.shared;
419
+ if (proxy?.modified) {
420
+ fs.writeFileSync(`${outdir}/proxy${path.basename(node.shared)}`, proxy.code);
421
+ }
422
+
423
+ const type = get_data_type(
424
+ node.shared,
425
+ `${parent_type} & EnsureDefined<${prefix}ServerData>`,
426
+ proxy
427
+ );
428
+
429
+ data = `Expand<Omit<${parent_type}, keyof ${type}> & OptionalUnion<EnsureDefined<${type}>>>`;
430
+
431
+ const output_data_shape =
432
+ !is_page && all_pages_have_load
433
+ ? `Partial<App.PageData> & Record<string, any> | void`
434
+ : `OutputDataShape<${parent_type}>`;
435
+ exports.push(
436
+ `export type ${prefix}Load<OutputData extends ${output_data_shape} = ${output_data_shape}> = Kit.Load<${params}, ${prefix}ServerData, ${parent_type}, OutputData, ${route_id}>;`
437
+ );
438
+
439
+ exports.push(`export type ${prefix}LoadEvent = Parameters<${prefix}Load>[0];`);
440
+ } else if (server_data === 'null') {
441
+ data = `Expand<${parent_type}>`;
442
+ } else {
443
+ data = `Expand<Omit<${parent_type}, keyof ${prefix}ServerData> & EnsureDefined<${prefix}ServerData>>`;
444
+ }
445
+
446
+ exports.push(`export type ${prefix}Data = ${data};`);
447
+
448
+ return { declarations, exports, proxies };
449
+
450
+ /**
451
+ * @param {string} file_path
452
+ * @param {string} fallback
453
+ * @param {Proxy} proxy
454
+ * @param {boolean} expand
455
+ */
456
+ function get_data_type(file_path, fallback, proxy, expand = false) {
457
+ if (proxy) {
458
+ if (proxy.exports.includes('load')) {
459
+ // If the file wasn't tweaked, we can use the return type of the original file.
460
+ // The advantage is that type updates are reflected without saving.
461
+ const from = proxy.modified
462
+ ? `./proxy${replace_ext_with_js(path.basename(file_path))}`
463
+ : path_to_original(outdir, file_path);
464
+ const type = `Kit.AwaitedProperties<Awaited<ReturnType<typeof import('${from}').load>>>`;
465
+ return expand ? `Expand<OptionalUnion<EnsureDefined<${type}>>>` : type;
466
+ } else {
467
+ return fallback;
468
+ }
469
+ } else {
470
+ return 'unknown';
471
+ }
472
+ }
473
+ }
474
+
475
+ /**
476
+ * This function populates the proxies object, if necessary and not already done.
477
+ * Proxies are used to tweak the code of a file before it's typechecked.
478
+ * They are needed in two places - when generating the types for a page or layout.
479
+ * To not do the same work twice, we generate the proxies once and pass them around.
480
+ *
481
+ * @param {import('types').PageNode} node
482
+ * @param {Proxies} proxies
483
+ */
484
+ function ensureProxies(node, proxies) {
485
+ if (node.server && !proxies.server) {
486
+ proxies.server = createProxy(node.server, true);
487
+ }
488
+
489
+ if (node.shared && !proxies.shared) {
490
+ proxies.shared = createProxy(node.shared, false);
491
+ }
492
+ }
493
+
494
+ /**
495
+ * @param {string} file_path
496
+ * @param {boolean} is_server
497
+ * @returns {Proxy}
498
+ */
499
+ function createProxy(file_path, is_server) {
500
+ const proxy = tweak_types(fs.readFileSync(file_path, 'utf8'), is_server);
501
+ if (proxy) {
502
+ return {
503
+ ...proxy,
504
+ file_name: `proxy${path.basename(file_path)}`
505
+ };
506
+ } else {
507
+ return null;
508
+ }
509
+ }
510
+
511
+ /**
512
+ * Get the parent type string by recursively looking up the parent layout and accumulate them to one type.
513
+ * @param {import('types').PageNode} node
514
+ * @param {string} type
515
+ */
516
+ function get_parent_type(node, type) {
517
+ const parent_imports = [];
518
+
519
+ let parent = node.parent;
520
+
521
+ while (parent) {
522
+ const d = node.depth - parent.depth;
523
+ // unshift because we need it the other way round for the import string
524
+ parent_imports.unshift(
525
+ `${d === 0 ? '' : `import('${'../'.repeat(d)}${'$types.js'}').`}${type}`
526
+ );
527
+ parent = parent.parent;
528
+ }
529
+
530
+ let parent_str = `EnsureDefined<${parent_imports[0] || '{}'}>`;
531
+ for (let i = 1; i < parent_imports.length; i++) {
532
+ // Omit is necessary because a parent could have a property with the same key which would
533
+ // cause a type conflict. At runtime the child overwrites the parent property in this case,
534
+ // so reflect that in the type definition.
535
+ // EnsureDefined is necessary because {something: string} & null becomes null.
536
+ // Output types of server loads can be null but when passed in through the `parent` parameter they are the empty object instead.
537
+ parent_str = `Omit<${parent_str}, keyof ${parent_imports[i]}> & EnsureDefined<${parent_imports[i]}>`;
538
+ }
539
+ return parent_str;
540
+ }
541
+
542
+ /**
543
+ * @param {string} outdir
544
+ * @param {string} file_path
545
+ */
546
+ function path_to_original(outdir, file_path) {
547
+ return posixify(path.relative(outdir, path.join(cwd, replace_ext_with_js(file_path))));
548
+ }
549
+
550
+ /**
551
+ * @param {string} file_path
552
+ */
553
+ function replace_ext_with_js(file_path) {
554
+ // Another extension than `.js` (or nothing, but that fails with node16 moduleResolution)
555
+ // will result in TS failing to lookup the file
556
+ const ext = path.extname(file_path);
557
+ return file_path.slice(0, -ext.length) + '.js';
558
+ }
559
+
560
+ /**
561
+ * @param {string} content
562
+ * @param {boolean} is_server
563
+ * @returns {Omit<NonNullable<Proxy>, 'file_name'> | null}
564
+ */
565
+ export function tweak_types(content, is_server) {
566
+ const names = new Set(is_server ? ['load', 'actions'] : ['load']);
567
+
568
+ try {
569
+ let modified = false;
570
+
571
+ const ast = ts.createSourceFile(
572
+ 'filename.ts',
573
+ content,
574
+ ts.ScriptTarget.Latest,
575
+ false,
576
+ ts.ScriptKind.TS
577
+ );
578
+
579
+ const code = new MagicString(content);
580
+
581
+ const exports = new Map();
582
+
583
+ ast.forEachChild((node) => {
584
+ if (
585
+ ts.isExportDeclaration(node) &&
586
+ node.exportClause &&
587
+ ts.isNamedExports(node.exportClause)
588
+ ) {
589
+ node.exportClause.elements.forEach((element) => {
590
+ const exported = element.name;
591
+ if (names.has(element.name.text)) {
592
+ const local = element.propertyName || element.name;
593
+ exports.set(exported.text, local.text);
594
+ }
595
+ });
596
+ }
597
+
598
+ if (node.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword)) {
599
+ if (ts.isFunctionDeclaration(node) && node.name?.text && names.has(node.name?.text)) {
600
+ exports.set(node.name.text, node.name.text);
601
+ }
602
+
603
+ if (ts.isVariableStatement(node)) {
604
+ node.declarationList.declarations.forEach((declaration) => {
605
+ if (ts.isIdentifier(declaration.name) && names.has(declaration.name.text)) {
606
+ exports.set(declaration.name.text, declaration.name.text);
607
+ }
608
+ });
609
+ }
610
+ }
611
+ });
612
+
613
+ /**
614
+ * @param {import('typescript').Node} node
615
+ * @param {import('typescript').Node} value
616
+ */
617
+ function replace_jsdoc_type_tags(node, value) {
618
+ let _modified = false;
619
+ // @ts-ignore
620
+ if (node.jsDoc) {
621
+ // @ts-ignore
622
+ for (const comment of node.jsDoc) {
623
+ for (const tag of comment.tags ?? []) {
624
+ if (ts.isJSDocTypeTag(tag)) {
625
+ const is_fn =
626
+ ts.isFunctionDeclaration(value) ||
627
+ ts.isFunctionExpression(value) ||
628
+ ts.isArrowFunction(value);
629
+
630
+ if (is_fn && value.parameters?.length > 0) {
631
+ const name = ts.isIdentifier(value.parameters[0].name)
632
+ ? value.parameters[0].name.text
633
+ : 'event';
634
+ code.overwrite(tag.tagName.pos, tag.tagName.end, 'param');
635
+ code.prependRight(tag.typeExpression.pos + 1, 'Parameters<');
636
+ code.appendLeft(tag.typeExpression.end - 1, '>[0]');
637
+ code.appendLeft(tag.typeExpression.end, ` ${name}`);
638
+ } else {
639
+ code.overwrite(tag.pos, tag.end, '');
640
+ }
641
+ _modified = true;
642
+ }
643
+ }
644
+ }
645
+ }
646
+ modified = modified || _modified;
647
+ return _modified;
648
+ }
649
+
650
+ ast.forEachChild((node) => {
651
+ if (ts.isFunctionDeclaration(node) && node.name?.text && node.name?.text === 'load') {
652
+ // remove JSDoc comment above `export function load ...`
653
+ replace_jsdoc_type_tags(node, node);
654
+ }
655
+
656
+ if (ts.isVariableStatement(node)) {
657
+ // remove JSDoc comment above `export const load = ...`
658
+ if (
659
+ ts.isIdentifier(node.declarationList.declarations[0].name) &&
660
+ names.has(node.declarationList.declarations[0].name.text) &&
661
+ node.declarationList.declarations[0].initializer
662
+ ) {
663
+ replace_jsdoc_type_tags(node, node.declarationList.declarations[0].initializer);
664
+ }
665
+
666
+ for (const declaration of node.declarationList.declarations) {
667
+ if (
668
+ ts.isIdentifier(declaration.name) &&
669
+ declaration.name.text === 'load' &&
670
+ declaration.initializer
671
+ ) {
672
+ // edge case — remove JSDoc comment above individual export
673
+ replace_jsdoc_type_tags(declaration, declaration.initializer);
674
+
675
+ // remove type from `export const load: Load ...`
676
+ if (declaration.type) {
677
+ let a = declaration.type.pos;
678
+ let b = declaration.type.end;
679
+ while (/\s/.test(content[a])) a += 1;
680
+
681
+ const type = content.slice(a, b);
682
+ code.remove(declaration.name.end, declaration.type.end);
683
+
684
+ const rhs = declaration.initializer;
685
+
686
+ if (
687
+ rhs &&
688
+ (ts.isArrowFunction(rhs) || ts.isFunctionExpression(rhs)) &&
689
+ rhs.parameters.length
690
+ ) {
691
+ const arg = rhs.parameters[0];
692
+ const add_parens = content[arg.pos - 1] !== '(';
693
+
694
+ if (add_parens) code.prependRight(arg.pos, '(');
695
+
696
+ if (arg && !arg.type) {
697
+ code.appendLeft(
698
+ arg.name.end,
699
+ `: Parameters<${type}>[0]` + (add_parens ? ')' : '')
700
+ );
701
+ } else {
702
+ // prevent "type X is imported but not used" (isn't silenced by @ts-nocheck) when svelte-check runs
703
+ code.append(`;null as any as ${type};`);
704
+ }
705
+ } else {
706
+ // prevent "type X is imported but not used" (isn't silenced by @ts-nocheck) when svelte-check runs
707
+ code.append(`;null as any as ${type};`);
708
+ }
709
+
710
+ modified = true;
711
+ }
712
+ } else if (
713
+ is_server &&
714
+ ts.isIdentifier(declaration.name) &&
715
+ declaration.name?.text === 'actions' &&
716
+ declaration.initializer
717
+ ) {
718
+ // remove JSDoc comment from `export const actions = ..`
719
+ const removed = replace_jsdoc_type_tags(node, declaration.initializer);
720
+ // ... and move type to each individual action
721
+ if (removed) {
722
+ const rhs = declaration.initializer;
723
+ if (ts.isObjectLiteralExpression(rhs)) {
724
+ for (const prop of rhs.properties) {
725
+ if (ts.isPropertyAssignment(prop) && ts.isIdentifier(prop.name)) {
726
+ const rhs = prop.initializer;
727
+ const replaced = replace_jsdoc_type_tags(prop, rhs);
728
+ if (
729
+ !replaced &&
730
+ rhs &&
731
+ (ts.isArrowFunction(rhs) || ts.isFunctionExpression(rhs)) &&
732
+ rhs.parameters?.[0]
733
+ ) {
734
+ const name = ts.isIdentifier(rhs.parameters[0].name)
735
+ ? rhs.parameters[0].name.text
736
+ : 'event';
737
+ code.prependRight(
738
+ rhs.pos,
739
+ `/** @param {import('./$types').RequestEvent} ${name} */ `
740
+ );
741
+ }
742
+ }
743
+ }
744
+ }
745
+ }
746
+
747
+ // remove type from `export const actions: Actions ...`
748
+ if (declaration.type) {
749
+ let a = declaration.type.pos;
750
+ let b = declaration.type.end;
751
+ while (/\s/.test(content[a])) a += 1;
752
+
753
+ const type = content.slice(a, b);
754
+ code.remove(declaration.name.end, declaration.type.end);
755
+ code.append(`;null as any as ${type};`);
756
+ modified = true;
757
+
758
+ // ... and move type to each individual action
759
+ const rhs = declaration.initializer;
760
+ if (ts.isObjectLiteralExpression(rhs)) {
761
+ for (const prop of rhs.properties) {
762
+ if (ts.isPropertyAssignment(prop) && ts.isIdentifier(prop.name)) {
763
+ const rhs = prop.initializer;
764
+
765
+ if (
766
+ rhs &&
767
+ (ts.isArrowFunction(rhs) || ts.isFunctionExpression(rhs)) &&
768
+ rhs.parameters.length
769
+ ) {
770
+ const arg = rhs.parameters[0];
771
+ const add_parens = content[arg.pos - 1] !== '(';
772
+
773
+ if (add_parens) code.prependRight(arg.pos, '(');
774
+
775
+ if (arg && !arg.type) {
776
+ code.appendLeft(
777
+ arg.name.end,
778
+ `: import('./$types').RequestEvent` + (add_parens ? ')' : '')
779
+ );
780
+ }
781
+ }
782
+ }
783
+ }
784
+ }
785
+ }
786
+ }
787
+ }
788
+ }
789
+ });
790
+
791
+ if (modified) {
792
+ // Ignore all type errors so they don't show up twice when svelte-check runs
793
+ // Account for possible @ts-check which would overwrite @ts-nocheck
794
+ if (code.original.startsWith('// @ts-check')) {
795
+ code.prependLeft('// @ts-check'.length, '\n// @ts-nocheck\n');
796
+ } else {
797
+ code.prepend('// @ts-nocheck\n');
798
+ }
799
+ }
800
+
801
+ return {
802
+ modified,
803
+ code: code.toString(),
804
+ exports: Array.from(exports.keys())
805
+ };
806
+ } catch {
807
+ return null;
808
+ }
809
+ }