@sveltejs/kit 1.0.0-next.291 → 1.0.0-next.292

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.
@@ -2,10 +2,11 @@ import fs__default from 'fs';
2
2
  import http from 'http';
3
3
  import https from 'https';
4
4
  import { join } from 'path';
5
- import { s as sirv, S as SVELTE_KIT_ASSETS } from './constants.js';
5
+ import { S as SVELTE_KIT_ASSETS, s as sirv } from './constants.js';
6
6
  import { pathToFileURL } from 'url';
7
7
  import { getRequest, setResponse } from '../node.js';
8
8
  import { installFetch } from '../install-fetch.js';
9
+ import { n as normalize_path } from './url.js';
9
10
  import 'querystring';
10
11
  import 'stream';
11
12
  import 'node:http';
@@ -16,12 +17,21 @@ import 'node:util';
16
17
  import 'node:url';
17
18
  import 'net';
18
19
 
19
- /** @param {string} dir */
20
+ /** @typedef {import('http').IncomingMessage} Req */
21
+ /** @typedef {import('http').ServerResponse} Res */
22
+ /** @typedef {(req: Req, res: Res, next: () => void) => void} Handler */
23
+
24
+ /**
25
+ * @param {string} dir
26
+ * @returns {Handler}
27
+ */
20
28
  const mutable = (dir) =>
21
- sirv(dir, {
22
- etag: true,
23
- maxAge: 0
24
- });
29
+ fs__default.existsSync(dir)
30
+ ? sirv(dir, {
31
+ etag: true,
32
+ maxAge: 0
33
+ })
34
+ : (req, res, next) => next();
25
35
 
26
36
  /**
27
37
  * @param {{
@@ -35,34 +45,21 @@ const mutable = (dir) =>
35
45
  async function preview({ port, host, config, https: use_https = false }) {
36
46
  installFetch();
37
47
 
48
+ const { paths } = config.kit;
49
+ const base = paths.base;
50
+ const assets = paths.assets ? SVELTE_KIT_ASSETS : paths.base;
51
+
52
+ const etag = `"${Date.now()}"`;
53
+
38
54
  const index_file = join(config.kit.outDir, 'output/server/index.js');
39
55
  const manifest_file = join(config.kit.outDir, 'output/server/manifest.js');
40
56
 
41
57
  /** @type {import('types').ServerModule} */
42
58
  const { Server, override } = await import(pathToFileURL(index_file).href);
43
-
44
59
  const { manifest } = await import(pathToFileURL(manifest_file).href);
45
60
 
46
- /** @type {import('sirv').RequestHandler} */
47
- const static_handler = fs__default.existsSync(config.kit.files.assets)
48
- ? mutable(config.kit.files.assets)
49
- : (_req, _res, next) => {
50
- if (!next) throw new Error('No next() handler is available');
51
- return next();
52
- };
53
-
54
- const assets_handler = sirv(join(config.kit.outDir, 'output/client'), {
55
- maxAge: 31536000,
56
- immutable: true
57
- });
58
-
59
- const has_asset_path = !!config.kit.paths.assets;
60
-
61
61
  override({
62
- paths: {
63
- base: config.kit.paths.base,
64
- assets: has_asset_path ? SVELTE_KIT_ASSETS : config.kit.paths.base
65
- },
62
+ paths: { base, assets },
66
63
  prerendering: false,
67
64
  protocol: use_https ? 'https' : 'http',
68
65
  read: (file) => fs__default.readFileSync(join(config.kit.files.assets, file))
@@ -70,61 +67,103 @@ async function preview({ port, host, config, https: use_https = false }) {
70
67
 
71
68
  const server = new Server(manifest);
72
69
 
73
- /** @type {import('vite').UserConfig} */
74
- const vite_config = (config.kit.vite && (await config.kit.vite())) || {};
70
+ const handle = compose([
71
+ // files in `static`
72
+ scoped(assets, mutable(config.kit.files.assets)),
73
+
74
+ // immutable generated client assets
75
+ scoped(
76
+ assets,
77
+ sirv(join(config.kit.outDir, 'output/client'), {
78
+ maxAge: 31536000,
79
+ immutable: true
80
+ })
81
+ ),
82
+
83
+ // prerendered dependencies
84
+ scoped(base, mutable(join(config.kit.outDir, 'output/prerendered/dependencies'))),
85
+
86
+ // prerendered pages (we can't just use sirv because we need to
87
+ // preserve the correct trailingSlash behaviour)
88
+ scoped(base, (req, res, next) => {
89
+ let if_none_match_value = req.headers['if-none-match'];
90
+
91
+ if (if_none_match_value?.startsWith('W/"')) {
92
+ if_none_match_value = if_none_match_value.substring(2);
93
+ }
75
94
 
76
- const http_server = await get_server(use_https, vite_config, (req, res) => {
77
- if (req.url == null) {
78
- throw new Error('Invalid request url');
79
- }
95
+ if (if_none_match_value === etag) {
96
+ res.statusCode = 304;
97
+ res.end();
98
+ return;
99
+ }
80
100
 
81
- const initial_url = req.url;
101
+ const { pathname, search } = new URL(/** @type {string} */ (req.url), 'http://dummy');
82
102
 
83
- const render_handler = async () => {
84
- if (initial_url.startsWith(config.kit.paths.base)) {
85
- const protocol = use_https ? 'https' : 'http';
86
- const host = req.headers['host'];
103
+ const normalized = normalize_path(pathname, config.kit.trailingSlash);
87
104
 
88
- let request;
105
+ if (normalized !== pathname) {
106
+ res.writeHead(307, {
107
+ location: base + normalized + search
108
+ });
109
+ res.end();
110
+ return;
111
+ }
89
112
 
90
- try {
91
- req.url = initial_url;
92
- request = await getRequest(`${protocol}://${host}`, req);
93
- } catch (/** @type {any} */ err) {
94
- res.statusCode = err.status || 400;
95
- return res.end(err.reason || 'Invalid request body');
113
+ // only treat this as a page if it doesn't include an extension
114
+ if (pathname === '/' || /\/[^./]+\/?$/.test(pathname)) {
115
+ const file = join(
116
+ config.kit.outDir,
117
+ 'output/prerendered/pages' + pathname + (pathname.endsWith('/') ? 'index.html' : '.html')
118
+ );
119
+
120
+ if (fs__default.existsSync(file)) {
121
+ res.writeHead(200, {
122
+ 'content-type': 'text/html',
123
+ etag
124
+ });
125
+
126
+ fs__default.createReadStream(file).pipe(res);
127
+ return;
96
128
  }
97
-
98
- setResponse(res, await server.respond(request));
99
- } else {
100
- res.statusCode = 404;
101
- res.end('Not found');
102
- }
103
- };
104
-
105
- if (has_asset_path) {
106
- if (initial_url.startsWith(SVELTE_KIT_ASSETS)) {
107
- // custom assets path
108
- req.url = initial_url.slice(SVELTE_KIT_ASSETS.length);
109
- assets_handler(req, res, () => {
110
- static_handler(req, res, render_handler);
111
- });
112
- } else {
113
- render_handler();
114
129
  }
115
- } else {
116
- if (initial_url.startsWith(config.kit.paths.base)) {
117
- req.url = initial_url.slice(config.kit.paths.base.length);
130
+
131
+ next();
132
+ }),
133
+
134
+ // SSR
135
+ async (req, res) => {
136
+ const protocol = use_https ? 'https' : 'http';
137
+ const host = req.headers['host'];
138
+
139
+ let request;
140
+
141
+ try {
142
+ request = await getRequest(`${protocol}://${host}`, req);
143
+ } catch (/** @type {any} */ err) {
144
+ res.statusCode = err.status || 400;
145
+ return res.end(err.reason || 'Invalid request body');
118
146
  }
119
- assets_handler(req, res, () => {
120
- static_handler(req, res, render_handler);
121
- });
147
+
148
+ setResponse(res, await server.respond(request));
122
149
  }
123
- });
150
+ ]);
124
151
 
125
- await http_server.listen(port, host || '0.0.0.0');
152
+ const vite_config = (config.kit.vite && (await config.kit.vite())) || {};
126
153
 
127
- return Promise.resolve(http_server);
154
+ const http_server = await get_server(use_https, vite_config, (req, res) => {
155
+ if (req.url == null) {
156
+ throw new Error('Invalid request url');
157
+ }
158
+
159
+ handle(req, res);
160
+ });
161
+
162
+ return new Promise((fulfil) => {
163
+ http_server.listen(port, host || '0.0.0.0', () => {
164
+ fulfil(http_server);
165
+ });
166
+ });
128
167
  }
129
168
 
130
169
  /**
@@ -150,11 +189,54 @@ async function get_server(use_https, user_config, handler) {
150
189
  }
151
190
  }
152
191
 
153
- return Promise.resolve(
154
- use_https
155
- ? https.createServer(/** @type {https.ServerOptions} */ (https_options), handler)
156
- : http.createServer(handler)
157
- );
192
+ return use_https
193
+ ? https.createServer(/** @type {https.ServerOptions} */ (https_options), handler)
194
+ : http.createServer(handler);
195
+ }
196
+
197
+ /** @param {Handler[]} handlers */
198
+ function compose(handlers) {
199
+ /**
200
+ * @param {Req} req
201
+ * @param {Res} res
202
+ */
203
+ return (req, res) => {
204
+ /** @param {number} i */
205
+ function next(i) {
206
+ const handler = handlers[i];
207
+
208
+ if (handler) {
209
+ handler(req, res, () => next(i + 1));
210
+ } else {
211
+ res.statusCode = 404;
212
+ res.end('Not found');
213
+ }
214
+ }
215
+
216
+ next(0);
217
+ };
218
+ }
219
+
220
+ /**
221
+ * @param {string} scope
222
+ * @param {Handler} handler
223
+ * @returns {Handler}
224
+ */
225
+ function scoped(scope, handler) {
226
+ if (scope === '') return handler;
227
+
228
+ return (req, res, next) => {
229
+ if (req.url?.startsWith(scope)) {
230
+ const original_url = req.url;
231
+ req.url = req.url.slice(scope.length);
232
+ handler(req, res, () => {
233
+ req.url = original_url;
234
+ next();
235
+ });
236
+ } else {
237
+ next();
238
+ }
239
+ };
158
240
  }
159
241
 
160
242
  export { preview };
@@ -1,7 +1,8 @@
1
1
  import * as fs from 'fs';
2
2
  import * as path from 'path';
3
3
  import { createRequire } from 'module';
4
- import { f as rimraf, m as mkdirp, w as walk$1, $ } from '../cli.js';
4
+ import { $ } from '../cli.js';
5
+ import { r as rimraf, m as mkdirp, w as walk$1 } from './filesystem.js';
5
6
  import 'sade';
6
7
  import 'child_process';
7
8
  import 'net';
@@ -0,0 +1,83 @@
1
+ /**
2
+ * Takes zero or more objects and returns a new object that has all the values
3
+ * deeply merged together. None of the original objects will be mutated at any
4
+ * level, and the returned object will have no references to the original
5
+ * objects at any depth. If there's a conflict the last one wins, except for
6
+ * arrays which will be combined.
7
+ * @param {...Object} objects
8
+ * @returns {[Record<string, any>, string[]]} a 2-tuple with the merged object,
9
+ * and a list of merge conflicts if there were any, in dotted notation
10
+ */
11
+ function deep_merge(...objects) {
12
+ const result = {};
13
+ /** @type {string[]} */
14
+ const conflicts = [];
15
+ objects.forEach((o) => merge_into(result, o, conflicts));
16
+ return [result, conflicts];
17
+ }
18
+
19
+ /**
20
+ * normalize kit.vite.resolve.alias as an array
21
+ * @param {import('vite').AliasOptions} o
22
+ * @returns {import('vite').Alias[]}
23
+ */
24
+ function normalize_alias(o) {
25
+ if (Array.isArray(o)) return o;
26
+ return Object.entries(o).map(([find, replacement]) => ({ find, replacement }));
27
+ }
28
+
29
+ /**
30
+ * Merges b into a, recursively, mutating a.
31
+ * @param {Record<string, any>} a
32
+ * @param {Record<string, any>} b
33
+ * @param {string[]} conflicts array to accumulate conflicts in
34
+ * @param {string[]} path array of property names representing the current
35
+ * location in the tree
36
+ */
37
+ function merge_into(a, b, conflicts = [], path = []) {
38
+ /**
39
+ * Checks for "plain old Javascript object", typically made as an object
40
+ * literal. Excludes Arrays and built-in types like Buffer.
41
+ * @param {any} x
42
+ */
43
+ const is_plain_object = (x) => typeof x === 'object' && x.constructor === Object;
44
+
45
+ for (const prop in b) {
46
+ // normalize alias objects to array
47
+ if (prop === 'alias' && path[path.length - 1] === 'resolve') {
48
+ if (a[prop]) a[prop] = normalize_alias(a[prop]);
49
+ if (b[prop]) b[prop] = normalize_alias(b[prop]);
50
+ }
51
+
52
+ if (is_plain_object(b[prop])) {
53
+ if (!is_plain_object(a[prop])) {
54
+ if (a[prop] !== undefined) {
55
+ conflicts.push([...path, prop].join('.'));
56
+ }
57
+ a[prop] = {};
58
+ }
59
+ merge_into(a[prop], b[prop], conflicts, [...path, prop]);
60
+ } else if (Array.isArray(b[prop])) {
61
+ if (!Array.isArray(a[prop])) {
62
+ if (a[prop] !== undefined) {
63
+ conflicts.push([...path, prop].join('.'));
64
+ }
65
+ a[prop] = [];
66
+ }
67
+ a[prop].push(...b[prop]);
68
+ } else {
69
+ // Since we're inside a for/in loop which loops over enumerable
70
+ // properties only, we want parity here and to check if 'a' has
71
+ // enumerable-only property 'prop'. Using 'hasOwnProperty' to
72
+ // exclude inherited properties is close enough. It is possible
73
+ // that someone uses Object.defineProperty to create a direct,
74
+ // non-enumerable property but let's not worry about that.
75
+ if (Object.prototype.hasOwnProperty.call(a, prop)) {
76
+ conflicts.push([...path, prop].join('.'));
77
+ }
78
+ a[prop] = b[prop];
79
+ }
80
+ }
81
+ }
82
+
83
+ export { deep_merge as d };