@sveltejs/kit 1.0.0-next.204 → 1.0.0-next.209

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,398 +1,109 @@
1
- import { m as mkdirp, r as rimraf, d as copy, $, l as logger } from '../cli.js';
2
- import { S as SVELTE_KIT } from './constants.js';
3
- import { readFileSync, writeFileSync } from 'fs';
4
- import { resolve, join, dirname } from 'path';
5
- import { pathToFileURL, URL } from 'url';
6
- import { __fetch_polyfill } from '../install-fetch.js';
7
- import { g as get_single_valued_header, r as resolve$1, i as is_root_relative } from './url.js';
8
- import 'sade';
9
- import 'child_process';
10
- import 'net';
11
- import 'os';
12
- import './error.js';
13
- import 'node:http';
14
- import 'node:https';
15
- import 'node:zlib';
16
- import 'node:stream';
17
- import 'node:util';
18
- import 'node:url';
1
+ import { s } from './misc.js';
2
+ import { g as get_mime_lookup } from '../cli.js';
19
3
 
20
4
  /**
21
- * @typedef {import('types/config').PrerenderErrorHandler} PrerenderErrorHandler
22
- * @typedef {import('types/config').PrerenderOnErrorValue} OnError
23
- * @typedef {import('types/internal').Logger} Logger
5
+ * @param {import('../../../types/internal').BuildData} build_data;
6
+ * @param {string} relative_path;
7
+ * @param {import('../../../types/internal').RouteData[]} routes;
8
+ * @param {'esm' | 'cjs'} format
24
9
  */
25
-
26
- /** @param {string} html */
27
- function clean_html(html) {
28
- return html
29
- .replace(/<!\[CDATA\[[\s\S]*?\]\]>/gm, '')
30
- .replace(/(<script[\s\S]*?>)[\s\S]*?<\/script>/gm, '$1</' + 'script>')
31
- .replace(/(<style[\s\S]*?>)[\s\S]*?<\/style>/gm, '$1</' + 'style>')
32
- .replace(/<!--[\s\S]*?-->/gm, '');
33
- }
34
-
35
- /** @param {string} attrs */
36
- function get_href(attrs) {
37
- const match = /(?:[\s'"]|^)href\s*=\s*(?:"(.*?)"|'(.*?)'|([^\s>]*))/.exec(attrs);
38
- return match && (match[1] || match[2] || match[3]);
39
- }
40
-
41
- /** @param {string} attrs */
42
- function get_src(attrs) {
43
- const match = /(?:[\s'"]|^)src\s*=\s*(?:"(.*?)"|'(.*?)'|([^\s>]*))/.exec(attrs);
44
- return match && (match[1] || match[2] || match[3]);
45
- }
46
-
47
- /** @param {string} attrs */
48
- function is_rel_external(attrs) {
49
- const match = /rel\s*=\s*(?:["'][^>]*(external)[^>]*["']|(external))/.exec(attrs);
50
- return !!match;
51
- }
52
-
53
- /** @param {string} attrs */
54
- function get_srcset_urls(attrs) {
55
- const results = [];
56
- // Note that the srcset allows any ASCII whitespace, including newlines.
57
- const match = /([\s'"]|^)srcset\s*=\s*(?:"(.*?)"|'(.*?)'|([^\s>]*))/s.exec(attrs);
58
- if (match) {
59
- const attr_content = match[1] || match[2] || match[3];
60
- // Parse the content of the srcset attribute.
61
- // The regexp is modelled after the srcset specs (https://html.spec.whatwg.org/multipage/images.html#srcset-attribute)
62
- // and should cover most reasonable cases.
63
- const regex = /\s*([^\s,]\S+[^\s,])\s*((?:\d+w)|(?:-?\d+(?:\.\d+)?(?:[eE]-?\d+)?x))?/gm;
64
- let sub_matches;
65
- while ((sub_matches = regex.exec(attr_content))) {
66
- results.push(sub_matches[1]);
67
- }
68
- }
69
- return results;
70
- }
71
-
72
- /** @type {(errorDetails: Parameters<PrerenderErrorHandler>[0] ) => string} */
73
- function errorDetailsToString({ status, path, referrer, referenceType }) {
74
- return `${status} ${path}${referrer ? ` (${referenceType} from ${referrer})` : ''}`;
75
- }
76
-
77
- /** @type {(log: Logger, onError: OnError) => PrerenderErrorHandler} */
78
- function chooseErrorHandler(log, onError) {
79
- switch (onError) {
80
- case 'continue':
81
- return (errorDetails) => {
82
- log.error(errorDetailsToString(errorDetails));
83
- };
84
- case 'fail':
85
- return (errorDetails) => {
86
- throw new Error(errorDetailsToString(errorDetails));
87
- };
88
- default:
89
- return onError;
90
- }
91
- }
92
-
93
- const OK = 2;
94
- const REDIRECT = 3;
95
-
96
- /**
97
- * @param {{
98
- * cwd: string;
99
- * out: string;
100
- * log: Logger;
101
- * config: import('types/config').ValidatedConfig;
102
- * build_data: import('types/internal').BuildData;
103
- * fallback?: string;
104
- * all: boolean; // disregard `export const prerender = true`
105
- * }} opts
106
- * @returns {Promise<Array<string>>} returns a promise that resolves to an array of paths corresponding to the files that have been prerendered.
107
- */
108
- async function prerender({ cwd, out, log, config, build_data, fallback, all }) {
109
- if (!config.kit.prerender.enabled && !fallback) {
110
- return [];
111
- }
112
-
113
- __fetch_polyfill();
114
-
115
- const dir = resolve(cwd, `${SVELTE_KIT}/output`);
116
-
117
- const seen = new Set();
118
-
119
- const server_root = resolve(dir);
120
-
121
- /** @type {import('types/internal').App} */
122
- const app = await import(pathToFileURL(`${server_root}/server/app.js`).href);
123
-
124
- app.init({
125
- paths: config.kit.paths,
126
- prerendering: true,
127
- read: (file) => readFileSync(join(config.kit.files.assets, file))
10
+ function generate_manifest(
11
+ build_data,
12
+ relative_path,
13
+ routes = build_data.manifest_data.routes,
14
+ format = 'esm'
15
+ ) {
16
+ const bundled_nodes = new Map();
17
+
18
+ // 0 and 1 are special, they correspond to the root layout and root error nodes
19
+ bundled_nodes.set(build_data.manifest_data.components[0], {
20
+ path: `${relative_path}/nodes/0.js`,
21
+ index: 0
128
22
  });
129
23
 
130
- const error = chooseErrorHandler(log, config.kit.prerender.onError);
131
-
132
- const files = new Set([...build_data.static, ...build_data.client]);
133
- const written_files = [];
134
-
135
- build_data.static.forEach((file) => {
136
- if (file.endsWith('/index.html')) {
137
- files.add(file.slice(0, -11));
138
- }
24
+ bundled_nodes.set(build_data.manifest_data.components[1], {
25
+ path: `${relative_path}/nodes/1.js`,
26
+ index: 1
139
27
  });
140
28
 
141
- /**
142
- * @param {string} path
143
- */
144
- function normalize(path) {
145
- if (config.kit.trailingSlash === 'always') {
146
- return path.endsWith('/') ? path : `${path}/`;
147
- } else if (config.kit.trailingSlash === 'never') {
148
- return !path.endsWith('/') || path === '/' ? path : path.slice(0, -1);
149
- }
150
-
151
- return path;
152
- }
153
-
154
- /**
155
- * @param {string} decoded_path
156
- * @param {string?} referrer
157
- */
158
- async function visit(decoded_path, referrer) {
159
- const path = encodeURI(normalize(decoded_path));
160
-
161
- if (seen.has(path)) return;
162
- seen.add(path);
163
-
164
- /** @type {Map<string, import('types/hooks').ServerResponse>} */
165
- const dependencies = new Map();
166
-
167
- const rendered = await app.render(
168
- {
169
- host: config.kit.host,
170
- method: 'GET',
171
- headers: {},
172
- path,
173
- rawBody: null,
174
- query: new URLSearchParams()
175
- },
176
- {
177
- prerender: {
178
- all,
179
- dependencies
180
- }
181
- }
182
- );
183
-
184
- if (rendered) {
185
- const response_type = Math.floor(rendered.status / 100);
186
- const headers = rendered.headers;
187
- const type = headers && headers['content-type'];
188
- const is_html = response_type === REDIRECT || type === 'text/html';
189
-
190
- const parts = decoded_path.split('/');
191
- if (is_html && parts[parts.length - 1] !== 'index.html') {
192
- parts.push('index.html');
193
- }
194
-
195
- const file = `${out}${parts.join('/')}`;
196
- mkdirp(dirname(file));
197
-
198
- if (response_type === REDIRECT) {
199
- const location = get_single_valued_header(headers, 'location');
200
-
201
- if (location) {
202
- log.warn(`${rendered.status} ${decoded_path} -> ${location}`);
203
- writeFileSync(file, `<meta http-equiv="refresh" content="0;url=${encodeURI(location)}">`);
204
- written_files.push(file);
205
-
206
- const resolved = resolve$1(path, location);
207
- if (is_root_relative(resolved)) {
208
- await visit(resolved, path);
209
- }
210
- } else {
211
- log.warn(`location header missing on redirect received from ${decoded_path}`);
212
- }
213
-
214
- return;
215
- }
216
-
217
- if (rendered.status === 200) {
218
- log.info(`${rendered.status} ${decoded_path}`);
219
- writeFileSync(file, rendered.body || '');
220
- written_files.push(file);
221
- } else if (response_type !== OK) {
222
- error({ status: rendered.status, path, referrer, referenceType: 'linked' });
223
- }
29
+ routes.forEach((route) => {
30
+ if (route.type === 'page') {
31
+ [...route.a, ...route.b].forEach((component) => {
32
+ if (component && !bundled_nodes.has(component)) {
33
+ const i = build_data.manifest_data.components.indexOf(component);
224
34
 
225
- dependencies.forEach((result, dependency_path) => {
226
- const response_type = Math.floor(result.status / 100);
227
-
228
- const is_html = result.headers['content-type'] === 'text/html';
229
-
230
- const parts = dependency_path.split('/');
231
- if (is_html && parts[parts.length - 1] !== 'index.html') {
232
- parts.push('index.html');
233
- }
234
-
235
- const file = `${out}${parts.join('/')}`;
236
- mkdirp(dirname(file));
237
-
238
- if (result.body) {
239
- writeFileSync(file, result.body);
240
- written_files.push(file);
241
- }
242
-
243
- if (response_type === OK) {
244
- log.info(`${result.status} ${dependency_path}`);
245
- } else {
246
- error({
247
- status: result.status,
248
- path: dependency_path,
249
- referrer: path,
250
- referenceType: 'fetched'
35
+ bundled_nodes.set(component, {
36
+ path: `${relative_path}/nodes/${i}.js`,
37
+ index: bundled_nodes.size
251
38
  });
252
39
  }
253
40
  });
41
+ }
42
+ });
254
43
 
255
- if (is_html && config.kit.prerender.crawl) {
256
- const cleaned = clean_html(/** @type {string} */ (rendered.body));
257
-
258
- let match;
259
- const pattern = /<(a|img|link|source)\s+([\s\S]+?)>/gm;
260
-
261
- const hrefs = [];
262
-
263
- while ((match = pattern.exec(cleaned))) {
264
- const element = match[1];
265
- const attrs = match[2];
266
-
267
- if (element === 'a' || element === 'link') {
268
- if (is_rel_external(attrs)) continue;
269
-
270
- hrefs.push(get_href(attrs));
44
+ /** @type {(path: string) => string} */
45
+ const importer =
46
+ format === 'esm'
47
+ ? (path) => `() => import('${path}')`
48
+ : (path) => `() => Promise.resolve().then(() => require('${path}'))`;
49
+
50
+ // prettier-ignore
51
+ return `{
52
+ appDir: ${s(build_data.app_dir)},
53
+ assets: new Set(${s(build_data.manifest_data.assets.map(asset => asset.file))}),
54
+ _: {
55
+ mime: ${s(get_mime_lookup(build_data.manifest_data))},
56
+ entry: ${s(build_data.client.entry)},
57
+ nodes: [
58
+ ${Array.from(bundled_nodes.values()).map(node => importer(node.path)).join(',\n\t\t\t\t')}
59
+ ],
60
+ routes: [
61
+ ${routes.map(route => {
62
+ if (route.type === 'page') {
63
+ return `{
64
+ type: 'page',
65
+ pattern: ${route.pattern},
66
+ params: ${get_params(route.params)},
67
+ path: ${route.path ? s(route.path) : null},
68
+ a: ${s(route.a.map(component => component && bundled_nodes.get(component).index))},
69
+ b: ${s(route.b.map(component => component && bundled_nodes.get(component).index))}
70
+ }`.replace(/^\t\t/gm, '');
271
71
  } else {
272
- if (element === 'img') {
273
- hrefs.push(get_src(attrs));
72
+ if (!build_data.server.vite_manifest[route.file]) {
73
+ // this is necessary in cases where a .css file snuck in —
74
+ // perhaps it would be better to disallow these (and others?)
75
+ return null;
274
76
  }
275
- hrefs.push(...get_srcset_urls(attrs));
276
- }
277
- }
278
-
279
- for (const href of hrefs) {
280
- if (!href) continue;
281
-
282
- const resolved = resolve$1(path, href);
283
- if (!is_root_relative(resolved)) continue;
284
77
 
285
- const parsed = new URL(resolved, 'http://localhost');
286
- const pathname = decodeURI(parsed.pathname).replace(config.kit.paths.base, '');
287
-
288
- const file = pathname.slice(1);
289
- if (files.has(file)) continue;
290
-
291
- if (parsed.search) ;
292
-
293
- await visit(pathname, path);
294
- }
295
- }
296
- }
297
- }
298
-
299
- if (config.kit.prerender.enabled) {
300
- for (const entry of config.kit.prerender.entries) {
301
- if (entry === '*') {
302
- for (const entry of build_data.entries) {
303
- await visit(entry, null);
304
- }
305
- } else {
306
- await visit(entry, null);
307
- }
308
- }
309
- }
310
-
311
- if (fallback) {
312
- const rendered = await app.render(
313
- {
314
- host: config.kit.host,
315
- method: 'GET',
316
- headers: {},
317
- path: '[fallback]', // this doesn't matter, but it's easiest if it's a string
318
- rawBody: null,
319
- query: new URLSearchParams()
320
- },
321
- {
322
- prerender: {
323
- fallback,
324
- all: false,
325
- dependencies: new Map()
326
- }
327
- }
328
- );
329
-
330
- const file = join(out, fallback);
331
- mkdirp(dirname(file));
332
- writeFileSync(file, rendered.body || '');
333
- written_files.push(file);
334
- }
335
-
336
- return written_files;
337
- }
338
-
339
- /**
340
- * @param {{
341
- * cwd: string;
342
- * config: import('types/config').ValidatedConfig;
343
- * build_data: import('types/internal').BuildData;
344
- * log: import('types/internal').Logger;
345
- * }} opts
346
- * @returns {import('types/config').AdapterUtils}
347
- */
348
- function get_utils({ cwd, config, build_data, log }) {
349
- return {
350
- log,
351
- rimraf,
352
- mkdirp,
353
- copy,
354
-
355
- copy_client_files(dest) {
356
- return copy(`${cwd}/${SVELTE_KIT}/output/client`, dest, (file) => file[0] !== '.');
357
- },
358
-
359
- copy_server_files(dest) {
360
- return copy(`${cwd}/${SVELTE_KIT}/output/server`, dest, (file) => file[0] !== '.');
361
- },
362
-
363
- copy_static_files(dest) {
364
- return copy(config.kit.files.assets, dest);
365
- },
366
-
367
- async prerender({ all = false, dest, fallback }) {
368
- await prerender({
369
- out: dest,
370
- all,
371
- cwd,
372
- config,
373
- build_data,
374
- fallback,
375
- log
376
- });
78
+ return `{
79
+ type: 'endpoint',
80
+ pattern: ${route.pattern},
81
+ params: ${get_params(route.params)},
82
+ load: ${importer(`${relative_path}/${build_data.server.vite_manifest[route.file].file}`)}
83
+ }`.replace(/^\t\t/gm, '');
84
+ }
85
+ }).filter(Boolean).join(',\n\t\t\t\t')}
86
+ ]
377
87
  }
378
- };
88
+ }`.replace(/^\t/gm, '');
379
89
  }
380
90
 
381
- /**
382
- * @param {import('types/config').ValidatedConfig} config
383
- * @param {import('types/internal').BuildData} build_data
384
- * @param {{ cwd?: string, verbose: boolean }} opts
385
- */
386
- async function adapt(config, build_data, { cwd = process.cwd(), verbose }) {
387
- const { name, adapt } = config.kit.adapter;
388
-
389
- console.log($.bold().cyan(`\n> Using ${name}`));
390
-
391
- const log = logger({ verbose });
392
- const utils = get_utils({ cwd, config, build_data, log });
393
- await adapt({ utils, config });
394
-
395
- log.success('done');
91
+ /** @param {string[]} array */
92
+ function get_params(array) {
93
+ // given an array of params like `['x', 'y', 'z']` for
94
+ // src/routes/[x]/[y]/[z]/svelte, create a function
95
+ // that turns a RexExpMatchArray into ({ x, y, z })
96
+ return array.length
97
+ ? '(m) => ({ ' +
98
+ array
99
+ .map((param, i) => {
100
+ return param.startsWith('...')
101
+ ? `${param.slice(3)}: m[${i + 1}] || ''`
102
+ : `${param}: m[${i + 1}]`;
103
+ })
104
+ .join(', ') +
105
+ '})'
106
+ : 'null';
396
107
  }
397
108
 
398
- export { adapt };
109
+ export { generate_manifest as g };