@sveltejs/kit 1.0.0-next.35 → 1.0.0-next.350

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 (69) hide show
  1. package/README.md +12 -9
  2. package/assets/app/env.js +16 -0
  3. package/assets/app/navigation.js +24 -0
  4. package/assets/app/paths.js +1 -0
  5. package/assets/app/stores.js +97 -0
  6. package/assets/client/singletons.js +13 -0
  7. package/assets/client/start.js +1788 -0
  8. package/assets/components/error.svelte +18 -2
  9. package/assets/env.js +8 -0
  10. package/assets/paths.js +13 -0
  11. package/assets/server/index.js +3371 -0
  12. package/dist/chunks/constants.js +663 -0
  13. package/dist/chunks/filesystem.js +110 -0
  14. package/dist/chunks/index.js +1363 -0
  15. package/dist/chunks/index2.js +120 -0
  16. package/dist/chunks/index3.js +183 -0
  17. package/dist/chunks/index4.js +215 -0
  18. package/dist/chunks/index5.js +15748 -0
  19. package/dist/chunks/misc.js +78 -0
  20. package/dist/chunks/multipart-parser.js +444 -0
  21. package/dist/chunks/object.js +83 -0
  22. package/dist/chunks/plugin.js +555 -0
  23. package/dist/chunks/sync.js +856 -0
  24. package/dist/chunks/write_tsconfig.js +169 -0
  25. package/dist/cli.js +1028 -87
  26. package/dist/hooks.js +28 -0
  27. package/dist/node/polyfills.js +6654 -0
  28. package/dist/node.js +301 -0
  29. package/package.json +95 -55
  30. package/types/ambient.d.ts +307 -0
  31. package/types/index.d.ts +294 -0
  32. package/types/internal.d.ts +326 -0
  33. package/types/private.d.ts +235 -0
  34. package/CHANGELOG.md +0 -371
  35. package/assets/runtime/app/navigation.js +0 -23
  36. package/assets/runtime/app/navigation.js.map +0 -1
  37. package/assets/runtime/app/paths.js +0 -2
  38. package/assets/runtime/app/paths.js.map +0 -1
  39. package/assets/runtime/app/stores.js +0 -78
  40. package/assets/runtime/app/stores.js.map +0 -1
  41. package/assets/runtime/internal/singletons.js +0 -15
  42. package/assets/runtime/internal/singletons.js.map +0 -1
  43. package/assets/runtime/internal/start.js +0 -614
  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 -28
  48. package/dist/api.js.map +0 -1
  49. package/dist/cli.js.map +0 -1
  50. package/dist/create_app.js +0 -502
  51. package/dist/create_app.js.map +0 -1
  52. package/dist/index.js +0 -327
  53. package/dist/index.js.map +0 -1
  54. package/dist/index2.js +0 -3497
  55. package/dist/index2.js.map +0 -1
  56. package/dist/index3.js +0 -296
  57. package/dist/index3.js.map +0 -1
  58. package/dist/index4.js +0 -311
  59. package/dist/index4.js.map +0 -1
  60. package/dist/index5.js +0 -221
  61. package/dist/index5.js.map +0 -1
  62. package/dist/index6.js +0 -730
  63. package/dist/index6.js.map +0 -1
  64. package/dist/renderer.js +0 -2429
  65. package/dist/renderer.js.map +0 -1
  66. package/dist/standard.js +0 -100
  67. package/dist/standard.js.map +0 -1
  68. package/dist/utils.js +0 -61
  69. package/dist/utils.js.map +0 -1
@@ -0,0 +1,555 @@
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 'sade';
16
+ import 'os';
17
+ import 'querystring';
18
+ import 'node:http';
19
+ import 'node:https';
20
+ import 'node:zlib';
21
+ import 'node:stream';
22
+ import 'node:buffer';
23
+ import 'node:util';
24
+ import 'node:url';
25
+ import 'node:net';
26
+ import 'node:fs';
27
+ import 'node:path';
28
+ import 'crypto';
29
+ import './write_tsconfig.js';
30
+ import 'stream';
31
+
32
+ // Vite doesn't expose this so we just copy the list for now
33
+ // https://github.com/vitejs/vite/blob/3edd1af56e980aef56641a5a51cf2932bb580d41/packages/vite/src/node/plugins/css.ts#L96
34
+ const style_pattern = /\.(css|less|sass|scss|styl|stylus|pcss|postcss)$/;
35
+
36
+ const cwd = process.cwd();
37
+
38
+ /**
39
+ * @param {import('types').ValidatedConfig} svelte_config
40
+ * @return {import('vite').Plugin}
41
+ */
42
+ const sveltekit = function (svelte_config) {
43
+ const kit_config = svelte_config.kit;
44
+ return {
45
+ name: 'vite-plugin-svelte-kit',
46
+
47
+ async config() {
48
+ const [vite_config] = deep_merge(
49
+ {
50
+ server: {
51
+ fs: {
52
+ allow: [
53
+ ...new Set([
54
+ kit_config.files.lib,
55
+ kit_config.files.routes,
56
+ kit_config.outDir,
57
+ path__default.resolve(cwd, 'src'),
58
+ path__default.resolve(cwd, 'node_modules'),
59
+ path__default.resolve(searchForWorkspaceRoot(cwd), 'node_modules')
60
+ ])
61
+ ]
62
+ },
63
+ port: 3000,
64
+ strictPort: true,
65
+ watch: {
66
+ ignored: [`${kit_config.outDir}/**`, `!${kit_config.outDir}/generated/**`]
67
+ }
68
+ }
69
+ },
70
+ await kit_config.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(kit_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(kit_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(kit_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: kit_config.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(kit_config.files.routes + path__default.sep)) {
235
+ update_manifest();
236
+ }
237
+ });
238
+ }
239
+
240
+ const assets = kit_config.paths.assets ? SVELTE_KIT_ASSETS : kit_config.paths.base;
241
+ const asset_server = sirv(kit_config.files.assets, {
242
+ dev: true,
243
+ etag: true,
244
+ maxAge: 0,
245
+ extensions: []
246
+ });
247
+
248
+ return () => {
249
+ const serve_static_middleware = vite.middlewares.stack.find(
250
+ (middleware) =>
251
+ /** @type {function} */ (middleware.handle).name === 'viteServeStaticMiddleware'
252
+ );
253
+
254
+ remove_html_middlewares(vite.middlewares);
255
+
256
+ vite.middlewares.use(async (req, res) => {
257
+ try {
258
+ if (!req.url || !req.method) throw new Error('Incomplete request');
259
+
260
+ const base = `${vite.config.server.https ? 'https' : 'http'}://${
261
+ req.headers[':authority'] || req.headers.host
262
+ }`;
263
+
264
+ const decoded = decodeURI(new URL(base + req.url).pathname);
265
+
266
+ if (decoded.startsWith(assets)) {
267
+ const pathname = decoded.slice(assets.length);
268
+ const file = svelte_config.kit.files.assets + pathname;
269
+
270
+ if (fs__default.existsSync(file) && !fs__default.statSync(file).isDirectory()) {
271
+ if (has_correct_case(file, svelte_config.kit.files.assets)) {
272
+ req.url = encodeURI(pathname); // don't need query/hash
273
+ asset_server(req, res);
274
+ return;
275
+ }
276
+ }
277
+ }
278
+
279
+ if (!decoded.startsWith(svelte_config.kit.paths.base)) {
280
+ return not_found(
281
+ res,
282
+ `Not found (did you mean ${svelte_config.kit.paths.base + req.url}?)`
283
+ );
284
+ }
285
+
286
+ /** @type {Partial<import('types').Hooks>} */
287
+ const user_hooks = resolve_entry(svelte_config.kit.files.hooks)
288
+ ? await vite.ssrLoadModule(`/${svelte_config.kit.files.hooks}`, {
289
+ fixStacktrace: false
290
+ })
291
+ : {};
292
+
293
+ const handle = user_hooks.handle || (({ event, resolve }) => resolve(event));
294
+
295
+ /** @type {import('types').Hooks} */
296
+ const hooks = {
297
+ getSession: user_hooks.getSession || (() => ({})),
298
+ handle,
299
+ handleError:
300
+ user_hooks.handleError ||
301
+ (({ /** @type {Error & { frame?: string }} */ error }) => {
302
+ console.error($.bold().red(error.message));
303
+ if (error.frame) {
304
+ console.error($.gray(error.frame));
305
+ }
306
+ if (error.stack) {
307
+ console.error($.gray(error.stack));
308
+ }
309
+ }),
310
+ externalFetch: user_hooks.externalFetch || fetch
311
+ };
312
+
313
+ if (/** @type {any} */ (hooks).getContext) {
314
+ // TODO remove this for 1.0
315
+ throw new Error(
316
+ 'The getContext hook has been removed. See https://kit.svelte.dev/docs/hooks'
317
+ );
318
+ }
319
+
320
+ if (/** @type {any} */ (hooks).serverFetch) {
321
+ // TODO remove this for 1.0
322
+ throw new Error('The serverFetch hook has been renamed to externalFetch.');
323
+ }
324
+
325
+ // TODO the / prefix will probably fail if outDir is outside the cwd (which
326
+ // could be the case in a monorepo setup), but without it these modules
327
+ // can get loaded twice via different URLs, which causes failures. Might
328
+ // require changes to Vite to fix
329
+ const { default: root } = await vite.ssrLoadModule(
330
+ `/${posixify(
331
+ path__default.relative(cwd, `${svelte_config.kit.outDir}/generated/root.svelte`)
332
+ )}`,
333
+ { fixStacktrace: false }
334
+ );
335
+
336
+ const paths = await vite.ssrLoadModule(
337
+ true
338
+ ? `/${posixify(path__default.relative(cwd, `${svelte_config.kit.outDir}/runtime/paths.js`))}`
339
+ : `/@fs${runtime}/paths.js`,
340
+ { fixStacktrace: false }
341
+ );
342
+
343
+ paths.set_paths({
344
+ base: svelte_config.kit.paths.base,
345
+ assets
346
+ });
347
+
348
+ let request;
349
+
350
+ try {
351
+ request = await getRequest(base, req);
352
+ } catch (/** @type {any} */ err) {
353
+ res.statusCode = err.status || 400;
354
+ return res.end(err.reason || 'Invalid request body');
355
+ }
356
+
357
+ const template = load_template(cwd, svelte_config);
358
+
359
+ const rendered = await respond(
360
+ request,
361
+ {
362
+ csp: svelte_config.kit.csp,
363
+ dev: true,
364
+ floc: svelte_config.kit.floc,
365
+ get_stack: (error) => {
366
+ return fix_stack_trace(error);
367
+ },
368
+ handle_error: (error, event) => {
369
+ hooks.handleError({
370
+ error: new Proxy(error, {
371
+ get: (target, property) => {
372
+ if (property === 'stack') {
373
+ return fix_stack_trace(error);
374
+ }
375
+
376
+ return Reflect.get(target, property, target);
377
+ }
378
+ }),
379
+ event,
380
+
381
+ // TODO remove for 1.0
382
+ // @ts-expect-error
383
+ get request() {
384
+ throw new Error(
385
+ 'request in handleError has been replaced with event. See https://github.com/sveltejs/kit/pull/3384 for details'
386
+ );
387
+ }
388
+ });
389
+ },
390
+ hooks,
391
+ hydrate: svelte_config.kit.browser.hydrate,
392
+ manifest,
393
+ method_override: svelte_config.kit.methodOverride,
394
+ paths: {
395
+ base: svelte_config.kit.paths.base,
396
+ assets
397
+ },
398
+ prefix: '',
399
+ prerender: {
400
+ default: svelte_config.kit.prerender.default,
401
+ enabled: svelte_config.kit.prerender.enabled
402
+ },
403
+ read: (file) => fs__default.readFileSync(path__default.join(svelte_config.kit.files.assets, file)),
404
+ root,
405
+ router: svelte_config.kit.browser.router,
406
+ template: ({ head, body, assets, nonce }) => {
407
+ return (
408
+ template
409
+ .replace(/%sveltekit\.assets%/g, assets)
410
+ .replace(/%sveltekit\.nonce%/g, nonce)
411
+ // head and body must be replaced last, in case someone tries to sneak in %sveltekit.assets% etc
412
+ .replace('%sveltekit.head%', () => head)
413
+ .replace('%sveltekit.body%', () => body)
414
+ );
415
+ },
416
+ template_contains_nonce: template.includes('%sveltekit.nonce%'),
417
+ trailing_slash: svelte_config.kit.trailingSlash
418
+ },
419
+ {
420
+ getClientAddress: () => {
421
+ const { remoteAddress } = req.socket;
422
+ if (remoteAddress) return remoteAddress;
423
+ throw new Error('Could not determine clientAddress');
424
+ }
425
+ }
426
+ );
427
+
428
+ if (rendered.status === 404) {
429
+ // @ts-expect-error
430
+ serve_static_middleware.handle(req, res, () => {
431
+ setResponse(res, rendered);
432
+ });
433
+ } else {
434
+ setResponse(res, rendered);
435
+ }
436
+ } catch (e) {
437
+ const error = coalesce_to_error(e);
438
+ vite.ssrFixStacktrace(error);
439
+ res.statusCode = 500;
440
+ res.end(error.stack);
441
+ }
442
+ });
443
+ };
444
+ }
445
+ };
446
+ };
447
+
448
+ /** @param {import('http').ServerResponse} res */
449
+ function not_found(res, message) {
450
+ res.statusCode = 404;
451
+ res.end(message);
452
+ }
453
+
454
+ /**
455
+ * @param {import('connect').Server} server
456
+ */
457
+ function remove_html_middlewares(server) {
458
+ const html_middlewares = [
459
+ 'viteIndexHtmlMiddleware',
460
+ 'vite404Middleware',
461
+ 'viteSpaFallbackMiddleware',
462
+ 'viteServeStaticMiddleware'
463
+ ];
464
+ for (let i = server.stack.length - 1; i > 0; i--) {
465
+ // @ts-expect-error using internals until https://github.com/vitejs/vite/pull/4640 is merged
466
+ if (html_middlewares.includes(server.stack[i].handle.name)) {
467
+ server.stack.splice(i, 1);
468
+ }
469
+ }
470
+ }
471
+
472
+ /**
473
+ * @param {import('vite').ViteDevServer} vite
474
+ * @param {import('vite').ModuleNode} node
475
+ * @param {Set<import('vite').ModuleNode>} deps
476
+ */
477
+ async function find_deps(vite, node, deps) {
478
+ // since `ssrTransformResult.deps` contains URLs instead of `ModuleNode`s, this process is asynchronous.
479
+ // instead of using `await`, we resolve all branches in parallel.
480
+ /** @type {Promise<void>[]} */
481
+ const branches = [];
482
+
483
+ /** @param {import('vite').ModuleNode} node */
484
+ async function add(node) {
485
+ if (!deps.has(node)) {
486
+ deps.add(node);
487
+ await find_deps(vite, node, deps);
488
+ }
489
+ }
490
+
491
+ /** @param {string} url */
492
+ async function add_by_url(url) {
493
+ const node = await vite.moduleGraph.getModuleByUrl(url);
494
+
495
+ if (node) {
496
+ await add(node);
497
+ }
498
+ }
499
+
500
+ if (node.ssrTransformResult) {
501
+ if (node.ssrTransformResult.deps) {
502
+ node.ssrTransformResult.deps.forEach((url) => branches.push(add_by_url(url)));
503
+ }
504
+ } else {
505
+ node.importedModules.forEach((node) => branches.push(add(node)));
506
+ }
507
+
508
+ await Promise.all(branches);
509
+ }
510
+
511
+ /**
512
+ * Determine if a file is being requested with the correct case,
513
+ * to ensure consistent behaviour between dev and prod and across
514
+ * operating systems. Note that we can't use realpath here,
515
+ * because we don't want to follow symlinks
516
+ * @param {string} file
517
+ * @param {string} assets
518
+ * @returns {boolean}
519
+ */
520
+ function has_correct_case(file, assets) {
521
+ if (file === assets) return true;
522
+
523
+ const parent = path__default.dirname(file);
524
+
525
+ if (fs__default.readdirSync(parent).includes(path__default.basename(file))) {
526
+ return has_correct_case(parent, assets);
527
+ }
528
+
529
+ return false;
530
+ }
531
+
532
+ /**
533
+ * @param {import('types').ValidatedConfig} svelte_config
534
+ * @return {import('vite').Plugin[]}
535
+ */
536
+ const svelte = function (svelte_config) {
537
+ return svelte$1({
538
+ ...svelte_config,
539
+ compilerOptions: {
540
+ ...svelte_config.compilerOptions,
541
+ hydratable: !!svelte_config.kit.browser.hydrate
542
+ },
543
+ configFile: false
544
+ });
545
+ };
546
+
547
+ /**
548
+ * @param {import('types').ValidatedConfig} svelte_config
549
+ * @return {import('vite').Plugin[]}
550
+ */
551
+ const plugins = function (svelte_config) {
552
+ return [...svelte(svelte_config), sveltekit(svelte_config)];
553
+ };
554
+
555
+ export { plugins, svelte, sveltekit };