@sveltejs/kit 1.0.0-next.99 → 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 -159
  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 -825
  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 -3532
  125. package/dist/chunks/index2.js +0 -583
  126. package/dist/chunks/index3.js +0 -31
  127. package/dist/chunks/index4.js +0 -1004
  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 -1523
  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 -21
  141. package/types/page.d.ts +0 -30
@@ -1,327 +0,0 @@
1
- import { $ } from '../cli.js';
2
- import { m as mkdirp, r as rimraf, b as copy, l as logger } from './utils.js';
3
- import { S as SVELTE_KIT } from './constants.js';
4
- import { readFileSync, writeFileSync } from 'fs';
5
- import { resolve, join, dirname } from 'path';
6
- import { pathToFileURL, resolve as resolve$1, parse } from 'url';
7
- import '../install-fetch.js';
8
- import 'sade';
9
- import 'child_process';
10
- import 'net';
11
- import 'os';
12
- import 'http';
13
- import 'https';
14
- import 'zlib';
15
- import 'stream';
16
- import 'util';
17
- import 'crypto';
18
-
19
- /** @param {string} html */
20
- function clean_html(html) {
21
- return html
22
- .replace(/<!\[CDATA\[[\s\S]*?\]\]>/gm, '')
23
- .replace(/(<script[\s\S]*?>)[\s\S]*?<\/script>/gm, '$1</' + 'script>')
24
- .replace(/(<style[\s\S]*?>)[\s\S]*?<\/style>/gm, '$1</' + 'style>')
25
- .replace(/<!--[\s\S]*?-->/gm, '');
26
- }
27
-
28
- /** @param {string} attrs */
29
- function get_href(attrs) {
30
- const match = /href\s*=\s*(?:"(.*?)"|'(.*?)'|([^\s>]*))/.exec(attrs);
31
- return match && (match[1] || match[2] || match[3]);
32
- }
33
-
34
- /** @param {string} attrs */
35
- function get_src(attrs) {
36
- const match = /src\s*=\s*(?:"(.*?)"|'(.*?)'|([^\s>]*))/.exec(attrs);
37
- return match && (match[1] || match[2] || match[3]);
38
- }
39
-
40
- /** @param {string} attrs */
41
- function get_srcset_urls(attrs) {
42
- const results = [];
43
- // Note that the srcset allows any ASCII whitespace, including newlines.
44
- const match = /srcset\s*=\s*(?:"(.*?)"|'(.*?)'|([^\s>]*))/s.exec(attrs);
45
- if (match) {
46
- const attr_content = match[1] || match[2] || match[3];
47
- // Parse the content of the srcset attribute.
48
- // The regexp is modelled after the srcset specs (https://html.spec.whatwg.org/multipage/images.html#srcset-attribute)
49
- // and should cover most reasonable cases.
50
- const regex = /\s*([^\s,]\S+[^\s,])\s*((?:\d+w)|(?:-?\d+(?:\.\d+)?(?:[eE]-?\d+)?x))?/gm;
51
- let sub_matches;
52
- while ((sub_matches = regex.exec(attr_content))) {
53
- results.push(sub_matches[1]);
54
- }
55
- }
56
- return results;
57
- }
58
-
59
- const OK = 2;
60
- const REDIRECT = 3;
61
-
62
- /** @param {{
63
- * cwd: string;
64
- * out: string;
65
- * log: import('types/internal').Logger;
66
- * config: import('types/config').ValidatedConfig;
67
- * build_data: import('types/internal').BuildData;
68
- * fallback: string;
69
- * all: boolean; // disregard `export const prerender = true`
70
- * }} opts */
71
- async function prerender({ cwd, out, log, config, build_data, fallback, all }) {
72
- const dir = resolve(cwd, `${SVELTE_KIT}/output`);
73
-
74
- const seen = new Set();
75
-
76
- const server_root = resolve(dir);
77
-
78
- /** @type {import('types/internal').App} */
79
- const app = await import(pathToFileURL(`${server_root}/server/app.js`).href);
80
-
81
- app.init({
82
- paths: config.kit.paths,
83
- prerendering: true,
84
- read: (file) => readFileSync(join(config.kit.files.assets, file))
85
- });
86
-
87
- /** @type {(status: number, path: string, parent: string, verb: string) => void} */
88
- const error = config.kit.prerender.force
89
- ? (status, path, parent, verb) => {
90
- log.error(`${status} ${path}${parent ? ` (${verb} from ${parent})` : ''}`);
91
- }
92
- : (status, path, parent, verb) => {
93
- throw new Error(`${status} ${path}${parent ? ` (${verb} from ${parent})` : ''}`);
94
- };
95
-
96
- const files = new Set([...build_data.static, ...build_data.client]);
97
-
98
- build_data.static.forEach((file) => {
99
- if (file.endsWith('/index.html')) {
100
- files.add(file.slice(0, -11));
101
- }
102
- });
103
-
104
- /**
105
- * @param {string} path
106
- * @param {string} parent
107
- */
108
- async function visit(path, parent) {
109
- if (seen.has(path)) return;
110
- seen.add(path);
111
-
112
- /** @type {Map<string, import('types/endpoint').ServerResponse>} */
113
- const dependencies = new Map();
114
-
115
- const rendered = await app.render(
116
- {
117
- host: config.kit.host,
118
- method: 'GET',
119
- headers: {},
120
- path,
121
- rawBody: null,
122
- query: new URLSearchParams()
123
- },
124
- {
125
- prerender: {
126
- fallback: null,
127
- all,
128
- dependencies
129
- }
130
- }
131
- );
132
-
133
- if (rendered) {
134
- const response_type = Math.floor(rendered.status / 100);
135
- const headers = rendered.headers;
136
- const type = headers && headers['content-type'];
137
- const is_html = response_type === REDIRECT || type === 'text/html';
138
-
139
- const parts = path.split('/');
140
- if (is_html && parts[parts.length - 1] !== 'index.html') {
141
- parts.push('index.html');
142
- }
143
-
144
- const file = `${out}${parts.join('/')}`;
145
- mkdirp(dirname(file));
146
-
147
- if (response_type === REDIRECT) {
148
- const { location } = headers;
149
-
150
- log.warn(`${rendered.status} ${path} -> ${location}`);
151
- writeFileSync(file, `<meta http-equiv="refresh" content="0;url=${encodeURI(location)}">`);
152
-
153
- return;
154
- }
155
-
156
- if (rendered.status === 200) {
157
- log.info(`${rendered.status} ${path}`);
158
- writeFileSync(file, rendered.body);
159
- } else if (response_type !== OK) {
160
- error(rendered.status, path, parent, 'linked');
161
- }
162
-
163
- dependencies.forEach((result, dependency_path) => {
164
- const response_type = Math.floor(result.status / 100);
165
-
166
- const is_html = result.headers['content-type'] === 'text/html';
167
-
168
- const parts = dependency_path.split('/');
169
- if (is_html && parts[parts.length - 1] !== 'index.html') {
170
- parts.push('index.html');
171
- }
172
-
173
- const file = `${out}${parts.join('/')}`;
174
- mkdirp(dirname(file));
175
-
176
- writeFileSync(file, result.body);
177
-
178
- if (response_type === OK) {
179
- log.info(`${result.status} ${dependency_path}`);
180
- } else {
181
- error(result.status, dependency_path, path, 'fetched');
182
- }
183
- });
184
-
185
- if (is_html && config.kit.prerender.crawl) {
186
- const cleaned = clean_html(rendered.body);
187
-
188
- let match;
189
- const pattern = /<(a|img|link|source)\s+([\s\S]+?)>/gm;
190
-
191
- const hrefs = [];
192
-
193
- while ((match = pattern.exec(cleaned))) {
194
- const element = match[1];
195
- const attrs = match[2];
196
-
197
- if (element === 'a' || element === 'link') {
198
- hrefs.push(get_href(attrs));
199
- } else {
200
- if (element === 'img') {
201
- hrefs.push(get_src(attrs));
202
- }
203
- hrefs.push(...get_srcset_urls(attrs));
204
- }
205
- }
206
-
207
- for (const href of hrefs) {
208
- if (!href) continue;
209
-
210
- const resolved = resolve$1(path, href);
211
- if (resolved[0] !== '/') continue;
212
-
213
- const parsed = parse(resolved);
214
-
215
- const file = parsed.pathname.replace(config.kit.paths.assets, '').slice(1);
216
- if (files.has(file)) continue;
217
-
218
- if (parsed.query) ;
219
-
220
- await visit(parsed.pathname.replace(config.kit.paths.base, ''), path);
221
- }
222
- }
223
- }
224
- }
225
-
226
- for (const entry of config.kit.prerender.pages) {
227
- if (entry === '*') {
228
- for (const entry of build_data.entries) {
229
- await visit(entry, null);
230
- }
231
- } else {
232
- await visit(entry, null);
233
- }
234
- }
235
-
236
- if (fallback) {
237
- const rendered = await app.render(
238
- {
239
- host: config.kit.host,
240
- method: 'GET',
241
- headers: {},
242
- path: '[fallback]', // this doesn't matter, but it's easiest if it's a string
243
- rawBody: null,
244
- query: new URLSearchParams()
245
- },
246
- {
247
- prerender: {
248
- fallback,
249
- all: false,
250
- dependencies: null
251
- }
252
- }
253
- );
254
-
255
- const file = join(out, fallback);
256
- mkdirp(dirname(file));
257
- writeFileSync(file, rendered.body);
258
- }
259
- }
260
-
261
- /**
262
- *
263
- * @param {{
264
- * cwd: string;
265
- * config: import('types/config').ValidatedConfig;
266
- * build_data: import('types/internal').BuildData;
267
- * log: import('types/internal').Logger;
268
- * }} opts
269
- * @returns {import('types/config').AdapterUtils}
270
- */
271
- function get_utils({ cwd, config, build_data, log }) {
272
- return {
273
- log,
274
- rimraf,
275
- mkdirp,
276
- copy,
277
-
278
- /** @param {string} dest */
279
- copy_client_files(dest) {
280
- copy(`${cwd}/${SVELTE_KIT}/output/client`, dest, (file) => file[0] !== '.');
281
- },
282
-
283
- /** @param {string} dest */
284
- copy_server_files(dest) {
285
- copy(`${cwd}/${SVELTE_KIT}/output/server`, dest, (file) => file[0] !== '.');
286
- },
287
-
288
- /** @param {string} dest */
289
- copy_static_files(dest) {
290
- copy(config.kit.files.assets, dest);
291
- },
292
-
293
- /** @param {{ all: boolean, dest: string, fallback: string }} opts */
294
- async prerender({ all = false, dest, fallback }) {
295
- if (config.kit.prerender.enabled) {
296
- await prerender({
297
- out: dest,
298
- all,
299
- cwd,
300
- config,
301
- build_data,
302
- fallback,
303
- log
304
- });
305
- }
306
- }
307
- };
308
- }
309
-
310
- /**
311
- * @param {import('types/config').ValidatedConfig} config
312
- * @param {import('types/internal').BuildData} build_data
313
- * @param {{ cwd?: string, verbose: boolean }} opts
314
- */
315
- async function adapt(config, build_data, { cwd = process.cwd(), verbose }) {
316
- const { name, adapt } = config.kit.adapter;
317
-
318
- console.log($.bold().cyan(`\n> Using ${name}`));
319
-
320
- const log = logger({ verbose });
321
- const utils = get_utils({ cwd, config, build_data, log });
322
- await adapt(utils);
323
-
324
- log.success('done');
325
- }
326
-
327
- export { adapt };
@@ -1,325 +0,0 @@
1
- import * as fs from 'fs';
2
- import fs__default, { readdirSync, statSync } from 'fs';
3
- import { pathToFileURL, parse as parse$1 } from 'url';
4
- import { resolve, join, normalize } from 'path';
5
- import { M as Mime_1, s as standard } from './standard.js';
6
- import { getRawBody } from '../http.js';
7
- import { g as get_server } from './index3.js';
8
- import '../install-fetch.js';
9
- import { S as SVELTE_KIT } from './constants.js';
10
- import 'http';
11
- import 'https';
12
- import 'zlib';
13
- import 'stream';
14
- import 'util';
15
- import 'crypto';
16
-
17
- function list(dir, callback, pre='') {
18
- dir = resolve('.', dir);
19
- let arr = readdirSync(dir);
20
- let i=0, abs, stats;
21
- for (; i < arr.length; i++) {
22
- abs = join(dir, arr[i]);
23
- stats = statSync(abs);
24
- stats.isDirectory()
25
- ? list(abs, callback, join(pre, arr[i]))
26
- : callback(join(pre, arr[i]), abs, stats);
27
- }
28
- }
29
-
30
- function parse(str) {
31
- let i=0, j=0, k, v;
32
- let out={}, arr=str.split('&');
33
- for (; i < arr.length; i++) {
34
- j = arr[i].indexOf('=');
35
- v = !!~j && arr[i].substring(j+1) || '';
36
- k = !!~j ? arr[i].substring(0, j) : arr[i];
37
- out[k] = out[k] !== void 0 ? [].concat(out[k], v) : v;
38
- }
39
- return out;
40
- }
41
-
42
- function parser (req, toDecode) {
43
- let url = req.url;
44
- if (url == null) return;
45
-
46
- let obj = req._parsedUrl;
47
- if (obj && obj._raw === url) return obj;
48
-
49
- obj = {
50
- path: url,
51
- pathname: url,
52
- search: null,
53
- query: null,
54
- href: url,
55
- _raw: url
56
- };
57
-
58
- if (url.length > 1) {
59
- if (toDecode && !req._decoded && !!~url.indexOf('%', 1)) {
60
- let nxt = url;
61
- try { nxt = decodeURIComponent(url); } catch (e) {/* bad */}
62
- url = req.url = obj.href = obj.path = obj.pathname = obj._raw = nxt;
63
- req._decoded = true;
64
- }
65
-
66
- let idx = url.indexOf('?', 1);
67
-
68
- if (idx !== -1) {
69
- obj.search = url.substring(idx);
70
- obj.query = obj.search.substring(1);
71
- obj.pathname = url.substring(0, idx);
72
- if (toDecode && obj.query.length > 0) {
73
- obj.query = parse(obj.query);
74
- }
75
- }
76
- }
77
-
78
- return (req._parsedUrl = obj);
79
- }
80
-
81
- var lite = new Mime_1(standard);
82
-
83
- const noop = () => {};
84
-
85
- function isMatch(uri, arr) {
86
- for (let i=0; i < arr.length; i++) {
87
- if (arr[i].test(uri)) return true;
88
- }
89
- }
90
-
91
- function toAssume(uri, extns) {
92
- let i=0, x, len=uri.length - 1;
93
- if (uri.charCodeAt(len) === 47) {
94
- uri = uri.substring(0, len);
95
- }
96
-
97
- let arr=[], tmp=`${uri}/index`;
98
- for (; i < extns.length; i++) {
99
- x = extns[i] ? `.${extns[i]}` : '';
100
- if (uri) arr.push(uri + x);
101
- arr.push(tmp + x);
102
- }
103
-
104
- return arr;
105
- }
106
-
107
- function viaCache(cache, uri, extns) {
108
- let i=0, data, arr=toAssume(uri, extns);
109
- for (; i < arr.length; i++) {
110
- if (data = cache[arr[i]]) return data;
111
- }
112
- }
113
-
114
- function viaLocal(dir, isEtag, uri, extns) {
115
- let i=0, arr=toAssume(uri, extns);
116
- let abs, stats, name, headers;
117
- for (; i < arr.length; i++) {
118
- abs = normalize(join(dir, name=arr[i]));
119
- if (abs.startsWith(dir) && fs.existsSync(abs)) {
120
- stats = fs.statSync(abs);
121
- if (stats.isDirectory()) continue;
122
- headers = toHeaders(name, stats, isEtag);
123
- headers['Cache-Control'] = isEtag ? 'no-cache' : 'no-store';
124
- return { abs, stats, headers };
125
- }
126
- }
127
- }
128
-
129
- function is404(req, res) {
130
- return (res.statusCode=404,res.end());
131
- }
132
-
133
- function send(req, res, file, stats, headers) {
134
- let code=200, tmp, opts={};
135
- headers = { ...headers };
136
-
137
- for (let key in headers) {
138
- tmp = res.getHeader(key);
139
- if (tmp) headers[key] = tmp;
140
- }
141
-
142
- if (tmp = res.getHeader('content-type')) {
143
- headers['Content-Type'] = tmp;
144
- }
145
-
146
- if (req.headers.range) {
147
- code = 206;
148
- let [x, y] = req.headers.range.replace('bytes=', '').split('-');
149
- let end = opts.end = parseInt(y, 10) || stats.size - 1;
150
- let start = opts.start = parseInt(x, 10) || 0;
151
-
152
- if (start >= stats.size || end >= stats.size) {
153
- res.setHeader('Content-Range', `bytes */${stats.size}`);
154
- res.statusCode = 416;
155
- return res.end();
156
- }
157
-
158
- headers['Content-Range'] = `bytes ${start}-${end}/${stats.size}`;
159
- headers['Content-Length'] = (end - start + 1);
160
- headers['Accept-Ranges'] = 'bytes';
161
- }
162
-
163
- res.writeHead(code, headers);
164
- fs.createReadStream(file, opts).pipe(res);
165
- }
166
-
167
- function isEncoding(name, type, headers) {
168
- headers['Content-Encoding'] = type;
169
- headers['Content-Type'] = lite.getType(name.replace(/\.([^.]*)$/, '')) || '';
170
- }
171
-
172
- function toHeaders(name, stats, isEtag) {
173
- let headers = {
174
- 'Content-Length': stats.size,
175
- 'Content-Type': lite.getType(name) || '',
176
- 'Last-Modified': stats.mtime.toUTCString(),
177
- };
178
- if (isEtag) headers['ETag'] = `W/"${stats.size}-${stats.mtime.getTime()}"`;
179
- if (/\.br$/.test(name)) isEncoding(name, 'br', headers);
180
- if (/\.gz$/.test(name)) isEncoding(name, 'gzip', headers);
181
- return headers;
182
- }
183
-
184
- function sirv (dir, opts={}) {
185
- dir = resolve(dir || '.');
186
-
187
- let isNotFound = opts.onNoMatch || is404;
188
- let setHeaders = opts.setHeaders || noop;
189
-
190
- let extensions = opts.extensions || ['html', 'htm'];
191
- let gzips = opts.gzip && extensions.map(x => `${x}.gz`).concat('gz');
192
- let brots = opts.brotli && extensions.map(x => `${x}.br`).concat('br');
193
-
194
- const FILES = {};
195
-
196
- let fallback = '/';
197
- let isEtag = !!opts.etag;
198
- let isSPA = !!opts.single;
199
- if (typeof opts.single === 'string') {
200
- let idx = opts.single.lastIndexOf('.');
201
- fallback += !!~idx ? opts.single.substring(0, idx) : opts.single;
202
- }
203
-
204
- let ignores = [];
205
- if (opts.ignores !== false) {
206
- ignores.push(/[/]([A-Za-z\s\d~$._-]+\.\w+){1,}$/); // any extn
207
- if (opts.dotfiles) ignores.push(/\/\.\w/);
208
- else ignores.push(/\/\.well-known/);
209
- [].concat(opts.ignores || []).forEach(x => {
210
- ignores.push(new RegExp(x, 'i'));
211
- });
212
- }
213
-
214
- let cc = opts.maxAge != null && `public,max-age=${opts.maxAge}`;
215
- if (cc && opts.immutable) cc += ',immutable';
216
- else if (cc && opts.maxAge === 0) cc += ',must-revalidate';
217
-
218
- if (!opts.dev) {
219
- list(dir, (name, abs, stats) => {
220
- if (/\.well-known[\\+\/]/.test(name)) ; // keep
221
- else if (!opts.dotfiles && /(^\.|[\\+|\/+]\.)/.test(name)) return;
222
-
223
- let headers = toHeaders(name, stats, isEtag);
224
- if (cc) headers['Cache-Control'] = cc;
225
-
226
- FILES['/' + name.normalize().replace(/\\+/g, '/')] = { abs, stats, headers };
227
- });
228
- }
229
-
230
- let lookup = opts.dev ? viaLocal.bind(0, dir, isEtag) : viaCache.bind(0, FILES);
231
-
232
- return function (req, res, next) {
233
- let extns = [''];
234
- let val = req.headers['accept-encoding'] || '';
235
- if (gzips && val.includes('gzip')) extns.unshift(...gzips);
236
- if (brots && /(br|brotli)/i.test(val)) extns.unshift(...brots);
237
- extns.push(...extensions); // [...br, ...gz, orig, ...exts]
238
-
239
- let pathname = req.path || parser(req, true).pathname;
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 start({ port, host, config, https: use_https = false, cwd = process.cwd() }) {
274
- const app_file = resolve(cwd, `${SVELTE_KIT}/output/server/app.js`);
275
-
276
- /** @type {import('types/internal').App} */
277
- const app = await import(pathToFileURL(app_file).href);
278
-
279
- /** @type {import('sirv').RequestHandler} */
280
- const static_handler = fs__default.existsSync(config.kit.files.assets)
281
- ? mutable(config.kit.files.assets)
282
- : (_req, _res, next) => next();
283
-
284
- const assets_handler = sirv(resolve(cwd, `${SVELTE_KIT}/output/client`), {
285
- maxAge: 31536000,
286
- immutable: true
287
- });
288
-
289
- app.init({
290
- paths: {
291
- base: '',
292
- assets: '/.'
293
- },
294
- prerendering: false,
295
- read: (file) => fs__default.readFileSync(join(config.kit.files.assets, file))
296
- });
297
-
298
- return get_server(port, host, use_https, (req, res) => {
299
- const parsed = parse$1(req.url || '');
300
-
301
- assets_handler(req, res, () => {
302
- static_handler(req, res, async () => {
303
- const rendered = await app.render({
304
- host: /** @type {string} */ (config.kit.host ||
305
- req.headers[config.kit.hostHeader || 'host']),
306
- method: req.method,
307
- headers: /** @type {import('types/helper').Headers} */ (req.headers),
308
- path: decodeURIComponent(parsed.pathname),
309
- rawBody: await getRawBody(req),
310
- query: new URLSearchParams(parsed.query || '')
311
- });
312
-
313
- if (rendered) {
314
- res.writeHead(rendered.status, rendered.headers);
315
- res.end(rendered.body);
316
- } else {
317
- res.statusCode = 404;
318
- res.end('Not found');
319
- }
320
- });
321
- });
322
- });
323
- }
324
-
325
- export { start };