@sveltejs/kit 1.0.0-next.344 → 1.0.0-next.347

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.
@@ -1,1390 +1,118 @@
1
- import fs__default, { readFileSync, writeFileSync } from 'fs';
2
- import path__default, { join, dirname } from 'path';
3
- import { p as posixify, m as mkdirp, r as rimraf } from './filesystem.js';
4
- import { all } from './sync.js';
5
- import { p as print_config_conflicts, d as get_aliases, r as resolve_entry, g as get_runtime_path, l as load_template } from '../cli.js';
6
- import { g as generate_manifest } from './index3.js';
7
- import * as vite from 'vite';
8
- import { s } from './misc.js';
9
- import { d as deep_merge } from './object.js';
10
- import { svelte } from '@sveltejs/vite-plugin-svelte';
11
- import { pathToFileURL, URL as URL$1 } from 'url';
12
- import { installPolyfills } from '../node/polyfills.js';
13
- import './write_tsconfig.js';
14
- import 'sade';
15
- import 'child_process';
16
- import 'net';
17
- import 'chokidar';
18
- import 'os';
19
- import 'node:http';
20
- import 'node:https';
21
- import 'node:zlib';
22
- import 'node:stream';
23
- import 'node:util';
24
- import 'node:url';
25
- import 'crypto';
26
-
27
- const absolute = /^([a-z]+:)?\/?\//;
28
- const scheme = /^[a-z]+:/;
29
-
30
- /**
31
- * @param {string} base
32
- * @param {string} path
33
- */
34
- function resolve(base, path) {
35
- if (scheme.test(path)) return path;
36
-
37
- const base_match = absolute.exec(base);
38
- const path_match = absolute.exec(path);
39
-
40
- if (!base_match) {
41
- throw new Error(`bad base path: "${base}"`);
42
- }
43
-
44
- const baseparts = path_match ? [] : base.slice(base_match[0].length).split('/');
45
- const pathparts = path_match ? path.slice(path_match[0].length).split('/') : path.split('/');
46
-
47
- baseparts.pop();
48
-
49
- for (let i = 0; i < pathparts.length; i += 1) {
50
- const part = pathparts[i];
51
- if (part === '.') continue;
52
- else if (part === '..') baseparts.pop();
53
- else baseparts.push(part);
54
- }
55
-
56
- const prefix = (path_match && path_match[0]) || (base_match && base_match[0]) || '';
57
-
58
- return `${prefix}${baseparts.join('/')}`;
59
- }
60
-
61
- /** @param {string} path */
62
- function is_root_relative(path) {
63
- return path[0] === '/' && path[1] !== '/';
64
- }
65
-
66
- /**
67
- * @param {string} path
68
- * @param {import('types').TrailingSlash} trailing_slash
69
- */
70
- function normalize_path(path, trailing_slash) {
71
- if (path === '/' || trailing_slash === 'ignore') return path;
72
-
73
- if (trailing_slash === 'never') {
74
- return path.endsWith('/') ? path.slice(0, -1) : path;
75
- } else if (trailing_slash === 'always' && !path.endsWith('/')) {
76
- return path + '/';
77
- }
78
-
79
- return path;
80
- }
1
+ import { s, p as parse_route_id } from './misc.js';
2
+ import { b as get_mime_lookup } from '../cli.js';
81
3
 
82
4
  /**
83
5
  * @param {{
84
- * cwd: string;
85
- * assets_base: string;
86
- * config: import('types').ValidatedConfig;
87
- * manifest_data: import('types').ManifestData;
88
- * output_dir: string;
89
- * service_worker_entry_file: string | null;
90
- * }} options
91
- * @param {import('types').Prerendered} prerendered
92
- * @param {import('vite').Manifest} client_manifest
93
- */
94
- async function build_service_worker(
95
- { cwd, assets_base, config, manifest_data, output_dir, service_worker_entry_file },
96
- prerendered,
97
- client_manifest
98
- ) {
99
- const build = new Set();
100
- for (const key in client_manifest) {
101
- const { file, css = [], assets = [] } = client_manifest[key];
102
- build.add(file);
103
- css.forEach((file) => build.add(file));
104
- assets.forEach((file) => build.add(file));
105
- }
106
-
107
- const service_worker = `${config.kit.outDir}/generated/service-worker.js`;
108
-
109
- fs__default.writeFileSync(
110
- service_worker,
111
- `
112
- // TODO remove for 1.0
113
- export const timestamp = {
114
- toString: () => {
115
- throw new Error('\`timestamp\` has been removed from $service-worker. Use \`version\` instead');
116
- }
117
- };
118
-
119
- export const build = [
120
- ${Array.from(build)
121
- .map((file) => `${s(`${config.kit.paths.base}/${config.kit.appDir}/immutable/${file}`)}`)
122
- .join(',\n\t\t\t\t')}
123
- ];
124
-
125
- export const files = [
126
- ${manifest_data.assets
127
- .filter((asset) => config.kit.serviceWorker.files(asset.file))
128
- .map((asset) => `${s(`${config.kit.paths.base}/${asset.file}`)}`)
129
- .join(',\n\t\t\t\t')}
130
- ];
131
-
132
- export const prerendered = [
133
- ${prerendered.paths
134
- .map((path) => s(normalize_path(path, config.kit.trailingSlash)))
135
- .join(',\n\t\t\t\t')}
136
- ];
137
-
138
- export const version = ${s(config.kit.version.name)};
139
- `
140
- .replace(/^\t{3}/gm, '')
141
- .trim()
142
- );
143
-
144
- /** @type {[any, string[]]} */
145
- const [merged_config, conflicts] = deep_merge(await config.kit.vite(), {
146
- configFile: false,
147
- root: cwd,
148
- base: assets_base,
149
- build: {
150
- lib: {
151
- entry: service_worker_entry_file,
152
- name: 'app',
153
- formats: ['es']
154
- },
155
- rollupOptions: {
156
- output: {
157
- entryFileNames: 'service-worker.js'
158
- }
159
- },
160
- outDir: `${output_dir}/client`,
161
- emptyOutDir: false
162
- },
163
- resolve: {
164
- alias: {
165
- '$service-worker': service_worker,
166
- $lib: config.kit.files.lib
167
- }
168
- }
169
- });
170
-
171
- print_config_conflicts(conflicts, 'kit.vite.', 'build_service_worker');
172
-
173
- await vite.build(merged_config);
174
- }
175
-
176
- /**
177
- * @typedef {import('rollup').RollupOutput} RollupOutput
178
- * @typedef {import('rollup').OutputChunk} OutputChunk
179
- * @typedef {import('rollup').OutputAsset} OutputAsset
180
- */
181
-
182
- /** @param {import('vite').UserConfig} config */
183
- async function create_build(config) {
184
- const { output } = /** @type {RollupOutput} */ (await vite.build(config));
185
-
186
- const chunks = output.filter(
187
- /** @returns {output is OutputChunk} */ (output) => output.type === 'chunk'
188
- );
189
-
190
- const assets = output.filter(
191
- /** @returns {output is OutputAsset} */ (output) => output.type === 'asset'
192
- );
193
-
194
- return { chunks, assets };
195
- }
196
-
197
- /**
198
- * @param {string} file
199
- * @param {import('vite').Manifest} manifest
200
- * @param {Set<string>} css
201
- * @param {Set<string>} js
202
- */
203
- function find_deps(file, manifest, js, css) {
204
- const chunk = manifest[file];
205
-
206
- if (js.has(chunk.file)) return;
207
- js.add(chunk.file);
208
-
209
- if (chunk.css) {
210
- chunk.css.forEach((file) => css.add(file));
211
- }
212
-
213
- if (chunk.imports) {
214
- chunk.imports.forEach((file) => find_deps(file, manifest, js, css));
215
- }
216
- }
217
-
218
- /**
219
- * @param {{
220
- * cwd: string;
221
- * assets_base: string;
222
- * config: import('types').ValidatedConfig
223
- * manifest_data: import('types').ManifestData
224
- * output_dir: string;
225
- * client_entry_file: string;
226
- * service_worker_entry_file: string | null;
227
- * service_worker_register: boolean;
228
- * }} options
229
- */
230
- async function build_client({
231
- cwd,
232
- assets_base,
233
- config,
234
- manifest_data,
235
- output_dir,
236
- client_entry_file
237
- }) {
238
- process.env.VITE_SVELTEKIT_APP_VERSION = config.kit.version.name;
239
- process.env.VITE_SVELTEKIT_APP_VERSION_FILE = `${config.kit.appDir}/version.json`;
240
- process.env.VITE_SVELTEKIT_APP_VERSION_POLL_INTERVAL = `${config.kit.version.pollInterval}`;
241
-
242
- const client_out_dir = `${output_dir}/client/${config.kit.appDir}`;
243
-
244
- /** @type {Record<string, string>} */
245
- const input = {
246
- start: path__default.resolve(cwd, client_entry_file)
247
- };
248
-
249
- // This step is optional — Vite/Rollup will create the necessary chunks
250
- // for everything regardless — but it means that entry chunks reflect
251
- // their location in the source code, which is helpful for debugging
252
- manifest_data.components.forEach((file) => {
253
- const resolved = path__default.resolve(cwd, file);
254
- const relative = path__default.relative(config.kit.files.routes, resolved);
255
-
256
- const name = relative.startsWith('..')
257
- ? path__default.basename(file)
258
- : posixify(path__default.join('pages', relative));
259
- input[name] = resolved;
260
- });
261
-
262
- /** @type {[any, string[]]} */
263
- const [merged_config, conflicts] = deep_merge(await config.kit.vite(), {
264
- configFile: false,
265
- root: cwd,
266
- base: assets_base,
267
- build: {
268
- cssCodeSplit: true,
269
- manifest: true,
270
- outDir: `${client_out_dir}/immutable`,
271
- polyfillDynamicImport: false,
272
- rollupOptions: {
273
- input,
274
- output: {
275
- entryFileNames: '[name]-[hash].js',
276
- chunkFileNames: 'chunks/[name]-[hash].js',
277
- assetFileNames: 'assets/[name]-[hash][extname]'
278
- },
279
- preserveEntrySignatures: 'strict'
280
- }
281
- },
282
- resolve: {
283
- alias: get_aliases(config)
284
- },
285
- plugins: [
286
- svelte({
287
- ...config,
288
- emitCss: true,
289
- compilerOptions: {
290
- ...config.compilerOptions,
291
- hydratable: !!config.kit.browser.hydrate
292
- },
293
- configFile: false
294
- })
295
- ],
296
- // prevent Vite copying the contents of `config.kit.files.assets`,
297
- // if it happens to be 'public' instead of 'static'
298
- publicDir: false
299
- });
300
-
301
- print_config_conflicts(conflicts, 'kit.vite.', 'build_client');
302
-
303
- const { chunks, assets } = await create_build(merged_config);
304
-
305
- /** @type {import('vite').Manifest} */
306
- const vite_manifest = JSON.parse(
307
- fs__default.readFileSync(`${client_out_dir}/immutable/manifest.json`, 'utf-8')
308
- );
309
-
310
- const entry = posixify(client_entry_file);
311
- const entry_js = new Set();
312
- const entry_css = new Set();
313
- find_deps(entry, vite_manifest, entry_js, entry_css);
314
-
315
- fs__default.writeFileSync(
316
- `${client_out_dir}/version.json`,
317
- JSON.stringify({ version: process.env.VITE_SVELTEKIT_APP_VERSION })
318
- );
319
-
320
- return {
321
- assets,
322
- chunks,
323
- entry: {
324
- file: vite_manifest[entry].file,
325
- js: Array.from(entry_js),
326
- css: Array.from(entry_css)
327
- },
328
- vite_manifest
329
- };
330
- }
331
-
332
- /**
333
- * @param {{
334
- * hooks: string;
335
- * config: import('types').ValidatedConfig;
336
- * has_service_worker: boolean;
337
- * runtime: string;
338
- * template: string;
6
+ * build_data: import('types').BuildData;
7
+ * relative_path: string;
8
+ * routes: import('types').RouteData[];
9
+ * format?: 'esm' | 'cjs'
339
10
  * }} opts
340
11
  */
341
- const server_template = ({ config, hooks, has_service_worker, runtime, template }) => `
342
- import root from '__GENERATED__/root.svelte';
343
- import { respond } from '${runtime}/server/index.js';
344
- import { set_paths, assets, base } from '${runtime}/paths.js';
345
- import { set_prerendering } from '${runtime}/env.js';
346
-
347
- const template = ({ head, body, assets, nonce }) => ${s(template)
348
- .replace('%sveltekit.head%', '" + head + "')
349
- .replace('%sveltekit.body%', '" + body + "')
350
- .replace(/%sveltekit\.assets%/g, '" + assets + "')
351
- .replace(/%sveltekit\.nonce%/g, '" + nonce + "')};
352
-
353
- let read = null;
354
-
355
- set_paths(${s(config.kit.paths)});
356
-
357
- let default_protocol = 'https';
358
-
359
- // allow paths to be globally overridden
360
- // in svelte-kit preview and in prerendering
361
- export function override(settings) {
362
- default_protocol = settings.protocol || default_protocol;
363
- set_paths(settings.paths);
364
- set_prerendering(settings.prerendering);
365
- read = settings.read;
366
- }
367
-
368
- export class Server {
369
- constructor(manifest) {
370
- this.options = {
371
- csp: ${s(config.kit.csp)},
372
- dev: false,
373
- floc: ${config.kit.floc},
374
- get_stack: error => String(error), // for security
375
- handle_error: (error, event) => {
376
- this.options.hooks.handleError({
377
- error,
378
- event,
379
-
380
- // TODO remove for 1.0
381
- // @ts-expect-error
382
- get request() {
383
- throw new Error('request in handleError has been replaced with event. See https://github.com/sveltejs/kit/pull/3384 for details');
384
- }
385
- });
386
- error.stack = this.options.get_stack(error);
387
- },
388
- hooks: null,
389
- hydrate: ${s(config.kit.browser.hydrate)},
390
- manifest,
391
- method_override: ${s(config.kit.methodOverride)},
392
- paths: { base, assets },
393
- prefix: assets + '/${config.kit.appDir}/immutable/',
394
- prerender: {
395
- default: ${config.kit.prerender.default},
396
- enabled: ${config.kit.prerender.enabled}
397
- },
398
- read,
399
- root,
400
- service_worker: ${has_service_worker ? "base + '/service-worker.js'" : 'null'},
401
- router: ${s(config.kit.browser.router)},
402
- template,
403
- template_contains_nonce: ${template.includes('%sveltekit.nonce%')},
404
- trailing_slash: ${s(config.kit.trailingSlash)}
405
- };
406
- }
407
-
408
- async respond(request, options = {}) {
409
- if (!(request instanceof Request)) {
410
- throw new Error('The first argument to server.respond must be a Request object. See https://github.com/sveltejs/kit/pull/3384 for details');
411
- }
412
-
413
- if (!this.options.hooks) {
414
- const module = await import(${s(hooks)});
415
- this.options.hooks = {
416
- getSession: module.getSession || (() => ({})),
417
- handle: module.handle || (({ event, resolve }) => resolve(event)),
418
- handleError: module.handleError || (({ error }) => console.error(error.stack)),
419
- externalFetch: module.externalFetch || fetch
420
- };
421
- }
422
-
423
- return respond(request, this.options, options);
424
- }
425
- }
426
- `;
427
-
428
- /**
429
- * @param {{
430
- * cwd: string;
431
- * assets_base: string;
432
- * config: import('types').ValidatedConfig
433
- * manifest_data: import('types').ManifestData
434
- * build_dir: string;
435
- * output_dir: string;
436
- * service_worker_entry_file: string | null;
437
- * service_worker_register: boolean;
438
- * }} options
439
- * @param {{ vite_manifest: import('vite').Manifest, assets: import('rollup').OutputAsset[] }} client
440
- */
441
- async function build_server(
442
- {
443
- cwd,
444
- assets_base,
445
- config,
446
- manifest_data,
447
- build_dir,
448
- output_dir,
449
- service_worker_entry_file,
450
- service_worker_register
451
- },
452
- client
453
- ) {
454
- let hooks_file = resolve_entry(config.kit.files.hooks);
455
- if (!hooks_file || !fs__default.existsSync(hooks_file)) {
456
- hooks_file = path__default.join(config.kit.outDir, 'build/hooks.js');
457
- fs__default.writeFileSync(hooks_file, '');
458
- }
12
+ function generate_manifest({ build_data, relative_path, routes, format = 'esm' }) {
13
+ /** @typedef {{ index: number, path: string }} LookupEntry */
14
+ /** @type {Map<string, LookupEntry>} */
15
+ const bundled_nodes = new Map();
459
16
 
460
- /** @type {Record<string, string>} */
461
- const input = {
462
- index: `${build_dir}/index.js`
463
- };
464
-
465
- // add entry points for every endpoint...
466
- manifest_data.routes.forEach((route) => {
467
- const file = route.type === 'endpoint' ? route.file : route.shadow;
468
-
469
- if (file) {
470
- const resolved = path__default.resolve(cwd, file);
471
- const relative = path__default.relative(config.kit.files.routes, resolved);
472
- const name = posixify(path__default.join('entries/endpoints', relative.replace(/\.js$/, '')));
473
- input[name] = resolved;
474
- }
475
- });
476
-
477
- // ...and every component used by pages...
478
- manifest_data.components.forEach((file) => {
479
- const resolved = path__default.resolve(cwd, file);
480
- const relative = path__default.relative(config.kit.files.routes, resolved);
481
-
482
- const name = relative.startsWith('..')
483
- ? posixify(path__default.join('entries/fallbacks', path__default.basename(file)))
484
- : posixify(path__default.join('entries/pages', relative));
485
- input[name] = resolved;
17
+ // 0 and 1 are special, they correspond to the root layout and root error nodes
18
+ bundled_nodes.set(build_data.manifest_data.components[0], {
19
+ path: `${relative_path}/nodes/0.js`,
20
+ index: 0
486
21
  });
487
22
 
488
- // ...and every matcher
489
- Object.entries(manifest_data.matchers).forEach(([key, file]) => {
490
- const name = posixify(path__default.join('entries/matchers', key));
491
- input[name] = path__default.resolve(cwd, file);
23
+ bundled_nodes.set(build_data.manifest_data.components[1], {
24
+ path: `${relative_path}/nodes/1.js`,
25
+ index: 1
492
26
  });
493
27
 
494
- /** @type {(file: string) => string} */
495
- const app_relative = (file) => {
496
- const relative_file = path__default.relative(build_dir, path__default.resolve(cwd, file));
497
- return relative_file[0] === '.' ? relative_file : `./${relative_file}`;
498
- };
499
-
500
- fs__default.writeFileSync(
501
- input.index,
502
- server_template({
503
- config,
504
- hooks: app_relative(hooks_file),
505
- has_service_worker: service_worker_register && !!service_worker_entry_file,
506
- runtime: get_runtime_path(config),
507
- template: load_template(cwd, config)
508
- })
509
- );
510
-
511
- /** @type {import('vite').UserConfig} */
512
- const vite_config = await config.kit.vite();
513
-
514
- const default_config = {
515
- build: {
516
- target: 'node14.8'
517
- },
518
- ssr: {
519
- // when developing against the Kit src code, we want to ensure that
520
- // our dependencies are bundled so that apps don't need to install
521
- // them as peerDependencies
522
- noExternal: []
523
-
524
- }
525
- };
526
-
527
- // don't warn on overriding defaults
528
- const [modified_vite_config] = deep_merge(default_config, vite_config);
529
-
530
- /** @type {[any, string[]]} */
531
- const [merged_config, conflicts] = deep_merge(modified_vite_config, {
532
- configFile: false,
533
- root: cwd,
534
- base: assets_base,
535
- build: {
536
- ssr: true,
537
- outDir: `${output_dir}/server`,
538
- manifest: true,
539
- polyfillDynamicImport: false,
540
- rollupOptions: {
541
- input,
542
- output: {
543
- format: 'esm',
544
- entryFileNames: '[name].js',
545
- chunkFileNames: 'chunks/[name]-[hash].js',
546
- assetFileNames: 'assets/[name]-[hash][extname]'
547
- },
548
- preserveEntrySignatures: 'strict'
549
- }
550
- },
551
- plugins: [
552
- svelte({
553
- ...config,
554
- compilerOptions: {
555
- ...config.compilerOptions,
556
- hydratable: !!config.kit.browser.hydrate
557
- },
558
- configFile: false
559
- })
560
- ],
561
- resolve: {
562
- alias: get_aliases(config)
563
- }
564
- });
565
-
566
- print_config_conflicts(conflicts, 'kit.vite.', 'build_server');
567
-
568
- process.env.VITE_SVELTEKIT_ADAPTER_NAME = config.kit.adapter?.name;
569
-
570
- const { chunks } = await create_build(merged_config);
571
-
572
- /** @type {import('vite').Manifest} */
573
- const vite_manifest = JSON.parse(fs__default.readFileSync(`${output_dir}/server/manifest.json`, 'utf-8'));
574
-
575
- mkdirp(`${output_dir}/server/nodes`);
576
- mkdirp(`${output_dir}/server/stylesheets`);
577
-
578
- const stylesheet_lookup = new Map();
579
-
580
- client.assets.forEach((asset) => {
581
- if (asset.fileName.endsWith('.css')) {
582
- if (asset.source.length < config.kit.inlineStyleThreshold) {
583
- const index = stylesheet_lookup.size;
584
- const file = `${output_dir}/server/stylesheets/${index}.js`;
585
-
586
- fs__default.writeFileSync(file, `// ${asset.fileName}\nexport default ${s(asset.source)};`);
587
- stylesheet_lookup.set(asset.fileName, index);
588
- }
589
- }
590
- });
591
-
592
- manifest_data.components.forEach((component, i) => {
593
- const file = `${output_dir}/server/nodes/${i}.js`;
594
-
595
- const js = new Set();
596
- const css = new Set();
597
- find_deps(component, client.vite_manifest, js, css);
598
-
599
- const imports = [`import * as module from '../${vite_manifest[component].file}';`];
600
-
601
- const exports = [
602
- 'export { module };',
603
- `export const entry = '${client.vite_manifest[component].file}';`,
604
- `export const js = ${s(Array.from(js))};`,
605
- `export const css = ${s(Array.from(css))};`
606
- ];
607
-
608
- /** @type {string[]} */
609
- const styles = [];
610
-
611
- css.forEach((file) => {
612
- if (stylesheet_lookup.has(file)) {
613
- const index = stylesheet_lookup.get(file);
614
- const name = `stylesheet_${index}`;
615
- imports.push(`import ${name} from '../stylesheets/${index}.js';`);
616
- styles.push(`\t${s(file)}: ${name}`);
617
- }
618
- });
28
+ routes.forEach((route) => {
29
+ if (route.type === 'page') {
30
+ [...route.a, ...route.b].forEach((component) => {
31
+ if (component && !bundled_nodes.has(component)) {
32
+ const i = build_data.manifest_data.components.indexOf(component);
619
33
 
620
- if (styles.length > 0) {
621
- exports.push(`export const styles = {\n${styles.join(',\n')}\n};`);
622
- }
623
-
624
- fs__default.writeFileSync(file, `${imports.join('\n')}\n\n${exports.join('\n')}\n`);
625
- });
626
-
627
- return {
628
- chunks,
629
- vite_manifest,
630
- methods: get_methods(cwd, chunks, manifest_data)
631
- };
632
- }
633
-
634
- /** @type {Record<string, string>} */
635
- const method_names = {
636
- get: 'get',
637
- head: 'head',
638
- post: 'post',
639
- put: 'put',
640
- del: 'delete',
641
- patch: 'patch'
642
- };
643
-
644
- /**
645
- * @param {string} cwd
646
- * @param {import('rollup').OutputChunk[]} output
647
- * @param {import('types').ManifestData} manifest_data
648
- */
649
- function get_methods(cwd, output, manifest_data) {
650
- /** @type {Record<string, string[]>} */
651
- const lookup = {};
652
- output.forEach((chunk) => {
653
- if (!chunk.facadeModuleId) return;
654
- const id = chunk.facadeModuleId.slice(cwd.length + 1);
655
- lookup[id] = chunk.exports;
656
- });
657
-
658
- /** @type {Record<string, import('types').HttpMethod[]>} */
659
- const methods = {};
660
- manifest_data.routes.forEach((route) => {
661
- const file = route.type === 'endpoint' ? route.file : route.shadow;
662
-
663
- if (file && lookup[file]) {
664
- methods[file] = lookup[file]
665
- .map((x) => /** @type {import('types').HttpMethod} */ (method_names[x]))
666
- .filter(Boolean);
667
- }
668
- });
669
-
670
- return methods;
671
- }
672
-
673
- /** @typedef {{
674
- * fn: () => Promise<any>,
675
- * fulfil: (value: any) => void,
676
- * reject: (error: Error) => void
677
- * }} Task */
678
-
679
- /** @param {number} concurrency */
680
- function queue(concurrency) {
681
- /** @type {Task[]} */
682
- const tasks = [];
683
-
684
- let current = 0;
685
-
686
- /** @type {(value?: any) => void} */
687
- let fulfil;
688
-
689
- /** @type {(error: Error) => void} */
690
- let reject;
691
-
692
- let closed = false;
693
-
694
- const done = new Promise((f, r) => {
695
- fulfil = f;
696
- reject = r;
697
- });
698
-
699
- done.catch(() => {
700
- // this is necessary in case a catch handler is never added
701
- // to the done promise by the user
702
- });
703
-
704
- function dequeue() {
705
- if (current < concurrency) {
706
- const task = tasks.shift();
707
-
708
- if (task) {
709
- current += 1;
710
- const promise = Promise.resolve(task.fn());
711
-
712
- promise
713
- .then(task.fulfil, (err) => {
714
- task.reject(err);
715
- reject(err);
716
- })
717
- .then(() => {
718
- current -= 1;
719
- dequeue();
34
+ bundled_nodes.set(component, {
35
+ path: `${relative_path}/nodes/${i}.js`,
36
+ index: bundled_nodes.size
720
37
  });
721
- } else if (current === 0) {
722
- closed = true;
723
- fulfil();
724
- }
725
- }
726
- }
727
-
728
- return {
729
- /** @param {() => any} fn */
730
- add: (fn) => {
731
- if (closed) throw new Error('Cannot add tasks to a queue that has ended');
732
-
733
- const promise = new Promise((fulfil, reject) => {
734
- tasks.push({ fn, fulfil, reject });
735
- });
736
-
737
- dequeue();
738
- return promise;
739
- },
740
-
741
- done: () => {
742
- if (current === 0) {
743
- closed = true;
744
- fulfil();
745
- }
746
-
747
- return done;
748
- }
749
- };
750
- }
751
-
752
- const DOCTYPE = 'DOCTYPE';
753
- const CDATA_OPEN = '[CDATA[';
754
- const CDATA_CLOSE = ']]>';
755
- const COMMENT_OPEN = '--';
756
- const COMMENT_CLOSE = '-->';
757
-
758
- const TAG_OPEN = /[a-zA-Z]/;
759
- const TAG_CHAR = /[a-zA-Z0-9]/;
760
- const ATTRIBUTE_NAME = /[^\t\n\f />"'=]/;
761
-
762
- const WHITESPACE = /[\s\n\r]/;
763
-
764
- /** @param {string} html */
765
- function crawl(html) {
766
- /** @type {string[]} */
767
- const hrefs = [];
768
-
769
- let i = 0;
770
- main: while (i < html.length) {
771
- const char = html[i];
772
-
773
- if (char === '<') {
774
- if (html[i + 1] === '!') {
775
- i += 2;
776
-
777
- if (html.slice(i, i + DOCTYPE.length).toUpperCase() === DOCTYPE) {
778
- i += DOCTYPE.length;
779
- while (i < html.length) {
780
- if (html[i++] === '>') {
781
- continue main;
782
- }
783
- }
784
38
  }
785
-
786
- // skip cdata
787
- if (html.slice(i, i + CDATA_OPEN.length) === CDATA_OPEN) {
788
- i += CDATA_OPEN.length;
789
- while (i < html.length) {
790
- if (html.slice(i, i + CDATA_CLOSE.length) === CDATA_CLOSE) {
791
- i += CDATA_CLOSE.length;
792
- continue main;
793
- }
794
-
795
- i += 1;
796
- }
797
- }
798
-
799
- // skip comments
800
- if (html.slice(i, i + COMMENT_OPEN.length) === COMMENT_OPEN) {
801
- i += COMMENT_OPEN.length;
802
- while (i < html.length) {
803
- if (html.slice(i, i + COMMENT_CLOSE.length) === COMMENT_CLOSE) {
804
- i += COMMENT_CLOSE.length;
805
- continue main;
806
- }
807
-
808
- i += 1;
809
- }
810
- }
811
- }
812
-
813
- // parse opening tags
814
- const start = ++i;
815
- if (TAG_OPEN.test(html[start])) {
816
- while (i < html.length) {
817
- if (!TAG_CHAR.test(html[i])) {
818
- break;
819
- }
820
-
821
- i += 1;
822
- }
823
-
824
- const tag = html.slice(start, i).toUpperCase();
825
-
826
- if (tag === 'SCRIPT' || tag === 'STYLE') {
827
- while (i < html.length) {
828
- if (
829
- html[i] === '<' &&
830
- html[i + 1] === '/' &&
831
- html.slice(i + 2, i + 2 + tag.length).toUpperCase() === tag
832
- ) {
833
- continue main;
834
- }
835
-
836
- i += 1;
837
- }
838
- }
839
-
840
- let href = '';
841
- let rel = '';
842
-
843
- while (i < html.length) {
844
- const start = i;
845
-
846
- const char = html[start];
847
- if (char === '>') break;
848
-
849
- if (ATTRIBUTE_NAME.test(char)) {
850
- i += 1;
851
-
852
- while (i < html.length) {
853
- if (!ATTRIBUTE_NAME.test(html[i])) {
854
- break;
855
- }
856
-
857
- i += 1;
858
- }
859
-
860
- const name = html.slice(start, i).toLowerCase();
861
-
862
- while (WHITESPACE.test(html[i])) i += 1;
863
-
864
- if (html[i] === '=') {
865
- i += 1;
866
- while (WHITESPACE.test(html[i])) i += 1;
867
-
868
- let value;
869
-
870
- if (html[i] === "'" || html[i] === '"') {
871
- const quote = html[i++];
872
-
873
- const start = i;
874
- let escaped = false;
875
-
876
- while (i < html.length) {
877
- if (!escaped) {
878
- const char = html[i];
879
-
880
- if (html[i] === quote) {
881
- break;
882
- }
883
-
884
- if (char === '\\') {
885
- escaped = true;
886
- }
887
- }
888
-
889
- i += 1;
890
- }
891
-
892
- value = html.slice(start, i);
893
- } else {
894
- const start = i;
895
- while (html[i] !== '>' && !WHITESPACE.test(html[i])) i += 1;
896
- value = html.slice(start, i);
897
-
898
- i -= 1;
899
- }
900
-
901
- if (name === 'href') {
902
- href = value;
903
- } else if (name === 'rel') {
904
- rel = value;
905
- } else if (name === 'src') {
906
- hrefs.push(value);
907
- } else if (name === 'srcset') {
908
- const candidates = [];
909
- let insideURL = true;
910
- value = value.trim();
911
- for (let i = 0; i < value.length; i++) {
912
- if (value[i] === ',' && (!insideURL || (insideURL && value[i + 1] === ' '))) {
913
- candidates.push(value.slice(0, i));
914
- value = value.substring(i + 1).trim();
915
- i = 0;
916
- insideURL = true;
917
- } else if (value[i] === ' ') {
918
- insideURL = false;
919
- }
920
- }
921
- candidates.push(value);
922
- for (const candidate of candidates) {
923
- const src = candidate.split(WHITESPACE)[0];
924
- hrefs.push(src);
925
- }
926
- }
927
- } else {
928
- i -= 1;
929
- }
930
- }
931
-
932
- i += 1;
933
- }
934
-
935
- if (href && !/\bexternal\b/i.test(rel)) {
936
- hrefs.push(href);
937
- }
938
- }
939
- }
940
-
941
- i += 1;
942
- }
943
-
944
- return hrefs;
945
- }
946
-
947
- /**
948
- * Inside a script element, only `</script` and `<!--` hold special meaning to the HTML parser.
949
- *
950
- * The first closes the script element, so everything after is treated as raw HTML.
951
- * The second disables further parsing until `-->`, so the script element might be unexpectedly
952
- * kept open until until an unrelated HTML comment in the page.
953
- *
954
- * U+2028 LINE SEPARATOR and U+2029 PARAGRAPH SEPARATOR are escaped for the sake of pre-2018
955
- * browsers.
956
- *
957
- * @see tests for unsafe parsing examples.
958
- * @see https://html.spec.whatwg.org/multipage/scripting.html#restrictions-for-contents-of-script-elements
959
- * @see https://html.spec.whatwg.org/multipage/syntax.html#cdata-rcdata-restrictions
960
- * @see https://html.spec.whatwg.org/multipage/parsing.html#script-data-state
961
- * @see https://html.spec.whatwg.org/multipage/parsing.html#script-data-double-escaped-state
962
- * @see https://github.com/tc39/proposal-json-superset
963
- * @type {Record<string, string>}
964
- */
965
- const render_json_payload_script_dict = {
966
- '<': '\\u003C',
967
- '\u2028': '\\u2028',
968
- '\u2029': '\\u2029'
969
- };
970
-
971
- new RegExp(
972
- `[${Object.keys(render_json_payload_script_dict).join('')}]`,
973
- 'g'
974
- );
975
-
976
- /**
977
- * When inside a double-quoted attribute value, only `&` and `"` hold special meaning.
978
- * @see https://html.spec.whatwg.org/multipage/parsing.html#attribute-value-(double-quoted)-state
979
- * @type {Record<string, string>}
980
- */
981
- const escape_html_attr_dict = {
982
- '&': '&amp;',
983
- '"': '&quot;'
984
- };
985
-
986
- const escape_html_attr_regex = new RegExp(
987
- // special characters
988
- `[${Object.keys(escape_html_attr_dict).join('')}]|` +
989
- // high surrogate without paired low surrogate
990
- '[\\ud800-\\udbff](?![\\udc00-\\udfff])|' +
991
- // a valid surrogate pair, the only match with 2 code units
992
- // we match it so that we can match unpaired low surrogates in the same pass
993
- // TODO: use lookbehind assertions once they are widely supported: (?<![\ud800-udbff])[\udc00-\udfff]
994
- '[\\ud800-\\udbff][\\udc00-\\udfff]|' +
995
- // unpaired low surrogate (see previous match)
996
- '[\\udc00-\\udfff]',
997
- 'g'
998
- );
999
-
1000
- /**
1001
- * Formats a string to be used as an attribute's value in raw HTML.
1002
- *
1003
- * It escapes unpaired surrogates (which are allowed in js strings but invalid in HTML), escapes
1004
- * characters that are special in attributes, and surrounds the whole string in double-quotes.
1005
- *
1006
- * @param {string} str
1007
- * @returns {string} Escaped string surrounded by double-quotes.
1008
- * @example const html = `<tag data-value=${escape_html_attr('value')}>...</tag>`;
1009
- */
1010
- function escape_html_attr(str) {
1011
- const escaped_str = str.replace(escape_html_attr_regex, (match) => {
1012
- if (match.length === 2) {
1013
- // valid surrogate pair
1014
- return match;
39
+ });
1015
40
  }
1016
-
1017
- return escape_html_attr_dict[match] ?? `&#${match.charCodeAt(0)};`;
1018
41
  });
1019
42
 
1020
- return `"${escaped_str}"`;
1021
- }
1022
-
1023
- /**
1024
- * @typedef {import('types').PrerenderErrorHandler} PrerenderErrorHandler
1025
- * @typedef {import('types').PrerenderOnErrorValue} OnError
1026
- * @typedef {import('types').Logger} Logger
1027
- */
1028
-
1029
- /** @type {(details: Parameters<PrerenderErrorHandler>[0] ) => string} */
1030
- function format_error({ status, path, referrer, referenceType }) {
1031
- return `${status} ${path}${referrer ? ` (${referenceType} from ${referrer})` : ''}`;
1032
- }
1033
-
1034
- /** @type {(log: Logger, onError: OnError) => PrerenderErrorHandler} */
1035
- function normalise_error_handler(log, onError) {
1036
- switch (onError) {
1037
- case 'continue':
1038
- return (details) => {
1039
- log.error(format_error(details));
1040
- };
1041
- case 'fail':
1042
- return (details) => {
1043
- throw new Error(format_error(details));
1044
- };
1045
- default:
1046
- return onError;
1047
- }
1048
- }
43
+ /** @type {(path: string) => string} */
44
+ const load =
45
+ format === 'esm'
46
+ ? (path) => `import('${path}')`
47
+ : (path) => `Promise.resolve().then(() => require('${path}'))`;
1049
48
 
1050
- const OK = 2;
1051
- const REDIRECT = 3;
49
+ /** @type {(path: string) => string} */
50
+ const loader = (path) => `() => ${load(path)}`;
1052
51
 
1053
- /**
1054
- * @param {{
1055
- * config: import('types').ValidatedConfig;
1056
- * entries: string[];
1057
- * files: Set<string>;
1058
- * log: Logger;
1059
- * }} opts
1060
- */
1061
- async function prerender({ config, entries, files, log }) {
1062
- /** @type {import('types').Prerendered} */
1063
- const prerendered = {
1064
- pages: new Map(),
1065
- assets: new Map(),
1066
- redirects: new Map(),
1067
- paths: []
1068
- };
1069
-
1070
- if (!config.kit.prerender.enabled) {
1071
- return prerendered;
52
+ const assets = build_data.manifest_data.assets.map((asset) => asset.file);
53
+ if (build_data.service_worker) {
54
+ assets.push(build_data.service_worker);
1072
55
  }
1073
56
 
1074
- installPolyfills();
1075
-
1076
- const server_root = join(config.kit.outDir, 'output');
57
+ /** @param {string | undefined} id */
58
+ const get_index = (id) => id && /** @type {LookupEntry} */ (bundled_nodes.get(id)).index;
1077
59
 
1078
- /** @type {import('types').ServerModule} */
1079
- const { Server, override } = await import(pathToFileURL(`${server_root}/server/index.js`).href);
1080
- const { manifest } = await import(pathToFileURL(`${server_root}/server/manifest.js`).href);
1081
-
1082
- override({
1083
- paths: config.kit.paths,
1084
- prerendering: true,
1085
- read: (file) => readFileSync(join(config.kit.files.assets, file))
1086
- });
60
+ const matchers = new Set();
1087
61
 
1088
- const server = new Server(manifest);
62
+ // prettier-ignore
63
+ return `{
64
+ appDir: ${s(build_data.app_dir)},
65
+ assets: new Set(${s(assets)}),
66
+ mimeTypes: ${s(get_mime_lookup(build_data.manifest_data))},
67
+ _: {
68
+ entry: ${s(build_data.client.entry)},
69
+ nodes: [
70
+ ${Array.from(bundled_nodes.values()).map(node => loader(node.path)).join(',\n\t\t\t\t')}
71
+ ],
72
+ routes: [
73
+ ${routes.map(route => {
74
+ const { pattern, names, types } = parse_route_id(route.id);
1089
75
 
1090
- const error = normalise_error_handler(log, config.kit.prerender.onError);
1091
-
1092
- const q = queue(config.kit.prerender.concurrency);
1093
-
1094
- /**
1095
- * @param {string} path
1096
- * @param {boolean} is_html
1097
- */
1098
- function output_filename(path, is_html) {
1099
- const file = path.slice(config.kit.paths.base.length + 1);
1100
-
1101
- if (file === '') {
1102
- return 'index.html';
1103
- }
1104
-
1105
- if (is_html && !file.endsWith('.html')) {
1106
- return file + (file.endsWith('/') ? 'index.html' : '.html');
1107
- }
1108
-
1109
- return file;
1110
- }
1111
-
1112
- const seen = new Set();
1113
- const written = new Set();
1114
-
1115
- /**
1116
- * @param {string | null} referrer
1117
- * @param {string} decoded
1118
- * @param {string} [encoded]
1119
- */
1120
- function enqueue(referrer, decoded, encoded) {
1121
- if (seen.has(decoded)) return;
1122
- seen.add(decoded);
1123
-
1124
- const file = decoded.slice(config.kit.paths.base.length + 1);
1125
- if (files.has(file)) return;
1126
-
1127
- return q.add(() => visit(decoded, encoded || encodeURI(decoded), referrer));
1128
- }
1129
-
1130
- /**
1131
- * @param {string} decoded
1132
- * @param {string} encoded
1133
- * @param {string?} referrer
1134
- */
1135
- async function visit(decoded, encoded, referrer) {
1136
- if (!decoded.startsWith(config.kit.paths.base)) {
1137
- error({ status: 404, path: decoded, referrer, referenceType: 'linked' });
1138
- return;
1139
- }
1140
-
1141
- /** @type {Map<string, import('types').PrerenderDependency>} */
1142
- const dependencies = new Map();
1143
-
1144
- const response = await server.respond(new Request(`http://sveltekit-prerender${encoded}`), {
1145
- getClientAddress,
1146
- prerendering: {
1147
- dependencies
1148
- }
1149
- });
1150
-
1151
- const text = await response.text();
1152
-
1153
- save('pages', response, text, decoded, encoded, referrer, 'linked');
1154
-
1155
- for (const [dependency_path, result] of dependencies) {
1156
- // this seems circuitous, but using new URL allows us to not care
1157
- // whether dependency_path is encoded or not
1158
- const encoded_dependency_path = new URL$1(dependency_path, 'http://localhost').pathname;
1159
- const decoded_dependency_path = decodeURI(encoded_dependency_path);
1160
-
1161
- const body = result.body ?? new Uint8Array(await result.response.arrayBuffer());
1162
- save(
1163
- 'dependencies',
1164
- result.response,
1165
- body,
1166
- decoded_dependency_path,
1167
- encoded_dependency_path,
1168
- decoded,
1169
- 'fetched'
1170
- );
1171
- }
1172
-
1173
- if (config.kit.prerender.crawl && response.headers.get('content-type') === 'text/html') {
1174
- for (const href of crawl(text)) {
1175
- if (href.startsWith('data:') || href.startsWith('#')) continue;
1176
-
1177
- const resolved = resolve(encoded, href);
1178
- if (!is_root_relative(resolved)) continue;
1179
-
1180
- const { pathname, search } = new URL$1(resolved, 'http://localhost');
1181
-
1182
- enqueue(decoded, decodeURI(pathname), pathname);
1183
- }
1184
- }
1185
- }
1186
-
1187
- /**
1188
- * @param {'pages' | 'dependencies'} category
1189
- * @param {Response} response
1190
- * @param {string | Uint8Array} body
1191
- * @param {string} decoded
1192
- * @param {string} encoded
1193
- * @param {string | null} referrer
1194
- * @param {'linked' | 'fetched'} referenceType
1195
- */
1196
- function save(category, response, body, decoded, encoded, referrer, referenceType) {
1197
- const response_type = Math.floor(response.status / 100);
1198
- const type = /** @type {string} */ (response.headers.get('content-type'));
1199
- const is_html = response_type === REDIRECT || type === 'text/html';
1200
-
1201
- const file = output_filename(decoded, is_html);
1202
- const dest = `${config.kit.outDir}/output/prerendered/${category}/${file}`;
1203
-
1204
- if (written.has(file)) return;
1205
-
1206
- if (response_type === REDIRECT) {
1207
- const location = response.headers.get('location');
1208
-
1209
- if (location) {
1210
- const resolved = resolve(encoded, location);
1211
- if (is_root_relative(resolved)) {
1212
- enqueue(decoded, decodeURI(resolved), resolved);
1213
- }
1214
-
1215
- if (!response.headers.get('x-sveltekit-normalize')) {
1216
- mkdirp(dirname(dest));
1217
-
1218
- log.warn(`${response.status} ${decoded} -> ${location}`);
1219
-
1220
- writeFileSync(
1221
- dest,
1222
- `<meta http-equiv="refresh" content=${escape_html_attr(`0;url=${location}`)}>`
1223
- );
1224
-
1225
- written.add(file);
76
+ types.forEach(type => {
77
+ if (type) matchers.add(type);
78
+ });
1226
79
 
1227
- if (!prerendered.redirects.has(decoded)) {
1228
- prerendered.redirects.set(decoded, {
1229
- status: response.status,
1230
- location: resolved
1231
- });
80
+ if (route.type === 'page') {
81
+ return `{
82
+ type: 'page',
83
+ id: ${s(route.id)},
84
+ pattern: ${pattern},
85
+ names: ${s(names)},
86
+ types: ${s(types)},
87
+ path: ${route.path ? s(route.path) : null},
88
+ shadow: ${route.shadow ? loader(`${relative_path}/${build_data.server.vite_manifest[route.shadow].file}`) : null},
89
+ a: ${s(route.a.map(get_index))},
90
+ b: ${s(route.b.map(get_index))}
91
+ }`.replace(/^\t\t/gm, '');
92
+ } else {
93
+ if (!build_data.server.vite_manifest[route.file]) {
94
+ // this is necessary in cases where a .css file snuck in —
95
+ // perhaps it would be better to disallow these (and others?)
96
+ return null;
97
+ }
1232
98
 
1233
- prerendered.paths.push(normalize_path(decoded, 'never'));
99
+ return `{
100
+ type: 'endpoint',
101
+ id: ${s(route.id)},
102
+ pattern: ${pattern},
103
+ names: ${s(names)},
104
+ types: ${s(types)},
105
+ load: ${loader(`${relative_path}/${build_data.server.vite_manifest[route.file].file}`)}
106
+ }`.replace(/^\t\t/gm, '');
1234
107
  }
1235
- }
1236
- } else {
1237
- log.warn(`location header missing on redirect received from ${decoded}`);
1238
- }
1239
-
1240
- return;
1241
- }
1242
-
1243
- if (response.status === 200) {
1244
- mkdirp(dirname(dest));
1245
-
1246
- log.info(`${response.status} ${decoded}`);
1247
- writeFileSync(dest, body);
1248
- written.add(file);
1249
-
1250
- if (is_html) {
1251
- prerendered.pages.set(decoded, {
1252
- file
1253
- });
1254
- } else {
1255
- prerendered.assets.set(decoded, {
1256
- type
1257
- });
1258
- }
1259
-
1260
- prerendered.paths.push(normalize_path(decoded, 'never'));
1261
- } else if (response_type !== OK) {
1262
- error({ status: response.status, path: decoded, referrer, referenceType });
1263
- }
1264
- }
1265
-
1266
- if (config.kit.prerender.enabled) {
1267
- for (const entry of config.kit.prerender.entries) {
1268
- if (entry === '*') {
1269
- for (const entry of entries) {
1270
- enqueue(null, config.kit.paths.base + entry); // TODO can we pre-normalize these?
1271
- }
1272
- } else {
1273
- enqueue(null, config.kit.paths.base + entry);
108
+ }).filter(Boolean).join(',\n\t\t\t\t')}
109
+ ],
110
+ matchers: async () => {
111
+ ${Array.from(matchers).map(type => `const { match: ${type} } = await ${load(`${relative_path}/entries/matchers/${type}.js`)}`).join('\n\t\t\t\t')}
112
+ return { ${Array.from(matchers).join(', ')} };
1274
113
  }
1275
114
  }
1276
-
1277
- await q.done();
1278
- }
1279
-
1280
- const rendered = await server.respond(new Request('http://sveltekit-prerender/[fallback]'), {
1281
- getClientAddress,
1282
- prerendering: {
1283
- fallback: true,
1284
- dependencies: new Map()
1285
- }
1286
- });
1287
-
1288
- const file = `${config.kit.outDir}/output/prerendered/fallback.html`;
1289
- mkdirp(dirname(file));
1290
- writeFileSync(file, await rendered.text());
1291
-
1292
- return prerendered;
1293
- }
1294
-
1295
- /** @return {string} */
1296
- function getClientAddress() {
1297
- throw new Error('Cannot read clientAddress during prerendering');
1298
- }
1299
-
1300
- /**
1301
- * @param {import('types').ValidatedConfig} config
1302
- * @param {{ log: import('types').Logger }} opts
1303
- */
1304
- async function build(config, { log }) {
1305
- const cwd = process.cwd(); // TODO is this necessary?
1306
-
1307
- const build_dir = path__default.join(config.kit.outDir, 'build');
1308
- rimraf(build_dir);
1309
- mkdirp(build_dir);
1310
-
1311
- const output_dir = path__default.join(config.kit.outDir, 'output');
1312
- rimraf(output_dir);
1313
- mkdirp(output_dir);
1314
-
1315
- const { manifest_data } = all(config);
1316
-
1317
- // TODO this is so that Vite's preloading works. Unfortunately, it fails
1318
- // during `svelte-kit preview`, because we use a local asset path. If Vite
1319
- // used relative paths, I _think_ this could get fixed. Issue here:
1320
- // https://github.com/vitejs/vite/issues/2009
1321
- const { base, assets } = config.kit.paths;
1322
- const assets_base = `${assets || base}/${config.kit.appDir}/immutable/`;
1323
-
1324
- const options = {
1325
- cwd,
1326
- config,
1327
- build_dir,
1328
- assets_base,
1329
- manifest_data,
1330
- output_dir,
1331
- client_entry_file: path__default.relative(cwd, `${get_runtime_path(config)}/client/start.js`),
1332
- service_worker_entry_file: resolve_entry(config.kit.files.serviceWorker),
1333
- service_worker_register: config.kit.serviceWorker.register
1334
- };
1335
-
1336
- const client = await build_client(options);
1337
- const server = await build_server(options, client);
1338
-
1339
- /** @type {import('types').BuildData} */
1340
- const build_data = {
1341
- app_dir: config.kit.appDir,
1342
- manifest_data: options.manifest_data,
1343
- service_worker: options.service_worker_entry_file ? 'service-worker.js' : null, // TODO make file configurable?
1344
- client,
1345
- server
1346
- };
1347
-
1348
- const manifest = `export const manifest = ${generate_manifest({
1349
- build_data,
1350
- relative_path: '.',
1351
- routes: options.manifest_data.routes
1352
- })};\n`;
1353
- fs__default.writeFileSync(`${output_dir}/server/manifest.js`, manifest);
1354
-
1355
- const static_files = options.manifest_data.assets.map((asset) => posixify(asset.file));
1356
-
1357
- const files = new Set([
1358
- ...static_files,
1359
- ...client.chunks.map((chunk) => `${config.kit.appDir}/immutable/${chunk.fileName}`),
1360
- ...client.assets.map((chunk) => `${config.kit.appDir}/immutable/${chunk.fileName}`)
1361
- ]);
1362
-
1363
- // TODO is this right?
1364
- static_files.forEach((file) => {
1365
- if (file.endsWith('/index.html')) {
1366
- files.add(file.slice(0, -11));
1367
- }
1368
- });
1369
-
1370
- const prerendered = await prerender({
1371
- config,
1372
- entries: options.manifest_data.routes
1373
- .map((route) => (route.type === 'page' ? route.path : ''))
1374
- .filter(Boolean),
1375
- files,
1376
- log
1377
- });
1378
-
1379
- if (options.service_worker_entry_file) {
1380
- if (config.kit.paths.assets) {
1381
- throw new Error('Cannot use service worker alongside config.kit.paths.assets');
1382
- }
1383
-
1384
- await build_service_worker(options, prerendered, client.vite_manifest);
1385
- }
1386
-
1387
- return { build_data, prerendered };
115
+ }`.replace(/^\t/gm, '');
1388
116
  }
1389
117
 
1390
- export { build };
118
+ export { generate_manifest as g };