@sveltejs/kit 1.0.0-next.345 → 1.0.0-next.346

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.
@@ -0,0 +1,538 @@
1
+ import { svelte as svelte$1 } from '@sveltejs/vite-plugin-svelte';
2
+ import fs__default from 'fs';
3
+ import { g as get_aliases, a as get_runtime_path, p as print_config_conflicts, r as resolve_entry, $, l as load_template, c as coalesce_to_error, b as get_mime_lookup } from '../cli.js';
4
+ import path__default from 'path';
5
+ import { S as SVELTE_KIT_ASSETS, s as sirv } from './constants.js';
6
+ import { URL } from 'url';
7
+ import { searchForWorkspaceRoot } from 'vite';
8
+ import { installPolyfills } from '../node/polyfills.js';
9
+ import { init, update } from './sync.js';
10
+ import { getRequest, setResponse } from '../node.js';
11
+ import { p as posixify } from './filesystem.js';
12
+ import { p as parse_route_id } from './misc.js';
13
+ import { d as deep_merge } from './object.js';
14
+ import 'chokidar';
15
+ import 'child_process';
16
+ import 'net';
17
+ import 'sade';
18
+ import 'os';
19
+ import 'querystring';
20
+ import 'node:http';
21
+ import 'node:https';
22
+ import 'node:zlib';
23
+ import 'node:stream';
24
+ import 'node:util';
25
+ import 'node:url';
26
+ import 'crypto';
27
+ import './write_tsconfig.js';
28
+ import 'stream';
29
+
30
+ // Vite doesn't expose this so we just copy the list for now
31
+ // https://github.com/vitejs/vite/blob/3edd1af56e980aef56641a5a51cf2932bb580d41/packages/vite/src/node/plugins/css.ts#L96
32
+ const style_pattern = /\.(css|less|sass|scss|styl|stylus|pcss|postcss)$/;
33
+
34
+ const cwd = process.cwd();
35
+
36
+ /**
37
+ * @param {import('types').ValidatedConfig} svelte_config
38
+ * @return {import('vite').Plugin}
39
+ */
40
+ const sveltekit = function (svelte_config) {
41
+ return {
42
+ name: 'vite-plugin-svelte-kit',
43
+
44
+ async config() {
45
+ const [vite_config] = deep_merge(
46
+ {
47
+ server: {
48
+ fs: {
49
+ allow: [
50
+ ...new Set([
51
+ svelte_config.kit.files.lib,
52
+ svelte_config.kit.files.routes,
53
+ svelte_config.kit.outDir,
54
+ path__default.resolve(cwd, 'src'),
55
+ path__default.resolve(cwd, 'node_modules'),
56
+ path__default.resolve(searchForWorkspaceRoot(cwd), 'node_modules')
57
+ ])
58
+ ]
59
+ },
60
+ port: 3000,
61
+ strictPort: true,
62
+ watch: {
63
+ ignored: [
64
+ `${svelte_config.kit.outDir}/**`,
65
+ `!${svelte_config.kit.outDir}/generated/**`
66
+ ]
67
+ }
68
+ }
69
+ },
70
+ await svelte_config.kit.vite()
71
+ );
72
+
73
+ /** @type {[any, string[]]} */
74
+ const [merged_config, conflicts] = deep_merge(vite_config, {
75
+ configFile: false,
76
+ root: cwd,
77
+ resolve: {
78
+ alias: get_aliases(svelte_config)
79
+ },
80
+ build: {
81
+ rollupOptions: {
82
+ // Vite dependency crawler needs an explicit JS entry point
83
+ // eventhough server otherwise works without it
84
+ input: `${get_runtime_path(svelte_config)}/client/start.js`
85
+ }
86
+ },
87
+ base: '/'
88
+ });
89
+
90
+ print_config_conflicts(conflicts, 'kit.vite.');
91
+
92
+ return merged_config;
93
+ },
94
+
95
+ async configureServer(vite) {
96
+ installPolyfills();
97
+
98
+ init(svelte_config);
99
+
100
+ const runtime = get_runtime_path(svelte_config);
101
+
102
+ process.env.VITE_SVELTEKIT_APP_VERSION_POLL_INTERVAL = '0';
103
+
104
+ /** @type {import('types').Respond} */
105
+ const respond = (await import(`${runtime}/server/index.js`)).respond;
106
+
107
+ /** @type {import('types').SSRManifest} */
108
+ let manifest;
109
+
110
+ function update_manifest() {
111
+ const { manifest_data } = update(svelte_config);
112
+
113
+ manifest = {
114
+ appDir: svelte_config.kit.appDir,
115
+ assets: new Set(manifest_data.assets.map((asset) => asset.file)),
116
+ mimeTypes: get_mime_lookup(manifest_data),
117
+ _: {
118
+ entry: {
119
+ file: `/@fs${runtime}/client/start.js`,
120
+ css: [],
121
+ js: []
122
+ },
123
+ nodes: manifest_data.components.map((id, index) => {
124
+ return async () => {
125
+ const url = id.startsWith('..') ? `/@fs${path__default.posix.resolve(id)}` : `/${id}`;
126
+
127
+ const module = /** @type {import('types').SSRComponent} */ (
128
+ await vite.ssrLoadModule(url, { fixStacktrace: false })
129
+ );
130
+ const node = await vite.moduleGraph.getModuleByUrl(url);
131
+
132
+ if (!node) throw new Error(`Could not find node for ${url}`);
133
+
134
+ const deps = new Set();
135
+ await find_deps(vite, node, deps);
136
+
137
+ /** @type {Record<string, string>} */
138
+ const styles = {};
139
+
140
+ for (const dep of deps) {
141
+ const parsed = new URL(dep.url, 'http://localhost/');
142
+ const query = parsed.searchParams;
143
+
144
+ if (
145
+ style_pattern.test(dep.file) ||
146
+ (query.has('svelte') && query.get('type') === 'style')
147
+ ) {
148
+ try {
149
+ const mod = await vite.ssrLoadModule(dep.url, { fixStacktrace: false });
150
+ styles[dep.url] = mod.default;
151
+ } catch {
152
+ // this can happen with dynamically imported modules, I think
153
+ // because the Vite module graph doesn't distinguish between
154
+ // static and dynamic imports? TODO investigate, submit fix
155
+ }
156
+ }
157
+ }
158
+
159
+ return {
160
+ module,
161
+ index,
162
+ entry: url.endsWith('.svelte') ? url : url + '?import',
163
+ css: [],
164
+ js: [],
165
+ // in dev we inline all styles to avoid FOUC
166
+ styles
167
+ };
168
+ };
169
+ }),
170
+ routes: manifest_data.routes.map((route) => {
171
+ const { pattern, names, types } = parse_route_id(route.id);
172
+
173
+ if (route.type === 'page') {
174
+ return {
175
+ type: 'page',
176
+ id: route.id,
177
+ pattern,
178
+ names,
179
+ types,
180
+ shadow: route.shadow
181
+ ? async () => {
182
+ const url = path__default.resolve(cwd, /** @type {string} */ (route.shadow));
183
+ return await vite.ssrLoadModule(url, { fixStacktrace: false });
184
+ }
185
+ : null,
186
+ a: route.a.map((id) => (id ? manifest_data.components.indexOf(id) : undefined)),
187
+ b: route.b.map((id) => (id ? manifest_data.components.indexOf(id) : undefined))
188
+ };
189
+ }
190
+
191
+ return {
192
+ type: 'endpoint',
193
+ id: route.id,
194
+ pattern,
195
+ names,
196
+ types,
197
+ load: async () => {
198
+ const url = path__default.resolve(cwd, route.file);
199
+ return await vite.ssrLoadModule(url, { fixStacktrace: false });
200
+ }
201
+ };
202
+ }),
203
+ matchers: async () => {
204
+ /** @type {Record<string, import('types').ParamMatcher>} */
205
+ const matchers = {};
206
+
207
+ for (const key in manifest_data.matchers) {
208
+ const file = manifest_data.matchers[key];
209
+ const url = path__default.resolve(cwd, file);
210
+ const module = await vite.ssrLoadModule(url, { fixStacktrace: false });
211
+
212
+ if (module.match) {
213
+ matchers[key] = module.match;
214
+ } else {
215
+ throw new Error(`${file} does not export a \`match\` function`);
216
+ }
217
+ }
218
+
219
+ return matchers;
220
+ }
221
+ }
222
+ };
223
+ }
224
+
225
+ /** @param {Error} error */
226
+ function fix_stack_trace(error) {
227
+ return error.stack ? vite.ssrRewriteStacktrace(error.stack) : error.stack;
228
+ }
229
+
230
+ update_manifest();
231
+
232
+ for (const event of ['add', 'unlink']) {
233
+ vite.watcher.on(event, (file) => {
234
+ if (file.startsWith(svelte_config.kit.files.routes + path__default.sep)) {
235
+ update_manifest();
236
+ }
237
+ });
238
+ }
239
+
240
+ const assets = svelte_config.kit.paths.assets
241
+ ? SVELTE_KIT_ASSETS
242
+ : svelte_config.kit.paths.base;
243
+ const asset_server = sirv(svelte_config.kit.files.assets, {
244
+ dev: true,
245
+ etag: true,
246
+ maxAge: 0,
247
+ extensions: []
248
+ });
249
+
250
+ return () => {
251
+ const serve_static_middleware = vite.middlewares.stack.find(
252
+ (middleware) =>
253
+ /** @type {function} */ (middleware.handle).name === 'viteServeStaticMiddleware'
254
+ );
255
+
256
+ remove_html_middlewares(vite.middlewares);
257
+
258
+ vite.middlewares.use(async (req, res) => {
259
+ try {
260
+ if (!req.url || !req.method) throw new Error('Incomplete request');
261
+
262
+ const base = `${vite.config.server.https ? 'https' : 'http'}://${
263
+ req.headers[':authority'] || req.headers.host
264
+ }`;
265
+
266
+ const decoded = decodeURI(new URL(base + req.url).pathname);
267
+
268
+ if (decoded.startsWith(assets)) {
269
+ const pathname = decoded.slice(assets.length);
270
+ const file = svelte_config.kit.files.assets + pathname;
271
+
272
+ if (fs__default.existsSync(file) && !fs__default.statSync(file).isDirectory()) {
273
+ const has_correct_case = fs__default.realpathSync.native(file) === path__default.resolve(file);
274
+
275
+ if (has_correct_case) {
276
+ req.url = encodeURI(pathname); // don't need query/hash
277
+ asset_server(req, res);
278
+ return;
279
+ }
280
+ }
281
+ }
282
+
283
+ if (!decoded.startsWith(svelte_config.kit.paths.base)) {
284
+ return not_found(
285
+ res,
286
+ `Not found (did you mean ${svelte_config.kit.paths.base + req.url}?)`
287
+ );
288
+ }
289
+
290
+ /** @type {Partial<import('types').Hooks>} */
291
+ const user_hooks = resolve_entry(svelte_config.kit.files.hooks)
292
+ ? await vite.ssrLoadModule(`/${svelte_config.kit.files.hooks}`, {
293
+ fixStacktrace: false
294
+ })
295
+ : {};
296
+
297
+ const handle = user_hooks.handle || (({ event, resolve }) => resolve(event));
298
+
299
+ /** @type {import('types').Hooks} */
300
+ const hooks = {
301
+ getSession: user_hooks.getSession || (() => ({})),
302
+ handle,
303
+ handleError:
304
+ user_hooks.handleError ||
305
+ (({ /** @type {Error & { frame?: string }} */ error }) => {
306
+ console.error($.bold().red(error.message));
307
+ if (error.frame) {
308
+ console.error($.gray(error.frame));
309
+ }
310
+ if (error.stack) {
311
+ console.error($.gray(error.stack));
312
+ }
313
+ }),
314
+ externalFetch: user_hooks.externalFetch || fetch
315
+ };
316
+
317
+ if (/** @type {any} */ (hooks).getContext) {
318
+ // TODO remove this for 1.0
319
+ throw new Error(
320
+ 'The getContext hook has been removed. See https://kit.svelte.dev/docs/hooks'
321
+ );
322
+ }
323
+
324
+ if (/** @type {any} */ (hooks).serverFetch) {
325
+ // TODO remove this for 1.0
326
+ throw new Error('The serverFetch hook has been renamed to externalFetch.');
327
+ }
328
+
329
+ // TODO the / prefix will probably fail if outDir is outside the cwd (which
330
+ // could be the case in a monorepo setup), but without it these modules
331
+ // can get loaded twice via different URLs, which causes failures. Might
332
+ // require changes to Vite to fix
333
+ const { default: root } = await vite.ssrLoadModule(
334
+ `/${posixify(
335
+ path__default.relative(cwd, `${svelte_config.kit.outDir}/generated/root.svelte`)
336
+ )}`,
337
+ { fixStacktrace: false }
338
+ );
339
+
340
+ const paths = await vite.ssrLoadModule(
341
+ true
342
+ ? `/${posixify(path__default.relative(cwd, `${svelte_config.kit.outDir}/runtime/paths.js`))}`
343
+ : `/@fs${runtime}/paths.js`,
344
+ { fixStacktrace: false }
345
+ );
346
+
347
+ paths.set_paths({
348
+ base: svelte_config.kit.paths.base,
349
+ assets
350
+ });
351
+
352
+ let request;
353
+
354
+ try {
355
+ request = await getRequest(base, req);
356
+ } catch (/** @type {any} */ err) {
357
+ res.statusCode = err.status || 400;
358
+ return res.end(err.reason || 'Invalid request body');
359
+ }
360
+
361
+ const template = load_template(cwd, svelte_config);
362
+
363
+ const rendered = await respond(
364
+ request,
365
+ {
366
+ csp: svelte_config.kit.csp,
367
+ dev: true,
368
+ floc: svelte_config.kit.floc,
369
+ get_stack: (error) => {
370
+ return fix_stack_trace(error);
371
+ },
372
+ handle_error: (error, event) => {
373
+ hooks.handleError({
374
+ error: new Proxy(error, {
375
+ get: (target, property) => {
376
+ if (property === 'stack') {
377
+ return fix_stack_trace(error);
378
+ }
379
+
380
+ return Reflect.get(target, property, target);
381
+ }
382
+ }),
383
+ event,
384
+
385
+ // TODO remove for 1.0
386
+ // @ts-expect-error
387
+ get request() {
388
+ throw new Error(
389
+ 'request in handleError has been replaced with event. See https://github.com/sveltejs/kit/pull/3384 for details'
390
+ );
391
+ }
392
+ });
393
+ },
394
+ hooks,
395
+ hydrate: svelte_config.kit.browser.hydrate,
396
+ manifest,
397
+ method_override: svelte_config.kit.methodOverride,
398
+ paths: {
399
+ base: svelte_config.kit.paths.base,
400
+ assets
401
+ },
402
+ prefix: '',
403
+ prerender: {
404
+ default: svelte_config.kit.prerender.default,
405
+ enabled: svelte_config.kit.prerender.enabled
406
+ },
407
+ read: (file) => fs__default.readFileSync(path__default.join(svelte_config.kit.files.assets, file)),
408
+ root,
409
+ router: svelte_config.kit.browser.router,
410
+ template: ({ head, body, assets, nonce }) => {
411
+ return (
412
+ template
413
+ .replace(/%sveltekit\.assets%/g, assets)
414
+ .replace(/%sveltekit\.nonce%/g, nonce)
415
+ // head and body must be replaced last, in case someone tries to sneak in %sveltekit.assets% etc
416
+ .replace('%sveltekit.head%', () => head)
417
+ .replace('%sveltekit.body%', () => body)
418
+ );
419
+ },
420
+ template_contains_nonce: template.includes('%sveltekit.nonce%'),
421
+ trailing_slash: svelte_config.kit.trailingSlash
422
+ },
423
+ {
424
+ getClientAddress: () => {
425
+ const { remoteAddress } = req.socket;
426
+ if (remoteAddress) return remoteAddress;
427
+ throw new Error('Could not determine clientAddress');
428
+ }
429
+ }
430
+ );
431
+
432
+ if (rendered.status === 404) {
433
+ // @ts-expect-error
434
+ serve_static_middleware.handle(req, res, () => {
435
+ setResponse(res, rendered);
436
+ });
437
+ } else {
438
+ setResponse(res, rendered);
439
+ }
440
+ } catch (e) {
441
+ const error = coalesce_to_error(e);
442
+ vite.ssrFixStacktrace(error);
443
+ res.statusCode = 500;
444
+ res.end(error.stack);
445
+ }
446
+ });
447
+ };
448
+ }
449
+ };
450
+ };
451
+
452
+ /** @param {import('http').ServerResponse} res */
453
+ function not_found(res, message = 'Not found') {
454
+ res.statusCode = 404;
455
+ res.end(message);
456
+ }
457
+
458
+ /**
459
+ * @param {import('connect').Server} server
460
+ */
461
+ function remove_html_middlewares(server) {
462
+ const html_middlewares = [
463
+ 'viteIndexHtmlMiddleware',
464
+ 'vite404Middleware',
465
+ 'viteSpaFallbackMiddleware',
466
+ 'viteServeStaticMiddleware'
467
+ ];
468
+ for (let i = server.stack.length - 1; i > 0; i--) {
469
+ // @ts-expect-error using internals until https://github.com/vitejs/vite/pull/4640 is merged
470
+ if (html_middlewares.includes(server.stack[i].handle.name)) {
471
+ server.stack.splice(i, 1);
472
+ }
473
+ }
474
+ }
475
+
476
+ /**
477
+ * @param {import('vite').ViteDevServer} vite
478
+ * @param {import('vite').ModuleNode} node
479
+ * @param {Set<import('vite').ModuleNode>} deps
480
+ */
481
+ async function find_deps(vite, node, deps) {
482
+ // since `ssrTransformResult.deps` contains URLs instead of `ModuleNode`s, this process is asynchronous.
483
+ // instead of using `await`, we resolve all branches in parallel.
484
+ /** @type {Promise<void>[]} */
485
+ const branches = [];
486
+
487
+ /** @param {import('vite').ModuleNode} node */
488
+ async function add(node) {
489
+ if (!deps.has(node)) {
490
+ deps.add(node);
491
+ await find_deps(vite, node, deps);
492
+ }
493
+ }
494
+
495
+ /** @param {string} url */
496
+ async function add_by_url(url) {
497
+ const node = await vite.moduleGraph.getModuleByUrl(url);
498
+
499
+ if (node) {
500
+ await add(node);
501
+ }
502
+ }
503
+
504
+ if (node.ssrTransformResult) {
505
+ if (node.ssrTransformResult.deps) {
506
+ node.ssrTransformResult.deps.forEach((url) => branches.push(add_by_url(url)));
507
+ }
508
+ } else {
509
+ node.importedModules.forEach((node) => branches.push(add(node)));
510
+ }
511
+
512
+ await Promise.all(branches);
513
+ }
514
+
515
+ /**
516
+ * @param {import('types').ValidatedConfig} svelte_config
517
+ * @return {import('vite').Plugin[]}
518
+ */
519
+ const svelte = function (svelte_config) {
520
+ return svelte$1({
521
+ ...svelte_config,
522
+ compilerOptions: {
523
+ ...svelte_config.compilerOptions,
524
+ hydratable: !!svelte_config.kit.browser.hydrate
525
+ },
526
+ configFile: false
527
+ });
528
+ };
529
+
530
+ /**
531
+ * @param {import('types').ValidatedConfig} svelte_config
532
+ * @return {import('vite').Plugin[]}
533
+ */
534
+ const plugins = function (svelte_config) {
535
+ return [...svelte(svelte_config), sveltekit(svelte_config)];
536
+ };
537
+
538
+ export { plugins, svelte, sveltekit };
@@ -1,14 +1,15 @@
1
1
  import path__default from 'path';
2
2
  import fs__default from 'fs';
3
- import { g as get_runtime_path } from '../cli.js';
3
+ import { a as get_runtime_path } from '../cli.js';
4
4
  import { p as posixify, c as copy, r as rimraf } from './filesystem.js';
5
5
  import { p as parse_route_id, s } from './misc.js';
6
6
  import { fileURLToPath } from 'url';
7
7
  import { w as write_if_changed, t as trim, a as write, b as write_tsconfig } from './write_tsconfig.js';
8
- import 'sade';
8
+ import 'chokidar';
9
9
  import 'child_process';
10
10
  import 'net';
11
- import 'chokidar';
11
+ import 'sade';
12
+ import 'vite';
12
13
  import 'os';
13
14
 
14
15
  /**