@sveltejs/kit 1.0.0-next.345 → 1.0.0-next.346

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,1391 +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 index = ${i};`,
604
- `export const entry = '${client.vite_manifest[component].file}';`,
605
- `export const js = ${s(Array.from(js))};`,
606
- `export const css = ${s(Array.from(css))};`
607
- ];
608
-
609
- /** @type {string[]} */
610
- const styles = [];
611
-
612
- css.forEach((file) => {
613
- if (stylesheet_lookup.has(file)) {
614
- const index = stylesheet_lookup.get(file);
615
- const name = `stylesheet_${index}`;
616
- imports.push(`import ${name} from '../stylesheets/${index}.js';`);
617
- styles.push(`\t${s(file)}: ${name}`);
618
- }
619
- });
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);
620
33
 
621
- if (styles.length > 0) {
622
- exports.push(`export const styles = {\n${styles.join(',\n')}\n};`);
623
- }
624
-
625
- fs__default.writeFileSync(file, `${imports.join('\n')}\n\n${exports.join('\n')}\n`);
626
- });
627
-
628
- return {
629
- chunks,
630
- vite_manifest,
631
- methods: get_methods(cwd, chunks, manifest_data)
632
- };
633
- }
634
-
635
- /** @type {Record<string, string>} */
636
- const method_names = {
637
- get: 'get',
638
- head: 'head',
639
- post: 'post',
640
- put: 'put',
641
- del: 'delete',
642
- patch: 'patch'
643
- };
644
-
645
- /**
646
- * @param {string} cwd
647
- * @param {import('rollup').OutputChunk[]} output
648
- * @param {import('types').ManifestData} manifest_data
649
- */
650
- function get_methods(cwd, output, manifest_data) {
651
- /** @type {Record<string, string[]>} */
652
- const lookup = {};
653
- output.forEach((chunk) => {
654
- if (!chunk.facadeModuleId) return;
655
- const id = chunk.facadeModuleId.slice(cwd.length + 1);
656
- lookup[id] = chunk.exports;
657
- });
658
-
659
- /** @type {Record<string, import('types').HttpMethod[]>} */
660
- const methods = {};
661
- manifest_data.routes.forEach((route) => {
662
- const file = route.type === 'endpoint' ? route.file : route.shadow;
663
-
664
- if (file && lookup[file]) {
665
- methods[file] = lookup[file]
666
- .map((x) => /** @type {import('types').HttpMethod} */ (method_names[x]))
667
- .filter(Boolean);
668
- }
669
- });
670
-
671
- return methods;
672
- }
673
-
674
- /** @typedef {{
675
- * fn: () => Promise<any>,
676
- * fulfil: (value: any) => void,
677
- * reject: (error: Error) => void
678
- * }} Task */
679
-
680
- /** @param {number} concurrency */
681
- function queue(concurrency) {
682
- /** @type {Task[]} */
683
- const tasks = [];
684
-
685
- let current = 0;
686
-
687
- /** @type {(value?: any) => void} */
688
- let fulfil;
689
-
690
- /** @type {(error: Error) => void} */
691
- let reject;
692
-
693
- let closed = false;
694
-
695
- const done = new Promise((f, r) => {
696
- fulfil = f;
697
- reject = r;
698
- });
699
-
700
- done.catch(() => {
701
- // this is necessary in case a catch handler is never added
702
- // to the done promise by the user
703
- });
704
-
705
- function dequeue() {
706
- if (current < concurrency) {
707
- const task = tasks.shift();
708
-
709
- if (task) {
710
- current += 1;
711
- const promise = Promise.resolve(task.fn());
712
-
713
- promise
714
- .then(task.fulfil, (err) => {
715
- task.reject(err);
716
- reject(err);
717
- })
718
- .then(() => {
719
- current -= 1;
720
- dequeue();
34
+ bundled_nodes.set(component, {
35
+ path: `${relative_path}/nodes/${i}.js`,
36
+ index: bundled_nodes.size
721
37
  });
722
- } else if (current === 0) {
723
- closed = true;
724
- fulfil();
725
- }
726
- }
727
- }
728
-
729
- return {
730
- /** @param {() => any} fn */
731
- add: (fn) => {
732
- if (closed) throw new Error('Cannot add tasks to a queue that has ended');
733
-
734
- const promise = new Promise((fulfil, reject) => {
735
- tasks.push({ fn, fulfil, reject });
736
- });
737
-
738
- dequeue();
739
- return promise;
740
- },
741
-
742
- done: () => {
743
- if (current === 0) {
744
- closed = true;
745
- fulfil();
746
- }
747
-
748
- return done;
749
- }
750
- };
751
- }
752
-
753
- const DOCTYPE = 'DOCTYPE';
754
- const CDATA_OPEN = '[CDATA[';
755
- const CDATA_CLOSE = ']]>';
756
- const COMMENT_OPEN = '--';
757
- const COMMENT_CLOSE = '-->';
758
-
759
- const TAG_OPEN = /[a-zA-Z]/;
760
- const TAG_CHAR = /[a-zA-Z0-9]/;
761
- const ATTRIBUTE_NAME = /[^\t\n\f />"'=]/;
762
-
763
- const WHITESPACE = /[\s\n\r]/;
764
-
765
- /** @param {string} html */
766
- function crawl(html) {
767
- /** @type {string[]} */
768
- const hrefs = [];
769
-
770
- let i = 0;
771
- main: while (i < html.length) {
772
- const char = html[i];
773
-
774
- if (char === '<') {
775
- if (html[i + 1] === '!') {
776
- i += 2;
777
-
778
- if (html.slice(i, i + DOCTYPE.length).toUpperCase() === DOCTYPE) {
779
- i += DOCTYPE.length;
780
- while (i < html.length) {
781
- if (html[i++] === '>') {
782
- continue main;
783
- }
784
- }
785
38
  }
786
-
787
- // skip cdata
788
- if (html.slice(i, i + CDATA_OPEN.length) === CDATA_OPEN) {
789
- i += CDATA_OPEN.length;
790
- while (i < html.length) {
791
- if (html.slice(i, i + CDATA_CLOSE.length) === CDATA_CLOSE) {
792
- i += CDATA_CLOSE.length;
793
- continue main;
794
- }
795
-
796
- i += 1;
797
- }
798
- }
799
-
800
- // skip comments
801
- if (html.slice(i, i + COMMENT_OPEN.length) === COMMENT_OPEN) {
802
- i += COMMENT_OPEN.length;
803
- while (i < html.length) {
804
- if (html.slice(i, i + COMMENT_CLOSE.length) === COMMENT_CLOSE) {
805
- i += COMMENT_CLOSE.length;
806
- continue main;
807
- }
808
-
809
- i += 1;
810
- }
811
- }
812
- }
813
-
814
- // parse opening tags
815
- const start = ++i;
816
- if (TAG_OPEN.test(html[start])) {
817
- while (i < html.length) {
818
- if (!TAG_CHAR.test(html[i])) {
819
- break;
820
- }
821
-
822
- i += 1;
823
- }
824
-
825
- const tag = html.slice(start, i).toUpperCase();
826
-
827
- if (tag === 'SCRIPT' || tag === 'STYLE') {
828
- while (i < html.length) {
829
- if (
830
- html[i] === '<' &&
831
- html[i + 1] === '/' &&
832
- html.slice(i + 2, i + 2 + tag.length).toUpperCase() === tag
833
- ) {
834
- continue main;
835
- }
836
-
837
- i += 1;
838
- }
839
- }
840
-
841
- let href = '';
842
- let rel = '';
843
-
844
- while (i < html.length) {
845
- const start = i;
846
-
847
- const char = html[start];
848
- if (char === '>') break;
849
-
850
- if (ATTRIBUTE_NAME.test(char)) {
851
- i += 1;
852
-
853
- while (i < html.length) {
854
- if (!ATTRIBUTE_NAME.test(html[i])) {
855
- break;
856
- }
857
-
858
- i += 1;
859
- }
860
-
861
- const name = html.slice(start, i).toLowerCase();
862
-
863
- while (WHITESPACE.test(html[i])) i += 1;
864
-
865
- if (html[i] === '=') {
866
- i += 1;
867
- while (WHITESPACE.test(html[i])) i += 1;
868
-
869
- let value;
870
-
871
- if (html[i] === "'" || html[i] === '"') {
872
- const quote = html[i++];
873
-
874
- const start = i;
875
- let escaped = false;
876
-
877
- while (i < html.length) {
878
- if (!escaped) {
879
- const char = html[i];
880
-
881
- if (html[i] === quote) {
882
- break;
883
- }
884
-
885
- if (char === '\\') {
886
- escaped = true;
887
- }
888
- }
889
-
890
- i += 1;
891
- }
892
-
893
- value = html.slice(start, i);
894
- } else {
895
- const start = i;
896
- while (html[i] !== '>' && !WHITESPACE.test(html[i])) i += 1;
897
- value = html.slice(start, i);
898
-
899
- i -= 1;
900
- }
901
-
902
- if (name === 'href') {
903
- href = value;
904
- } else if (name === 'rel') {
905
- rel = value;
906
- } else if (name === 'src') {
907
- hrefs.push(value);
908
- } else if (name === 'srcset') {
909
- const candidates = [];
910
- let insideURL = true;
911
- value = value.trim();
912
- for (let i = 0; i < value.length; i++) {
913
- if (value[i] === ',' && (!insideURL || (insideURL && value[i + 1] === ' '))) {
914
- candidates.push(value.slice(0, i));
915
- value = value.substring(i + 1).trim();
916
- i = 0;
917
- insideURL = true;
918
- } else if (value[i] === ' ') {
919
- insideURL = false;
920
- }
921
- }
922
- candidates.push(value);
923
- for (const candidate of candidates) {
924
- const src = candidate.split(WHITESPACE)[0];
925
- hrefs.push(src);
926
- }
927
- }
928
- } else {
929
- i -= 1;
930
- }
931
- }
932
-
933
- i += 1;
934
- }
935
-
936
- if (href && !/\bexternal\b/i.test(rel)) {
937
- hrefs.push(href);
938
- }
939
- }
940
- }
941
-
942
- i += 1;
943
- }
944
-
945
- return hrefs;
946
- }
947
-
948
- /**
949
- * Inside a script element, only `</script` and `<!--` hold special meaning to the HTML parser.
950
- *
951
- * The first closes the script element, so everything after is treated as raw HTML.
952
- * The second disables further parsing until `-->`, so the script element might be unexpectedly
953
- * kept open until until an unrelated HTML comment in the page.
954
- *
955
- * U+2028 LINE SEPARATOR and U+2029 PARAGRAPH SEPARATOR are escaped for the sake of pre-2018
956
- * browsers.
957
- *
958
- * @see tests for unsafe parsing examples.
959
- * @see https://html.spec.whatwg.org/multipage/scripting.html#restrictions-for-contents-of-script-elements
960
- * @see https://html.spec.whatwg.org/multipage/syntax.html#cdata-rcdata-restrictions
961
- * @see https://html.spec.whatwg.org/multipage/parsing.html#script-data-state
962
- * @see https://html.spec.whatwg.org/multipage/parsing.html#script-data-double-escaped-state
963
- * @see https://github.com/tc39/proposal-json-superset
964
- * @type {Record<string, string>}
965
- */
966
- const render_json_payload_script_dict = {
967
- '<': '\\u003C',
968
- '\u2028': '\\u2028',
969
- '\u2029': '\\u2029'
970
- };
971
-
972
- new RegExp(
973
- `[${Object.keys(render_json_payload_script_dict).join('')}]`,
974
- 'g'
975
- );
976
-
977
- /**
978
- * When inside a double-quoted attribute value, only `&` and `"` hold special meaning.
979
- * @see https://html.spec.whatwg.org/multipage/parsing.html#attribute-value-(double-quoted)-state
980
- * @type {Record<string, string>}
981
- */
982
- const escape_html_attr_dict = {
983
- '&': '&amp;',
984
- '"': '&quot;'
985
- };
986
-
987
- const escape_html_attr_regex = new RegExp(
988
- // special characters
989
- `[${Object.keys(escape_html_attr_dict).join('')}]|` +
990
- // high surrogate without paired low surrogate
991
- '[\\ud800-\\udbff](?![\\udc00-\\udfff])|' +
992
- // a valid surrogate pair, the only match with 2 code units
993
- // we match it so that we can match unpaired low surrogates in the same pass
994
- // TODO: use lookbehind assertions once they are widely supported: (?<![\ud800-udbff])[\udc00-\udfff]
995
- '[\\ud800-\\udbff][\\udc00-\\udfff]|' +
996
- // unpaired low surrogate (see previous match)
997
- '[\\udc00-\\udfff]',
998
- 'g'
999
- );
1000
-
1001
- /**
1002
- * Formats a string to be used as an attribute's value in raw HTML.
1003
- *
1004
- * It escapes unpaired surrogates (which are allowed in js strings but invalid in HTML), escapes
1005
- * characters that are special in attributes, and surrounds the whole string in double-quotes.
1006
- *
1007
- * @param {string} str
1008
- * @returns {string} Escaped string surrounded by double-quotes.
1009
- * @example const html = `<tag data-value=${escape_html_attr('value')}>...</tag>`;
1010
- */
1011
- function escape_html_attr(str) {
1012
- const escaped_str = str.replace(escape_html_attr_regex, (match) => {
1013
- if (match.length === 2) {
1014
- // valid surrogate pair
1015
- return match;
39
+ });
1016
40
  }
1017
-
1018
- return escape_html_attr_dict[match] ?? `&#${match.charCodeAt(0)};`;
1019
41
  });
1020
42
 
1021
- return `"${escaped_str}"`;
1022
- }
1023
-
1024
- /**
1025
- * @typedef {import('types').PrerenderErrorHandler} PrerenderErrorHandler
1026
- * @typedef {import('types').PrerenderOnErrorValue} OnError
1027
- * @typedef {import('types').Logger} Logger
1028
- */
1029
-
1030
- /** @type {(details: Parameters<PrerenderErrorHandler>[0] ) => string} */
1031
- function format_error({ status, path, referrer, referenceType }) {
1032
- return `${status} ${path}${referrer ? ` (${referenceType} from ${referrer})` : ''}`;
1033
- }
1034
-
1035
- /** @type {(log: Logger, onError: OnError) => PrerenderErrorHandler} */
1036
- function normalise_error_handler(log, onError) {
1037
- switch (onError) {
1038
- case 'continue':
1039
- return (details) => {
1040
- log.error(format_error(details));
1041
- };
1042
- case 'fail':
1043
- return (details) => {
1044
- throw new Error(format_error(details));
1045
- };
1046
- default:
1047
- return onError;
1048
- }
1049
- }
43
+ /** @type {(path: string) => string} */
44
+ const load =
45
+ format === 'esm'
46
+ ? (path) => `import('${path}')`
47
+ : (path) => `Promise.resolve().then(() => require('${path}'))`;
1050
48
 
1051
- const OK = 2;
1052
- const REDIRECT = 3;
49
+ /** @type {(path: string) => string} */
50
+ const loader = (path) => `() => ${load(path)}`;
1053
51
 
1054
- /**
1055
- * @param {{
1056
- * config: import('types').ValidatedConfig;
1057
- * entries: string[];
1058
- * files: Set<string>;
1059
- * log: Logger;
1060
- * }} opts
1061
- */
1062
- async function prerender({ config, entries, files, log }) {
1063
- /** @type {import('types').Prerendered} */
1064
- const prerendered = {
1065
- pages: new Map(),
1066
- assets: new Map(),
1067
- redirects: new Map(),
1068
- paths: []
1069
- };
1070
-
1071
- if (!config.kit.prerender.enabled) {
1072
- 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);
1073
55
  }
1074
56
 
1075
- installPolyfills();
1076
-
1077
- 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;
1078
59
 
1079
- /** @type {import('types').ServerModule} */
1080
- const { Server, override } = await import(pathToFileURL(`${server_root}/server/index.js`).href);
1081
- const { manifest } = await import(pathToFileURL(`${server_root}/server/manifest.js`).href);
1082
-
1083
- override({
1084
- paths: config.kit.paths,
1085
- prerendering: true,
1086
- read: (file) => readFileSync(join(config.kit.files.assets, file))
1087
- });
60
+ const matchers = new Set();
1088
61
 
1089
- 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);
1090
75
 
1091
- const error = normalise_error_handler(log, config.kit.prerender.onError);
1092
-
1093
- const q = queue(config.kit.prerender.concurrency);
1094
-
1095
- /**
1096
- * @param {string} path
1097
- * @param {boolean} is_html
1098
- */
1099
- function output_filename(path, is_html) {
1100
- const file = path.slice(config.kit.paths.base.length + 1);
1101
-
1102
- if (file === '') {
1103
- return 'index.html';
1104
- }
1105
-
1106
- if (is_html && !file.endsWith('.html')) {
1107
- return file + (file.endsWith('/') ? 'index.html' : '.html');
1108
- }
1109
-
1110
- return file;
1111
- }
1112
-
1113
- const seen = new Set();
1114
- const written = new Set();
1115
-
1116
- /**
1117
- * @param {string | null} referrer
1118
- * @param {string} decoded
1119
- * @param {string} [encoded]
1120
- */
1121
- function enqueue(referrer, decoded, encoded) {
1122
- if (seen.has(decoded)) return;
1123
- seen.add(decoded);
1124
-
1125
- const file = decoded.slice(config.kit.paths.base.length + 1);
1126
- if (files.has(file)) return;
1127
-
1128
- return q.add(() => visit(decoded, encoded || encodeURI(decoded), referrer));
1129
- }
1130
-
1131
- /**
1132
- * @param {string} decoded
1133
- * @param {string} encoded
1134
- * @param {string?} referrer
1135
- */
1136
- async function visit(decoded, encoded, referrer) {
1137
- if (!decoded.startsWith(config.kit.paths.base)) {
1138
- error({ status: 404, path: decoded, referrer, referenceType: 'linked' });
1139
- return;
1140
- }
1141
-
1142
- /** @type {Map<string, import('types').PrerenderDependency>} */
1143
- const dependencies = new Map();
1144
-
1145
- const response = await server.respond(new Request(`http://sveltekit-prerender${encoded}`), {
1146
- getClientAddress,
1147
- prerendering: {
1148
- dependencies
1149
- }
1150
- });
1151
-
1152
- const text = await response.text();
1153
-
1154
- save('pages', response, text, decoded, encoded, referrer, 'linked');
1155
-
1156
- for (const [dependency_path, result] of dependencies) {
1157
- // this seems circuitous, but using new URL allows us to not care
1158
- // whether dependency_path is encoded or not
1159
- const encoded_dependency_path = new URL$1(dependency_path, 'http://localhost').pathname;
1160
- const decoded_dependency_path = decodeURI(encoded_dependency_path);
1161
-
1162
- const body = result.body ?? new Uint8Array(await result.response.arrayBuffer());
1163
- save(
1164
- 'dependencies',
1165
- result.response,
1166
- body,
1167
- decoded_dependency_path,
1168
- encoded_dependency_path,
1169
- decoded,
1170
- 'fetched'
1171
- );
1172
- }
1173
-
1174
- if (config.kit.prerender.crawl && response.headers.get('content-type') === 'text/html') {
1175
- for (const href of crawl(text)) {
1176
- if (href.startsWith('data:') || href.startsWith('#')) continue;
1177
-
1178
- const resolved = resolve(encoded, href);
1179
- if (!is_root_relative(resolved)) continue;
1180
-
1181
- const { pathname, search } = new URL$1(resolved, 'http://localhost');
1182
-
1183
- enqueue(decoded, decodeURI(pathname), pathname);
1184
- }
1185
- }
1186
- }
1187
-
1188
- /**
1189
- * @param {'pages' | 'dependencies'} category
1190
- * @param {Response} response
1191
- * @param {string | Uint8Array} body
1192
- * @param {string} decoded
1193
- * @param {string} encoded
1194
- * @param {string | null} referrer
1195
- * @param {'linked' | 'fetched'} referenceType
1196
- */
1197
- function save(category, response, body, decoded, encoded, referrer, referenceType) {
1198
- const response_type = Math.floor(response.status / 100);
1199
- const type = /** @type {string} */ (response.headers.get('content-type'));
1200
- const is_html = response_type === REDIRECT || type === 'text/html';
1201
-
1202
- const file = output_filename(decoded, is_html);
1203
- const dest = `${config.kit.outDir}/output/prerendered/${category}/${file}`;
1204
-
1205
- if (written.has(file)) return;
1206
-
1207
- if (response_type === REDIRECT) {
1208
- const location = response.headers.get('location');
1209
-
1210
- if (location) {
1211
- const resolved = resolve(encoded, location);
1212
- if (is_root_relative(resolved)) {
1213
- enqueue(decoded, decodeURI(resolved), resolved);
1214
- }
1215
-
1216
- if (!response.headers.get('x-sveltekit-normalize')) {
1217
- mkdirp(dirname(dest));
1218
-
1219
- log.warn(`${response.status} ${decoded} -> ${location}`);
1220
-
1221
- writeFileSync(
1222
- dest,
1223
- `<meta http-equiv="refresh" content=${escape_html_attr(`0;url=${location}`)}>`
1224
- );
1225
-
1226
- written.add(file);
76
+ types.forEach(type => {
77
+ if (type) matchers.add(type);
78
+ });
1227
79
 
1228
- if (!prerendered.redirects.has(decoded)) {
1229
- prerendered.redirects.set(decoded, {
1230
- status: response.status,
1231
- location: resolved
1232
- });
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
+ }
1233
98
 
1234
- 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, '');
1235
107
  }
1236
- }
1237
- } else {
1238
- log.warn(`location header missing on redirect received from ${decoded}`);
1239
- }
1240
-
1241
- return;
1242
- }
1243
-
1244
- if (response.status === 200) {
1245
- mkdirp(dirname(dest));
1246
-
1247
- log.info(`${response.status} ${decoded}`);
1248
- writeFileSync(dest, body);
1249
- written.add(file);
1250
-
1251
- if (is_html) {
1252
- prerendered.pages.set(decoded, {
1253
- file
1254
- });
1255
- } else {
1256
- prerendered.assets.set(decoded, {
1257
- type
1258
- });
1259
- }
1260
-
1261
- prerendered.paths.push(normalize_path(decoded, 'never'));
1262
- } else if (response_type !== OK) {
1263
- error({ status: response.status, path: decoded, referrer, referenceType });
1264
- }
1265
- }
1266
-
1267
- if (config.kit.prerender.enabled) {
1268
- for (const entry of config.kit.prerender.entries) {
1269
- if (entry === '*') {
1270
- for (const entry of entries) {
1271
- enqueue(null, config.kit.paths.base + entry); // TODO can we pre-normalize these?
1272
- }
1273
- } else {
1274
- 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(', ')} };
1275
113
  }
1276
114
  }
1277
-
1278
- await q.done();
1279
- }
1280
-
1281
- const rendered = await server.respond(new Request('http://sveltekit-prerender/[fallback]'), {
1282
- getClientAddress,
1283
- prerendering: {
1284
- fallback: true,
1285
- dependencies: new Map()
1286
- }
1287
- });
1288
-
1289
- const file = `${config.kit.outDir}/output/prerendered/fallback.html`;
1290
- mkdirp(dirname(file));
1291
- writeFileSync(file, await rendered.text());
1292
-
1293
- return prerendered;
1294
- }
1295
-
1296
- /** @return {string} */
1297
- function getClientAddress() {
1298
- throw new Error('Cannot read clientAddress during prerendering');
1299
- }
1300
-
1301
- /**
1302
- * @param {import('types').ValidatedConfig} config
1303
- * @param {{ log: import('types').Logger }} opts
1304
- */
1305
- async function build(config, { log }) {
1306
- const cwd = process.cwd(); // TODO is this necessary?
1307
-
1308
- const build_dir = path__default.join(config.kit.outDir, 'build');
1309
- rimraf(build_dir);
1310
- mkdirp(build_dir);
1311
-
1312
- const output_dir = path__default.join(config.kit.outDir, 'output');
1313
- rimraf(output_dir);
1314
- mkdirp(output_dir);
1315
-
1316
- const { manifest_data } = all(config);
1317
-
1318
- // TODO this is so that Vite's preloading works. Unfortunately, it fails
1319
- // during `svelte-kit preview`, because we use a local asset path. If Vite
1320
- // used relative paths, I _think_ this could get fixed. Issue here:
1321
- // https://github.com/vitejs/vite/issues/2009
1322
- const { base, assets } = config.kit.paths;
1323
- const assets_base = `${assets || base}/${config.kit.appDir}/immutable/`;
1324
-
1325
- const options = {
1326
- cwd,
1327
- config,
1328
- build_dir,
1329
- assets_base,
1330
- manifest_data,
1331
- output_dir,
1332
- client_entry_file: path__default.relative(cwd, `${get_runtime_path(config)}/client/start.js`),
1333
- service_worker_entry_file: resolve_entry(config.kit.files.serviceWorker),
1334
- service_worker_register: config.kit.serviceWorker.register
1335
- };
1336
-
1337
- const client = await build_client(options);
1338
- const server = await build_server(options, client);
1339
-
1340
- /** @type {import('types').BuildData} */
1341
- const build_data = {
1342
- app_dir: config.kit.appDir,
1343
- manifest_data: options.manifest_data,
1344
- service_worker: options.service_worker_entry_file ? 'service-worker.js' : null, // TODO make file configurable?
1345
- client,
1346
- server
1347
- };
1348
-
1349
- const manifest = `export const manifest = ${generate_manifest({
1350
- build_data,
1351
- relative_path: '.',
1352
- routes: options.manifest_data.routes
1353
- })};\n`;
1354
- fs__default.writeFileSync(`${output_dir}/server/manifest.js`, manifest);
1355
-
1356
- const static_files = options.manifest_data.assets.map((asset) => posixify(asset.file));
1357
-
1358
- const files = new Set([
1359
- ...static_files,
1360
- ...client.chunks.map((chunk) => `${config.kit.appDir}/immutable/${chunk.fileName}`),
1361
- ...client.assets.map((chunk) => `${config.kit.appDir}/immutable/${chunk.fileName}`)
1362
- ]);
1363
-
1364
- // TODO is this right?
1365
- static_files.forEach((file) => {
1366
- if (file.endsWith('/index.html')) {
1367
- files.add(file.slice(0, -11));
1368
- }
1369
- });
1370
-
1371
- const prerendered = await prerender({
1372
- config,
1373
- entries: options.manifest_data.routes
1374
- .map((route) => (route.type === 'page' ? route.path : ''))
1375
- .filter(Boolean),
1376
- files,
1377
- log
1378
- });
1379
-
1380
- if (options.service_worker_entry_file) {
1381
- if (config.kit.paths.assets) {
1382
- throw new Error('Cannot use service worker alongside config.kit.paths.assets');
1383
- }
1384
-
1385
- await build_service_worker(options, prerendered, client.vite_manifest);
1386
- }
1387
-
1388
- return { build_data, prerendered };
115
+ }`.replace(/^\t/gm, '');
1389
116
  }
1390
117
 
1391
- export { build };
118
+ export { generate_manifest as g };