-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
index.js
435 lines (376 loc) · 11.6 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
import fs from 'fs';
import path from 'path';
import { parse } from 'url';
import { EventEmitter } from 'events';
import CheapWatch from 'cheap-watch';
import amp_validator from 'amphtml-validator';
import vite from 'vite';
import colors from 'kleur';
import create_manifest_data from '../../core/create_manifest_data/index.js';
import { create_app } from '../../core/create_app/index.js';
import { rimraf } from '../filesystem/index.js';
import { respond } from '../../runtime/server/index.js';
import { getRawBody } from '../node/index.js';
import { copy_assets, get_no_external, resolve_entry } from '../utils.js';
import { deep_merge, print_config_conflicts } from '../config/index.js';
import { svelte } from '@sveltejs/vite-plugin-svelte';
import { get_server } from '../server/index.js';
import { __fetch_polyfill } from '../../install-fetch.js';
import { SVELTE_KIT } from '../constants.js';
/** @typedef {{ cwd?: string, port: number, host: string, https: boolean, config: import('types/config').ValidatedConfig }} Options */
/** @typedef {import('types/internal').SSRComponent} SSRComponent */
/** @param {Options} opts */
export function dev(opts) {
__fetch_polyfill();
return new Watcher(opts).init();
}
class Watcher extends EventEmitter {
/** @param {Options} opts */
constructor({ cwd = process.cwd(), port, host, https, config }) {
super();
this.cwd = cwd;
this.dir = path.resolve(cwd, `${SVELTE_KIT}/dev`);
this.port = port;
this.host = host;
this.https = https;
this.config = config;
process.on('exit', () => {
this.close();
});
}
async init() {
rimraf(this.dir);
copy_assets(this.dir);
process.env.VITE_SVELTEKIT_AMP = this.config.kit.amp ? 'true' : '';
await this.init_filewatcher();
await this.init_server();
this.update();
return this;
}
async init_filewatcher() {
this.cheapwatch = new CheapWatch({
dir: this.config.kit.files.routes,
/** @type {({ path }: { path: string }) => boolean} */
filter: ({ path }) => path.split('/').every((part) => part[0] !== '_' || part[1] === '_')
});
await this.cheapwatch.init();
// not sure why TS doesn't understand that CheapWatch extends EventEmitter
this.cheapwatch.on('+', ({ isNew }) => {
if (isNew) this.update();
});
this.cheapwatch.on('-', () => {
this.update();
});
}
async init_server() {
/** @type {any} */
const user_config = (this.config.kit.vite && this.config.kit.vite()) || {};
const default_config = {
server: {
fs: {
strict: true
}
}
};
/** @type {(req: import("http").IncomingMessage, res: import("http").ServerResponse) => void} */
let handler = (req, res) => {};
this.server = await get_server(this.https, user_config, (req, res) => handler(req, res));
const alias = user_config.resolve && user_config.resolve.alias;
// don't warn on overriding defaults
const [modified_user_config] = deep_merge(default_config, user_config);
/** @type {[any, string[]]} */
const [merged_config, conflicts] = deep_merge(modified_user_config, {
configFile: false,
root: this.cwd,
resolve: {
alias: Array.isArray(alias)
? [
{
find: '$app',
replacement: path.resolve(`${this.dir}/runtime/app`)
},
{
find: '$lib',
replacement: this.config.kit.files.lib
}
]
: {
$app: path.resolve(`${this.dir}/runtime/app`),
$lib: this.config.kit.files.lib
}
},
plugins: [
svelte({
extensions: this.config.extensions,
emitCss: !this.config.kit.amp
})
],
publicDir: this.config.kit.files.assets,
server: {
middlewareMode: true,
hmr: {
...(this.https ? { server: this.server, port: this.port } : {})
}
},
optimizeDeps: {
entries: []
},
ssr: {
noExternal: get_no_external(this.cwd, user_config.ssr && user_config.ssr.noExternal)
}
});
print_config_conflicts(conflicts, 'kit.vite.');
/**
* @type {vite.ViteDevServer}
*/
this.vite = await vite.createServer(merged_config);
const validator = this.config.kit.amp && (await amp_validator.getInstance());
/**
* @param {import('vite').ModuleNode} node
* @param {Set<import('vite').ModuleNode>} deps
*/
const find_deps = (node, deps) => {
for (const dep of node.importedModules) {
if (!deps.has(dep)) {
deps.add(dep);
find_deps(dep, deps);
}
}
};
handler = (req, res) => {
this.vite.middlewares(req, res, async () => {
try {
const parsed = parse(req.url);
if (req.url === '/favicon.ico') return;
/** @type {import('types/internal').Hooks} */
const hooks = resolve_entry(this.config.kit.files.hooks)
? await this.vite.ssrLoadModule(`/${this.config.kit.files.hooks}`)
: {};
if (/** @type {any} */ (hooks).getContext) {
// TODO remove this for 1.0
throw new Error(
'The getContext hook has been removed. See https://kit.svelte.dev/docs#hooks'
);
}
const root = (await this.vite.ssrLoadModule(`/${this.dir}/generated/root.svelte`))
.default;
let body;
try {
body = await getRawBody(req);
} catch (err) {
res.statusCode = err.status || 400;
return res.end(err.reason || 'Invalid request body');
}
const host = /** @type {string} */ (this.config.kit.host ||
req.headers[this.config.kit.hostHeader || 'host']);
const rendered = await respond(
{
headers: /** @type {import('types/helper').Headers} */ (req.headers),
method: req.method,
host,
path: parsed.pathname,
query: new URLSearchParams(parsed.query),
rawBody: body
},
{
amp: this.config.kit.amp,
dev: true,
entry: {
file: `/${SVELTE_KIT}/dev/runtime/internal/start.js`,
css: [],
js: []
},
floc: this.config.kit.floc,
get_stack: (error) => {
this.vite.ssrFixStacktrace(error);
return error.stack;
},
handle_error: /** @param {Error & {frame?: string}} error */ (error) => {
this.vite.ssrFixStacktrace(error);
console.error(colors.bold().red(error.message));
if (error.frame) {
console.error(colors.gray(error.frame));
}
console.error(colors.gray(error.stack));
},
hooks: {
getSession: hooks.getSession || (() => ({})),
handle: hooks.handle || (({ request, resolve }) => resolve(request)),
serverFetch: hooks.serverFetch || fetch
},
hydrate: this.config.kit.hydrate,
paths: this.config.kit.paths,
load_component: async (id) => {
const url = path.resolve(this.cwd, id);
const module = /** @type {SSRComponent} */ (await this.vite.ssrLoadModule(url));
const node = await this.vite.moduleGraph.getModuleByUrl(url);
const deps = new Set();
find_deps(node, deps);
const styles = new Set();
for (const dep of deps) {
const parsed = parse(dep.url);
const query = new URLSearchParams(parsed.query);
// TODO what about .scss files, etc?
if (
dep.file.endsWith('.css') ||
(query.has('svelte') && query.get('type') === 'style')
) {
try {
const mod = await this.vite.ssrLoadModule(dep.url);
styles.add(mod.default);
} catch {
// this can happen with dynamically imported modules, I think
// because the Vite module graph doesn't distinguish between
// static and dynamic imports? TODO investigate, submit fix
}
}
}
let entry = `/${id}`;
if (!entry.endsWith('.svelte')) {
entry += '?import';
}
return {
module,
entry,
css: [],
js: [],
styles: Array.from(styles)
};
},
manifest: this.manifest,
read: (file) => fs.readFileSync(path.join(this.config.kit.files.assets, file)),
root,
router: this.config.kit.router,
ssr: this.config.kit.ssr,
target: this.config.kit.target,
template: ({ head, body }) => {
let rendered = fs
.readFileSync(this.config.kit.files.template, 'utf8')
.replace('%svelte.head%', () => head)
.replace('%svelte.body%', () => body);
if (this.config.kit.amp) {
const result = validator.validateString(rendered);
if (result.status !== 'PASS') {
const lines = rendered.split('\n');
/** @param {string} str */
const escape = (str) =>
str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
rendered = `<!doctype html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
color: #333;
}
pre {
background: #f4f4f4;
padding: 1em;
overflow-x: auto;
}
</style>
</head>
<h1>AMP validation failed</h1>
${result.errors
.map(
(error) => `
<h2>${error.severity}</h2>
<p>Line ${error.line}, column ${error.col}: ${error.message} (<a href="${error.specUrl}">${
error.code
}</a>)</p>
<pre>${escape(lines[error.line - 1])}</pre>
`
)
.join('\n\n')}
`;
}
}
return rendered;
},
trailing_slash: this.config.kit.trailingSlash
}
);
if (rendered) {
res.writeHead(rendered.status, rendered.headers);
if (rendered.body) res.write(rendered.body);
res.end();
} else {
res.statusCode = 404;
res.end('Not found');
}
} catch (e) {
this.vite.ssrFixStacktrace(e);
res.statusCode = 500;
res.end(e.stack);
}
});
};
await this.server.listen(this.port, this.host || '0.0.0.0');
}
update() {
const manifest_data = create_manifest_data({
config: this.config,
output: this.dir,
cwd: this.cwd
});
create_app({
manifest_data,
output: this.dir,
cwd: this.cwd
});
/** @type {import('types/internal').SSRManifest} */
this.manifest = {
assets: manifest_data.assets,
layout: manifest_data.layout,
error: manifest_data.error,
routes: manifest_data.routes.map((route) => {
if (route.type === 'page') {
return {
type: 'page',
pattern: route.pattern,
params: get_params(route.params),
a: route.a,
b: route.b
};
}
return {
type: 'endpoint',
pattern: route.pattern,
params: get_params(route.params),
load: async () => {
const url = path.resolve(this.cwd, route.file);
return await this.vite.ssrLoadModule(url);
}
};
})
};
}
close() {
if (this.closed) return;
this.closed = true;
this.vite.close();
this.server.close();
this.cheapwatch.close();
}
}
/** @param {string[]} array */
function get_params(array) {
// given an array of params like `['x', 'y', 'z']` for
// src/routes/[x]/[y]/[z]/svelte, create a function
// that turns a RegExpExecArray into ({ x, y, z })
/** @param {RegExpExecArray} match */
const fn = (match) => {
/** @type {Record<string, string>} */
const params = {};
array.forEach((key, i) => {
if (key.startsWith('...')) {
params[key.slice(3)] = decodeURIComponent(match[i + 1] || '');
} else {
params[key] = decodeURIComponent(match[i + 1]);
}
});
return params;
};
return fn;
}