@sveltejs/kit 1.0.0-next.20 → 1.0.0-next.200

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 (77) hide show
  1. package/README.md +12 -9
  2. package/assets/components/error.svelte +19 -3
  3. package/assets/runtime/app/env.js +20 -0
  4. package/assets/runtime/app/navigation.js +45 -13
  5. package/assets/runtime/app/paths.js +1 -2
  6. package/assets/runtime/app/stores.js +15 -9
  7. package/assets/runtime/chunks/utils.js +13 -0
  8. package/assets/runtime/env.js +8 -0
  9. package/assets/runtime/internal/singletons.js +5 -11
  10. package/assets/runtime/internal/start.js +979 -351
  11. package/assets/runtime/paths.js +13 -0
  12. package/dist/chunks/cert.js +29254 -0
  13. package/dist/chunks/constants.js +8 -0
  14. package/dist/chunks/error.js +21 -0
  15. package/dist/chunks/index.js +4745 -0
  16. package/dist/chunks/index2.js +700 -0
  17. package/dist/chunks/index3.js +1060 -0
  18. package/dist/chunks/index4.js +398 -0
  19. package/dist/chunks/index5.js +413 -0
  20. package/dist/chunks/index6.js +15574 -0
  21. package/dist/{standard.js → chunks/standard.js} +16 -18
  22. package/dist/chunks/url.js +59 -0
  23. package/dist/cli.js +947 -67
  24. package/dist/hooks.js +28 -0
  25. package/dist/install-fetch.js +6070 -0
  26. package/dist/node.js +51 -0
  27. package/dist/ssr.js +1771 -0
  28. package/package.json +89 -54
  29. package/svelte-kit.js +2 -0
  30. package/types/ambient-modules.d.ts +173 -0
  31. package/types/app.d.ts +21 -0
  32. package/types/config.d.ts +96 -0
  33. package/types/endpoint.d.ts +18 -0
  34. package/types/helper.d.ts +41 -0
  35. package/types/hooks.d.ts +36 -0
  36. package/types/index.d.ts +17 -0
  37. package/types/internal.d.ts +219 -0
  38. package/types/page.d.ts +77 -0
  39. package/CHANGELOG.md +0 -276
  40. package/assets/runtime/app/navigation.js.map +0 -1
  41. package/assets/runtime/app/paths.js.map +0 -1
  42. package/assets/runtime/app/stores.js.map +0 -1
  43. package/assets/runtime/internal/singletons.js.map +0 -1
  44. package/assets/runtime/internal/start.js.map +0 -1
  45. package/assets/runtime/utils-85ebcc60.js +0 -18
  46. package/assets/runtime/utils-85ebcc60.js.map +0 -1
  47. package/dist/api.js +0 -44
  48. package/dist/api.js.map +0 -1
  49. package/dist/build.js +0 -246
  50. package/dist/build.js.map +0 -1
  51. package/dist/cli.js.map +0 -1
  52. package/dist/colors.js +0 -37
  53. package/dist/colors.js.map +0 -1
  54. package/dist/create_app.js +0 -578
  55. package/dist/create_app.js.map +0 -1
  56. package/dist/index.js +0 -12042
  57. package/dist/index.js.map +0 -1
  58. package/dist/index2.js +0 -544
  59. package/dist/index2.js.map +0 -1
  60. package/dist/index3.js +0 -71
  61. package/dist/index3.js.map +0 -1
  62. package/dist/index4.js +0 -466
  63. package/dist/index4.js.map +0 -1
  64. package/dist/index5.js +0 -725
  65. package/dist/index5.js.map +0 -1
  66. package/dist/index6.js +0 -713
  67. package/dist/index6.js.map +0 -1
  68. package/dist/logging.js +0 -43
  69. package/dist/logging.js.map +0 -1
  70. package/dist/package.js +0 -432
  71. package/dist/package.js.map +0 -1
  72. package/dist/renderer.js +0 -2391
  73. package/dist/renderer.js.map +0 -1
  74. package/dist/standard.js.map +0 -1
  75. package/dist/utils.js +0 -54
  76. package/dist/utils.js.map +0 -1
  77. package/svelte-kit +0 -3
@@ -0,0 +1,413 @@
1
+ import * as fs from 'fs';
2
+ import fs__default, { readdirSync, statSync } from 'fs';
3
+ import http from 'http';
4
+ import https from 'https';
5
+ import { resolve, join, normalize } from 'path';
6
+ import * as require$$7 from 'querystring';
7
+ import { s as standard, M as Mime_1 } from './standard.js';
8
+ import { pathToFileURL } from 'url';
9
+ import { getRawBody } from '../node.js';
10
+ import { __fetch_polyfill } from '../install-fetch.js';
11
+ import { S as SVELTE_KIT, a as SVELTE_KIT_ASSETS } from './constants.js';
12
+ import 'zlib';
13
+ import 'stream';
14
+ import 'util';
15
+ import 'crypto';
16
+
17
+ /**
18
+ * @typedef ParsedURL
19
+ * @type {import('.').ParsedURL}
20
+ */
21
+
22
+ /**
23
+ * @typedef Request
24
+ * @property {string} url
25
+ * @property {ParsedURL} _parsedUrl
26
+ */
27
+
28
+ /**
29
+ * @param {Request} req
30
+ * @returns {ParsedURL|void}
31
+ */
32
+ function parse(req) {
33
+ let raw = req.url;
34
+ if (raw == null) return;
35
+
36
+ let prev = req._parsedUrl;
37
+ if (prev && prev.raw === raw) return prev;
38
+
39
+ let pathname=raw, search='', query;
40
+
41
+ if (raw.length > 1) {
42
+ let idx = raw.indexOf('?', 1);
43
+
44
+ if (idx !== -1) {
45
+ search = raw.substring(idx);
46
+ pathname = raw.substring(0, idx);
47
+ if (search.length > 1) {
48
+ query = require$$7.parse(search.substring(1));
49
+ }
50
+ }
51
+ }
52
+
53
+ return req._parsedUrl = { pathname, search, query, raw };
54
+ }
55
+
56
+ function list(dir, callback, pre='') {
57
+ dir = resolve('.', dir);
58
+ let arr = readdirSync(dir);
59
+ let i=0, abs, stats;
60
+ for (; i < arr.length; i++) {
61
+ abs = join(dir, arr[i]);
62
+ stats = statSync(abs);
63
+ stats.isDirectory()
64
+ ? list(abs, callback, join(pre, arr[i]))
65
+ : callback(join(pre, arr[i]), abs, stats);
66
+ }
67
+ }
68
+
69
+ let Mime = Mime_1;
70
+ var lite = new Mime(standard);
71
+
72
+ const noop = () => {};
73
+
74
+ function isMatch(uri, arr) {
75
+ for (let i=0; i < arr.length; i++) {
76
+ if (arr[i].test(uri)) return true;
77
+ }
78
+ }
79
+
80
+ function toAssume(uri, extns) {
81
+ let i=0, x, len=uri.length - 1;
82
+ if (uri.charCodeAt(len) === 47) {
83
+ uri = uri.substring(0, len);
84
+ }
85
+
86
+ let arr=[], tmp=`${uri}/index`;
87
+ for (; i < extns.length; i++) {
88
+ x = extns[i] ? `.${extns[i]}` : '';
89
+ if (uri) arr.push(uri + x);
90
+ arr.push(tmp + x);
91
+ }
92
+
93
+ return arr;
94
+ }
95
+
96
+ function viaCache(cache, uri, extns) {
97
+ let i=0, data, arr=toAssume(uri, extns);
98
+ for (; i < arr.length; i++) {
99
+ if (data = cache[arr[i]]) return data;
100
+ }
101
+ }
102
+
103
+ function viaLocal(dir, isEtag, uri, extns) {
104
+ let i=0, arr=toAssume(uri, extns);
105
+ let abs, stats, name, headers;
106
+ for (; i < arr.length; i++) {
107
+ abs = normalize(join(dir, name=arr[i]));
108
+ if (abs.startsWith(dir) && fs.existsSync(abs)) {
109
+ stats = fs.statSync(abs);
110
+ if (stats.isDirectory()) continue;
111
+ headers = toHeaders(name, stats, isEtag);
112
+ headers['Cache-Control'] = isEtag ? 'no-cache' : 'no-store';
113
+ return { abs, stats, headers };
114
+ }
115
+ }
116
+ }
117
+
118
+ function is404(req, res) {
119
+ return (res.statusCode=404,res.end());
120
+ }
121
+
122
+ function send(req, res, file, stats, headers) {
123
+ let code=200, tmp, opts={};
124
+ headers = { ...headers };
125
+
126
+ for (let key in headers) {
127
+ tmp = res.getHeader(key);
128
+ if (tmp) headers[key] = tmp;
129
+ }
130
+
131
+ if (tmp = res.getHeader('content-type')) {
132
+ headers['Content-Type'] = tmp;
133
+ }
134
+
135
+ if (req.headers.range) {
136
+ code = 206;
137
+ let [x, y] = req.headers.range.replace('bytes=', '').split('-');
138
+ let end = opts.end = parseInt(y, 10) || stats.size - 1;
139
+ let start = opts.start = parseInt(x, 10) || 0;
140
+
141
+ if (start >= stats.size || end >= stats.size) {
142
+ res.setHeader('Content-Range', `bytes */${stats.size}`);
143
+ res.statusCode = 416;
144
+ return res.end();
145
+ }
146
+
147
+ headers['Content-Range'] = `bytes ${start}-${end}/${stats.size}`;
148
+ headers['Content-Length'] = (end - start + 1);
149
+ headers['Accept-Ranges'] = 'bytes';
150
+ }
151
+
152
+ res.writeHead(code, headers);
153
+ fs.createReadStream(file, opts).pipe(res);
154
+ }
155
+
156
+ const ENCODING = {
157
+ '.br': 'br',
158
+ '.gz': 'gzip',
159
+ };
160
+
161
+ function toHeaders(name, stats, isEtag) {
162
+ let enc = ENCODING[name.slice(-3)];
163
+
164
+ let ctype = lite.getType(name.slice(0, enc && -3)) || '';
165
+ if (ctype === 'text/html') ctype += ';charset=utf-8';
166
+
167
+ let headers = {
168
+ 'Content-Length': stats.size,
169
+ 'Content-Type': ctype,
170
+ 'Last-Modified': stats.mtime.toUTCString(),
171
+ };
172
+
173
+ if (enc) headers['Content-Encoding'] = enc;
174
+ if (isEtag) headers['ETag'] = `W/"${stats.size}-${stats.mtime.getTime()}"`;
175
+
176
+ return headers;
177
+ }
178
+
179
+ function sirv (dir, opts={}) {
180
+ dir = resolve(dir || '.');
181
+
182
+ let isNotFound = opts.onNoMatch || is404;
183
+ let setHeaders = opts.setHeaders || noop;
184
+
185
+ let extensions = opts.extensions || ['html', 'htm'];
186
+ let gzips = opts.gzip && extensions.map(x => `${x}.gz`).concat('gz');
187
+ let brots = opts.brotli && extensions.map(x => `${x}.br`).concat('br');
188
+
189
+ const FILES = {};
190
+
191
+ let fallback = '/';
192
+ let isEtag = !!opts.etag;
193
+ let isSPA = !!opts.single;
194
+ if (typeof opts.single === 'string') {
195
+ let idx = opts.single.lastIndexOf('.');
196
+ fallback += !!~idx ? opts.single.substring(0, idx) : opts.single;
197
+ }
198
+
199
+ let ignores = [];
200
+ if (opts.ignores !== false) {
201
+ ignores.push(/[/]([A-Za-z\s\d~$._-]+\.\w+){1,}$/); // any extn
202
+ if (opts.dotfiles) ignores.push(/\/\.\w/);
203
+ else ignores.push(/\/\.well-known/);
204
+ [].concat(opts.ignores || []).forEach(x => {
205
+ ignores.push(new RegExp(x, 'i'));
206
+ });
207
+ }
208
+
209
+ let cc = opts.maxAge != null && `public,max-age=${opts.maxAge}`;
210
+ if (cc && opts.immutable) cc += ',immutable';
211
+ else if (cc && opts.maxAge === 0) cc += ',must-revalidate';
212
+
213
+ if (!opts.dev) {
214
+ list(dir, (name, abs, stats) => {
215
+ if (/\.well-known[\\+\/]/.test(name)) ; // keep
216
+ else if (!opts.dotfiles && /(^\.|[\\+|\/+]\.)/.test(name)) return;
217
+
218
+ let headers = toHeaders(name, stats, isEtag);
219
+ if (cc) headers['Cache-Control'] = cc;
220
+
221
+ FILES['/' + name.normalize().replace(/\\+/g, '/')] = { abs, stats, headers };
222
+ });
223
+ }
224
+
225
+ let lookup = opts.dev ? viaLocal.bind(0, dir, isEtag) : viaCache.bind(0, FILES);
226
+
227
+ return function (req, res, next) {
228
+ let extns = [''];
229
+ let pathname = parse(req).pathname;
230
+ let val = req.headers['accept-encoding'] || '';
231
+ if (gzips && val.includes('gzip')) extns.unshift(...gzips);
232
+ if (brots && /(br|brotli)/i.test(val)) extns.unshift(...brots);
233
+ extns.push(...extensions); // [...br, ...gz, orig, ...exts]
234
+
235
+ if (pathname.indexOf('%') !== -1) {
236
+ try { pathname = decodeURIComponent(pathname); }
237
+ catch (err) { /* malform uri */ }
238
+ }
239
+
240
+ let data = lookup(pathname, extns) || isSPA && !isMatch(pathname, ignores) && lookup(fallback, extns);
241
+ if (!data) return next ? next() : isNotFound(req, res);
242
+
243
+ if (isEtag && req.headers['if-none-match'] === data.headers['ETag']) {
244
+ res.writeHead(304);
245
+ return res.end();
246
+ }
247
+
248
+ if (gzips || brots) {
249
+ res.setHeader('Vary', 'Accept-Encoding');
250
+ }
251
+
252
+ setHeaders(res, pathname, data.stats);
253
+ send(req, res, data.abs, data.stats, data.headers);
254
+ };
255
+ }
256
+
257
+ /** @param {string} dir */
258
+ const mutable = (dir) =>
259
+ sirv(dir, {
260
+ etag: true,
261
+ maxAge: 0
262
+ });
263
+
264
+ /**
265
+ * @param {{
266
+ * port: number;
267
+ * host?: string;
268
+ * config: import('types/config').ValidatedConfig;
269
+ * https?: boolean;
270
+ * cwd?: string;
271
+ * }} opts
272
+ */
273
+ async function preview({
274
+ port,
275
+ host,
276
+ config,
277
+ https: use_https = false,
278
+ cwd = process.cwd()
279
+ }) {
280
+ __fetch_polyfill();
281
+
282
+ const app_file = resolve(cwd, `${SVELTE_KIT}/output/server/app.js`);
283
+
284
+ /** @type {import('types/internal').App} */
285
+ const app = await import(pathToFileURL(app_file).href);
286
+
287
+ /** @type {import('sirv').RequestHandler} */
288
+ const static_handler = fs__default.existsSync(config.kit.files.assets)
289
+ ? mutable(config.kit.files.assets)
290
+ : (_req, _res, next) => {
291
+ if (!next) throw new Error('No next() handler is available');
292
+ return next();
293
+ };
294
+
295
+ const assets_handler = sirv(resolve(cwd, `${SVELTE_KIT}/output/client`), {
296
+ maxAge: 31536000,
297
+ immutable: true
298
+ });
299
+
300
+ const has_asset_path = !!config.kit.paths.assets;
301
+
302
+ app.init({
303
+ paths: {
304
+ base: config.kit.paths.base,
305
+ assets: has_asset_path ? SVELTE_KIT_ASSETS : config.kit.paths.base
306
+ },
307
+ prerendering: false,
308
+ read: (file) => fs__default.readFileSync(join(config.kit.files.assets, file))
309
+ });
310
+
311
+ /** @type {import('vite').UserConfig} */
312
+ const vite_config = (config.kit.vite && config.kit.vite()) || {};
313
+
314
+ const server = await get_server(use_https, vite_config, (req, res) => {
315
+ if (req.url == null) {
316
+ throw new Error('Invalid request url');
317
+ }
318
+
319
+ const initial_url = req.url;
320
+
321
+ const render_handler = async () => {
322
+ if (!req.method) throw new Error('Incomplete request');
323
+
324
+ let body;
325
+
326
+ try {
327
+ body = await getRawBody(req);
328
+ } catch (/** @type {any} */ err) {
329
+ res.statusCode = err.status || 400;
330
+ return res.end(err.reason || 'Invalid request body');
331
+ }
332
+
333
+ const parsed = new URL(initial_url, 'http://localhost/');
334
+
335
+ const rendered =
336
+ parsed.pathname.startsWith(config.kit.paths.base) &&
337
+ (await app.render({
338
+ host: /** @type {string} */ (
339
+ config.kit.host || req.headers[config.kit.hostHeader || 'host']
340
+ ),
341
+ method: req.method,
342
+ headers: /** @type {import('types/helper').RequestHeaders} */ (req.headers),
343
+ path: parsed.pathname.replace(config.kit.paths.base, ''),
344
+ query: parsed.searchParams,
345
+ rawBody: body
346
+ }));
347
+
348
+ if (rendered) {
349
+ res.writeHead(rendered.status, rendered.headers);
350
+ if (rendered.body) res.write(rendered.body);
351
+ res.end();
352
+ } else {
353
+ res.statusCode = 404;
354
+ res.end('Not found');
355
+ }
356
+ };
357
+
358
+ if (has_asset_path) {
359
+ if (initial_url.startsWith(SVELTE_KIT_ASSETS)) {
360
+ // custom assets path
361
+ req.url = initial_url.slice(SVELTE_KIT_ASSETS.length);
362
+ assets_handler(req, res, () => {
363
+ static_handler(req, res, render_handler);
364
+ });
365
+ } else {
366
+ render_handler();
367
+ }
368
+ } else {
369
+ if (initial_url.startsWith(config.kit.paths.base)) {
370
+ req.url = initial_url.slice(config.kit.paths.base.length);
371
+ }
372
+ assets_handler(req, res, () => {
373
+ static_handler(req, res, render_handler);
374
+ });
375
+ }
376
+ });
377
+
378
+ await server.listen(port, host || '0.0.0.0');
379
+
380
+ return Promise.resolve(server);
381
+ }
382
+
383
+ /**
384
+ * @param {boolean} use_https
385
+ * @param {import('vite').UserConfig} user_config
386
+ * @param {(req: http.IncomingMessage, res: http.ServerResponse) => void} handler
387
+ * @returns {Promise<import('net').Server>}
388
+ */
389
+ async function get_server(use_https, user_config, handler) {
390
+ /** @type {https.ServerOptions} */
391
+ const https_options = {};
392
+
393
+ if (use_https) {
394
+ const secure_opts = user_config.server
395
+ ? /** @type {import('tls').SecureContextOptions} */ (user_config.server.https)
396
+ : {};
397
+
398
+ if (secure_opts.key && secure_opts.cert) {
399
+ https_options.key = secure_opts.key.toString();
400
+ https_options.cert = secure_opts.cert.toString();
401
+ } else {
402
+ https_options.key = https_options.cert = (await import('./cert.js')).createCertificate();
403
+ }
404
+ }
405
+
406
+ return Promise.resolve(
407
+ use_https
408
+ ? https.createServer(/** @type {https.ServerOptions} */ (https_options), handler)
409
+ : http.createServer(handler)
410
+ );
411
+ }
412
+
413
+ export { preview };