@sveltejs/kit 1.0.0-next.98 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (141) hide show
  1. package/README.md +5 -1
  2. package/package.json +91 -77
  3. package/postinstall.js +47 -0
  4. package/src/cli.js +44 -0
  5. package/src/constants.js +5 -0
  6. package/src/core/adapt/builder.js +221 -0
  7. package/src/core/adapt/index.js +31 -0
  8. package/src/core/config/default-error.html +56 -0
  9. package/src/core/config/index.js +100 -0
  10. package/src/core/config/options.js +387 -0
  11. package/src/core/config/types.d.ts +1 -0
  12. package/src/core/env.js +138 -0
  13. package/src/core/generate_manifest/index.js +116 -0
  14. package/src/core/prerender/crawl.js +207 -0
  15. package/src/core/prerender/entities.js +2252 -0
  16. package/src/core/prerender/fallback.js +43 -0
  17. package/src/core/prerender/prerender.js +459 -0
  18. package/src/core/prerender/queue.js +80 -0
  19. package/src/core/sync/create_manifest_data/conflict.js +0 -0
  20. package/src/core/sync/create_manifest_data/index.js +523 -0
  21. package/src/core/sync/create_manifest_data/sort.js +161 -0
  22. package/src/core/sync/create_manifest_data/types.d.ts +37 -0
  23. package/src/core/sync/sync.js +59 -0
  24. package/src/core/sync/utils.js +33 -0
  25. package/src/core/sync/write_ambient.js +58 -0
  26. package/src/core/sync/write_client_manifest.js +107 -0
  27. package/src/core/sync/write_matchers.js +25 -0
  28. package/src/core/sync/write_root.js +91 -0
  29. package/src/core/sync/write_tsconfig.js +195 -0
  30. package/src/core/sync/write_types/index.js +809 -0
  31. package/src/core/utils.js +67 -0
  32. package/src/exports/hooks/index.js +1 -0
  33. package/src/exports/hooks/sequence.js +44 -0
  34. package/src/exports/index.js +55 -0
  35. package/src/exports/node/index.js +172 -0
  36. package/src/exports/node/polyfills.js +28 -0
  37. package/src/exports/vite/build/build_server.js +359 -0
  38. package/src/exports/vite/build/build_service_worker.js +85 -0
  39. package/src/exports/vite/build/utils.js +230 -0
  40. package/src/exports/vite/dev/index.js +597 -0
  41. package/src/exports/vite/graph_analysis/index.js +99 -0
  42. package/src/exports/vite/graph_analysis/types.d.ts +5 -0
  43. package/src/exports/vite/graph_analysis/utils.js +6 -0
  44. package/src/exports/vite/index.js +708 -0
  45. package/src/exports/vite/preview/index.js +194 -0
  46. package/src/exports/vite/types.d.ts +3 -0
  47. package/src/exports/vite/utils.js +184 -0
  48. package/src/runtime/app/env.js +1 -0
  49. package/src/runtime/app/environment.js +13 -0
  50. package/src/runtime/app/forms.js +135 -0
  51. package/src/runtime/app/navigation.js +22 -0
  52. package/src/runtime/app/paths.js +1 -0
  53. package/src/runtime/app/stores.js +57 -0
  54. package/src/runtime/client/ambient.d.ts +30 -0
  55. package/src/runtime/client/client.js +1725 -0
  56. package/src/runtime/client/constants.js +10 -0
  57. package/src/runtime/client/fetcher.js +127 -0
  58. package/src/runtime/client/parse.js +60 -0
  59. package/src/runtime/client/singletons.js +21 -0
  60. package/src/runtime/client/start.js +45 -0
  61. package/src/runtime/client/types.d.ts +86 -0
  62. package/src/runtime/client/utils.js +257 -0
  63. package/src/runtime/components/error.svelte +6 -0
  64. package/{assets → src/runtime}/components/layout.svelte +0 -0
  65. package/src/runtime/control.js +45 -0
  66. package/src/runtime/env/dynamic/private.js +1 -0
  67. package/src/runtime/env/dynamic/public.js +1 -0
  68. package/src/runtime/env-private.js +6 -0
  69. package/src/runtime/env-public.js +6 -0
  70. package/src/runtime/env.js +12 -0
  71. package/src/runtime/hash.js +20 -0
  72. package/src/runtime/paths.js +11 -0
  73. package/src/runtime/server/cookie.js +228 -0
  74. package/src/runtime/server/data/index.js +158 -0
  75. package/src/runtime/server/endpoint.js +86 -0
  76. package/src/runtime/server/fetch.js +175 -0
  77. package/src/runtime/server/index.js +405 -0
  78. package/src/runtime/server/page/actions.js +267 -0
  79. package/src/runtime/server/page/crypto.js +239 -0
  80. package/src/runtime/server/page/csp.js +250 -0
  81. package/src/runtime/server/page/index.js +326 -0
  82. package/src/runtime/server/page/load_data.js +270 -0
  83. package/src/runtime/server/page/render.js +393 -0
  84. package/src/runtime/server/page/respond_with_error.js +103 -0
  85. package/src/runtime/server/page/serialize_data.js +87 -0
  86. package/src/runtime/server/page/types.d.ts +35 -0
  87. package/src/runtime/server/utils.js +179 -0
  88. package/src/utils/array.js +9 -0
  89. package/src/utils/error.js +22 -0
  90. package/src/utils/escape.js +46 -0
  91. package/src/utils/exports.js +54 -0
  92. package/src/utils/filesystem.js +178 -0
  93. package/src/utils/functions.js +16 -0
  94. package/src/utils/http.js +72 -0
  95. package/src/utils/misc.js +1 -0
  96. package/src/utils/promises.js +17 -0
  97. package/src/utils/routing.js +201 -0
  98. package/src/utils/unit_test.js +11 -0
  99. package/src/utils/url.js +161 -0
  100. package/svelte-kit.js +1 -1
  101. package/types/ambient.d.ts +451 -0
  102. package/types/index.d.ts +1168 -5
  103. package/types/internal.d.ts +348 -160
  104. package/types/private.d.ts +237 -0
  105. package/types/synthetic/$env+dynamic+private.md +10 -0
  106. package/types/synthetic/$env+dynamic+public.md +8 -0
  107. package/types/synthetic/$env+static+private.md +19 -0
  108. package/types/synthetic/$env+static+public.md +7 -0
  109. package/types/synthetic/$lib.md +5 -0
  110. package/CHANGELOG.md +0 -819
  111. package/assets/components/error.svelte +0 -21
  112. package/assets/runtime/app/env.js +0 -16
  113. package/assets/runtime/app/navigation.js +0 -53
  114. package/assets/runtime/app/paths.js +0 -1
  115. package/assets/runtime/app/stores.js +0 -87
  116. package/assets/runtime/chunks/utils.js +0 -13
  117. package/assets/runtime/env.js +0 -8
  118. package/assets/runtime/internal/singletons.js +0 -20
  119. package/assets/runtime/internal/start.js +0 -1061
  120. package/assets/runtime/paths.js +0 -12
  121. package/dist/chunks/_commonjsHelpers.js +0 -8
  122. package/dist/chunks/cert.js +0 -29079
  123. package/dist/chunks/constants.js +0 -3
  124. package/dist/chunks/index.js +0 -3526
  125. package/dist/chunks/index2.js +0 -583
  126. package/dist/chunks/index3.js +0 -31
  127. package/dist/chunks/index4.js +0 -1005
  128. package/dist/chunks/index5.js +0 -327
  129. package/dist/chunks/index6.js +0 -325
  130. package/dist/chunks/standard.js +0 -99
  131. package/dist/chunks/utils.js +0 -149
  132. package/dist/cli.js +0 -711
  133. package/dist/http.js +0 -66
  134. package/dist/install-fetch.js +0 -1699
  135. package/dist/ssr.js +0 -1529
  136. package/types/ambient-modules.d.ts +0 -115
  137. package/types/config.d.ts +0 -101
  138. package/types/endpoint.d.ts +0 -23
  139. package/types/helper.d.ts +0 -19
  140. package/types/hooks.d.ts +0 -23
  141. package/types/page.d.ts +0 -30
@@ -1,1005 +0,0 @@
1
- import fs__default from 'fs';
2
- import path from 'path';
3
- import { r as rimraf, a as resolve_entry, p as posixify, c as copy_assets, g as get_no_external } from './utils.js';
4
- import { c as create_manifest_data, a as create_app } from './index2.js';
5
- import vite from 'vite';
6
- import svelte from '@sveltejs/vite-plugin-svelte';
7
- import os from 'os';
8
- import { S as SVELTE_KIT } from './constants.js';
9
- import '../cli.js';
10
- import 'sade';
11
- import 'child_process';
12
- import 'net';
13
- import 'url';
14
- import './standard.js';
15
-
16
- const isWin$1 = process.platform === 'win32';
17
- const SEP = isWin$1 ? `\\\\+` : `\\/`;
18
- const SEP_ESC = isWin$1 ? `\\\\` : `/`;
19
- const GLOBSTAR = `((?:[^/]*(?:/|$))*)`;
20
- const WILDCARD = `([^/]*)`;
21
- const GLOBSTAR_SEGMENT = `((?:[^${SEP_ESC}]*(?:${SEP_ESC}|$))*)`;
22
- const WILDCARD_SEGMENT = `([^${SEP_ESC}]*)`;
23
-
24
- /**
25
- * Convert any glob pattern to a JavaScript Regexp object
26
- * @param {String} glob Glob pattern to convert
27
- * @param {Object} opts Configuration object
28
- * @param {Boolean} [opts.extended=false] Support advanced ext globbing
29
- * @param {Boolean} [opts.globstar=false] Support globstar
30
- * @param {Boolean} [opts.strict=true] be laissez faire about mutiple slashes
31
- * @param {Boolean} [opts.filepath=''] Parse as filepath for extra path related features
32
- * @param {String} [opts.flags=''] RegExp globs
33
- * @returns {Object} converted object with string, segments and RegExp object
34
- */
35
- function globrex(glob, {extended = false, globstar = false, strict = false, filepath = false, flags = ''} = {}) {
36
- let regex = '';
37
- let segment = '';
38
- let path = { regex: '', segments: [] };
39
-
40
- // If we are doing extended matching, this boolean is true when we are inside
41
- // a group (eg {*.html,*.js}), and false otherwise.
42
- let inGroup = false;
43
- let inRange = false;
44
-
45
- // extglob stack. Keep track of scope
46
- const ext = [];
47
-
48
- // Helper function to build string and segments
49
- function add(str, {split, last, only}={}) {
50
- if (only !== 'path') regex += str;
51
- if (filepath && only !== 'regex') {
52
- path.regex += (str === '\\/' ? SEP : str);
53
- if (split) {
54
- if (last) segment += str;
55
- if (segment !== '') {
56
- if (!flags.includes('g')) segment = `^${segment}$`; // change it 'includes'
57
- path.segments.push(new RegExp(segment, flags));
58
- }
59
- segment = '';
60
- } else {
61
- segment += str;
62
- }
63
- }
64
- }
65
-
66
- let c, n;
67
- for (let i = 0; i < glob.length; i++) {
68
- c = glob[i];
69
- n = glob[i + 1];
70
-
71
- if (['\\', '$', '^', '.', '='].includes(c)) {
72
- add(`\\${c}`);
73
- continue;
74
- }
75
-
76
- if (c === '/') {
77
- add(`\\${c}`, {split: true});
78
- if (n === '/' && !strict) regex += '?';
79
- continue;
80
- }
81
-
82
- if (c === '(') {
83
- if (ext.length) {
84
- add(c);
85
- continue;
86
- }
87
- add(`\\${c}`);
88
- continue;
89
- }
90
-
91
- if (c === ')') {
92
- if (ext.length) {
93
- add(c);
94
- let type = ext.pop();
95
- if (type === '@') {
96
- add('{1}');
97
- } else if (type === '!') {
98
- add('([^\/]*)');
99
- } else {
100
- add(type);
101
- }
102
- continue;
103
- }
104
- add(`\\${c}`);
105
- continue;
106
- }
107
-
108
- if (c === '|') {
109
- if (ext.length) {
110
- add(c);
111
- continue;
112
- }
113
- add(`\\${c}`);
114
- continue;
115
- }
116
-
117
- if (c === '+') {
118
- if (n === '(' && extended) {
119
- ext.push(c);
120
- continue;
121
- }
122
- add(`\\${c}`);
123
- continue;
124
- }
125
-
126
- if (c === '@' && extended) {
127
- if (n === '(') {
128
- ext.push(c);
129
- continue;
130
- }
131
- }
132
-
133
- if (c === '!') {
134
- if (extended) {
135
- if (inRange) {
136
- add('^');
137
- continue
138
- }
139
- if (n === '(') {
140
- ext.push(c);
141
- add('(?!');
142
- i++;
143
- continue;
144
- }
145
- add(`\\${c}`);
146
- continue;
147
- }
148
- add(`\\${c}`);
149
- continue;
150
- }
151
-
152
- if (c === '?') {
153
- if (extended) {
154
- if (n === '(') {
155
- ext.push(c);
156
- } else {
157
- add('.');
158
- }
159
- continue;
160
- }
161
- add(`\\${c}`);
162
- continue;
163
- }
164
-
165
- if (c === '[') {
166
- if (inRange && n === ':') {
167
- i++; // skip [
168
- let value = '';
169
- while(glob[++i] !== ':') value += glob[i];
170
- if (value === 'alnum') add('(\\w|\\d)');
171
- else if (value === 'space') add('\\s');
172
- else if (value === 'digit') add('\\d');
173
- i++; // skip last ]
174
- continue;
175
- }
176
- if (extended) {
177
- inRange = true;
178
- add(c);
179
- continue;
180
- }
181
- add(`\\${c}`);
182
- continue;
183
- }
184
-
185
- if (c === ']') {
186
- if (extended) {
187
- inRange = false;
188
- add(c);
189
- continue;
190
- }
191
- add(`\\${c}`);
192
- continue;
193
- }
194
-
195
- if (c === '{') {
196
- if (extended) {
197
- inGroup = true;
198
- add('(');
199
- continue;
200
- }
201
- add(`\\${c}`);
202
- continue;
203
- }
204
-
205
- if (c === '}') {
206
- if (extended) {
207
- inGroup = false;
208
- add(')');
209
- continue;
210
- }
211
- add(`\\${c}`);
212
- continue;
213
- }
214
-
215
- if (c === ',') {
216
- if (inGroup) {
217
- add('|');
218
- continue;
219
- }
220
- add(`\\${c}`);
221
- continue;
222
- }
223
-
224
- if (c === '*') {
225
- if (n === '(' && extended) {
226
- ext.push(c);
227
- continue;
228
- }
229
- // Move over all consecutive "*"'s.
230
- // Also store the previous and next characters
231
- let prevChar = glob[i - 1];
232
- let starCount = 1;
233
- while (glob[i + 1] === '*') {
234
- starCount++;
235
- i++;
236
- }
237
- let nextChar = glob[i + 1];
238
- if (!globstar) {
239
- // globstar is disabled, so treat any number of "*" as one
240
- add('.*');
241
- } else {
242
- // globstar is enabled, so determine if this is a globstar segment
243
- let isGlobstar =
244
- starCount > 1 && // multiple "*"'s
245
- (prevChar === '/' || prevChar === undefined) && // from the start of the segment
246
- (nextChar === '/' || nextChar === undefined); // to the end of the segment
247
- if (isGlobstar) {
248
- // it's a globstar, so match zero or more path segments
249
- add(GLOBSTAR, {only:'regex'});
250
- add(GLOBSTAR_SEGMENT, {only:'path', last:true, split:true});
251
- i++; // move over the "/"
252
- } else {
253
- // it's not a globstar, so only match one path segment
254
- add(WILDCARD, {only:'regex'});
255
- add(WILDCARD_SEGMENT, {only:'path'});
256
- }
257
- }
258
- continue;
259
- }
260
-
261
- add(c);
262
- }
263
-
264
-
265
- // When regexp 'g' flag is specified don't
266
- // constrain the regular expression with ^ & $
267
- if (!flags.includes('g')) {
268
- regex = `^${regex}$`;
269
- segment = `^${segment}$`;
270
- if (filepath) path.regex = `^${path.regex}$`;
271
- }
272
-
273
- const result = {regex: new RegExp(regex, flags)};
274
-
275
- // Push the last segment
276
- if (filepath) {
277
- path.segments.push(new RegExp(segment, flags));
278
- path.regex = new RegExp(path.regex, flags);
279
- path.globstar = new RegExp(!flags.includes('g') ? `^${GLOBSTAR_SEGMENT}$` : GLOBSTAR_SEGMENT, flags);
280
- result.path = path;
281
- }
282
-
283
- return result;
284
- }
285
-
286
- var globrex_1 = globrex;
287
-
288
- const isWin = os.platform() === 'win32';
289
-
290
- const CHARS = { '{': '}', '(': ')', '[': ']'};
291
- const STRICT = /\\(.)|(^!|\*|[\].+)]\?|\[[^\\\]]+\]|\{[^\\}]+\}|\(\?[:!=][^\\)]+\)|\([^|]+\|[^\\)]+\)|(\\).|([@?!+*]\(.*\)))/;
292
- const RELAXED = /\\(.)|(^!|[*?{}()[\]]|\(\?)/;
293
-
294
- /**
295
- * Detect if a string cointains glob
296
- * @param {String} str Input string
297
- * @param {Object} [options] Configuration object
298
- * @param {Boolean} [options.strict=true] Use relaxed regex if true
299
- * @returns {Boolean} true if string contains glob
300
- */
301
- function isglob(str, { strict = true } = {}) {
302
- if (str === '') return false;
303
- let match, rgx = strict ? STRICT : RELAXED;
304
-
305
- while ((match = rgx.exec(str))) {
306
- if (match[2]) return true;
307
- let idx = match.index + match[0].length;
308
-
309
- // if an open bracket/brace/paren is escaped,
310
- // set the index to the next closing character
311
- let open = match[1];
312
- let close = open ? CHARS[open] : null;
313
- if (open && close) {
314
- let n = str.indexOf(close, idx);
315
- if (n !== -1) idx = n + 1;
316
- }
317
-
318
- str = str.slice(idx);
319
- }
320
- return false;
321
- }
322
-
323
-
324
- /**
325
- * Find the static part of a glob-path,
326
- * split path and return path part
327
- * @param {String} str Path/glob string
328
- * @returns {String} static path section of glob
329
- */
330
- function parent(str, { strict = false } = {}) {
331
- if (isWin && str.includes('/'))
332
- str = str.split('\\').join('/');
333
-
334
- // special case for strings ending in enclosure containing path separator
335
- if (/[\{\[].*[\/]*.*[\}\]]$/.test(str)) str += '/';
336
-
337
- // preserves full path in case of trailing path separator
338
- str += 'a';
339
-
340
- do {str = path.dirname(str);}
341
- while (isglob(str, {strict}) || /(^|[^\\])([\{\[]|\([^\)]+$)/.test(str));
342
-
343
- // remove escape chars and return result
344
- return str.replace(/\\([\*\?\|\[\]\(\)\{\}])/g, '$1');
345
- }
346
-
347
- /**
348
- * Parse a glob path, and split it by static/glob part
349
- * @param {String} pattern String path
350
- * @param {Object} [opts] Options
351
- * @param {Object} [opts.strict=false] Use strict parsing
352
- * @returns {Object} object with parsed path
353
- */
354
- function globalyzer(pattern, opts = {}) {
355
- let base = parent(pattern, opts);
356
- let isGlob = isglob(pattern, opts);
357
- let glob;
358
-
359
- if (base != '.') {
360
- glob = pattern.substr(base.length);
361
- if (glob.startsWith('/')) glob = glob.substr(1);
362
- } else {
363
- glob = pattern;
364
- }
365
-
366
- if (!isGlob) {
367
- base = path.dirname(pattern);
368
- glob = base !== '.' ? pattern.substr(base.length) : pattern;
369
- }
370
-
371
- if (glob.startsWith('./')) glob = glob.substr(2);
372
- if (glob.startsWith('/')) glob = glob.substr(1);
373
-
374
- return { base, glob, isGlob };
375
- }
376
-
377
-
378
- var src = globalyzer;
379
-
380
- const { join, resolve, relative } = path;
381
- const isHidden = /(^|[\\\/])\.[^\\\/\.]/g;
382
-
383
- let CACHE = {};
384
-
385
- function walk(output, prefix, lexer, opts, dirname='', level=0) {
386
- const rgx = lexer.segments[level];
387
- const dir = resolve(opts.cwd, prefix, dirname);
388
- const files = fs__default.readdirSync(dir);
389
- const { dot, filesOnly } = opts;
390
-
391
- let i=0, len=files.length, file;
392
- let fullpath, relpath, stats, isMatch;
393
-
394
- for (; i < len; i++) {
395
- fullpath = join(dir, file=files[i]);
396
- relpath = dirname ? join(dirname, file) : file;
397
- if (!dot && isHidden.test(relpath)) continue;
398
- isMatch = lexer.regex.test(relpath);
399
-
400
- if ((stats=CACHE[relpath]) === void 0) {
401
- CACHE[relpath] = stats = fs__default.lstatSync(fullpath);
402
- }
403
-
404
- if (!stats.isDirectory()) {
405
- isMatch && output.push(relative(opts.cwd, fullpath));
406
- continue;
407
- }
408
-
409
- if (rgx && !rgx.test(file)) continue;
410
- !filesOnly && isMatch && output.push(join(prefix, relpath));
411
-
412
- walk(output, prefix, lexer, opts, relpath, rgx && rgx.toString() !== lexer.globstar && level + 1);
413
- }
414
- }
415
-
416
- /**
417
- * Find files using bash-like globbing.
418
- * All paths are normalized compared to node-glob.
419
- * @param {String} str Glob string
420
- * @param {String} [options.cwd='.'] Current working directory
421
- * @param {Boolean} [options.dot=false] Include dotfile matches
422
- * @param {Boolean} [options.absolute=false] Return absolute paths
423
- * @param {Boolean} [options.filesOnly=false] Do not include folders if true
424
- * @param {Boolean} [options.flush=false] Reset cache object
425
- * @returns {Array} array containing matching files
426
- */
427
- var sync = function (str, opts={}) {
428
- if (!str) return [];
429
-
430
- let glob = src(str);
431
-
432
- opts.cwd = opts.cwd || '.';
433
-
434
- if (!glob.isGlob) {
435
- try {
436
- let resolved = resolve(opts.cwd, str);
437
- let dirent = fs__default.statSync(resolved);
438
- if (opts.filesOnly && !dirent.isFile()) return [];
439
-
440
- return opts.absolute ? [resolved] : [str];
441
- } catch (err) {
442
- if (err.code != 'ENOENT') throw err;
443
-
444
- return [];
445
- }
446
- }
447
-
448
- if (opts.flush) CACHE = {};
449
-
450
- let matches = [];
451
- const { path } = globrex_1(glob.glob, { filepath:true, globstar:true, extended:true });
452
-
453
- path.globstar = path.globstar.toString();
454
- walk(matches, glob.base, path, opts, '.', 0);
455
-
456
- return opts.absolute ? matches.map(x => resolve(opts.cwd, x)) : matches;
457
- };
458
-
459
- /** @param {any} value */
460
- const s = (value) => JSON.stringify(value);
461
-
462
- /** @typedef {Record<string, {
463
- * file: string;
464
- * css: string[];
465
- * imports: string[];
466
- * }>} ClientManifest */
467
-
468
- /**
469
- * @param {import('types/config').ValidatedConfig} config
470
- * @param {{
471
- * cwd?: string;
472
- * runtime?: string;
473
- * }} [opts]
474
- * @returns {Promise<import('types/internal').BuildData>}
475
- */
476
- async function build(config, { cwd = process.cwd(), runtime = '@sveltejs/kit/ssr' } = {}) {
477
- const build_dir = path.resolve(cwd, `${SVELTE_KIT}/build`);
478
-
479
- rimraf(build_dir);
480
-
481
- const output_dir = path.resolve(cwd, `${SVELTE_KIT}/output`);
482
-
483
- const options = {
484
- cwd,
485
- config,
486
- build_dir,
487
- base:
488
- config.kit.paths.assets === '/.'
489
- ? `/${config.kit.appDir}/`
490
- : `${config.kit.paths.assets}/${config.kit.appDir}/`,
491
- manifest: create_manifest_data({
492
- config,
493
- output: build_dir,
494
- cwd
495
- }),
496
- output_dir,
497
- client_entry_file: `${SVELTE_KIT}/build/runtime/internal/start.js`,
498
- service_worker_entry_file: resolve_entry(config.kit.files.serviceWorker)
499
- };
500
-
501
- const client_manifest = await build_client(options);
502
- await build_server(options, client_manifest, runtime);
503
-
504
- if (options.service_worker_entry_file) {
505
- const { base, assets } = config.kit.paths;
506
-
507
- if (assets !== base && assets !== '/.') {
508
- throw new Error('Cannot use service worker alongside config.kit.paths.assets');
509
- }
510
-
511
- await build_service_worker(options, client_manifest);
512
- }
513
-
514
- const client = sync('**', { cwd: `${output_dir}/client`, filesOnly: true }).map(posixify);
515
- const server = sync('**', { cwd: `${output_dir}/server`, filesOnly: true }).map(posixify);
516
-
517
- return {
518
- client,
519
- server,
520
- static: options.manifest.assets.map((asset) => posixify(asset.file)),
521
- entries: options.manifest.routes
522
- .map((route) => route.type === 'page' && route.path)
523
- .filter(Boolean)
524
- };
525
- }
526
-
527
- /**
528
- * @param {{
529
- * cwd: string;
530
- * base: string;
531
- * config: import('types/config').ValidatedConfig
532
- * manifest: import('types/internal').ManifestData
533
- * build_dir: string;
534
- * output_dir: string;
535
- * client_entry_file: string;
536
- * service_worker_entry_file: string;
537
- * }} options
538
- */
539
- async function build_client({
540
- cwd,
541
- base,
542
- config,
543
- manifest,
544
- build_dir,
545
- output_dir,
546
- client_entry_file,
547
- service_worker_entry_file
548
- }) {
549
- create_app({
550
- manifest_data: manifest,
551
- output: build_dir,
552
- cwd
553
- });
554
-
555
- copy_assets(build_dir);
556
-
557
- process.env.VITE_SVELTEKIT_AMP = config.kit.amp ? 'true' : '';
558
- process.env.VITE_SVELTEKIT_SERVICE_WORKER = service_worker_entry_file ? '/service-worker.js' : '';
559
-
560
- const client_out_dir = `${output_dir}/client/${config.kit.appDir}`;
561
- const client_manifest_file = `${client_out_dir}/manifest.json`;
562
-
563
- /** @type {Record<string, string>} */
564
- const input = {
565
- start: path.resolve(cwd, client_entry_file)
566
- };
567
-
568
- // This step is optional — Vite/Rollup will create the necessary chunks
569
- // for everything regardless — but it means that entry chunks reflect
570
- // their location in the source code, which is helpful for debugging
571
- manifest.components.forEach((file) => {
572
- const resolved = path.resolve(cwd, file);
573
- const relative = path.relative(config.kit.files.routes, resolved);
574
-
575
- const name = relative.startsWith('..')
576
- ? path.basename(file)
577
- : posixify(path.join('pages', relative));
578
- input[name] = resolved;
579
- });
580
-
581
- /** @type {any} */
582
- const user_config = config.kit.vite();
583
-
584
- await vite.build({
585
- ...user_config,
586
- configFile: false,
587
- root: cwd,
588
- base,
589
- build: {
590
- ...user_config.build,
591
- cssCodeSplit: true,
592
- manifest: true,
593
- outDir: client_out_dir,
594
- polyfillDynamicImport: false,
595
- rollupOptions: {
596
- ...(user_config.build && user_config.build.rollupOptions),
597
- input,
598
- output: {
599
- entryFileNames: '[name]-[hash].js',
600
- chunkFileNames: 'chunks/[name]-[hash].js',
601
- assetFileNames: 'assets/[name]-[hash][extname]'
602
- },
603
- preserveEntrySignatures: 'strict'
604
- }
605
- },
606
- resolve: {
607
- ...user_config.resolve,
608
- alias: {
609
- ...(user_config.resolve && user_config.resolve.alias),
610
- $app: path.resolve(`${build_dir}/runtime/app`),
611
- $lib: config.kit.files.lib
612
- }
613
- },
614
- plugins: [
615
- ...(user_config.plugins || []),
616
- svelte({
617
- extensions: config.extensions
618
- })
619
- ]
620
- });
621
-
622
- /** @type {ClientManifest} */
623
- const client_manifest = JSON.parse(fs__default.readFileSync(client_manifest_file, 'utf-8'));
624
- fs__default.renameSync(client_manifest_file, `${output_dir}/manifest.json`); // inspectable but not shipped
625
-
626
- return client_manifest;
627
- }
628
-
629
- /**
630
- * @param {{
631
- * cwd: string;
632
- * base: string;
633
- * config: import('types/config').ValidatedConfig
634
- * manifest: import('types/internal').ManifestData
635
- * build_dir: string;
636
- * output_dir: string;
637
- * client_entry_file: string;
638
- * service_worker_entry_file: string;
639
- * }} options
640
- * @param {ClientManifest} client_manifest
641
- * @param {string} runtime
642
- */
643
- async function build_server(
644
- { cwd, base, config, manifest, build_dir, output_dir, client_entry_file },
645
- client_manifest,
646
- runtime
647
- ) {
648
- let hooks_file = resolve_entry(config.kit.files.hooks);
649
- if (!fs__default.existsSync(hooks_file)) {
650
- hooks_file = path.resolve(cwd, `${SVELTE_KIT}/build/hooks.js`);
651
- fs__default.writeFileSync(hooks_file, '');
652
- }
653
-
654
- const app_file = `${build_dir}/app.js`;
655
-
656
- /** @type {(file: string) => string} */
657
- const app_relative = (file) => {
658
- const relative_file = path.relative(build_dir, path.resolve(cwd, file));
659
- return relative_file[0] === '.' ? relative_file : `./${relative_file}`;
660
- };
661
-
662
- const prefix = `${config.kit.paths.assets}/${config.kit.appDir}/`;
663
-
664
- /**
665
- * @param {string} file
666
- * @param {Set<string>} js_deps
667
- * @param {Set<string>} css_deps
668
- */
669
- function find_deps(file, js_deps, css_deps) {
670
- const chunk = client_manifest[file];
671
-
672
- if (js_deps.has(chunk.file)) return;
673
- js_deps.add(chunk.file);
674
-
675
- if (chunk.css) {
676
- chunk.css.forEach((file) => css_deps.add(file));
677
- }
678
-
679
- if (chunk.imports) {
680
- chunk.imports.forEach((file) => find_deps(file, js_deps, css_deps));
681
- }
682
- }
683
-
684
- /** @type {Record<string, { entry: string, css: string[], js: string[], styles: string[] }>} */
685
- const metadata_lookup = {};
686
-
687
- manifest.components.forEach((file) => {
688
- const js_deps = new Set();
689
- const css_deps = new Set();
690
-
691
- find_deps(file, js_deps, css_deps);
692
-
693
- const js = Array.from(js_deps).map((url) => prefix + url);
694
- const css = Array.from(css_deps).map((url) => prefix + url);
695
-
696
- const styles = config.kit.amp
697
- ? Array.from(css_deps).map((url) => {
698
- const resolved = `${output_dir}/client/${config.kit.appDir}/${url}`;
699
- return fs__default.readFileSync(resolved, 'utf-8');
700
- })
701
- : null;
702
-
703
- metadata_lookup[file] = {
704
- entry: prefix + client_manifest[file].file,
705
- css,
706
- js,
707
- styles
708
- };
709
- });
710
-
711
- /** @type {Set<string>} */
712
- const entry_js = new Set();
713
- /** @type {Set<string>} */
714
- const entry_css = new Set();
715
-
716
- find_deps(client_entry_file, entry_js, entry_css);
717
-
718
- // prettier-ignore
719
- fs__default.writeFileSync(
720
- app_file,
721
- `
722
- import { respond } from '${runtime}';
723
- import root from './generated/root.svelte';
724
- import { set_paths } from './runtime/paths.js';
725
- import { set_prerendering } from './runtime/env.js';
726
- import * as user_hooks from ${s(app_relative(hooks_file))};
727
-
728
- const template = ({ head, body }) => ${s(fs__default.readFileSync(config.kit.files.template, 'utf-8'))
729
- .replace('%svelte.head%', '" + head + "')
730
- .replace('%svelte.body%', '" + body + "')};
731
-
732
- let options = null;
733
-
734
- // allow paths to be overridden in svelte-kit preview
735
- // and in prerendering
736
- export function init(settings) {
737
- set_paths(settings.paths);
738
- set_prerendering(settings.prerendering || false);
739
-
740
- options = {
741
- amp: ${config.kit.amp},
742
- dev: false,
743
- entry: {
744
- file: ${s(prefix + client_manifest[client_entry_file].file)},
745
- css: ${s(Array.from(entry_css).map(dep => prefix + dep))},
746
- js: ${s(Array.from(entry_js).map(dep => prefix + dep))}
747
- },
748
- fetched: undefined,
749
- floc: ${config.kit.floc},
750
- get_component_path: id => ${s(`${config.kit.paths.assets}/${config.kit.appDir}/`)} + entry_lookup[id],
751
- get_stack: error => String(error), // for security
752
- handle_error: error => {
753
- console.error(error.stack);
754
- error.stack = options.get_stack(error);
755
- },
756
- hooks: get_hooks(user_hooks),
757
- hydrate: ${s(config.kit.hydrate)},
758
- initiator: undefined,
759
- load_component,
760
- manifest,
761
- paths: settings.paths,
762
- read: settings.read,
763
- root,
764
- router: ${s(config.kit.router)},
765
- ssr: ${s(config.kit.ssr)},
766
- target: ${s(config.kit.target)},
767
- template
768
- };
769
- }
770
-
771
- const d = decodeURIComponent;
772
- const empty = () => ({});
773
-
774
- const manifest = {
775
- assets: ${s(manifest.assets)},
776
- layout: ${s(manifest.layout)},
777
- error: ${s(manifest.error)},
778
- routes: [
779
- ${manifest.routes
780
- .map((route) => {
781
- if (route.type === 'page') {
782
- const params = get_params(route.params);
783
-
784
- return `{
785
- type: 'page',
786
- pattern: ${route.pattern},
787
- params: ${params},
788
- a: [${route.a.map(file => file && s(file)).join(', ')}],
789
- b: [${route.b.map(file => file && s(file)).join(', ')}]
790
- }`;
791
- } else {
792
- const params = get_params(route.params);
793
- const load = `() => import(${s(app_relative(route.file))})`;
794
-
795
- return `{
796
- type: 'endpoint',
797
- pattern: ${route.pattern},
798
- params: ${params},
799
- load: ${load}
800
- }`;
801
- }
802
- })
803
- .join(',\n\t\t\t\t\t')}
804
- ]
805
- };
806
-
807
- // this looks redundant, but the indirection allows us to access
808
- // named imports without triggering Rollup's missing import detection
809
- const get_hooks = hooks => ({
810
- getContext: hooks.getContext || (() => ({})),
811
- getSession: hooks.getSession || (() => ({})),
812
- handle: hooks.handle || (({ request, render }) => render(request))
813
- });
814
-
815
- const module_lookup = {
816
- ${manifest.components.map(file => `${s(file)}: () => import(${s(app_relative(file))})`)}
817
- };
818
-
819
- const metadata_lookup = ${s(metadata_lookup)};
820
-
821
- async function load_component(file) {
822
- return {
823
- module: await module_lookup[file](),
824
- ...metadata_lookup[file]
825
- };
826
- }
827
-
828
- init({ paths: ${s(config.kit.paths)} });
829
-
830
- export function render(request, {
831
- prerender
832
- } = {}) {
833
- const host = ${config.kit.host ? s(config.kit.host) : `request.headers[${s(config.kit.hostHeader || 'host')}]`};
834
- return respond({ ...request, host }, options, { prerender });
835
- }
836
- `
837
- .replace(/^\t{3}/gm, '')
838
- .trim()
839
- );
840
-
841
- /** @type {any} */
842
- const user_config = config.kit.vite();
843
-
844
- await vite.build({
845
- ...user_config,
846
- configFile: false,
847
- root: cwd,
848
- base,
849
- build: {
850
- target: 'es2018',
851
- ...user_config.build,
852
- ssr: true,
853
- outDir: `${output_dir}/server`,
854
- polyfillDynamicImport: false,
855
- rollupOptions: {
856
- ...(user_config.build && user_config.build.rollupOptions),
857
- input: {
858
- app: app_file
859
- },
860
- output: {
861
- format: 'esm',
862
- entryFileNames: '[name].js',
863
- chunkFileNames: 'chunks/[name]-[hash].js',
864
- assetFileNames: 'assets/[name]-[hash][extname]',
865
- inlineDynamicImports: true
866
- },
867
- preserveEntrySignatures: 'strict'
868
- }
869
- },
870
- resolve: {
871
- ...user_config.resolve,
872
- alias: {
873
- ...(user_config.resolve && user_config.resolve.alias),
874
- $app: path.resolve(`${build_dir}/runtime/app`),
875
- $lib: config.kit.files.lib
876
- }
877
- },
878
- plugins: [
879
- ...(user_config.plugins || []),
880
- svelte({
881
- extensions: config.extensions
882
- })
883
- ],
884
- // this API is marked as @alpha https://github.com/vitejs/vite/blob/27785f7fcc5b45987b5f0bf308137ddbdd9f79ea/packages/vite/src/node/config.ts#L129
885
- // it's not exposed in the typescript definitions as a result
886
- // so we need to ignore the fact that it's missing
887
- // @ts-ignore
888
- ssr: {
889
- ...user_config.ssr,
890
- // note to self: this _might_ need to be ['svelte', '@sveltejs/kit', ...get_no_external()]
891
- // but I'm honestly not sure. roll with this for now and see if it's ok
892
- noExternal: get_no_external(cwd, user_config.ssr && user_config.ssr.noExternal)
893
- },
894
- optimizeDeps: {
895
- entries: []
896
- }
897
- });
898
- }
899
-
900
- /**
901
- * @param {{
902
- * cwd: string;
903
- * base: string;
904
- * config: import('types/config').ValidatedConfig
905
- * manifest: import('types/internal').ManifestData
906
- * build_dir: string;
907
- * output_dir: string;
908
- * client_entry_file: string;
909
- * service_worker_entry_file: string;
910
- * }} options
911
- * @param {ClientManifest} client_manifest
912
- */
913
- async function build_service_worker(
914
- { cwd, base, config, manifest, build_dir, output_dir, service_worker_entry_file },
915
- client_manifest
916
- ) {
917
- // TODO add any assets referenced in template .html file, e.g. favicon?
918
- const app_files = new Set();
919
- for (const key in client_manifest) {
920
- const { file, css } = client_manifest[key];
921
- app_files.add(file);
922
- if (css) {
923
- css.forEach((file) => {
924
- app_files.add(file);
925
- });
926
- }
927
- }
928
-
929
- fs__default.writeFileSync(
930
- `${build_dir}/runtime/service-worker.js`,
931
- `
932
- export const timestamp = ${Date.now()};
933
-
934
- export const build = [
935
- ${Array.from(app_files)
936
- .map((file) => `${s(`${config.kit.paths.base}/${config.kit.appDir}/${file}`)}`)
937
- .join(',\n\t\t\t\t')}
938
- ];
939
-
940
- export const files = [
941
- ${manifest.assets
942
- .map((asset) => `${s(`${config.kit.paths.base}/${asset.file}`)}`)
943
- .join(',\n\t\t\t\t')}
944
- ];
945
- `
946
- .replace(/^\t{3}/gm, '')
947
- .trim()
948
- );
949
-
950
- /** @type {any} */
951
- const user_config = config.kit.vite();
952
-
953
- await vite.build({
954
- ...user_config,
955
- configFile: false,
956
- root: cwd,
957
- base,
958
- build: {
959
- ...user_config.build,
960
- lib: {
961
- entry: service_worker_entry_file,
962
- name: 'app',
963
- formats: ['es']
964
- },
965
- rollupOptions: {
966
- ...(user_config.build && user_config.build.rollupOptions),
967
- output: {
968
- entryFileNames: 'service-worker.js'
969
- }
970
- },
971
- outDir: `${output_dir}/client`,
972
- emptyOutDir: false
973
- },
974
- resolve: {
975
- ...user_config.resolve,
976
- alias: {
977
- ...(user_config.resolve && user_config.resolve.alias),
978
- '$service-worker': path.resolve(`${build_dir}/runtime/service-worker`)
979
- }
980
- },
981
- optimizeDeps: {
982
- entries: []
983
- }
984
- });
985
- }
986
-
987
- /** @param {string[]} array */
988
- function get_params(array) {
989
- // given an array of params like `['x', 'y', 'z']` for
990
- // src/routes/[x]/[y]/[z]/svelte, create a function
991
- // that turns a RexExpMatchArray into ({ x, y, z })
992
- return array.length
993
- ? '(m) => ({ ' +
994
- array
995
- .map((param, i) => {
996
- return param.startsWith('...')
997
- ? `${param.slice(3)}: d(m[${i + 1}] || '')`
998
- : `${param}: d(m[${i + 1}])`;
999
- })
1000
- .join(', ') +
1001
- '})'
1002
- : 'empty';
1003
- }
1004
-
1005
- export { build };