@sveltejs/kit 1.0.0-next.50 → 1.0.0-next.501

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (126) hide show
  1. package/README.md +12 -9
  2. package/package.json +94 -67
  3. package/postinstall.js +38 -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 +7 -0
  11. package/src/core/adapt/builder.js +206 -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 +504 -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 +93 -0
  19. package/src/core/prerender/crawl.js +198 -0
  20. package/src/core/prerender/entities.js +2252 -0
  21. package/src/core/prerender/prerender.js +431 -0
  22. package/src/core/prerender/queue.js +80 -0
  23. package/src/core/sync/create_manifest_data/index.js +488 -0
  24. package/src/core/sync/create_manifest_data/types.d.ts +37 -0
  25. package/src/core/sync/sync.js +70 -0
  26. package/src/core/sync/utils.js +33 -0
  27. package/src/core/sync/write_ambient.js +53 -0
  28. package/src/core/sync/write_client_manifest.js +106 -0
  29. package/src/core/sync/write_matchers.js +25 -0
  30. package/src/core/sync/write_root.js +91 -0
  31. package/src/core/sync/write_tsconfig.js +195 -0
  32. package/src/core/sync/write_types/index.js +678 -0
  33. package/src/core/utils.js +70 -0
  34. package/src/exports/hooks/index.js +1 -0
  35. package/src/exports/hooks/sequence.js +44 -0
  36. package/src/exports/index.js +45 -0
  37. package/src/exports/node/index.js +173 -0
  38. package/src/exports/node/polyfills.js +41 -0
  39. package/src/exports/vite/build/build_server.js +378 -0
  40. package/src/exports/vite/build/build_service_worker.js +90 -0
  41. package/src/exports/vite/build/utils.js +180 -0
  42. package/src/exports/vite/dev/index.js +577 -0
  43. package/src/exports/vite/graph_analysis/index.js +277 -0
  44. package/src/exports/vite/graph_analysis/types.d.ts +5 -0
  45. package/src/exports/vite/graph_analysis/utils.js +30 -0
  46. package/src/exports/vite/index.js +598 -0
  47. package/src/exports/vite/preview/index.js +189 -0
  48. package/src/exports/vite/types.d.ts +3 -0
  49. package/src/exports/vite/utils.js +157 -0
  50. package/src/runtime/app/env.js +1 -0
  51. package/src/runtime/app/environment.js +11 -0
  52. package/src/runtime/app/forms.js +114 -0
  53. package/src/runtime/app/navigation.js +23 -0
  54. package/src/runtime/app/paths.js +1 -0
  55. package/src/runtime/app/stores.js +102 -0
  56. package/src/runtime/client/ambient.d.ts +30 -0
  57. package/src/runtime/client/client.js +1585 -0
  58. package/src/runtime/client/fetcher.js +107 -0
  59. package/src/runtime/client/parse.js +60 -0
  60. package/src/runtime/client/singletons.js +21 -0
  61. package/src/runtime/client/start.js +37 -0
  62. package/src/runtime/client/types.d.ts +84 -0
  63. package/src/runtime/client/utils.js +159 -0
  64. package/src/runtime/components/error.svelte +16 -0
  65. package/{assets → src/runtime}/components/layout.svelte +0 -0
  66. package/src/runtime/control.js +98 -0
  67. package/src/runtime/env/dynamic/private.js +1 -0
  68. package/src/runtime/env/dynamic/public.js +1 -0
  69. package/src/runtime/env-private.js +6 -0
  70. package/src/runtime/env-public.js +6 -0
  71. package/src/runtime/env.js +6 -0
  72. package/src/runtime/hash.js +16 -0
  73. package/src/runtime/paths.js +11 -0
  74. package/src/runtime/server/cookie.js +127 -0
  75. package/src/runtime/server/data/index.js +136 -0
  76. package/src/runtime/server/endpoint.js +90 -0
  77. package/src/runtime/server/index.js +340 -0
  78. package/src/runtime/server/page/actions.js +243 -0
  79. package/src/runtime/server/page/crypto.js +239 -0
  80. package/src/runtime/server/page/csp.js +250 -0
  81. package/src/runtime/server/page/fetch.js +301 -0
  82. package/src/runtime/server/page/index.js +304 -0
  83. package/src/runtime/server/page/load_data.js +112 -0
  84. package/src/runtime/server/page/render.js +342 -0
  85. package/src/runtime/server/page/respond_with_error.js +104 -0
  86. package/src/runtime/server/page/serialize_data.js +87 -0
  87. package/src/runtime/server/page/types.d.ts +41 -0
  88. package/src/runtime/server/utils.js +179 -0
  89. package/src/utils/array.js +9 -0
  90. package/src/utils/error.js +22 -0
  91. package/src/utils/escape.js +46 -0
  92. package/src/utils/filesystem.js +137 -0
  93. package/src/utils/functions.js +16 -0
  94. package/src/utils/http.js +55 -0
  95. package/src/utils/misc.js +1 -0
  96. package/src/utils/promises.js +17 -0
  97. package/src/utils/routing.js +117 -0
  98. package/src/utils/unit_test.js +11 -0
  99. package/src/utils/url.js +142 -0
  100. package/svelte-kit.js +1 -1
  101. package/types/ambient.d.ts +426 -0
  102. package/types/index.d.ts +444 -0
  103. package/types/internal.d.ts +378 -0
  104. package/types/private.d.ts +224 -0
  105. package/CHANGELOG.md +0 -484
  106. package/assets/components/error.svelte +0 -13
  107. package/assets/runtime/app/env.js +0 -5
  108. package/assets/runtime/app/navigation.js +0 -44
  109. package/assets/runtime/app/paths.js +0 -1
  110. package/assets/runtime/app/stores.js +0 -93
  111. package/assets/runtime/chunks/utils.js +0 -22
  112. package/assets/runtime/internal/singletons.js +0 -23
  113. package/assets/runtime/internal/start.js +0 -779
  114. package/assets/runtime/paths.js +0 -12
  115. package/dist/chunks/index.js +0 -3516
  116. package/dist/chunks/index2.js +0 -587
  117. package/dist/chunks/index3.js +0 -246
  118. package/dist/chunks/index4.js +0 -528
  119. package/dist/chunks/index5.js +0 -763
  120. package/dist/chunks/index6.js +0 -322
  121. package/dist/chunks/standard.js +0 -99
  122. package/dist/chunks/utils.js +0 -83
  123. package/dist/cli.js +0 -550
  124. package/dist/ssr.js +0 -2588
  125. package/types.d.ts +0 -89
  126. package/types.internal.d.ts +0 -191
@@ -0,0 +1,378 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import { mkdirp, posixify, resolve_entry } from '../../../utils/filesystem.js';
4
+ import { get_vite_config, merge_vite_configs } from '../utils.js';
5
+ import { load_error_page, load_template } from '../../../core/config/index.js';
6
+ import { runtime_directory } from '../../../core/utils.js';
7
+ import {
8
+ create_build,
9
+ find_deps,
10
+ get_default_build_config,
11
+ is_http_method,
12
+ resolve_symlinks
13
+ } from './utils.js';
14
+ import { s } from '../../../utils/misc.js';
15
+
16
+ /**
17
+ * @param {{
18
+ * hooks: string;
19
+ * config: import('types').ValidatedConfig;
20
+ * has_service_worker: boolean;
21
+ * runtime: string;
22
+ * template: string;
23
+ * error_page: string;
24
+ * }} opts
25
+ */
26
+ const server_template = ({ config, hooks, has_service_worker, runtime, template, error_page }) => `
27
+ import root from '__GENERATED__/root.svelte';
28
+ import { respond } from '${runtime}/server/index.js';
29
+ import { set_paths, assets, base } from '${runtime}/paths.js';
30
+ import { set_prerendering } from '${runtime}/env.js';
31
+ import { set_private_env } from '${runtime}/env-private.js';
32
+ import { set_public_env } from '${runtime}/env-public.js';
33
+
34
+ const app_template = ({ head, body, assets, nonce }) => ${s(template)
35
+ .replace('%sveltekit.head%', '" + head + "')
36
+ .replace('%sveltekit.body%', '" + body + "')
37
+ .replace(/%sveltekit\.assets%/g, '" + assets + "')
38
+ .replace(/%sveltekit\.nonce%/g, '" + nonce + "')};
39
+
40
+ const error_template = ({ status, message }) => ${s(error_page)
41
+ .replace(/%sveltekit\.status%/g, '" + status + "')
42
+ .replace(/%sveltekit\.error\.message%/g, '" + message + "')};
43
+
44
+ let read = null;
45
+
46
+ set_paths(${s(config.kit.paths)});
47
+
48
+ let default_protocol = 'https';
49
+
50
+ // allow paths to be globally overridden
51
+ // in svelte-kit preview and in prerendering
52
+ export function override(settings) {
53
+ default_protocol = settings.protocol || default_protocol;
54
+ set_paths(settings.paths);
55
+ set_prerendering(settings.prerendering);
56
+ read = settings.read;
57
+ }
58
+
59
+ export class Server {
60
+ constructor(manifest) {
61
+ this.options = {
62
+ csp: ${s(config.kit.csp)},
63
+ csrf: {
64
+ check_origin: ${s(config.kit.csrf.checkOrigin)},
65
+ },
66
+ dev: false,
67
+ handle_error: (error, event) => {
68
+ return this.options.hooks.handleError({
69
+ error,
70
+ event,
71
+
72
+ // TODO remove for 1.0
73
+ // @ts-expect-error
74
+ get request() {
75
+ throw new Error('request in handleError has been replaced with event. See https://github.com/sveltejs/kit/pull/3384 for details');
76
+ }
77
+ }) ?? { message: event.routeId != null ? 'Internal Error' : 'Not Found' };
78
+ },
79
+ hooks: null,
80
+ manifest,
81
+ paths: { base, assets },
82
+ public_env: {},
83
+ read,
84
+ root,
85
+ service_worker: ${has_service_worker},
86
+ app_template,
87
+ app_template_contains_nonce: ${template.includes('%sveltekit.nonce%')},
88
+ error_template,
89
+ trailing_slash: ${s(config.kit.trailingSlash)}
90
+ };
91
+ }
92
+
93
+ /**
94
+ * Take care: Some adapters may have to call \`Server.init\` per-request to set env vars,
95
+ * so anything that shouldn't be rerun should be wrapped in an \`if\` block to make sure it hasn't
96
+ * been done already.
97
+ */
98
+ async init({ env }) {
99
+ const entries = Object.entries(env);
100
+
101
+ const prv = Object.fromEntries(entries.filter(([k]) => !k.startsWith('${
102
+ config.kit.env.publicPrefix
103
+ }')));
104
+
105
+ const pub = Object.fromEntries(entries.filter(([k]) => k.startsWith('${
106
+ config.kit.env.publicPrefix
107
+ }')));
108
+
109
+ set_private_env(prv);
110
+ set_public_env(pub);
111
+
112
+ this.options.public_env = pub;
113
+
114
+ if (!this.options.hooks) {
115
+ const module = await import(${s(hooks)});
116
+
117
+ // TODO remove this for 1.0
118
+ if (module.externalFetch) {
119
+ throw new Error('externalFetch has been removed — use handleFetch instead. See https://github.com/sveltejs/kit/pull/6565 for details');
120
+ }
121
+
122
+ this.options.hooks = {
123
+ handle: module.handle || (({ event, resolve }) => resolve(event)),
124
+ handleError: module.handleError || (({ error }) => console.error(error.stack)),
125
+ handleFetch: module.handleFetch || (({ request, fetch }) => fetch(request))
126
+ };
127
+ }
128
+ }
129
+
130
+ async respond(request, options = {}) {
131
+ if (!(request instanceof Request)) {
132
+ throw new Error('The first argument to server.respond must be a Request object. See https://github.com/sveltejs/kit/pull/3384 for details');
133
+ }
134
+
135
+ return respond(request, this.options, options);
136
+ }
137
+ }
138
+ `;
139
+
140
+ /**
141
+ * @param {{
142
+ * cwd: string;
143
+ * config: import('types').ValidatedConfig;
144
+ * vite_config: import('vite').ResolvedConfig;
145
+ * vite_config_env: import('vite').ConfigEnv;
146
+ * manifest_data: import('types').ManifestData;
147
+ * build_dir: string;
148
+ * output_dir: string;
149
+ * service_worker_entry_file: string | null;
150
+ * }} options
151
+ * @param {{ vite_manifest: import('vite').Manifest, assets: import('rollup').OutputAsset[] }} client
152
+ */
153
+ export async function build_server(options, client) {
154
+ const {
155
+ cwd,
156
+ config,
157
+ vite_config,
158
+ vite_config_env,
159
+ manifest_data,
160
+ build_dir,
161
+ output_dir,
162
+ service_worker_entry_file
163
+ } = options;
164
+
165
+ let hooks_file = resolve_entry(config.kit.files.hooks.server);
166
+
167
+ // TODO remove for 1.0
168
+ if (!hooks_file) {
169
+ const old_file = resolve_entry(path.join(process.cwd(), 'src', 'hooks'));
170
+ if (old_file && fs.existsSync(old_file)) {
171
+ throw new Error(
172
+ `Rename your server hook file from ${posixify(
173
+ path.relative(process.cwd(), old_file)
174
+ )} to ${posixify(
175
+ path.relative(process.cwd(), config.kit.files.hooks.server)
176
+ )}${path.extname(
177
+ old_file
178
+ )} (because there's also client hooks now). See the PR for more information: https://github.com/sveltejs/kit/pull/6586`
179
+ );
180
+ }
181
+ }
182
+
183
+ if (!hooks_file || !fs.existsSync(hooks_file)) {
184
+ hooks_file = path.join(config.kit.outDir, 'build/hooks.js');
185
+ fs.writeFileSync(hooks_file, '');
186
+ }
187
+
188
+ /** @type {Record<string, string>} */
189
+ const input = {
190
+ index: `${build_dir}/index.js`
191
+ };
192
+
193
+ // add entry points for every endpoint...
194
+ manifest_data.routes.forEach((route) => {
195
+ if (route.endpoint) {
196
+ const resolved = path.resolve(cwd, route.endpoint.file);
197
+ const relative = decodeURIComponent(path.relative(config.kit.files.routes, resolved));
198
+ const name = posixify(path.join('entries/endpoints', relative.replace(/\.js$/, '')));
199
+ input[name] = resolved;
200
+ }
201
+ });
202
+
203
+ // ...and every component used by pages...
204
+ manifest_data.nodes.forEach((node) => {
205
+ for (const file of [node.component, node.shared, node.server]) {
206
+ if (file) {
207
+ const resolved = path.resolve(cwd, file);
208
+ const relative = decodeURIComponent(path.relative(config.kit.files.routes, resolved));
209
+
210
+ const name = relative.startsWith('..')
211
+ ? posixify(path.join('entries/fallbacks', path.basename(file)))
212
+ : posixify(path.join('entries/pages', relative.replace(/\.js$/, '')));
213
+ input[name] = resolved;
214
+ }
215
+ }
216
+ });
217
+
218
+ // ...and every matcher
219
+ Object.entries(manifest_data.matchers).forEach(([key, file]) => {
220
+ const name = posixify(path.join('entries/matchers', key));
221
+ input[name] = path.resolve(cwd, file);
222
+ });
223
+
224
+ /** @type {(file: string) => string} */
225
+ const app_relative = (file) => {
226
+ const relative_file = path.relative(build_dir, path.resolve(cwd, file));
227
+ return relative_file[0] === '.' ? relative_file : `./${relative_file}`;
228
+ };
229
+
230
+ fs.writeFileSync(
231
+ input.index,
232
+ server_template({
233
+ config,
234
+ hooks: app_relative(hooks_file),
235
+ has_service_worker: config.kit.serviceWorker.register && !!service_worker_entry_file,
236
+ runtime: posixify(path.relative(build_dir, runtime_directory)),
237
+ template: load_template(cwd, config),
238
+ error_page: load_error_page(config)
239
+ })
240
+ );
241
+
242
+ const merged_config = merge_vite_configs(
243
+ get_default_build_config({ config, input, ssr: true, outDir: `${output_dir}/server` }),
244
+ await get_vite_config(vite_config, vite_config_env)
245
+ );
246
+
247
+ const { chunks } = await create_build(merged_config);
248
+
249
+ /** @type {import('vite').Manifest} */
250
+ const vite_manifest = JSON.parse(
251
+ fs.readFileSync(`${output_dir}/server/${vite_config.build.manifest}`, 'utf-8')
252
+ );
253
+
254
+ mkdirp(`${output_dir}/server/nodes`);
255
+ mkdirp(`${output_dir}/server/stylesheets`);
256
+
257
+ const stylesheet_lookup = new Map();
258
+
259
+ client.assets.forEach((asset) => {
260
+ if (asset.fileName.endsWith('.css')) {
261
+ if (asset.source.length < config.kit.inlineStyleThreshold) {
262
+ const index = stylesheet_lookup.size;
263
+ const file = `${output_dir}/server/stylesheets/${index}.js`;
264
+
265
+ fs.writeFileSync(file, `// ${asset.fileName}\nexport default ${s(asset.source)};`);
266
+ stylesheet_lookup.set(asset.fileName, index);
267
+ }
268
+ }
269
+ });
270
+
271
+ manifest_data.nodes.forEach((node, i) => {
272
+ /** @type {string[]} */
273
+ const imports = [];
274
+
275
+ // String representation of
276
+ /** @type {import('types').SSRNode} */
277
+ /** @type {string[]} */
278
+ const exports = [`export const index = ${i};`];
279
+
280
+ /** @type {string[]} */
281
+ const imported = [];
282
+
283
+ /** @type {string[]} */
284
+ const stylesheets = [];
285
+
286
+ if (node.component) {
287
+ const entry = find_deps(client.vite_manifest, node.component, true);
288
+
289
+ imported.push(...entry.imports);
290
+ stylesheets.push(...entry.stylesheets);
291
+
292
+ exports.push(
293
+ `export const component = async () => (await import('../${
294
+ resolve_symlinks(vite_manifest, node.component).chunk.file
295
+ }')).default;`,
296
+ `export const file = '${entry.file}';` // TODO what is this?
297
+ );
298
+ }
299
+
300
+ if (node.shared) {
301
+ const entry = find_deps(client.vite_manifest, node.shared, true);
302
+
303
+ imported.push(...entry.imports);
304
+ stylesheets.push(...entry.stylesheets);
305
+
306
+ imports.push(`import * as shared from '../${vite_manifest[node.shared].file}';`);
307
+ exports.push(`export { shared };`);
308
+ }
309
+
310
+ if (node.server) {
311
+ imports.push(`import * as server from '../${vite_manifest[node.server].file}';`);
312
+ exports.push(`export { server };`);
313
+ }
314
+
315
+ exports.push(
316
+ `export const imports = ${s(imported)};`,
317
+ `export const stylesheets = ${s(stylesheets)};`
318
+ );
319
+
320
+ /** @type {string[]} */
321
+ const styles = [];
322
+
323
+ stylesheets.forEach((file) => {
324
+ if (stylesheet_lookup.has(file)) {
325
+ const index = stylesheet_lookup.get(file);
326
+ const name = `stylesheet_${index}`;
327
+ imports.push(`import ${name} from '../stylesheets/${index}.js';`);
328
+ styles.push(`\t${s(file)}: ${name}`);
329
+ }
330
+ });
331
+
332
+ if (styles.length > 0) {
333
+ exports.push(`export const inline_styles = () => ({\n${styles.join(',\n')}\n});`);
334
+ }
335
+
336
+ const out = `${output_dir}/server/nodes/${i}.js`;
337
+ fs.writeFileSync(out, `${imports.join('\n')}\n\n${exports.join('\n')}\n`);
338
+ });
339
+
340
+ return {
341
+ chunks,
342
+ vite_manifest,
343
+ methods: get_methods(cwd, chunks, manifest_data)
344
+ };
345
+ }
346
+
347
+ /**
348
+ * @param {string} cwd
349
+ * @param {import('rollup').OutputChunk[]} output
350
+ * @param {import('types').ManifestData} manifest_data
351
+ */
352
+ function get_methods(cwd, output, manifest_data) {
353
+ /** @type {Record<string, string[]>} */
354
+ const lookup = {};
355
+ output.forEach((chunk) => {
356
+ if (!chunk.facadeModuleId) return;
357
+ const id = chunk.facadeModuleId.slice(cwd.length + 1);
358
+ lookup[id] = chunk.exports;
359
+ });
360
+
361
+ /** @type {Record<string, import('types').HttpMethod[]>} */
362
+ const methods = {};
363
+ manifest_data.routes.forEach((route) => {
364
+ if (route.endpoint) {
365
+ if (lookup[route.endpoint.file]) {
366
+ methods[route.endpoint.file] = lookup[route.endpoint.file].filter(is_http_method);
367
+ }
368
+ }
369
+
370
+ if (route.leaf?.server) {
371
+ if (lookup[route.leaf.server]) {
372
+ methods[route.leaf.server] = lookup[route.leaf.server].filter(is_http_method);
373
+ }
374
+ }
375
+ });
376
+
377
+ return methods;
378
+ }
@@ -0,0 +1,90 @@
1
+ import fs from 'fs';
2
+ import * as vite from 'vite';
3
+ import { s } from '../../../utils/misc.js';
4
+ import { assets_base } from './utils.js';
5
+
6
+ /**
7
+ * @param {{
8
+ * config: import('types').ValidatedConfig;
9
+ * vite_config: import('vite').ResolvedConfig;
10
+ * vite_config_env: import('vite').ConfigEnv;
11
+ * manifest_data: import('types').ManifestData;
12
+ * output_dir: string;
13
+ * service_worker_entry_file: string | null;
14
+ * }} options
15
+ * @param {import('types').Prerendered} prerendered
16
+ * @param {import('vite').Manifest} client_manifest
17
+ */
18
+ export async function build_service_worker(
19
+ { config, manifest_data, output_dir, service_worker_entry_file },
20
+ prerendered,
21
+ client_manifest
22
+ ) {
23
+ const build = new Set();
24
+ for (const key in client_manifest) {
25
+ const { file, css = [], assets = [] } = client_manifest[key];
26
+ build.add(file);
27
+ css.forEach((file) => build.add(file));
28
+ assets.forEach((file) => build.add(file));
29
+ }
30
+
31
+ const service_worker = `${config.kit.outDir}/generated/service-worker.js`;
32
+
33
+ fs.writeFileSync(
34
+ service_worker,
35
+ `
36
+ // TODO remove for 1.0
37
+ export const timestamp = {
38
+ toString: () => {
39
+ throw new Error('\`timestamp\` has been removed from $service-worker. Use \`version\` instead');
40
+ }
41
+ };
42
+
43
+ export const build = [
44
+ ${Array.from(build)
45
+ .map((file) => `${s(`${config.kit.paths.base}/${file}`)}`)
46
+ .join(',\n\t\t\t\t')}
47
+ ];
48
+
49
+ export const files = [
50
+ ${manifest_data.assets
51
+ .filter((asset) => config.kit.serviceWorker.files(asset.file))
52
+ .map((asset) => `${s(`${config.kit.paths.base}/${asset.file}`)}`)
53
+ .join(',\n\t\t\t\t')}
54
+ ];
55
+
56
+ export const prerendered = [
57
+ ${prerendered.paths.map((path) => s(path)).join(',\n\t\t\t\t')}
58
+ ];
59
+
60
+ export const version = ${s(config.kit.version.name)};
61
+ `
62
+ .replace(/^\t{3}/gm, '')
63
+ .trim()
64
+ );
65
+
66
+ await vite.build({
67
+ base: assets_base(config.kit),
68
+ build: {
69
+ lib: {
70
+ entry: /** @type {string} */ (service_worker_entry_file),
71
+ name: 'app',
72
+ formats: ['es']
73
+ },
74
+ rollupOptions: {
75
+ output: {
76
+ entryFileNames: 'service-worker.js'
77
+ }
78
+ },
79
+ outDir: `${output_dir}/client`,
80
+ emptyOutDir: false
81
+ },
82
+ configFile: false,
83
+ resolve: {
84
+ alias: {
85
+ '$service-worker': service_worker,
86
+ $lib: config.kit.files.lib
87
+ }
88
+ }
89
+ });
90
+ }
@@ -0,0 +1,180 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import * as vite from 'vite';
4
+ import { get_aliases } from '../utils.js';
5
+
6
+ /**
7
+ * @typedef {import('rollup').RollupOutput} RollupOutput
8
+ * @typedef {import('rollup').OutputChunk} OutputChunk
9
+ * @typedef {import('rollup').OutputAsset} OutputAsset
10
+ */
11
+
12
+ /**
13
+ * Invokes Vite.
14
+ * @param {import('vite').UserConfig} config
15
+ */
16
+ export async function create_build(config) {
17
+ const { output } = /** @type {RollupOutput} */ (
18
+ await vite.build({ ...config, configFile: false })
19
+ );
20
+
21
+ const chunks = output.filter(
22
+ /** @returns {output is OutputChunk} */ (output) => output.type === 'chunk'
23
+ );
24
+
25
+ const assets = output.filter(
26
+ /** @returns {output is OutputAsset} */ (output) => output.type === 'asset'
27
+ );
28
+
29
+ return { chunks, assets };
30
+ }
31
+
32
+ /**
33
+ * Adds transitive JS and CSS dependencies to the js and css inputs.
34
+ * @param {import('vite').Manifest} manifest
35
+ * @param {string} entry
36
+ * @param {boolean} add_dynamic_css
37
+ */
38
+ export function find_deps(manifest, entry, add_dynamic_css) {
39
+ /** @type {Set<string>} */
40
+ const seen = new Set();
41
+
42
+ /** @type {Set<string>} */
43
+ const imports = new Set();
44
+
45
+ /** @type {Set<string>} */
46
+ const stylesheets = new Set();
47
+
48
+ /**
49
+ * @param {string} current
50
+ * @param {boolean} add_js
51
+ */
52
+ function traverse(current, add_js) {
53
+ if (seen.has(current)) return;
54
+ seen.add(current);
55
+
56
+ const { chunk } = resolve_symlinks(manifest, current);
57
+
58
+ if (add_js) imports.add(chunk.file);
59
+
60
+ if (chunk.css) {
61
+ chunk.css.forEach((file) => stylesheets.add(file));
62
+ }
63
+
64
+ if (chunk.imports) {
65
+ chunk.imports.forEach((file) => traverse(file, add_js));
66
+ }
67
+
68
+ if (add_dynamic_css && chunk.dynamicImports) {
69
+ chunk.dynamicImports.forEach((file) => traverse(file, false));
70
+ }
71
+ }
72
+
73
+ const { chunk, file } = resolve_symlinks(manifest, entry);
74
+
75
+ traverse(file, true);
76
+
77
+ return {
78
+ file: chunk.file,
79
+ imports: Array.from(imports),
80
+ stylesheets: Array.from(stylesheets)
81
+ };
82
+ }
83
+
84
+ /**
85
+ * @param {import('vite').Manifest} manifest
86
+ * @param {string} file
87
+ */
88
+ export function resolve_symlinks(manifest, file) {
89
+ while (!manifest[file]) {
90
+ file = path.relative('.', fs.realpathSync(file));
91
+ }
92
+
93
+ const chunk = manifest[file];
94
+
95
+ return { chunk, file };
96
+ }
97
+
98
+ /**
99
+ * The Vite configuration that we use by default.
100
+ * @param {{
101
+ * config: import('types').ValidatedConfig;
102
+ * input: Record<string, string>;
103
+ * ssr: boolean;
104
+ * outDir: string;
105
+ * }} options
106
+ * @return {import('vite').UserConfig}
107
+ */
108
+ export function get_default_build_config({ config, input, ssr, outDir }) {
109
+ const prefix = `${config.kit.appDir}/immutable`;
110
+
111
+ return {
112
+ appType: 'custom',
113
+ base: ssr ? assets_base(config.kit) : './',
114
+ build: {
115
+ cssCodeSplit: true,
116
+ // don't use the default name to avoid collisions with 'static/manifest.json'
117
+ manifest: 'vite-manifest.json',
118
+ outDir,
119
+ polyfillModulePreload: false,
120
+ rollupOptions: {
121
+ input,
122
+ output: {
123
+ format: 'esm',
124
+ entryFileNames: ssr ? '[name].js' : `${prefix}/[name]-[hash].js`,
125
+ chunkFileNames: ssr ? 'chunks/[name].js' : `${prefix}/chunks/[name]-[hash].js`,
126
+ assetFileNames: `${prefix}/assets/[name]-[hash][extname]`,
127
+ hoistTransitiveImports: false
128
+ },
129
+ preserveEntrySignatures: 'strict'
130
+ },
131
+ ssr,
132
+ target: ssr ? 'node14.8' : undefined
133
+ },
134
+ define: {
135
+ __SVELTEKIT_ADAPTER_NAME__: JSON.stringify(config.kit.adapter?.name),
136
+ __SVELTEKIT_APP_VERSION__: JSON.stringify(config.kit.version.name),
137
+ __SVELTEKIT_APP_VERSION_FILE__: JSON.stringify(`${config.kit.appDir}/version.json`),
138
+ __SVELTEKIT_APP_VERSION_POLL_INTERVAL__: JSON.stringify(config.kit.version.pollInterval),
139
+ __SVELTEKIT_DEV__: 'false'
140
+ },
141
+ publicDir: ssr ? false : config.kit.files.assets,
142
+ resolve: {
143
+ alias: get_aliases(config.kit)
144
+ },
145
+ optimizeDeps: {
146
+ exclude: ['@sveltejs/kit']
147
+ },
148
+ ssr: {
149
+ noExternal: ['@sveltejs/kit']
150
+ },
151
+ worker: {
152
+ rollupOptions: {
153
+ output: {
154
+ entryFileNames: `${prefix}/workers/[name]-[hash].js`,
155
+ chunkFileNames: `${prefix}/workers/chunks/[name]-[hash].js`,
156
+ hoistTransitiveImports: false
157
+ }
158
+ }
159
+ }
160
+ };
161
+ }
162
+
163
+ /**
164
+ * @param {import('types').ValidatedKitConfig} config
165
+ * @returns {string}
166
+ */
167
+ export function assets_base(config) {
168
+ return (config.paths.assets || config.paths.base || '.') + '/';
169
+ }
170
+
171
+ const method_names = new Set(['GET', 'HEAD', 'PUT', 'POST', 'DELETE', 'PATCH']);
172
+
173
+ // If we'd written this in TypeScript, it could be easy...
174
+ /**
175
+ * @param {string} str
176
+ * @returns {str is import('types').HttpMethod}
177
+ */
178
+ export function is_http_method(str) {
179
+ return method_names.has(str);
180
+ }