@sveltejs/kit 1.0.0-next.48 → 1.0.0-next.480

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