@sveltejs/kit 1.0.0-next.203 → 1.0.0-next.208

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,827 +1,628 @@
1
- import * as fs from 'fs';
2
- import fs__default, { readdirSync, statSync } from 'fs';
3
- import require$$2 from 'http';
4
- import require$$3 from 'https';
5
- import { resolve, join, normalize } from 'path';
6
- import * as require$$7 from 'querystring';
7
- import { pathToFileURL } from 'url';
8
- import { getRawBody } from '../node.js';
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';
9
6
  import { __fetch_polyfill } from '../install-fetch.js';
10
- import { S as SVELTE_KIT, a as SVELTE_KIT_ASSETS } from './constants.js';
7
+ import { g as get_single_valued_header, r as resolve$1, i as is_root_relative } from './url.js';
8
+ import { g as generate_manifest } from './index4.js';
9
+ import 'sade';
10
+ import 'child_process';
11
+ import 'net';
12
+ import 'os';
13
+ import './error.js';
11
14
  import 'node:http';
12
15
  import 'node:https';
13
16
  import 'node:zlib';
14
17
  import 'node:stream';
15
18
  import 'node:util';
16
19
  import 'node:url';
17
- import 'net';
20
+ import './misc.js';
18
21
 
19
- /**
20
- * @typedef ParsedURL
21
- * @type {import('.').ParsedURL}
22
- */
22
+ /** @typedef {{
23
+ * fn: () => Promise<any>,
24
+ * fulfil: (value: any) => void,
25
+ * reject: (error: Error) => void
26
+ * }} Task */
23
27
 
24
- /**
25
- * @typedef Request
26
- * @property {string} url
27
- * @property {ParsedURL} _parsedUrl
28
- */
28
+ /** @param {number} concurrency */
29
+ function queue(concurrency) {
30
+ /** @type {Task[]} */
31
+ const tasks = [];
29
32
 
30
- /**
31
- * @param {Request} req
32
- * @returns {ParsedURL|void}
33
- */
34
- function parse(req) {
35
- let raw = req.url;
36
- if (raw == null) return;
33
+ let current = 0;
37
34
 
38
- let prev = req._parsedUrl;
39
- if (prev && prev.raw === raw) return prev;
35
+ /** @type {(value?: any) => void} */
36
+ let fulfil;
40
37
 
41
- let pathname=raw, search='', query;
38
+ /** @type {(error: Error) => void} */
39
+ let reject;
42
40
 
43
- if (raw.length > 1) {
44
- let idx = raw.indexOf('?', 1);
41
+ let closed = false;
45
42
 
46
- if (idx !== -1) {
47
- search = raw.substring(idx);
48
- pathname = raw.substring(0, idx);
49
- if (search.length > 1) {
50
- query = require$$7.parse(search.substring(1));
43
+ const done = new Promise((f, r) => {
44
+ fulfil = f;
45
+ reject = r;
46
+ });
47
+
48
+ done.catch(() => {
49
+ // this is necessary in case a catch handler is never added
50
+ // to the done promise by the user
51
+ });
52
+
53
+ function dequeue() {
54
+ if (current < concurrency) {
55
+ const task = tasks.shift();
56
+
57
+ if (task) {
58
+ current += 1;
59
+ const promise = Promise.resolve(task.fn());
60
+
61
+ promise
62
+ .then(task.fulfil, (err) => {
63
+ task.reject(err);
64
+ reject(err);
65
+ })
66
+ .then(() => {
67
+ current -= 1;
68
+ dequeue();
69
+ });
70
+ } else if (current === 0) {
71
+ closed = true;
72
+ fulfil();
51
73
  }
52
74
  }
53
75
  }
54
76
 
55
- return req._parsedUrl = { pathname, search, query, raw };
56
- }
77
+ return {
78
+ /** @param {() => any} fn */
79
+ add: (fn) => {
80
+ if (closed) throw new Error('Cannot add tasks to a queue that has ended');
57
81
 
58
- function list(dir, callback, pre='') {
59
- dir = resolve('.', dir);
60
- let arr = readdirSync(dir);
61
- let i=0, abs, stats;
62
- for (; i < arr.length; i++) {
63
- abs = join(dir, arr[i]);
64
- stats = statSync(abs);
65
- stats.isDirectory()
66
- ? list(abs, callback, join(pre, arr[i]))
67
- : callback(join(pre, arr[i]), abs, stats);
68
- }
69
- }
82
+ const promise = new Promise((fulfil, reject) => {
83
+ tasks.push({ fn, fulfil, reject });
84
+ });
70
85
 
71
- const mimes = {
72
- "ez": "application/andrew-inset",
73
- "aw": "application/applixware",
74
- "atom": "application/atom+xml",
75
- "atomcat": "application/atomcat+xml",
76
- "atomdeleted": "application/atomdeleted+xml",
77
- "atomsvc": "application/atomsvc+xml",
78
- "dwd": "application/atsc-dwd+xml",
79
- "held": "application/atsc-held+xml",
80
- "rsat": "application/atsc-rsat+xml",
81
- "bdoc": "application/bdoc",
82
- "xcs": "application/calendar+xml",
83
- "ccxml": "application/ccxml+xml",
84
- "cdfx": "application/cdfx+xml",
85
- "cdmia": "application/cdmi-capability",
86
- "cdmic": "application/cdmi-container",
87
- "cdmid": "application/cdmi-domain",
88
- "cdmio": "application/cdmi-object",
89
- "cdmiq": "application/cdmi-queue",
90
- "cu": "application/cu-seeme",
91
- "mpd": "application/dash+xml",
92
- "davmount": "application/davmount+xml",
93
- "dbk": "application/docbook+xml",
94
- "dssc": "application/dssc+der",
95
- "xdssc": "application/dssc+xml",
96
- "es": "application/ecmascript",
97
- "ecma": "application/ecmascript",
98
- "emma": "application/emma+xml",
99
- "emotionml": "application/emotionml+xml",
100
- "epub": "application/epub+zip",
101
- "exi": "application/exi",
102
- "fdt": "application/fdt+xml",
103
- "pfr": "application/font-tdpfr",
104
- "geojson": "application/geo+json",
105
- "gml": "application/gml+xml",
106
- "gpx": "application/gpx+xml",
107
- "gxf": "application/gxf",
108
- "gz": "application/gzip",
109
- "hjson": "application/hjson",
110
- "stk": "application/hyperstudio",
111
- "ink": "application/inkml+xml",
112
- "inkml": "application/inkml+xml",
113
- "ipfix": "application/ipfix",
114
- "its": "application/its+xml",
115
- "jar": "application/java-archive",
116
- "war": "application/java-archive",
117
- "ear": "application/java-archive",
118
- "ser": "application/java-serialized-object",
119
- "class": "application/java-vm",
120
- "js": "application/javascript",
121
- "mjs": "application/javascript",
122
- "json": "application/json",
123
- "map": "application/json",
124
- "json5": "application/json5",
125
- "jsonml": "application/jsonml+json",
126
- "jsonld": "application/ld+json",
127
- "lgr": "application/lgr+xml",
128
- "lostxml": "application/lost+xml",
129
- "hqx": "application/mac-binhex40",
130
- "cpt": "application/mac-compactpro",
131
- "mads": "application/mads+xml",
132
- "webmanifest": "application/manifest+json",
133
- "mrc": "application/marc",
134
- "mrcx": "application/marcxml+xml",
135
- "ma": "application/mathematica",
136
- "nb": "application/mathematica",
137
- "mb": "application/mathematica",
138
- "mathml": "application/mathml+xml",
139
- "mbox": "application/mbox",
140
- "mscml": "application/mediaservercontrol+xml",
141
- "metalink": "application/metalink+xml",
142
- "meta4": "application/metalink4+xml",
143
- "mets": "application/mets+xml",
144
- "maei": "application/mmt-aei+xml",
145
- "musd": "application/mmt-usd+xml",
146
- "mods": "application/mods+xml",
147
- "m21": "application/mp21",
148
- "mp21": "application/mp21",
149
- "mp4s": "application/mp4",
150
- "m4p": "application/mp4",
151
- "doc": "application/msword",
152
- "dot": "application/msword",
153
- "mxf": "application/mxf",
154
- "nq": "application/n-quads",
155
- "nt": "application/n-triples",
156
- "cjs": "application/node",
157
- "bin": "application/octet-stream",
158
- "dms": "application/octet-stream",
159
- "lrf": "application/octet-stream",
160
- "mar": "application/octet-stream",
161
- "so": "application/octet-stream",
162
- "dist": "application/octet-stream",
163
- "distz": "application/octet-stream",
164
- "pkg": "application/octet-stream",
165
- "bpk": "application/octet-stream",
166
- "dump": "application/octet-stream",
167
- "elc": "application/octet-stream",
168
- "deploy": "application/octet-stream",
169
- "exe": "application/octet-stream",
170
- "dll": "application/octet-stream",
171
- "deb": "application/octet-stream",
172
- "dmg": "application/octet-stream",
173
- "iso": "application/octet-stream",
174
- "img": "application/octet-stream",
175
- "msi": "application/octet-stream",
176
- "msp": "application/octet-stream",
177
- "msm": "application/octet-stream",
178
- "buffer": "application/octet-stream",
179
- "oda": "application/oda",
180
- "opf": "application/oebps-package+xml",
181
- "ogx": "application/ogg",
182
- "omdoc": "application/omdoc+xml",
183
- "onetoc": "application/onenote",
184
- "onetoc2": "application/onenote",
185
- "onetmp": "application/onenote",
186
- "onepkg": "application/onenote",
187
- "oxps": "application/oxps",
188
- "relo": "application/p2p-overlay+xml",
189
- "xer": "application/patch-ops-error+xml",
190
- "pdf": "application/pdf",
191
- "pgp": "application/pgp-encrypted",
192
- "asc": "application/pgp-signature",
193
- "sig": "application/pgp-signature",
194
- "prf": "application/pics-rules",
195
- "p10": "application/pkcs10",
196
- "p7m": "application/pkcs7-mime",
197
- "p7c": "application/pkcs7-mime",
198
- "p7s": "application/pkcs7-signature",
199
- "p8": "application/pkcs8",
200
- "ac": "application/pkix-attr-cert",
201
- "cer": "application/pkix-cert",
202
- "crl": "application/pkix-crl",
203
- "pkipath": "application/pkix-pkipath",
204
- "pki": "application/pkixcmp",
205
- "pls": "application/pls+xml",
206
- "ai": "application/postscript",
207
- "eps": "application/postscript",
208
- "ps": "application/postscript",
209
- "provx": "application/provenance+xml",
210
- "cww": "application/prs.cww",
211
- "pskcxml": "application/pskc+xml",
212
- "raml": "application/raml+yaml",
213
- "rdf": "application/rdf+xml",
214
- "owl": "application/rdf+xml",
215
- "rif": "application/reginfo+xml",
216
- "rnc": "application/relax-ng-compact-syntax",
217
- "rl": "application/resource-lists+xml",
218
- "rld": "application/resource-lists-diff+xml",
219
- "rs": "application/rls-services+xml",
220
- "rapd": "application/route-apd+xml",
221
- "sls": "application/route-s-tsid+xml",
222
- "rusd": "application/route-usd+xml",
223
- "gbr": "application/rpki-ghostbusters",
224
- "mft": "application/rpki-manifest",
225
- "roa": "application/rpki-roa",
226
- "rsd": "application/rsd+xml",
227
- "rss": "application/rss+xml",
228
- "rtf": "application/rtf",
229
- "sbml": "application/sbml+xml",
230
- "scq": "application/scvp-cv-request",
231
- "scs": "application/scvp-cv-response",
232
- "spq": "application/scvp-vp-request",
233
- "spp": "application/scvp-vp-response",
234
- "sdp": "application/sdp",
235
- "senmlx": "application/senml+xml",
236
- "sensmlx": "application/sensml+xml",
237
- "setpay": "application/set-payment-initiation",
238
- "setreg": "application/set-registration-initiation",
239
- "shf": "application/shf+xml",
240
- "siv": "application/sieve",
241
- "sieve": "application/sieve",
242
- "smi": "application/smil+xml",
243
- "smil": "application/smil+xml",
244
- "rq": "application/sparql-query",
245
- "srx": "application/sparql-results+xml",
246
- "gram": "application/srgs",
247
- "grxml": "application/srgs+xml",
248
- "sru": "application/sru+xml",
249
- "ssdl": "application/ssdl+xml",
250
- "ssml": "application/ssml+xml",
251
- "swidtag": "application/swid+xml",
252
- "tei": "application/tei+xml",
253
- "teicorpus": "application/tei+xml",
254
- "tfi": "application/thraud+xml",
255
- "tsd": "application/timestamped-data",
256
- "toml": "application/toml",
257
- "trig": "application/trig",
258
- "ttml": "application/ttml+xml",
259
- "ubj": "application/ubjson",
260
- "rsheet": "application/urc-ressheet+xml",
261
- "td": "application/urc-targetdesc+xml",
262
- "vxml": "application/voicexml+xml",
263
- "wasm": "application/wasm",
264
- "wgt": "application/widget",
265
- "hlp": "application/winhlp",
266
- "wsdl": "application/wsdl+xml",
267
- "wspolicy": "application/wspolicy+xml",
268
- "xaml": "application/xaml+xml",
269
- "xav": "application/xcap-att+xml",
270
- "xca": "application/xcap-caps+xml",
271
- "xdf": "application/xcap-diff+xml",
272
- "xel": "application/xcap-el+xml",
273
- "xns": "application/xcap-ns+xml",
274
- "xenc": "application/xenc+xml",
275
- "xhtml": "application/xhtml+xml",
276
- "xht": "application/xhtml+xml",
277
- "xlf": "application/xliff+xml",
278
- "xml": "application/xml",
279
- "xsl": "application/xml",
280
- "xsd": "application/xml",
281
- "rng": "application/xml",
282
- "dtd": "application/xml-dtd",
283
- "xop": "application/xop+xml",
284
- "xpl": "application/xproc+xml",
285
- "xslt": "application/xml",
286
- "xspf": "application/xspf+xml",
287
- "mxml": "application/xv+xml",
288
- "xhvml": "application/xv+xml",
289
- "xvml": "application/xv+xml",
290
- "xvm": "application/xv+xml",
291
- "yang": "application/yang",
292
- "yin": "application/yin+xml",
293
- "zip": "application/zip",
294
- "3gpp": "video/3gpp",
295
- "adp": "audio/adpcm",
296
- "amr": "audio/amr",
297
- "au": "audio/basic",
298
- "snd": "audio/basic",
299
- "mid": "audio/midi",
300
- "midi": "audio/midi",
301
- "kar": "audio/midi",
302
- "rmi": "audio/midi",
303
- "mxmf": "audio/mobile-xmf",
304
- "mp3": "audio/mpeg",
305
- "m4a": "audio/mp4",
306
- "mp4a": "audio/mp4",
307
- "mpga": "audio/mpeg",
308
- "mp2": "audio/mpeg",
309
- "mp2a": "audio/mpeg",
310
- "m2a": "audio/mpeg",
311
- "m3a": "audio/mpeg",
312
- "oga": "audio/ogg",
313
- "ogg": "audio/ogg",
314
- "spx": "audio/ogg",
315
- "opus": "audio/ogg",
316
- "s3m": "audio/s3m",
317
- "sil": "audio/silk",
318
- "wav": "audio/wav",
319
- "weba": "audio/webm",
320
- "xm": "audio/xm",
321
- "ttc": "font/collection",
322
- "otf": "font/otf",
323
- "ttf": "font/ttf",
324
- "woff": "font/woff",
325
- "woff2": "font/woff2",
326
- "exr": "image/aces",
327
- "apng": "image/apng",
328
- "avif": "image/avif",
329
- "bmp": "image/bmp",
330
- "cgm": "image/cgm",
331
- "drle": "image/dicom-rle",
332
- "emf": "image/emf",
333
- "fits": "image/fits",
334
- "g3": "image/g3fax",
335
- "gif": "image/gif",
336
- "heic": "image/heic",
337
- "heics": "image/heic-sequence",
338
- "heif": "image/heif",
339
- "heifs": "image/heif-sequence",
340
- "hej2": "image/hej2k",
341
- "hsj2": "image/hsj2",
342
- "ief": "image/ief",
343
- "jls": "image/jls",
344
- "jp2": "image/jp2",
345
- "jpg2": "image/jp2",
346
- "jpeg": "image/jpeg",
347
- "jpg": "image/jpeg",
348
- "jpe": "image/jpeg",
349
- "jph": "image/jph",
350
- "jhc": "image/jphc",
351
- "jpm": "image/jpm",
352
- "jpx": "image/jpx",
353
- "jpf": "image/jpx",
354
- "jxr": "image/jxr",
355
- "jxra": "image/jxra",
356
- "jxrs": "image/jxrs",
357
- "jxs": "image/jxs",
358
- "jxsc": "image/jxsc",
359
- "jxsi": "image/jxsi",
360
- "jxss": "image/jxss",
361
- "ktx": "image/ktx",
362
- "ktx2": "image/ktx2",
363
- "png": "image/png",
364
- "btif": "image/prs.btif",
365
- "pti": "image/prs.pti",
366
- "sgi": "image/sgi",
367
- "svg": "image/svg+xml",
368
- "svgz": "image/svg+xml",
369
- "t38": "image/t38",
370
- "tif": "image/tiff",
371
- "tiff": "image/tiff",
372
- "tfx": "image/tiff-fx",
373
- "webp": "image/webp",
374
- "wmf": "image/wmf",
375
- "disposition-notification": "message/disposition-notification",
376
- "u8msg": "message/global",
377
- "u8dsn": "message/global-delivery-status",
378
- "u8mdn": "message/global-disposition-notification",
379
- "u8hdr": "message/global-headers",
380
- "eml": "message/rfc822",
381
- "mime": "message/rfc822",
382
- "3mf": "model/3mf",
383
- "gltf": "model/gltf+json",
384
- "glb": "model/gltf-binary",
385
- "igs": "model/iges",
386
- "iges": "model/iges",
387
- "msh": "model/mesh",
388
- "mesh": "model/mesh",
389
- "silo": "model/mesh",
390
- "mtl": "model/mtl",
391
- "obj": "model/obj",
392
- "stpz": "model/step+zip",
393
- "stpxz": "model/step-xml+zip",
394
- "stl": "model/stl",
395
- "wrl": "model/vrml",
396
- "vrml": "model/vrml",
397
- "x3db": "model/x3d+fastinfoset",
398
- "x3dbz": "model/x3d+binary",
399
- "x3dv": "model/x3d-vrml",
400
- "x3dvz": "model/x3d+vrml",
401
- "x3d": "model/x3d+xml",
402
- "x3dz": "model/x3d+xml",
403
- "appcache": "text/cache-manifest",
404
- "manifest": "text/cache-manifest",
405
- "ics": "text/calendar",
406
- "ifb": "text/calendar",
407
- "coffee": "text/coffeescript",
408
- "litcoffee": "text/coffeescript",
409
- "css": "text/css",
410
- "csv": "text/csv",
411
- "html": "text/html",
412
- "htm": "text/html",
413
- "shtml": "text/html",
414
- "jade": "text/jade",
415
- "jsx": "text/jsx",
416
- "less": "text/less",
417
- "markdown": "text/markdown",
418
- "md": "text/markdown",
419
- "mml": "text/mathml",
420
- "mdx": "text/mdx",
421
- "n3": "text/n3",
422
- "txt": "text/plain",
423
- "text": "text/plain",
424
- "conf": "text/plain",
425
- "def": "text/plain",
426
- "list": "text/plain",
427
- "log": "text/plain",
428
- "in": "text/plain",
429
- "ini": "text/plain",
430
- "dsc": "text/prs.lines.tag",
431
- "rtx": "text/richtext",
432
- "sgml": "text/sgml",
433
- "sgm": "text/sgml",
434
- "shex": "text/shex",
435
- "slim": "text/slim",
436
- "slm": "text/slim",
437
- "spdx": "text/spdx",
438
- "stylus": "text/stylus",
439
- "styl": "text/stylus",
440
- "tsv": "text/tab-separated-values",
441
- "t": "text/troff",
442
- "tr": "text/troff",
443
- "roff": "text/troff",
444
- "man": "text/troff",
445
- "me": "text/troff",
446
- "ms": "text/troff",
447
- "ttl": "text/turtle",
448
- "uri": "text/uri-list",
449
- "uris": "text/uri-list",
450
- "urls": "text/uri-list",
451
- "vcard": "text/vcard",
452
- "vtt": "text/vtt",
453
- "yaml": "text/yaml",
454
- "yml": "text/yaml",
455
- "3gp": "video/3gpp",
456
- "3g2": "video/3gpp2",
457
- "h261": "video/h261",
458
- "h263": "video/h263",
459
- "h264": "video/h264",
460
- "m4s": "video/iso.segment",
461
- "jpgv": "video/jpeg",
462
- "jpgm": "image/jpm",
463
- "mj2": "video/mj2",
464
- "mjp2": "video/mj2",
465
- "ts": "video/mp2t",
466
- "mp4": "video/mp4",
467
- "mp4v": "video/mp4",
468
- "mpg4": "video/mp4",
469
- "mpeg": "video/mpeg",
470
- "mpg": "video/mpeg",
471
- "mpe": "video/mpeg",
472
- "m1v": "video/mpeg",
473
- "m2v": "video/mpeg",
474
- "ogv": "video/ogg",
475
- "qt": "video/quicktime",
476
- "mov": "video/quicktime",
477
- "webm": "video/webm"
478
- };
479
-
480
- function lookup(extn) {
481
- let tmp = ('' + extn).trim().toLowerCase();
482
- let idx = tmp.lastIndexOf('.');
483
- return mimes[!~idx ? tmp : tmp.substring(++idx)];
484
- }
86
+ dequeue();
87
+ return promise;
88
+ },
485
89
 
486
- const noop = () => {};
90
+ done: () => {
91
+ if (current === 0) {
92
+ closed = true;
93
+ fulfil();
94
+ }
487
95
 
488
- function isMatch(uri, arr) {
489
- for (let i=0; i < arr.length; i++) {
490
- if (arr[i].test(uri)) return true;
491
- }
96
+ return done;
97
+ }
98
+ };
492
99
  }
493
100
 
494
- function toAssume(uri, extns) {
495
- let i=0, x, len=uri.length - 1;
496
- if (uri.charCodeAt(len) === 47) {
497
- uri = uri.substring(0, len);
498
- }
101
+ /**
102
+ * @typedef {import('types/config').PrerenderErrorHandler} PrerenderErrorHandler
103
+ * @typedef {import('types/config').PrerenderOnErrorValue} OnError
104
+ * @typedef {import('types/internal').Logger} Logger
105
+ */
499
106
 
500
- let arr=[], tmp=`${uri}/index`;
501
- for (; i < extns.length; i++) {
502
- x = extns[i] ? `.${extns[i]}` : '';
503
- if (uri) arr.push(uri + x);
504
- arr.push(tmp + x);
505
- }
107
+ /** @param {string} html */
108
+ function clean_html(html) {
109
+ return html
110
+ .replace(/<!\[CDATA\[[\s\S]*?\]\]>/gm, '')
111
+ .replace(/(<script[\s\S]*?>)[\s\S]*?<\/script>/gm, '$1</' + 'script>')
112
+ .replace(/(<style[\s\S]*?>)[\s\S]*?<\/style>/gm, '$1</' + 'style>')
113
+ .replace(/<!--[\s\S]*?-->/gm, '');
114
+ }
506
115
 
507
- return arr;
116
+ /** @param {string} attrs */
117
+ function get_href(attrs) {
118
+ const match = /(?:[\s'"]|^)href\s*=\s*(?:"(.*?)"|'(.*?)'|([^\s>]*))/.exec(attrs);
119
+ return match && (match[1] || match[2] || match[3]);
508
120
  }
509
121
 
510
- function viaCache(cache, uri, extns) {
511
- let i=0, data, arr=toAssume(uri, extns);
512
- for (; i < arr.length; i++) {
513
- if (data = cache[arr[i]]) return data;
514
- }
122
+ /** @param {string} attrs */
123
+ function get_src(attrs) {
124
+ const match = /(?:[\s'"]|^)src\s*=\s*(?:"(.*?)"|'(.*?)'|([^\s>]*))/.exec(attrs);
125
+ return match && (match[1] || match[2] || match[3]);
126
+ }
127
+
128
+ /** @param {string} attrs */
129
+ function is_rel_external(attrs) {
130
+ const match = /rel\s*=\s*(?:["'][^>]*(external)[^>]*["']|(external))/.exec(attrs);
131
+ return !!match;
515
132
  }
516
133
 
517
- function viaLocal(dir, isEtag, uri, extns) {
518
- let i=0, arr=toAssume(uri, extns);
519
- let abs, stats, name, headers;
520
- for (; i < arr.length; i++) {
521
- abs = normalize(join(dir, name=arr[i]));
522
- if (abs.startsWith(dir) && fs.existsSync(abs)) {
523
- stats = fs.statSync(abs);
524
- if (stats.isDirectory()) continue;
525
- headers = toHeaders(name, stats, isEtag);
526
- headers['Cache-Control'] = isEtag ? 'no-cache' : 'no-store';
527
- return { abs, stats, headers };
134
+ /** @param {string} attrs */
135
+ function get_srcset_urls(attrs) {
136
+ const results = [];
137
+ // Note that the srcset allows any ASCII whitespace, including newlines.
138
+ const match = /([\s'"]|^)srcset\s*=\s*(?:"(.*?)"|'(.*?)'|([^\s>]*))/s.exec(attrs);
139
+ if (match) {
140
+ const attr_content = match[1] || match[2] || match[3];
141
+ // Parse the content of the srcset attribute.
142
+ // The regexp is modelled after the srcset specs (https://html.spec.whatwg.org/multipage/images.html#srcset-attribute)
143
+ // and should cover most reasonable cases.
144
+ const regex = /\s*([^\s,]\S+[^\s,])\s*((?:\d+w)|(?:-?\d+(?:\.\d+)?(?:[eE]-?\d+)?x))?/gm;
145
+ let sub_matches;
146
+ while ((sub_matches = regex.exec(attr_content))) {
147
+ results.push(sub_matches[1]);
528
148
  }
529
149
  }
150
+ return results;
530
151
  }
531
152
 
532
- function is404(req, res) {
533
- return (res.statusCode=404,res.end());
153
+ /** @type {(errorDetails: Parameters<PrerenderErrorHandler>[0] ) => string} */
154
+ function errorDetailsToString({ status, path, referrer, referenceType }) {
155
+ return `${status} ${path}${referrer ? ` (${referenceType} from ${referrer})` : ''}`;
534
156
  }
535
157
 
536
- function send(req, res, file, stats, headers) {
537
- let code=200, tmp, opts={};
538
- headers = { ...headers };
539
-
540
- for (let key in headers) {
541
- tmp = res.getHeader(key);
542
- if (tmp) headers[key] = tmp;
158
+ /** @type {(log: Logger, onError: OnError) => PrerenderErrorHandler} */
159
+ function chooseErrorHandler(log, onError) {
160
+ switch (onError) {
161
+ case 'continue':
162
+ return (errorDetails) => {
163
+ log.error(errorDetailsToString(errorDetails));
164
+ };
165
+ case 'fail':
166
+ return (errorDetails) => {
167
+ throw new Error(errorDetailsToString(errorDetails));
168
+ };
169
+ default:
170
+ return onError;
543
171
  }
172
+ }
173
+
174
+ const OK = 2;
175
+ const REDIRECT = 3;
544
176
 
545
- if (tmp = res.getHeader('content-type')) {
546
- headers['Content-Type'] = tmp;
177
+ /**
178
+ * @param {{
179
+ * cwd: string;
180
+ * out: string;
181
+ * log: Logger;
182
+ * config: import('types/config').ValidatedConfig;
183
+ * build_data: import('types/internal').BuildData;
184
+ * fallback?: string;
185
+ * all: boolean; // disregard `export const prerender = true`
186
+ * }} opts
187
+ * @returns {Promise<{ paths: string[] }>} returns a promise that resolves to an array of paths corresponding to the files that have been prerendered.
188
+ */
189
+ async function prerender({ cwd, out, log, config, build_data, fallback, all }) {
190
+ if (!config.kit.prerender.enabled && !fallback) {
191
+ return { paths: [] };
547
192
  }
548
193
 
549
- if (req.headers.range) {
550
- code = 206;
551
- let [x, y] = req.headers.range.replace('bytes=', '').split('-');
552
- let end = opts.end = parseInt(y, 10) || stats.size - 1;
553
- let start = opts.start = parseInt(x, 10) || 0;
194
+ __fetch_polyfill();
554
195
 
555
- if (start >= stats.size || end >= stats.size) {
556
- res.setHeader('Content-Range', `bytes */${stats.size}`);
557
- res.statusCode = 416;
558
- return res.end();
559
- }
196
+ mkdirp(out);
560
197
 
561
- headers['Content-Range'] = `bytes ${start}-${end}/${stats.size}`;
562
- headers['Content-Length'] = (end - start + 1);
563
- headers['Accept-Ranges'] = 'bytes';
564
- }
198
+ const dir = resolve(cwd, `${SVELTE_KIT}/output`);
565
199
 
566
- res.writeHead(code, headers);
567
- fs.createReadStream(file, opts).pipe(res);
568
- }
200
+ const seen = new Set();
569
201
 
570
- const ENCODING = {
571
- '.br': 'br',
572
- '.gz': 'gzip',
573
- };
202
+ const server_root = resolve(dir);
574
203
 
575
- function toHeaders(name, stats, isEtag) {
576
- let enc = ENCODING[name.slice(-3)];
204
+ /** @type {import('types/internal').AppModule} */
205
+ const { App, override } = await import(pathToFileURL(`${server_root}/server/app.js`).href);
577
206
 
578
- let ctype = lookup(name.slice(0, enc && -3)) || '';
579
- if (ctype === 'text/html') ctype += ';charset=utf-8';
207
+ override({
208
+ paths: config.kit.paths,
209
+ prerendering: true,
210
+ read: (file) => readFileSync(join(config.kit.files.assets, file))
211
+ });
580
212
 
581
- let headers = {
582
- 'Content-Length': stats.size,
583
- 'Content-Type': ctype,
584
- 'Last-Modified': stats.mtime.toUTCString(),
585
- };
213
+ const { manifest } = await import(pathToFileURL(`${server_root}/server/manifest.js`).href);
586
214
 
587
- if (enc) headers['Content-Encoding'] = enc;
588
- if (isEtag) headers['ETag'] = `W/"${stats.size}-${stats.mtime.getTime()}"`;
215
+ const app = new App(manifest);
589
216
 
590
- return headers;
591
- }
217
+ const error = chooseErrorHandler(log, config.kit.prerender.onError);
592
218
 
593
- function sirv (dir, opts={}) {
594
- dir = resolve(dir || '.');
219
+ const files = new Set([
220
+ ...build_data.static,
221
+ ...build_data.client.chunks.map((chunk) => `${config.kit.appDir}/${chunk.fileName}`),
222
+ ...build_data.client.assets.map((chunk) => `${config.kit.appDir}/${chunk.fileName}`)
223
+ ]);
595
224
 
596
- let isNotFound = opts.onNoMatch || is404;
597
- let setHeaders = opts.setHeaders || noop;
225
+ /** @type {string[]} */
226
+ const paths = [];
598
227
 
599
- let extensions = opts.extensions || ['html', 'htm'];
600
- let gzips = opts.gzip && extensions.map(x => `${x}.gz`).concat('gz');
601
- let brots = opts.brotli && extensions.map(x => `${x}.br`).concat('br');
228
+ build_data.static.forEach((file) => {
229
+ if (file.endsWith('/index.html')) {
230
+ files.add(file.slice(0, -11));
231
+ }
232
+ });
602
233
 
603
- const FILES = {};
234
+ /**
235
+ * @param {string} path
236
+ */
237
+ function normalize(path) {
238
+ if (config.kit.trailingSlash === 'always') {
239
+ return path.endsWith('/') ? path : `${path}/`;
240
+ } else if (config.kit.trailingSlash === 'never') {
241
+ return !path.endsWith('/') || path === '/' ? path : path.slice(0, -1);
242
+ }
604
243
 
605
- let fallback = '/';
606
- let isEtag = !!opts.etag;
607
- let isSPA = !!opts.single;
608
- if (typeof opts.single === 'string') {
609
- let idx = opts.single.lastIndexOf('.');
610
- fallback += !!~idx ? opts.single.substring(0, idx) : opts.single;
244
+ return path;
611
245
  }
612
246
 
613
- let ignores = [];
614
- if (opts.ignores !== false) {
615
- ignores.push(/[/]([A-Za-z\s\d~$._-]+\.\w+){1,}$/); // any extn
616
- if (opts.dotfiles) ignores.push(/\/\.\w/);
617
- else ignores.push(/\/\.well-known/);
618
- [].concat(opts.ignores || []).forEach(x => {
619
- ignores.push(new RegExp(x, 'i'));
620
- });
247
+ const q = queue(config.kit.prerender.concurrency);
248
+
249
+ /**
250
+ * @param {string} decoded_path
251
+ * @param {string?} referrer
252
+ */
253
+ function enqueue(decoded_path, referrer) {
254
+ const path = encodeURI(normalize(decoded_path));
255
+
256
+ if (seen.has(path)) return;
257
+ seen.add(path);
258
+
259
+ return q.add(() => visit(path, decoded_path, referrer));
621
260
  }
622
261
 
623
- let cc = opts.maxAge != null && `public,max-age=${opts.maxAge}`;
624
- if (cc && opts.immutable) cc += ',immutable';
625
- else if (cc && opts.maxAge === 0) cc += ',must-revalidate';
262
+ /**
263
+ * @param {string} path
264
+ * @param {string} decoded_path
265
+ * @param {string?} referrer
266
+ */
267
+ async function visit(path, decoded_path, referrer) {
268
+ /** @type {Map<string, import('types/hooks').ServerResponse>} */
269
+ const dependencies = new Map();
270
+
271
+ const rendered = await app.render(
272
+ {
273
+ url: `${config.kit.protocol || 'sveltekit'}://${config.kit.host || 'prerender'}${path}`,
274
+ method: 'GET',
275
+ headers: {},
276
+ rawBody: null
277
+ },
278
+ {
279
+ prerender: {
280
+ all,
281
+ dependencies
282
+ }
283
+ }
284
+ );
626
285
 
627
- if (!opts.dev) {
628
- list(dir, (name, abs, stats) => {
629
- if (/\.well-known[\\+\/]/.test(name)) ; // keep
630
- else if (!opts.dotfiles && /(^\.|[\\+|\/+]\.)/.test(name)) return;
286
+ if (rendered) {
287
+ const response_type = Math.floor(rendered.status / 100);
288
+ const headers = rendered.headers;
289
+ const type = headers && headers['content-type'];
290
+ const is_html = response_type === REDIRECT || type === 'text/html';
631
291
 
632
- let headers = toHeaders(name, stats, isEtag);
633
- if (cc) headers['Cache-Control'] = cc;
292
+ const parts = decoded_path.split('/');
293
+ if (is_html && parts[parts.length - 1] !== 'index.html') {
294
+ parts.push('index.html');
295
+ }
634
296
 
635
- FILES['/' + name.normalize().replace(/\\+/g, '/')] = { abs, stats, headers };
636
- });
637
- }
297
+ const file = `${out}${parts.join('/')}`;
638
298
 
639
- let lookup = opts.dev ? viaLocal.bind(0, dir, isEtag) : viaCache.bind(0, FILES);
299
+ if (response_type === REDIRECT) {
300
+ const location = get_single_valued_header(headers, 'location');
640
301
 
641
- return function (req, res, next) {
642
- let extns = [''];
643
- let pathname = parse(req).pathname;
644
- let val = req.headers['accept-encoding'] || '';
645
- if (gzips && val.includes('gzip')) extns.unshift(...gzips);
646
- if (brots && /(br|brotli)/i.test(val)) extns.unshift(...brots);
647
- extns.push(...extensions); // [...br, ...gz, orig, ...exts]
302
+ if (location) {
303
+ mkdirp(dirname(file));
648
304
 
649
- if (pathname.indexOf('%') !== -1) {
650
- try { pathname = decodeURIComponent(pathname); }
651
- catch (err) { /* malform uri */ }
652
- }
305
+ log.warn(`${rendered.status} ${decoded_path} -> ${location}`);
306
+ writeFileSync(file, `<meta http-equiv="refresh" content="0;url=${encodeURI(location)}">`);
307
+
308
+ const resolved = resolve$1(path, location);
309
+ if (is_root_relative(resolved)) {
310
+ enqueue(resolved, path);
311
+ }
312
+ } else {
313
+ log.warn(`location header missing on redirect received from ${decoded_path}`);
314
+ }
315
+
316
+ return;
317
+ }
318
+
319
+ if (rendered.status === 200) {
320
+ mkdirp(dirname(file));
321
+
322
+ log.info(`${rendered.status} ${decoded_path}`);
323
+ writeFileSync(file, rendered.body || '');
324
+ paths.push(normalize(decoded_path));
325
+ } else if (response_type !== OK) {
326
+ error({ status: rendered.status, path, referrer, referenceType: 'linked' });
327
+ }
328
+
329
+ dependencies.forEach((result, dependency_path) => {
330
+ const response_type = Math.floor(result.status / 100);
331
+
332
+ const is_html = result.headers['content-type'] === 'text/html';
333
+
334
+ const parts = dependency_path.split('/');
335
+ if (is_html && parts[parts.length - 1] !== 'index.html') {
336
+ parts.push('index.html');
337
+ }
338
+
339
+ const file = `${out}${parts.join('/')}`;
340
+ mkdirp(dirname(file));
341
+
342
+ if (result.body) {
343
+ writeFileSync(file, result.body);
344
+ paths.push(dependency_path);
345
+ }
346
+
347
+ if (response_type === OK) {
348
+ log.info(`${result.status} ${dependency_path}`);
349
+ } else {
350
+ error({
351
+ status: result.status,
352
+ path: dependency_path,
353
+ referrer: path,
354
+ referenceType: 'fetched'
355
+ });
356
+ }
357
+ });
358
+
359
+ if (is_html && config.kit.prerender.crawl) {
360
+ const cleaned = clean_html(/** @type {string} */ (rendered.body));
361
+
362
+ let match;
363
+ const pattern = /<(a|img|link|source)\s+([\s\S]+?)>/gm;
364
+
365
+ const hrefs = [];
653
366
 
654
- let data = lookup(pathname, extns) || isSPA && !isMatch(pathname, ignores) && lookup(fallback, extns);
655
- if (!data) return next ? next() : isNotFound(req, res);
367
+ while ((match = pattern.exec(cleaned))) {
368
+ const element = match[1];
369
+ const attrs = match[2];
656
370
 
657
- if (isEtag && req.headers['if-none-match'] === data.headers['ETag']) {
658
- res.writeHead(304);
659
- return res.end();
371
+ if (element === 'a' || element === 'link') {
372
+ if (is_rel_external(attrs)) continue;
373
+
374
+ hrefs.push(get_href(attrs));
375
+ } else {
376
+ if (element === 'img') {
377
+ hrefs.push(get_src(attrs));
378
+ }
379
+ hrefs.push(...get_srcset_urls(attrs));
380
+ }
381
+ }
382
+
383
+ for (const href of hrefs) {
384
+ if (!href) continue;
385
+
386
+ const resolved = resolve$1(path, href);
387
+ if (!is_root_relative(resolved)) continue;
388
+
389
+ const parsed = new URL(resolved, 'http://localhost');
390
+ const pathname = decodeURI(parsed.pathname).replace(config.kit.paths.base, '');
391
+
392
+ const file = pathname.slice(1);
393
+ if (files.has(file)) continue;
394
+
395
+ if (parsed.search) ;
396
+
397
+ enqueue(pathname, path);
398
+ }
399
+ }
660
400
  }
401
+ }
661
402
 
662
- if (gzips || brots) {
663
- res.setHeader('Vary', 'Accept-Encoding');
403
+ if (config.kit.prerender.enabled) {
404
+ for (const entry of config.kit.prerender.entries) {
405
+ if (entry === '*') {
406
+ for (const entry of build_data.entries) {
407
+ enqueue(entry, null);
408
+ }
409
+ } else {
410
+ enqueue(entry, null);
411
+ }
664
412
  }
665
413
 
666
- setHeaders(res, pathname, data.stats);
667
- send(req, res, data.abs, data.stats, data.headers);
414
+ await q.done();
415
+ }
416
+
417
+ if (fallback) {
418
+ const rendered = await app.render(
419
+ {
420
+ url: `${config.kit.host || 'sveltekit'}://${config.kit.host || 'prerender'}/[fallback]`,
421
+ method: 'GET',
422
+ headers: {},
423
+ rawBody: null
424
+ },
425
+ {
426
+ prerender: {
427
+ fallback,
428
+ all: false,
429
+ dependencies: new Map()
430
+ }
431
+ }
432
+ );
433
+
434
+ const file = join(out, fallback);
435
+ mkdirp(dirname(file));
436
+ writeFileSync(file, rendered.body || '');
437
+ }
438
+
439
+ return {
440
+ paths
668
441
  };
669
442
  }
670
443
 
671
- /** @param {string} dir */
672
- const mutable = (dir) =>
673
- sirv(dir, {
674
- etag: true,
675
- maxAge: 0
676
- });
677
-
678
444
  /**
679
445
  * @param {{
680
- * port: number;
681
- * host?: string;
446
+ * cwd: string;
682
447
  * config: import('types/config').ValidatedConfig;
683
- * https?: boolean;
684
- * cwd?: string;
448
+ * build_data: import('types/internal').BuildData;
449
+ * log: import('types/internal').Logger;
685
450
  * }} opts
451
+ * @returns {import('types/config').Builder}
686
452
  */
687
- async function preview({
688
- port,
689
- host,
690
- config,
691
- https: use_https = false,
692
- cwd = process.cwd()
693
- }) {
694
- __fetch_polyfill();
453
+ function create_builder({ cwd, config, build_data, log }) {
454
+ /** @type {Set<string>} */
455
+ const prerendered_paths = new Set();
456
+ let generated_manifest = false;
457
+
458
+ /** @param {import('types/internal').RouteData} route */
459
+ function not_prerendered(route) {
460
+ if (route.type === 'page' && route.path) {
461
+ return !prerendered_paths.has(route.path);
462
+ }
695
463
 
696
- const app_file = resolve(cwd, `${SVELTE_KIT}/output/server/app.js`);
464
+ return true;
465
+ }
697
466
 
698
- /** @type {import('types/internal').App} */
699
- const app = await import(pathToFileURL(app_file).href);
467
+ return {
468
+ log,
469
+ rimraf,
470
+ mkdirp,
471
+ copy,
700
472
 
701
- /** @type {import('sirv').RequestHandler} */
702
- const static_handler = fs__default.existsSync(config.kit.files.assets)
703
- ? mutable(config.kit.files.assets)
704
- : (_req, _res, next) => {
705
- if (!next) throw new Error('No next() handler is available');
706
- return next();
707
- };
473
+ createEntries(fn) {
474
+ generated_manifest = true;
708
475
 
709
- const assets_handler = sirv(resolve(cwd, `${SVELTE_KIT}/output/client`), {
710
- maxAge: 31536000,
711
- immutable: true
712
- });
476
+ const { routes } = build_data.manifest_data;
713
477
 
714
- const has_asset_path = !!config.kit.paths.assets;
478
+ /** @type {import('types/config').RouteDefinition[]} */
479
+ const facades = routes.map((route) => ({
480
+ type: route.type,
481
+ segments: route.segments,
482
+ pattern: route.pattern,
483
+ methods: route.type === 'page' ? ['get'] : build_data.server.methods[route.file]
484
+ }));
715
485
 
716
- app.init({
717
- paths: {
718
- base: config.kit.paths.base,
719
- assets: has_asset_path ? SVELTE_KIT_ASSETS : config.kit.paths.base
720
- },
721
- prerendering: false,
722
- read: (file) => fs__default.readFileSync(join(config.kit.files.assets, file))
723
- });
486
+ const seen = new Set();
724
487
 
725
- /** @type {import('vite').UserConfig} */
726
- const vite_config = (config.kit.vite && config.kit.vite()) || {};
488
+ for (let i = 0; i < routes.length; i += 1) {
489
+ const route = routes[i];
490
+ const { id, filter, complete } = fn(facades[i]);
727
491
 
728
- const server = await get_server(use_https, vite_config, (req, res) => {
729
- if (req.url == null) {
730
- throw new Error('Invalid request url');
731
- }
492
+ if (seen.has(id)) continue;
493
+ seen.add(id);
732
494
 
733
- const initial_url = req.url;
495
+ const group = [route];
734
496
 
735
- const render_handler = async () => {
736
- if (!req.method) throw new Error('Incomplete request');
497
+ // figure out which lower priority routes should be considered fallbacks
498
+ for (let j = i + 1; j < routes.length; j += 1) {
499
+ if (filter(facades[j])) {
500
+ group.push(routes[j]);
501
+ }
502
+ }
737
503
 
738
- let body;
504
+ const filtered = new Set(group.filter(not_prerendered));
739
505
 
740
- try {
741
- body = await getRawBody(req);
742
- } catch (/** @type {any} */ err) {
743
- res.statusCode = err.status || 400;
744
- return res.end(err.reason || 'Invalid request body');
745
- }
506
+ // heuristic: if /foo/[bar] is included, /foo/[bar].json should
507
+ // also be included, since the page likely needs the endpoint
508
+ filtered.forEach((route) => {
509
+ if (route.type === 'page') {
510
+ const length = route.segments.length;
746
511
 
747
- const parsed = new URL(initial_url, 'http://localhost/');
748
-
749
- const rendered =
750
- parsed.pathname.startsWith(config.kit.paths.base) &&
751
- (await app.render({
752
- host: /** @type {string} */ (
753
- config.kit.host || req.headers[config.kit.hostHeader || 'host']
754
- ),
755
- method: req.method,
756
- headers: /** @type {import('types/helper').RequestHeaders} */ (req.headers),
757
- path: parsed.pathname.replace(config.kit.paths.base, ''),
758
- query: parsed.searchParams,
759
- rawBody: body
760
- }));
761
-
762
- if (rendered) {
763
- res.writeHead(rendered.status, rendered.headers);
764
- if (rendered.body) res.write(rendered.body);
765
- res.end();
766
- } else {
767
- res.statusCode = 404;
768
- res.end('Not found');
769
- }
770
- };
771
-
772
- if (has_asset_path) {
773
- if (initial_url.startsWith(SVELTE_KIT_ASSETS)) {
774
- // custom assets path
775
- req.url = initial_url.slice(SVELTE_KIT_ASSETS.length);
776
- assets_handler(req, res, () => {
777
- static_handler(req, res, render_handler);
512
+ const endpoint = routes.find((candidate) => {
513
+ if (candidate.segments.length !== length) return false;
514
+
515
+ for (let i = 0; i < length; i += 1) {
516
+ const a = route.segments[i];
517
+ const b = candidate.segments[i];
518
+
519
+ if (i === length - 1) {
520
+ return b.content === `${a.content}.json`;
521
+ }
522
+
523
+ if (a.content !== b.content) return false;
524
+ }
525
+ });
526
+
527
+ if (endpoint) {
528
+ filtered.add(endpoint);
529
+ }
530
+ }
778
531
  });
779
- } else {
780
- render_handler();
532
+
533
+ if (filtered.size > 0) {
534
+ complete({
535
+ generateManifest: ({ relativePath, format }) =>
536
+ generate_manifest(build_data, relativePath, Array.from(filtered), format)
537
+ });
538
+ }
781
539
  }
782
- } else {
783
- if (initial_url.startsWith(config.kit.paths.base)) {
784
- req.url = initial_url.slice(config.kit.paths.base.length);
540
+ },
541
+
542
+ generateManifest: ({ relativePath, format }) => {
543
+ generated_manifest = true;
544
+ return generate_manifest(
545
+ build_data,
546
+ relativePath,
547
+ build_data.manifest_data.routes.filter(not_prerendered),
548
+ format
549
+ );
550
+ },
551
+
552
+ getBuildDirectory(name) {
553
+ return `${cwd}/${SVELTE_KIT}/${name}`;
554
+ },
555
+
556
+ getClientDirectory() {
557
+ return `${cwd}/${SVELTE_KIT}/output/client`;
558
+ },
559
+
560
+ getServerDirectory() {
561
+ return `${cwd}/${SVELTE_KIT}/output/server`;
562
+ },
563
+
564
+ getStaticDirectory() {
565
+ return config.kit.files.assets;
566
+ },
567
+
568
+ writeClient(dest) {
569
+ return copy(`${cwd}/${SVELTE_KIT}/output/client`, dest, {
570
+ filter: (file) => file[0] !== '.'
571
+ });
572
+ },
573
+
574
+ writeServer(dest) {
575
+ return copy(`${cwd}/${SVELTE_KIT}/output/server`, dest, {
576
+ filter: (file) => file[0] !== '.'
577
+ });
578
+ },
579
+
580
+ writeStatic(dest) {
581
+ return copy(config.kit.files.assets, dest);
582
+ },
583
+
584
+ async prerender({ all = false, dest, fallback }) {
585
+ if (generated_manifest) {
586
+ throw new Error(
587
+ 'Adapters must call prerender(...) before createEntries(...) or generateManifest(...)'
588
+ );
785
589
  }
786
- assets_handler(req, res, () => {
787
- static_handler(req, res, render_handler);
590
+
591
+ const prerendered = await prerender({
592
+ out: dest,
593
+ all,
594
+ cwd,
595
+ config,
596
+ build_data,
597
+ fallback,
598
+ log
788
599
  });
789
- }
790
- });
791
600
 
792
- await server.listen(port, host || '0.0.0.0');
601
+ prerendered.paths.forEach((path) => {
602
+ prerendered_paths.add(path);
603
+ prerendered_paths.add(path + '/');
604
+ });
793
605
 
794
- return Promise.resolve(server);
606
+ return prerendered;
607
+ }
608
+ };
795
609
  }
796
610
 
797
611
  /**
798
- * @param {boolean} use_https
799
- * @param {import('vite').UserConfig} user_config
800
- * @param {(req: http.IncomingMessage, res: http.ServerResponse) => void} handler
801
- * @returns {Promise<import('net').Server>}
612
+ * @param {import('types/config').ValidatedConfig} config
613
+ * @param {import('types/internal').BuildData} build_data
614
+ * @param {{ cwd?: string, verbose: boolean }} opts
802
615
  */
803
- async function get_server(use_https, user_config, handler) {
804
- /** @type {https.ServerOptions} */
805
- const https_options = {};
806
-
807
- if (use_https) {
808
- const secure_opts = user_config.server
809
- ? /** @type {import('tls').SecureContextOptions} */ (user_config.server.https)
810
- : {};
811
-
812
- if (secure_opts.key && secure_opts.cert) {
813
- https_options.key = secure_opts.key.toString();
814
- https_options.cert = secure_opts.cert.toString();
815
- } else {
816
- https_options.key = https_options.cert = (await import('./cert.js')).createCertificate();
817
- }
818
- }
616
+ async function adapt(config, build_data, { cwd = process.cwd(), verbose }) {
617
+ const { name, adapt } = config.kit.adapter;
618
+
619
+ console.log($.bold().cyan(`\n> Using ${name}`));
620
+
621
+ const log = logger({ verbose });
622
+ const builder = create_builder({ cwd, config, build_data, log });
623
+ await adapt(builder);
819
624
 
820
- return Promise.resolve(
821
- use_https
822
- ? require$$3.createServer(/** @type {https.ServerOptions} */ (https_options), handler)
823
- : require$$2.createServer(handler)
824
- );
625
+ log.success('done');
825
626
  }
826
627
 
827
- export { preview };
628
+ export { adapt };