From 9d8376f22d0d8db42327ce422ccb44d32cc91c04 Mon Sep 17 00:00:00 2001 From: Rich Harris Date: Thu, 25 May 2023 13:10:54 -0400 Subject: [PATCH] Generate .d.ts bundle from source (#9992) * use dts-buddy * updates * fixes * tidy up * rename * format * bump dts-buddy * bump * add prepublishOnly script * build types before running check * Invalid should be Failure * ugh * fix * fix * fix * get site building * try this * fix * reinstate code * appease eslint * fix some stuff * prettier * fix * appease typescript * fix * "eslint: so you can remember why you hate programming" * remove unused types * use proper imports for ambient types * jfc eslint fuck OFF * try this * bump dts-buddy * try this * function interfaces need to be types now. who the hell knows why * hide-the-pain-harold.jpg * juggle some stuff * jfc * expose __sveltekit/paths and __sveltekit/environment * exclude internal module declarations * fix docs * Update packages/kit/src/exports/public.d.ts Co-authored-by: Ben McCann <322311+benmccann@users.noreply.github.com> * format --------- Co-authored-by: Rich Harris Co-authored-by: Ben McCann <322311+benmccann@users.noreply.github.com> --- .eslintrc.json | 9 +- .github/workflows/ci.yml | 2 + package.json | 2 +- packages/kit/.gitignore | 1 + packages/kit/package.json | 8 +- packages/kit/scripts/generate-dts.js | 18 + packages/kit/src/core/adapt/builder.js | 6 +- packages/kit/src/core/adapt/builder.spec.js | 2 +- packages/kit/src/core/config/index.js | 4 +- packages/kit/src/core/config/index.spec.js | 4 +- .../kit/src/core/generate_manifest/index.js | 2 +- packages/kit/src/core/postbuild/analyse.js | 2 +- packages/kit/src/core/postbuild/fallback.js | 2 +- packages/kit/src/core/postbuild/prerender.js | 2 +- .../sync/create_manifest_data/index.spec.js | 2 +- packages/kit/src/core/sync/write_ambient.js | 2 +- .../write_types/test/actions/+page.server.js | 56 +- .../core/sync/write_types/test/tsconfig.json | 3 +- packages/kit/src/exports/hooks/sequence.js | 78 ++- .../kit/src/exports/hooks/sequence.spec.js | 10 +- packages/kit/src/exports/index.js | 54 +- packages/kit/src/exports/node/index.js | 15 +- packages/kit/src/exports/node/polyfills.js | 8 + .../index.d.ts => src/exports/public.d.ts} | 219 +++----- packages/kit/src/exports/vite/dev/index.js | 4 +- packages/kit/src/exports/vite/index.js | 5 +- packages/kit/src/internal.d.ts | 16 - packages/kit/src/runtime/app/environment.js | 7 +- packages/kit/src/runtime/app/forms.js | 70 ++- packages/kit/src/runtime/app/navigation.js | 95 ++++ packages/kit/src/runtime/app/stores.js | 31 +- packages/kit/src/runtime/client/client.js | 24 +- packages/kit/src/runtime/client/singletons.js | 4 +- packages/kit/src/runtime/client/types.d.ts | 16 +- packages/kit/src/runtime/control.js | 21 +- packages/kit/src/runtime/server/ambient.d.ts | 6 +- packages/kit/src/runtime/server/cookie.js | 4 +- packages/kit/src/runtime/server/data/index.js | 6 +- packages/kit/src/runtime/server/endpoint.js | 6 +- packages/kit/src/runtime/server/fetch.js | 4 +- packages/kit/src/runtime/server/index.js | 4 +- .../kit/src/runtime/server/page/actions.js | 18 +- packages/kit/src/runtime/server/page/index.js | 6 +- .../kit/src/runtime/server/page/load_data.js | 12 +- .../src/runtime/server/page/load_data.spec.js | 4 +- .../kit/src/runtime/server/page/render.js | 8 +- .../runtime/server/page/respond_with_error.js | 4 +- packages/kit/src/runtime/server/respond.js | 8 +- packages/kit/src/runtime/server/utils.js | 6 +- packages/kit/src/types/ambient-private.d.ts | 11 + packages/kit/src/types/ambient.d.ts | 108 ++++ packages/kit/{ => src}/types/internal.d.ts | 16 +- packages/kit/{ => src}/types/private.d.ts | 11 +- .../types/synthetic/$env+dynamic+private.md | 0 .../types/synthetic/$env+dynamic+public.md | 0 .../types/synthetic/$env+static+private.md | 0 .../types/synthetic/$env+static+public.md | 0 .../kit/{ => src}/types/synthetic/$lib.md | 0 packages/kit/src/utils/routing.js | 2 +- packages/kit/src/utils/streaming.js | 2 +- packages/kit/tsconfig.json | 7 +- packages/kit/types/ambient.d.ts | 486 ------------------ packages/package/test/index.js | 4 +- pnpm-lock.yaml | 49 ++ sites/kit.svelte.dev/scripts/types/index.js | 41 +- .../src/lib/docs/server/render.js | 1 + sites/kit.svelte.dev/vercel.json | 2 +- 67 files changed, 804 insertions(+), 836 deletions(-) create mode 100644 packages/kit/scripts/generate-dts.js rename packages/kit/{types/index.d.ts => src/exports/public.d.ts} (90%) delete mode 100644 packages/kit/src/internal.d.ts create mode 100644 packages/kit/src/types/ambient-private.d.ts create mode 100644 packages/kit/src/types/ambient.d.ts rename packages/kit/{ => src}/types/internal.d.ts (96%) rename packages/kit/{ => src}/types/private.d.ts (96%) rename packages/kit/{ => src}/types/synthetic/$env+dynamic+private.md (100%) rename packages/kit/{ => src}/types/synthetic/$env+dynamic+public.md (100%) rename packages/kit/{ => src}/types/synthetic/$env+static+private.md (100%) rename packages/kit/{ => src}/types/synthetic/$env+static+public.md (100%) rename packages/kit/{ => src}/types/synthetic/$lib.md (100%) delete mode 100644 packages/kit/types/ambient.d.ts diff --git a/.eslintrc.json b/.eslintrc.json index 0d7ea6301105..9501511a710b 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -4,7 +4,14 @@ "env": { "es2022": true }, - "ignorePatterns": ["packages/create-svelte/shared/"], + "ignorePatterns": [ + "packages/create-svelte/shared/", + "packages/kit/test/prerendering/*/build", + "packages/adapter-static/test/apps/*/build", + "packages/adapter-cloudflare/files", + "packages/adapter-netlify/files", + "packages/adapter-node/files" + ], "rules": { "no-undef": "off" } diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index cfded7f93eff..c7a1464302d8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -30,6 +30,7 @@ jobs: cache: pnpm - run: pnpm install --frozen-lockfile - run: pnpm run lint + - run: cd packages/kit && pnpm prepublishOnly - run: pnpm run check Tests: runs-on: ${{ matrix.os }} @@ -136,4 +137,5 @@ jobs: node-version: 16 cache: pnpm - run: pnpm install --frozen-lockfile + - run: cd packages/kit && pnpm prepublishOnly - run: pnpm run test:create-svelte diff --git a/package.json b/package.json index 031e3cadc1fa..e056b3f3d487 100644 --- a/package.json +++ b/package.json @@ -9,7 +9,7 @@ "test:cross-platform:build": "pnpm run --dir packages/kit test:cross-platform:build", "test:vite-ecosystem-ci": "pnpm test --dir packages/kit", "test:create-svelte": "pnpm run --dir packages/create-svelte test", - "check": "pnpm -r check", + "check": "pnpm -r prepublishOnly && pnpm -r check", "lint": "pnpm -r lint && eslint 'packages/**/*.js'", "format": "pnpm -r format", "precommit": "pnpm format && pnpm lint", diff --git a/packages/kit/.gitignore b/packages/kit/.gitignore index b8a64baa8b3f..913a7f9a6583 100644 --- a/packages/kit/.gitignore +++ b/packages/kit/.gitignore @@ -7,6 +7,7 @@ !/src/core/adapt/fixtures/*/.svelte-kit !/test/node_modules /test/apps/basics/test/errors.json +/types .custom-out-dir # these are already ignored by the top level .gitignore diff --git a/packages/kit/package.json b/packages/kit/package.json index a3ff7b4d19d3..a09476eee2a8 100644 --- a/packages/kit/package.json +++ b/packages/kit/package.json @@ -33,6 +33,7 @@ "@types/node": "^16.18.6", "@types/sade": "^1.7.4", "@types/set-cookie-parser": "^2.4.2", + "dts-buddy": "^0.0.9", "marked": "^4.2.3", "rollup": "^3.7.0", "svelte": "^3.56.0", @@ -67,7 +68,8 @@ "test:cross-platform:dev": "pnpm -r --workspace-concurrency 1 --filter=\"./test/**\" test:cross-platform:dev", "test:cross-platform:build": "pnpm test:unit && pnpm -r --workspace-concurrency 1 --filter=\"./test/**\" test:cross-platform:build", "test:unit": "vitest --config kit.vitest.config.js run", - "postinstall": "node postinstall.js" + "postinstall": "node postinstall.js", + "prepublishOnly": "node scripts/generate-dts.js" }, "exports": { "./package.json": "./package.json", @@ -76,15 +78,19 @@ "import": "./src/exports/index.js" }, "./node": { + "types": "./types/index.d.ts", "import": "./src/exports/node/index.js" }, "./node/polyfills": { + "types": "./types/index.d.ts", "import": "./src/exports/node/polyfills.js" }, "./hooks": { + "types": "./types/index.d.ts", "import": "./src/exports/hooks/index.js" }, "./vite": { + "types": "./types/index.d.ts", "import": "./src/exports/vite/index.js" } }, diff --git a/packages/kit/scripts/generate-dts.js b/packages/kit/scripts/generate-dts.js new file mode 100644 index 000000000000..8eeffb5b2f82 --- /dev/null +++ b/packages/kit/scripts/generate-dts.js @@ -0,0 +1,18 @@ +import { createBundle } from 'dts-buddy'; + +createBundle({ + output: 'types/index.d.ts', + modules: { + '@sveltejs/kit': 'src/exports/public.d.ts', + '@sveltejs/kit/hooks': 'src/exports/hooks/index.js', + '@sveltejs/kit/node': 'src/exports/node/index.js', + '@sveltejs/kit/node/polyfills': 'src/exports/node/polyfills.js', + '@sveltejs/kit/vite': 'src/exports/vite/index.js', + '$app/environment': 'src/runtime/app/environment.js', + '$app/forms': 'src/runtime/app/forms.js', + '$app/navigation': 'src/runtime/app/navigation.js', + '$app/paths': 'src/runtime/app/paths.js', + '$app/stores': 'src/runtime/app/stores.js' + }, + include: ['src'] +}); diff --git a/packages/kit/src/core/adapt/builder.js b/packages/kit/src/core/adapt/builder.js index 91ecf525f447..8493fca45152 100644 --- a/packages/kit/src/core/adapt/builder.js +++ b/packages/kit/src/core/adapt/builder.js @@ -24,7 +24,7 @@ const pipe = promisify(pipeline); * prerender_map: import('types').PrerenderMap; * log: import('types').Logger; * }} opts - * @returns {import('types').Builder} + * @returns {import('@sveltejs/kit').Builder} */ export function create_builder({ config, @@ -35,7 +35,7 @@ export function create_builder({ prerender_map, log }) { - /** @type {Map} */ + /** @type {Map} */ const lookup = new Map(); /** @@ -47,7 +47,7 @@ export function create_builder({ server_metadata.routes.get(route.id) ); - /** @type {import('types').RouteDefinition} */ + /** @type {import('@sveltejs/kit').RouteDefinition} */ const facade = { id: route.id, api, diff --git a/packages/kit/src/core/adapt/builder.spec.js b/packages/kit/src/core/adapt/builder.spec.js index 16832bef7d41..483e9fffce2a 100644 --- a/packages/kit/src/core/adapt/builder.spec.js +++ b/packages/kit/src/core/adapt/builder.spec.js @@ -13,7 +13,7 @@ test('copy files', () => { const cwd = join(__dirname, 'fixtures/basic'); const outDir = join(cwd, '.svelte-kit'); - /** @type {import('types').Config} */ + /** @type {import('@sveltejs/kit').Config} */ const mocked = { extensions: ['.svelte'], kit: { diff --git a/packages/kit/src/core/config/index.js b/packages/kit/src/core/config/index.js index aab5520c7087..a6e37d794277 100644 --- a/packages/kit/src/core/config/index.js +++ b/packages/kit/src/core/config/index.js @@ -73,7 +73,7 @@ export async function load_config({ cwd = process.cwd() } = {}) { } /** - * @param {import('types').Config} config + * @param {import('@sveltejs/kit').Config} config * @returns {import('types').ValidatedConfig} */ function process_config(config, { cwd = process.cwd() } = {}) { @@ -95,7 +95,7 @@ function process_config(config, { cwd = process.cwd() } = {}) { } /** - * @param {import('types').Config} config + * @param {import('@sveltejs/kit').Config} config * @returns {import('types').ValidatedConfig} */ export function validate_config(config) { diff --git a/packages/kit/src/core/config/index.spec.js b/packages/kit/src/core/config/index.spec.js index 3388f149b7df..a7fb7a678874 100644 --- a/packages/kit/src/core/config/index.spec.js +++ b/packages/kit/src/core/config/index.spec.js @@ -297,8 +297,8 @@ test('fails if prerender.entries are invalid', () => { /** * @param {string} name - * @param {import('types').KitConfig['paths']} input - * @param {import('types').KitConfig['paths']} output + * @param {import('@sveltejs/kit').KitConfig['paths']} input + * @param {import('@sveltejs/kit').KitConfig['paths']} output */ function validate_paths(name, input, output) { test(name, () => { diff --git a/packages/kit/src/core/generate_manifest/index.js b/packages/kit/src/core/generate_manifest/index.js index 20ef3bd760b3..505dea26c800 100644 --- a/packages/kit/src/core/generate_manifest/index.js +++ b/packages/kit/src/core/generate_manifest/index.js @@ -65,7 +65,7 @@ export function generate_manifest({ build_data, relative_path, routes }) { // prettier-ignore // String representation of - /** @type {import('types').SSRManifest} */ + /** @type {import('@sveltejs/kit').SSRManifest} */ return dedent` { appDir: ${s(build_data.app_dir)}, diff --git a/packages/kit/src/core/postbuild/analyse.js b/packages/kit/src/core/postbuild/analyse.js index 1b82177fba66..64a93478af0e 100644 --- a/packages/kit/src/core/postbuild/analyse.js +++ b/packages/kit/src/core/postbuild/analyse.js @@ -23,7 +23,7 @@ export default forked(import.meta.url, analyse); * }} opts */ async function analyse({ manifest_path, env }) { - /** @type {import('types').SSRManifest} */ + /** @type {import('@sveltejs/kit').SSRManifest} */ const manifest = (await import(pathToFileURL(manifest_path).href)).manifest; /** @type {import('types').ValidatedKitConfig} */ diff --git a/packages/kit/src/core/postbuild/fallback.js b/packages/kit/src/core/postbuild/fallback.js index dbce677d7094..40d6a9a78289 100644 --- a/packages/kit/src/core/postbuild/fallback.js +++ b/packages/kit/src/core/postbuild/fallback.js @@ -27,7 +27,7 @@ async function generate_fallback({ manifest_path, env }) { /** @type {import('types').ServerModule} */ const { Server } = await import(pathToFileURL(`${server_root}/server/index.js`).href); - /** @type {import('types').SSRManifest} */ + /** @type {import('@sveltejs/kit').SSRManifest} */ const manifest = (await import(pathToFileURL(manifest_path).href)).manifest; set_building(true); diff --git a/packages/kit/src/core/postbuild/prerender.js b/packages/kit/src/core/postbuild/prerender.js index fa112ca152bc..e64b7f852364 100644 --- a/packages/kit/src/core/postbuild/prerender.js +++ b/packages/kit/src/core/postbuild/prerender.js @@ -26,7 +26,7 @@ export default forked(import.meta.url, prerender); * }} opts */ async function prerender({ out, manifest_path, metadata, verbose, env }) { - /** @type {import('types').SSRManifest} */ + /** @type {import('@sveltejs/kit').SSRManifest} */ const manifest = (await import(pathToFileURL(manifest_path).href)).manifest; /** @type {import('types').ServerInternalModule} */ diff --git a/packages/kit/src/core/sync/create_manifest_data/index.spec.js b/packages/kit/src/core/sync/create_manifest_data/index.spec.js index cde94b1c1489..758206be45d5 100644 --- a/packages/kit/src/core/sync/create_manifest_data/index.spec.js +++ b/packages/kit/src/core/sync/create_manifest_data/index.spec.js @@ -10,7 +10,7 @@ const cwd = fileURLToPath(new URL('./test', import.meta.url)); /** * @param {string} dir - * @param {import('types').Config} config + * @param {import('@sveltejs/kit').Config} config */ const create = (dir, config = {}) => { const initial = options(config, 'config'); diff --git a/packages/kit/src/core/sync/write_ambient.js b/packages/kit/src/core/sync/write_ambient.js index 500ffe17c772..b55b92f4246f 100644 --- a/packages/kit/src/core/sync/write_ambient.js +++ b/packages/kit/src/core/sync/write_ambient.js @@ -8,7 +8,7 @@ import { write_if_changed } from './utils.js'; // TODO these types should be described in a neutral place, rather than // inside either `packages/kit` or `kit.svelte.dev` -const descriptions_dir = fileURLToPath(new URL('../../../types/synthetic', import.meta.url)); +const descriptions_dir = fileURLToPath(new URL('../../../src/types/synthetic', import.meta.url)); /** @param {string} filename */ function read_description(filename) { diff --git a/packages/kit/src/core/sync/write_types/test/actions/+page.server.js b/packages/kit/src/core/sync/write_types/test/actions/+page.server.js index d3bd4e7fc562..3347ea120fac 100644 --- a/packages/kit/src/core/sync/write_types/test/actions/+page.server.js +++ b/packages/kit/src/core/sync/write_types/test/actions/+page.server.js @@ -1,4 +1,4 @@ -import { fail } from '../../../../../../types/internal.js'; +import { fail } from '../../../../../../src/exports/index.js'; const condition = false; @@ -35,3 +35,57 @@ export const actions = { return fail(400); } }; + +/** + * Ordinarily this would live in a +page.svelte, but to make it easy to run the tests, we put it here. + * The `export` is so that eslint doesn't throw a hissy fit about the unused variable + * @type {import('./.svelte-kit/types/src/core/sync/write_types/test/actions/$types').SubmitFunction} + */ +export const submit = () => { + return ({ result }) => { + if (result.type === 'success') { + // @ts-expect-error does only exist on `failure` result + result.data?.fail; + // @ts-expect-error unknown property + result.data?.something; + + if (result.data && 'success' in result.data) { + result.data.success === true; + // @ts-expect-error should be of type `boolean` + result.data.success === 'success'; + // @ts-expect-error does not exist in this branch + result.data.id; + } + + if (result.data && 'id' in result.data) { + result.data.id === 42; + // @ts-expect-error should be of type `number` + result.data.id === 'John'; + // @ts-expect-error does not exist in this branch + result.data.success; + } + } + + if (result.type === 'failure') { + result.data; + // @ts-expect-error does only exist on `success` result + result.data.success; + // @ts-expect-error unknown property + result.data.unknown; + + if (result.data && 'fail' in result.data) { + result.data.fail === ''; + // @ts-expect-error does not exist in this branch + result.data.reason; + } + + if (result.data && 'reason' in result.data) { + result.data.reason.error.code === 'VALIDATION_FAILED'; + // @ts-expect-error should be a const + result.data.reason.error.code === ''; + // @ts-expect-error does not exist in this branch + result.data.fail; + } + } + }; +}; diff --git a/packages/kit/src/core/sync/write_types/test/tsconfig.json b/packages/kit/src/core/sync/write_types/test/tsconfig.json index 14e7da72eb96..fc3cf322453b 100644 --- a/packages/kit/src/core/sync/write_types/test/tsconfig.json +++ b/packages/kit/src/core/sync/write_types/test/tsconfig.json @@ -10,7 +10,8 @@ "allowSyntheticDefaultImports": true, "baseUrl": ".", "paths": { - "@sveltejs/kit": ["../../../../../types/index"] + "@sveltejs/kit": ["../../../../exports/public"], + "types": ["../../../../types/internal"] } }, "include": ["./**/*.js"], diff --git a/packages/kit/src/exports/hooks/sequence.js b/packages/kit/src/exports/hooks/sequence.js index 267224c11a2d..3a6995f14b8e 100644 --- a/packages/kit/src/exports/hooks/sequence.js +++ b/packages/kit/src/exports/hooks/sequence.js @@ -1,6 +1,70 @@ /** - * @param {...import('types').Handle} handlers - * @returns {import('types').Handle} + * A helper function for sequencing multiple `handle` calls in a middleware-like manner. + * The behavior for the `handle` options is as follows: + * - `transformPageChunk` is applied in reverse order and merged + * - `preload` is applied in forward order, the first option "wins" and no `preload` options after it are called + * - `filterSerializedResponseHeaders` behaves the same as `preload` + * + * ```js + * /// file: src/hooks.server.js + * import { sequence } from '@sveltejs/kit/hooks'; + * + * /// type: import('@sveltejs/kit').Handle + * async function first({ event, resolve }) { + * console.log('first pre-processing'); + * const result = await resolve(event, { + * transformPageChunk: ({ html }) => { + * // transforms are applied in reverse order + * console.log('first transform'); + * return html; + * }, + * preload: () => { + * // this one wins as it's the first defined in the chain + * console.log('first preload'); + * } + * }); + * console.log('first post-processing'); + * return result; + * } + * + * /// type: import('@sveltejs/kit').Handle + * async function second({ event, resolve }) { + * console.log('second pre-processing'); + * const result = await resolve(event, { + * transformPageChunk: ({ html }) => { + * console.log('second transform'); + * return html; + * }, + * preload: () => { + * console.log('second preload'); + * }, + * filterSerializedResponseHeaders: () => { + * // this one wins as it's the first defined in the chain + * console.log('second filterSerializedResponseHeaders'); + * } + * }); + * console.log('second post-processing'); + * return result; + * } + * + * export const handle = sequence(first, second); + * ``` + * + * The example above would print: + * + * ``` + * first pre-processing + * first preload + * second pre-processing + * second filterSerializedResponseHeaders + * second transform + * first transform + * second post-processing + * first post-processing + * ``` + * + * @param {...import('@sveltejs/kit').Handle} handlers The chain of `handle` functions + * @returns {import('@sveltejs/kit').Handle} */ export function sequence(...handlers) { const length = handlers.length; @@ -11,8 +75,8 @@ export function sequence(...handlers) { /** * @param {number} i - * @param {import('types').RequestEvent} event - * @param {import('types').ResolveOptions | undefined} parent_options + * @param {import('@sveltejs/kit').RequestEvent} event + * @param {import('@sveltejs/kit').ResolveOptions | undefined} parent_options * @returns {import('types').MaybePromise} */ function apply_handle(i, event, parent_options) { @@ -21,7 +85,7 @@ export function sequence(...handlers) { return handle({ event, resolve: (event, options) => { - /** @type {import('types').ResolveOptions['transformPageChunk']} */ + /** @type {import('@sveltejs/kit').ResolveOptions['transformPageChunk']} */ const transformPageChunk = async ({ html, done }) => { if (options?.transformPageChunk) { html = (await options.transformPageChunk({ html, done })) ?? ''; @@ -34,12 +98,12 @@ export function sequence(...handlers) { return html; }; - /** @type {import('types').ResolveOptions['filterSerializedResponseHeaders']} */ + /** @type {import('@sveltejs/kit').ResolveOptions['filterSerializedResponseHeaders']} */ const filterSerializedResponseHeaders = parent_options?.filterSerializedResponseHeaders ?? options?.filterSerializedResponseHeaders; - /** @type {import('types').ResolveOptions['preload']} */ + /** @type {import('@sveltejs/kit').ResolveOptions['preload']} */ const preload = parent_options?.preload ?? options?.preload; return i < length - 1 diff --git a/packages/kit/src/exports/hooks/sequence.spec.js b/packages/kit/src/exports/hooks/sequence.spec.js index da5e4e8d1b2f..a4912bdd5790 100644 --- a/packages/kit/src/exports/hooks/sequence.spec.js +++ b/packages/kit/src/exports/hooks/sequence.spec.js @@ -29,7 +29,7 @@ test('applies handlers in sequence', async () => { } ); - const event = /** @type {import('types').RequestEvent} */ ({}); + const event = /** @type {import('@sveltejs/kit').RequestEvent} */ ({}); const response = new Response(); assert.equal(await handler({ event, resolve: () => response }), response); @@ -47,7 +47,7 @@ test('uses transformPageChunk option passed to non-terminal handle function', as async ({ event, resolve }) => resolve(event) ); - const event = /** @type {import('types').RequestEvent} */ ({}); + const event = /** @type {import('@sveltejs/kit').RequestEvent} */ ({}); const response = await handler({ event, resolve: async (_event, opts = {}) => { @@ -84,7 +84,7 @@ test('merges transformPageChunk option', async () => { } ); - const event = /** @type {import('types').RequestEvent} */ ({}); + const event = /** @type {import('@sveltejs/kit').RequestEvent} */ ({}); const response = await handler({ event, resolve: async (_event, opts = {}) => { @@ -117,7 +117,7 @@ test('uses first defined preload option', async () => { } ); - const event = /** @type {import('types').RequestEvent} */ ({}); + const event = /** @type {import('@sveltejs/kit').RequestEvent} */ ({}); const response = await handler({ event, resolve: async (_event, opts = {}) => { @@ -150,7 +150,7 @@ test('uses first defined filterSerializedResponseHeaders option', async () => { } ); - const event = /** @type {import('types').RequestEvent} */ ({}); + const event = /** @type {import('@sveltejs/kit').RequestEvent} */ ({}); const response = await handler({ event, resolve: async (_event, opts = {}) => { diff --git a/packages/kit/src/exports/index.js b/packages/kit/src/exports/index.js index 3050bdb91d30..b1d50790c444 100644 --- a/packages/kit/src/exports/index.js +++ b/packages/kit/src/exports/index.js @@ -2,22 +2,42 @@ import { HttpError, Redirect, ActionFailure } from '../runtime/control.js'; import { BROWSER, DEV } from 'esm-env'; import { get_route_segments } from '../utils/routing.js'; -// For some reason we need to type the params as well here, -// JSdoc doesn't seem to like @type with function overloads /** - * @type {import('@sveltejs/kit').error} + * @overload * @param {number} status - * @param {any} message + * @param {App.Error} body + * @return {HttpError} */ -export function error(status, message) { + +/** + * @overload + * @param {number} status + * @param {{ message: string } extends App.Error ? App.Error | string | undefined : never} [body] + * @return {HttpError} + */ + +/** + * Creates an `HttpError` object with an HTTP status code and an optional message. + * This object, if thrown during request handling, will cause SvelteKit to + * return an error response without invoking `handleError`. + * Make sure you're not catching the thrown error, which would prevent SvelteKit from handling it. + * @param {number} status The [HTTP status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#client_error_responses). Must be in the range 400-599. + * @param {{ message: string } extends App.Error ? App.Error | string | undefined : never} body An object that conforms to the App.Error type. If a string is passed, it will be used as the message property. + */ +export function error(status, body) { if ((!BROWSER || DEV) && (isNaN(status) || status < 400 || status > 599)) { throw new Error(`HTTP error status codes must be between 400 and 599 — ${status} is invalid`); } - return new HttpError(status, message); + return new HttpError(status, body); } -/** @type {import('@sveltejs/kit').redirect} */ +/** + * Create a `Redirect` object. If thrown during request handling, SvelteKit will return a redirect response. + * Make sure you're not catching the thrown redirect, which would prevent SvelteKit from handling it. + * @param {300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308} status The [HTTP status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#redirection_messages). Must be in the range 300-308. + * @param {string} location The location to redirect to. + */ export function redirect(status, location) { if ((!BROWSER || DEV) && (isNaN(status) || status < 300 || status > 308)) { throw new Error('Invalid status code'); @@ -26,7 +46,11 @@ export function redirect(status, location) { return new Redirect(status, location); } -/** @type {import('@sveltejs/kit').json} */ +/** + * Create a JSON `Response` object from the supplied data. + * @param {any} data The value that will be serialized as JSON. + * @param {ResponseInit} [init] Options such as `status` and `headers` that will be added to the response. `Content-Type: application/json` and `Content-Length` headers will be added automatically. + */ export function json(data, init) { // TODO deprecate this in favour of `Response.json` when it's // more widely supported @@ -52,7 +76,11 @@ export function json(data, init) { const encoder = new TextEncoder(); -/** @type {import('@sveltejs/kit').text} */ +/** + * Create a `Response` object from the supplied body. + * @param {string} body The value that will be used as-is. + * @param {ResponseInit} [init] Options such as `status` and `headers` that will be added to the response. A `Content-Length` header will be added automatically. + */ export function text(body, init) { const headers = new Headers(init?.headers); if (!headers.has('content-length')) { @@ -66,9 +94,11 @@ export function text(body, init) { } /** - * Generates an `ActionFailure` object. - * @param {number} status - * @param {Record | undefined} [data] + * Create an `ActionFailure` object. + * @template {Record | undefined} [T=undefined] + * @param {number} status The [HTTP status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#client_error_responses). Must be in the range 400-599. + * @param {T} [data] Data associated with the failure (e.g. validation errors) + * @returns {ActionFailure} */ export function fail(status, data) { return new ActionFailure(status, data); diff --git a/packages/kit/src/exports/node/index.js b/packages/kit/src/exports/node/index.js index 9356cdd9d76a..1f4175206814 100644 --- a/packages/kit/src/exports/node/index.js +++ b/packages/kit/src/exports/node/index.js @@ -92,7 +92,14 @@ function get_raw_body(req, body_size_limit) { }); } -/** @type {import('@sveltejs/kit/node').getRequest} */ +/** + * @param {{ + * request: import('http').IncomingMessage; + * base: string; + * bodySizeLimit?: number; + * }} options + * @returns {Promise} + */ export async function getRequest({ request, base, bodySizeLimit }) { return new Request(base + request.url, { // @ts-expect-error @@ -103,7 +110,11 @@ export async function getRequest({ request, base, bodySizeLimit }) { }); } -/** @type {import('@sveltejs/kit/node').setResponse} */ +/** + * @param {import('http').ServerResponse} res + * @param {Response} response + * @returns {Promise} + */ export async function setResponse(res, response) { for (const [key, value] of response.headers) { try { diff --git a/packages/kit/src/exports/node/polyfills.js b/packages/kit/src/exports/node/polyfills.js index 950c645258bc..d1bb58d72b74 100644 --- a/packages/kit/src/exports/node/polyfills.js +++ b/packages/kit/src/exports/node/polyfills.js @@ -22,6 +22,14 @@ const globals = { // exported for dev/preview and node environments // TODO: remove this once we only support Node 18.11+ (the version multipart/form-data was added) +/** + * Make various web APIs available as globals: + * - `crypto` + * - `fetch` + * - `Headers` + * - `Request` + * - `Response` + */ export function installPolyfills() { for (const name in globals) { Object.defineProperty(globalThis, name, { diff --git a/packages/kit/types/index.d.ts b/packages/kit/src/exports/public.d.ts similarity index 90% rename from packages/kit/types/index.d.ts rename to packages/kit/src/exports/public.d.ts index 7ef60082de58..b6108a1d0a54 100644 --- a/packages/kit/types/index.d.ts +++ b/packages/kit/src/exports/public.d.ts @@ -1,7 +1,6 @@ -/// -/// - -import './ambient.js'; +import 'svelte'; // pick up `declare module "*.svelte"` +import 'vite/client'; // pick up `declare module "*.jpg"`, etc. +import '../types/ambient.js'; import { CompileOptions } from 'svelte/types/compiler/interfaces'; import { @@ -16,13 +15,14 @@ import { PrerenderMissingIdHandlerValue, PrerenderOption, RequestOptions, - RouteSegment, - UniqueInterface -} from './private.js'; -import { BuildData, SSRNodeLoader, SSRRoute, ValidatedConfig } from './internal.js'; + RouteSegment +} from '../types/private.js'; +import { ActionFailure } from '../runtime/control.js'; +import { BuildData, SSRNodeLoader, SSRRoute, ValidatedConfig } from 'types'; import type { PluginOptions } from '@sveltejs/vite-plugin-svelte'; -export { PrerenderOption } from './private.js'; +export { PrerenderOption } from '../types/private.js'; +export { ActionFailure }; /** * [Adapters](https://kit.svelte.dev/docs/adapters) are responsible for taking the production build and turning it into something that can be deployed to a platform of your choosing. @@ -631,12 +631,10 @@ export interface KitConfig { * It receives an `event` object representing the request and a function called `resolve`, which renders the route and generates a `Response`. * This allows you to modify response headers or bodies, or bypass SvelteKit entirely (for implementing routes programmatically, for example). */ -export interface Handle { - (input: { - event: RequestEvent; - resolve(event: RequestEvent, opts?: ResolveOptions): MaybePromise; - }): MaybePromise; -} +export type Handle = (input: { + event: RequestEvent; + resolve(event: RequestEvent, opts?: ResolveOptions): MaybePromise; +}) => MaybePromise; /** * The server-side [`handleError`](https://kit.svelte.dev/docs/hooks#shared-hooks-handleerror) hook runs when an unexpected error is thrown while responding to a request. @@ -644,9 +642,10 @@ export interface Handle { * If an unexpected error is thrown during loading or rendering, this function will be called with the error and the event. * Make sure that this function _never_ throws an error. */ -export interface HandleServerError { - (input: { error: unknown; event: RequestEvent }): MaybePromise; -} +export type HandleServerError = (input: { + error: unknown; + event: RequestEvent; +}) => MaybePromise; /** * The client-side [`handleError`](https://kit.svelte.dev/docs/hooks#shared-hooks-handleerror) hook runs when an unexpected error is thrown while navigating. @@ -654,30 +653,31 @@ export interface HandleServerError { * If an unexpected error is thrown during loading or the following render, this function will be called with the error and the event. * Make sure that this function _never_ throws an error. */ -export interface HandleClientError { - (input: { error: unknown; event: NavigationEvent }): MaybePromise; -} +export type HandleClientError = (input: { + error: unknown; + event: NavigationEvent; +}) => MaybePromise; /** * The [`handleFetch`](https://kit.svelte.dev/docs/hooks#server-hooks-handlefetch) hook allows you to modify (or replace) a `fetch` request that happens inside a `load` function that runs on the server (or during pre-rendering) */ -export interface HandleFetch { - (input: { event: RequestEvent; request: Request; fetch: typeof fetch }): MaybePromise; -} +export type HandleFetch = (input: { + event: RequestEvent; + request: Request; + fetch: typeof fetch; +}) => MaybePromise; /** * The generic form of `PageLoad` and `LayoutLoad`. You should import those from `./$types` (see [generated types](https://kit.svelte.dev/docs/types#generated-types)) * rather than using `Load` directly. */ -export interface Load< +export type Load< Params extends Partial> = Partial>, InputData extends Record | null = Record | null, ParentData extends Record = Record, OutputData extends Record | void = Record | void, RouteId extends string | null = string | null -> { - (event: LoadEvent): MaybePromise; -} +> = (event: LoadEvent) => MaybePromise; /** * The generic form of `PageLoadEvent` and `LayoutLoadEvent`. You should import those from `./$types` (see [generated types](https://kit.svelte.dev/docs/types#generated-types)) @@ -931,9 +931,7 @@ export interface Page< /** * The shape of a param matcher. See [matching](https://kit.svelte.dev/docs/advanced-routing#matching) for more info. */ -export interface ParamMatcher { - (param: string): boolean; -} +export type ParamMatcher = (param: string) => boolean; export interface RequestEvent< Params extends Partial> = Partial>, @@ -1021,12 +1019,10 @@ export interface RequestEvent< * * It receives `Params` as the first generic argument, which you can skip by using [generated types](https://kit.svelte.dev/docs/types#generated-types) instead. */ -export interface RequestHandler< +export type RequestHandler< Params extends Partial> = Partial>, RouteId extends string | null = string | null -> { - (event: RequestEvent): MaybePromise; -} +> = (event: RequestEvent) => MaybePromise; export interface ResolveOptions { /** @@ -1095,14 +1091,12 @@ export interface SSRManifest { * The generic form of `PageServerLoad` and `LayoutServerLoad`. You should import those from `./$types` (see [generated types](https://kit.svelte.dev/docs/types#generated-types)) * rather than using `ServerLoad` directly. */ -export interface ServerLoad< +export type ServerLoad< Params extends Partial> = Partial>, ParentData extends Record = Record, OutputData extends Record | void = Record | void, RouteId extends string | null = string | null -> { - (event: ServerLoadEvent): MaybePromise; -} +> = (event: ServerLoadEvent) => MaybePromise; export interface ServerLoadEvent< Params extends Partial> = Partial>, @@ -1159,13 +1153,11 @@ export interface ServerLoadEvent< * Shape of a form action method that is part of `export const actions = {..}` in `+page.server.js`. * See [form actions](https://kit.svelte.dev/docs/form-actions) for more information. */ -export interface Action< +export type Action< Params extends Partial> = Partial>, OutputData extends Record | void = Record | void, RouteId extends string | null = string | null -> { - (event: RequestEvent): MaybePromise; -} +> = (event: RequestEvent) => MaybePromise; /** * Shape of the `export const actions = {..}` object in `+page.server.js`. @@ -1196,21 +1188,6 @@ export type ActionResult< | { type: 'redirect'; status: number; location: string } | { type: 'error'; status?: number; error: any }; -/** - * Creates an `HttpError` object with an HTTP status code and an optional message. - * This object, if thrown during request handling, will cause SvelteKit to - * return an error response without invoking `handleError`. - * Make sure you're not catching the thrown error, which would prevent SvelteKit from handling it. - * @param status The [HTTP status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#client_error_responses). Must be in the range 400-599. - * @param body An object that conforms to the App.Error type. If a string is passed, it will be used as the message property. - */ -export function error(status: number, body: App.Error): HttpError; -export function error( - status: number, - // this overload ensures you can omit the argument or pass in a string if App.Error is of type { message: string } - body?: { message: string } extends App.Error ? App.Error | string | undefined : never -): HttpError; - /** * The object returned by the [`error`](https://kit.svelte.dev/docs/modules#sveltejs-kit-error) function. */ @@ -1221,17 +1198,6 @@ export interface HttpError { body: App.Error; } -/** - * Create a `Redirect` object. If thrown during request handling, SvelteKit will return a redirect response. - * Make sure you're not catching the thrown redirect, which would prevent SvelteKit from handling it. - * @param status The [HTTP status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#redirection_messages). Must be in the range 300-308. - * @param location The location to redirect to. - */ -export function redirect( - status: 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308, - location: string -): Redirect; - /** * The object returned by the [`redirect`](https://kit.svelte.dev/docs/modules#sveltejs-kit-redirect) function */ @@ -1242,66 +1208,50 @@ export interface Redirect { location: string; } -/** - * Create a JSON `Response` object from the supplied data. - * @param data The value that will be serialized as JSON. - * @param init Options such as `status` and `headers` that will be added to the response. `Content-Type: application/json` and `Content-Length` headers will be added automatically. - */ -export function json(data: any, init?: ResponseInit): Response; - -/** - * Create a `Response` object from the supplied body. - * @param body The value that will be used as-is. - * @param init Options such as `status` and `headers` that will be added to the response. A `Content-Length` header will be added automatically. - */ -export function text(body: string, init?: ResponseInit): Response; - -/** - * Create an `ActionFailure` object. - * @param status The [HTTP status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#client_error_responses). Must be in the range 400-599. - * @param data Data associated with the failure (e.g. validation errors) - */ -export function fail | undefined = undefined>( - status: number, - data?: T -): ActionFailure; - -/** - * The object returned by the [`fail`](https://kit.svelte.dev/docs/modules#sveltejs-kit-fail) function - */ -export interface ActionFailure | undefined = undefined> - extends UniqueInterface { - /** The [HTTP status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#client_error_responses), in the range 400-599. */ - status: number; - /** Data associated with the failure (e.g. validation errors) */ - data: T; -} - -export interface SubmitFunction< +export type SubmitFunction< Success extends Record | undefined = Record, Failure extends Record | undefined = Record -> { - (input: { - action: URL; - data: FormData; - form: HTMLFormElement; - controller: AbortController; - submitter: HTMLElement | null; - cancel(): void; - }): MaybePromise< - | void - | ((opts: { - form: HTMLFormElement; - action: URL; - result: ActionResult; - /** - * Call this to get the default behavior of a form submission response. - * @param options Set `reset: false` if you don't want the `
` values to be reset after a successful submission. - */ - update(options?: { reset: boolean }): Promise; - }) => void) - >; -} +> = (input: { + action: URL; + /** + * use `formData` instead of `data` + * @deprecated + */ + data: FormData; + formData: FormData; + /** + * use `formElement` instead of `form` + * @deprecated + */ + form: HTMLFormElement; + formElement: HTMLFormElement; + controller: AbortController; + submitter: HTMLElement | null; + cancel(): void; +}) => MaybePromise< + | void + | ((opts: { + /** + * use `formData` instead of `data` + * @deprecated + */ + data: FormData; + formData: FormData; + /** + * use `formElement` instead of `form` + * @deprecated + */ + form: HTMLFormElement; + formElement: HTMLFormElement; + action: URL; + result: ActionResult; + /** + * Call this to get the default behavior of a form submission response. + * @param options Set `reset: false` if you don't want the `` values to be reset after a successful submission. + */ + update(options?: { reset: boolean }): Promise; + }) => void) +>; /** * The type of `export const snapshot` exported from a page or layout component. @@ -1311,17 +1261,4 @@ export interface Snapshot { restore: (snapshot: T) => void; } -/** - * Populate a route ID with params to resolve a pathname. - * @example - * ```js - * resolvePath( - * `/blog/[slug]/[...somethingElse]`, - * { - * slug: 'hello-world', - * somethingElse: 'something/else' - * } - * ); // `/blog/hello-world/something/else` - * ``` - */ -export function resolvePath(id: string, params: Record): string; +export * from './index.js'; diff --git a/packages/kit/src/exports/vite/dev/index.js b/packages/kit/src/exports/vite/dev/index.js index 09a02cb7fde2..0c9ea37c4444 100644 --- a/packages/kit/src/exports/vite/dev/index.js +++ b/packages/kit/src/exports/vite/dev/index.js @@ -44,7 +44,7 @@ export async function dev(vite, vite_config, svelte_config) { /** @type {import('types').ManifestData} */ let manifest_data; - /** @type {import('types').SSRManifest} */ + /** @type {import('@sveltejs/kit').SSRManifest} */ let manifest; /** @type {Error | null} */ @@ -226,7 +226,7 @@ export async function dev(vite, vite_config, svelte_config) { }) ), matchers: async () => { - /** @type {Record} */ + /** @type {Record} */ const matchers = {}; for (const key in manifest_data.matchers) { diff --git a/packages/kit/src/exports/vite/index.js b/packages/kit/src/exports/vite/index.js index ede34d578308..a26ca5ba3805 100644 --- a/packages/kit/src/exports/vite/index.js +++ b/packages/kit/src/exports/vite/index.js @@ -111,7 +111,10 @@ const warning_preprocessor = { } }; -/** @return {Promise} */ +/** + * Returns the SvelteKit Vite plugins. + * @returns {Promise} + */ export async function sveltekit() { const svelte_config = await load_config(); diff --git a/packages/kit/src/internal.d.ts b/packages/kit/src/internal.d.ts deleted file mode 100644 index c248d9d528f6..000000000000 --- a/packages/kit/src/internal.d.ts +++ /dev/null @@ -1,16 +0,0 @@ -/** Internal version of $app/environment */ -declare module '__sveltekit/environment' { - export const building: boolean; - export const version: string; - export function set_building(): void; -} - -/** Internal version of $app/paths */ -declare module '__sveltekit/paths' { - export let base: '' | `/${string}`; - export let assets: '' | `https://${string}` | `http://${string}` | '/_svelte_kit_assets'; - export let relative: boolean | undefined; // TODO in 2.0, make this a `boolean` that defaults to `true` - export function reset(): void; - export function override(paths: { base: string; assets: string }): void; - export function set_assets(path: string): void; -} diff --git a/packages/kit/src/runtime/app/environment.js b/packages/kit/src/runtime/app/environment.js index 0d11daf31b1b..8393ee6dbda6 100644 --- a/packages/kit/src/runtime/app/environment.js +++ b/packages/kit/src/runtime/app/environment.js @@ -1,13 +1,12 @@ import { BROWSER, DEV } from 'esm-env'; +export { building, version } from '__sveltekit/environment'; /** - * @type {import('$app/environment').browser} + * `true` if the app is running in the browser. */ export const browser = BROWSER; /** - * @type {import('$app/environment').dev} + * Whether the dev server is running. This is not guaranteed to correspond to `NODE_ENV` or `MODE`. */ export const dev = DEV; - -export { building, version } from '__sveltekit/environment'; diff --git a/packages/kit/src/runtime/app/forms.js b/packages/kit/src/runtime/app/forms.js index 30858235032f..f6a42c745c6f 100644 --- a/packages/kit/src/runtime/app/forms.js +++ b/packages/kit/src/runtime/app/forms.js @@ -1,11 +1,46 @@ import * as devalue from 'devalue'; -import { DEV } from 'esm-env'; -import { client_method } from '../client/singletons.js'; +import { BROWSER, DEV } from 'esm-env'; +import { client } from '../client/singletons.js'; import { invalidateAll } from './navigation.js'; -export const applyAction = client_method('apply_action'); +/** + * This action updates the `form` property of the current page with the given data and updates `$page.status`. + * In case of an error, it redirects to the nearest error page. + * @template {Record | undefined} Success + * @template {Record | undefined} Failure + * @param {import('@sveltejs/kit').ActionResult} result + * @returns {Promise} + */ +export function applyAction(result) { + if (BROWSER) { + return client.apply_action(result); + } else { + throw new Error('Cannot call applyAction(...) on the server'); + } +} -/** @type {import('$app/forms').deserialize} */ +/** + * Use this function to deserialize the response from a form submission. + * Usage: + * + * ```js + * import { deserialize } from '$app/forms'; + * + * async function handleSubmit(event) { + * const response = await fetch('/form?/action', { + * method: 'POST', + * body: new FormData(event.target) + * }); + * + * const result = deserialize(await response.text()); + * // ... + * } + * ``` + * @template {Record | undefined} Success + * @template {Record | undefined} Failure + * @param {string} result + * @returns {import('@sveltejs/kit').ActionResult} + */ export function deserialize(result) { const parsed = JSON.parse(result); if (parsed.data) { @@ -39,7 +74,28 @@ function clone(element) { return /** @type {T} */ (HTMLElement.prototype.cloneNode.call(element)); } -/** @type {import('$app/forms').enhance} */ +/** + * This action enhances a `` element that otherwise would work without JavaScript. + * + * The `submit` function is called upon submission with the given FormData and the `action` that should be triggered. + * If `cancel` is called, the form will not be submitted. + * You can use the abort `controller` to cancel the submission in case another one starts. + * If a function is returned, that function is called with the response from the server. + * If nothing is returned, the fallback will be used. + * + * If this function or its return value isn't set, it + * - falls back to updating the `form` prop with the returned data if the action is one same page as the form + * - updates `$page.status` + * - resets the `` element and invalidates all data in case of successful submission with no redirect response + * - redirects in case of a redirect response + * - redirects to the nearest error page in case of an unexpected error + * + * If you provide a custom function with a callback and want to use the default behavior, invoke `update` in your callback. + * @template {Record | undefined} Success + * @template {Record | undefined} Failure + * @param {HTMLFormElement} form_element The form element + * @param {import('@sveltejs/kit').SubmitFunction} submit Submit callback + */ export function enhance(form_element, submit = () => {}) { if (DEV && clone(form_element).method !== 'post') { throw new Error('use:enhance can only be used on fields with method="POST"'); @@ -48,7 +104,7 @@ export function enhance(form_element, submit = () => {}) { /** * @param {{ * action: URL; - * result: import('types').ActionResult; + * result: import('@sveltejs/kit').ActionResult; * reset?: boolean * }} opts */ @@ -127,7 +183,7 @@ export function enhance(form_element, submit = () => {}) { })) ?? fallback_callback; if (cancelled) return; - /** @type {import('types').ActionResult} */ + /** @type {import('@sveltejs/kit').ActionResult} */ let result; try { diff --git a/packages/kit/src/runtime/app/navigation.js b/packages/kit/src/runtime/app/navigation.js index 30fa41375531..bea51d1b12c1 100644 --- a/packages/kit/src/runtime/app/navigation.js +++ b/packages/kit/src/runtime/app/navigation.js @@ -1,17 +1,112 @@ import { client_method } from '../client/singletons.js'; +/** + * If called when the page is being updated following a navigation (in `onMount` or `afterNavigate` or an action, for example), this disables SvelteKit's built-in scroll handling. + * This is generally discouraged, since it breaks user expectations. + * @returns {void} + */ export const disableScrollHandling = /* @__PURE__ */ client_method('disable_scroll_handling'); +/** + * Returns a Promise that resolves when SvelteKit navigates (or fails to navigate, in which case the promise rejects) to the specified `url`. + * For external URLs, use `window.location = url` instead of calling `goto(url)`. + * + * @type {(url: string | URL, opts?: { + * replaceState?: boolean; + * noScroll?: boolean; + * keepFocus?: boolean; + * invalidateAll?: boolean; + * state?: any + * }) => Promise} + * @param {string | URL} url Where to navigate to. Note that if you've set [`config.kit.paths.base`](https://kit.svelte.dev/docs/configuration#paths) and the URL is root-relative, you need to prepend the base path if you want to navigate within the app. + * @param {Object} [opts] Options related to the navigation + * @param {boolean} [opts.replaceState] If `true`, will replace the current `history` entry rather than creating a new one with `pushState` + * @param {boolean} [opts.noScroll] If `true`, the browser will maintain its scroll position rather than scrolling to the top of the page after navigation + * @param {boolean} [opts.keepFocus] If `true`, the currently focused element will retain focus after navigation. Otherwise, focus will be reset to the body + * @param {boolean} [invalidateAll] If `true`, all `load` functions of the page will be rerun. See https://kit.svelte.dev/docs/load#rerunning-load-functions for more info on invalidation. + * @param {any} [opts.state] The state of the new/updated history entry + * @returns {Promise} + */ export const goto = /* @__PURE__ */ client_method('goto'); +/** + * Causes any `load` functions belonging to the currently active page to re-run if they depend on the `url` in question, via `fetch` or `depends`. Returns a `Promise` that resolves when the page is subsequently updated. + * + * If the argument is given as a `string` or `URL`, it must resolve to the same URL that was passed to `fetch` or `depends` (including query parameters). + * To create a custom identifier, use a string beginning with `[a-z]+:` (e.g. `custom:state`) — this is a valid URL. + * + * The `function` argument can be used define a custom predicate. It receives the full `URL` and causes `load` to rerun if `true` is returned. + * This can be useful if you want to invalidate based on a pattern instead of a exact match. + * + * ```ts + * // Example: Match '/path' regardless of the query parameters + * import { invalidate } from '$app/navigation'; + * + * invalidate((url) => url.pathname === '/path'); + * ``` + * @type {(url: string | URL | ((url: URL) => boolean)) => Promise} + * @param {string | URL | ((url: URL) => boolean)} url The invalidated URL + * @returns {Promise} + */ export const invalidate = /* @__PURE__ */ client_method('invalidate'); +/** + * Causes all `load` functions belonging to the currently active page to re-run. Returns a `Promise` that resolves when the page is subsequently updated. + * @type {() => Promise} + * @returns {Promise} + */ export const invalidateAll = /* @__PURE__ */ client_method('invalidate_all'); +/** + * Programmatically preloads the given page, which means + * 1. ensuring that the code for the page is loaded, and + * 2. calling the page's load function with the appropriate options. + * + * This is the same behaviour that SvelteKit triggers when the user taps or mouses over an `` element with `data-sveltekit-preload-data`. + * If the next navigation is to `href`, the values returned from load will be used, making navigation instantaneous. + * Returns a Promise that resolves when the preload is complete. + * + * @type {(href: string) => Promise} + * @param {string} href Page to preload + * @returns {Promise} + */ export const preloadData = /* @__PURE__ */ client_method('preload_data'); +/** + * Programmatically imports the code for routes that haven't yet been fetched. + * Typically, you might call this to speed up subsequent navigation. + * + * You can specify routes by any matching pathname such as `/about` (to match `src/routes/about/+page.svelte`) or `/blog/*` (to match `src/routes/blog/[slug]/+page.svelte`). + * + * Unlike `preloadData`, this won't call `load` functions. + * Returns a Promise that resolves when the modules have been imported. + * + * @type {(...urls: string[]) => Promise} + * @param {...string[]} urls + * @returns {Promise} + */ export const preloadCode = /* @__PURE__ */ client_method('preload_code'); +/** + * A navigation interceptor that triggers before we navigate to a new URL, whether by clicking a link, calling `goto(...)`, or using the browser back/forward controls. + * Calling `cancel()` will prevent the navigation from completing. If the navigation would have directly unloaded the current page, calling `cancel` will trigger the native + * browser unload confirmation dialog. In these cases, `navigation.willUnload` is `true`. + * + * When a navigation isn't client side, `navigation.to.route.id` will be `null`. + * + * `beforeNavigate` must be called during a component initialization. It remains active as long as the component is mounted. + * @type {(callback: (navigation: import('@sveltejs/kit').BeforeNavigate) => void) => void} + * @param {(navigation: import('@sveltejs/kit').BeforeNavigate) => void} callback + * @returns {void} + */ export const beforeNavigate = /* @__PURE__ */ client_method('before_navigate'); +/** + * A lifecycle function that runs the supplied `callback` when the current component mounts, and also whenever we navigate to a new URL. + * + * `afterNavigate` must be called during a component initialization. It remains active as long as the component is mounted. + * @type {(callback: (navigation: import('@sveltejs/kit').AfterNavigate) => void) => void} + * @param {(navigation: import('@sveltejs/kit').AfterNavigate) => void} callback + * @returns {void} + */ export const afterNavigate = /* @__PURE__ */ client_method('after_navigate'); diff --git a/packages/kit/src/runtime/app/stores.js b/packages/kit/src/runtime/app/stores.js index 67500ba8169a..23ee5cd6cbf0 100644 --- a/packages/kit/src/runtime/app/stores.js +++ b/packages/kit/src/runtime/app/stores.js @@ -3,32 +3,48 @@ import { browser } from './environment.js'; import { stores as browser_stores } from '../client/singletons.js'; /** - * @type {import('$app/stores').getStores} + * A function that returns all of the contextual stores. On the server, this must be called during component initialization. + * Only use this if you need to defer store subscription until after the component has mounted, for some reason. */ export const getStores = () => { const stores = browser ? browser_stores : getContext('__svelte__'); return { + /** @type {typeof page} */ page: { subscribe: stores.page.subscribe }, + /** @type {typeof navigating} */ navigating: { subscribe: stores.navigating.subscribe }, + /** @type {typeof updated} */ updated: stores.updated }; }; -/** @type {typeof import('$app/stores').page} */ +/** + * A readable store whose value contains page data. + * + * On the server, this store can only be subscribed to during component initialization. In the browser, it can be subscribed to at any time. + * + * @type {import('svelte/store').Readable} + */ export const page = { - /** @param {(value: any) => void} fn */ subscribe(fn) { const store = __SVELTEKIT_DEV__ ? get_store('page') : getStores().page; return store.subscribe(fn); } }; -/** @type {typeof import('$app/stores').navigating} */ +/** + * A readable store. + * When navigating starts, its value is a `Navigation` object with `from`, `to`, `type` and (if `type === 'popstate'`) `delta` properties. + * When navigating finishes, its value reverts to `null`. + * + * On the server, this store can only be subscribed to during component initialization. In the browser, it can be subscribed to at any time. + * @type {import('svelte/store').Readable} + */ export const navigating = { subscribe(fn) { const store = __SVELTEKIT_DEV__ ? get_store('navigating') : getStores().navigating; @@ -36,7 +52,12 @@ export const navigating = { } }; -/** @type {typeof import('$app/stores').updated} */ +/** + * A readable store whose initial value is `false`. If [`version.pollInterval`](https://kit.svelte.dev/docs/configuration#version) is a non-zero value, SvelteKit will poll for new versions of the app and update the store value to `true` when it detects one. `updated.check()` will force an immediate check, regardless of polling. + * + * On the server, this store can only be subscribed to during component initialization. In the browser, it can be subscribed to at any time. + * @type {import('svelte/store').Readable & { check(): Promise }} + */ export const updated = { subscribe(fn) { const store = __SVELTEKIT_DEV__ ? get_store('updated') : getStores().updated; diff --git a/packages/kit/src/runtime/client/client.js b/packages/kit/src/runtime/client/client.js index eeaa007f91e2..352daca6cd55 100644 --- a/packages/kit/src/runtime/client/client.js +++ b/packages/kit/src/runtime/client/client.js @@ -86,10 +86,10 @@ export function create_client(app, target) { let load_cache = null; const callbacks = { - /** @type {Array<(navigation: import('types').BeforeNavigate) => void>} */ + /** @type {Array<(navigation: import('@sveltejs/kit').BeforeNavigate) => void>} */ before_navigate: [], - /** @type {Array<(navigation: import('types').AfterNavigate) => void>} */ + /** @type {Array<(navigation: import('@sveltejs/kit').AfterNavigate) => void>} */ after_navigate: [] }; @@ -138,7 +138,7 @@ export function create_client(app, target) { scrollTo(scroll.x, scroll.y); } - /** @type {import('types').Page} */ + /** @type {import('@sveltejs/kit').Page} */ let page; /** @type {{}} */ @@ -279,7 +279,7 @@ export function create_client(app, target) { const style = document.querySelector('style[data-sveltekit]'); if (style) style.remove(); - page = /** @type {import('types').Page} */ (result.props.page); + page = /** @type {import('@sveltejs/kit').Page} */ (result.props.page); root = new app.root({ target, @@ -289,7 +289,7 @@ export function create_client(app, target) { restore_snapshot(current_history_index); - /** @type {import('types').AfterNavigate} */ + /** @type {import('@sveltejs/kit').AfterNavigate} */ const navigation = { from: null, to: { @@ -446,7 +446,7 @@ export function create_client(app, target) { } } - /** @type {import('types').LoadEvent} */ + /** @type {import('@sveltejs/kit').LoadEvent} */ const load_input = { route: { get id() { @@ -901,7 +901,7 @@ export function create_client(app, target) { /** * @param {{ * url: URL; - * type: import('types').NavigationType; + * type: import('@sveltejs/kit').NavigationType; * intent?: import('./types').NavigationIntent; * delta?: number; * }} opts @@ -909,7 +909,7 @@ export function create_client(app, target) { function before_navigate({ url, type, intent, delta }) { let should_block = false; - /** @type {import('types').Navigation} */ + /** @type {import('@sveltejs/kit').Navigation} */ const navigation = { from: { params: current.params, @@ -954,7 +954,7 @@ export function create_client(app, target) { * replaceState: boolean; * state: any; * } | null; - * type: import('types').NavigationType; + * type: import('@sveltejs/kit').NavigationType; * delta?: number; * nav_token?: {}; * accepted: () => void; @@ -1142,7 +1142,7 @@ export function create_client(app, target) { } callbacks.after_navigate.forEach((fn) => - fn(/** @type {import('types').AfterNavigate} */ (navigation)) + fn(/** @type {import('@sveltejs/kit').AfterNavigate} */ (navigation)) ); stores.navigating.set(null); @@ -1296,7 +1296,7 @@ export function create_client(app, target) { /** * @param {unknown} error - * @param {import('types').NavigationEvent} event + * @param {import('@sveltejs/kit').NavigationEvent} event * @returns {import('types').MaybePromise} */ function handle_error(error, event) { @@ -1445,7 +1445,7 @@ export function create_client(app, target) { if (!navigating) { // If we're navigating, beforeNavigate was already called. If we end up in here during navigation, // it's due to an external or full-page-reload link, for which we don't want to call the hook again. - /** @type {import('types').BeforeNavigate} */ + /** @type {import('@sveltejs/kit').BeforeNavigate} */ const navigation = { from: { params: current.params, diff --git a/packages/kit/src/runtime/client/singletons.js b/packages/kit/src/runtime/client/singletons.js index f92efb259a3b..9e1e7c1779a1 100644 --- a/packages/kit/src/runtime/client/singletons.js +++ b/packages/kit/src/runtime/client/singletons.js @@ -46,6 +46,8 @@ export function client_method(key) { export const stores = { url: /* @__PURE__ */ notifiable_store({}), page: /* @__PURE__ */ notifiable_store({}), - navigating: /* @__PURE__ */ writable(/** @type {import('types').Navigation | null} */ (null)), + navigating: /* @__PURE__ */ writable( + /** @type {import('@sveltejs/kit').Navigation | null} */ (null) + ), updated: /* @__PURE__ */ create_updated_store() }; diff --git a/packages/kit/src/runtime/client/types.d.ts b/packages/kit/src/runtime/client/types.d.ts index c3e2a916e9b6..8fba78e51e0b 100644 --- a/packages/kit/src/runtime/client/types.d.ts +++ b/packages/kit/src/runtime/client/types.d.ts @@ -1,4 +1,4 @@ -import { applyAction } from '$app/forms'; +import { applyAction } from '../app/forms'; import { afterNavigate, beforeNavigate, @@ -7,18 +7,10 @@ import { invalidateAll, preloadCode, preloadData -} from '$app/navigation'; +} from '../app/navigation'; import { SvelteComponent } from 'svelte'; -import { - ClientHooks, - CSRPageNode, - CSRPageNodeLoader, - CSRRoute, - Page, - ParamMatcher, - TrailingSlash, - Uses -} from 'types'; +import { ClientHooks, CSRPageNode, CSRPageNodeLoader, CSRRoute, TrailingSlash, Uses } from 'types'; +import { Page, ParamMatcher } from '@sveltejs/kit'; export interface SvelteKitApp { /** diff --git a/packages/kit/src/runtime/control.js b/packages/kit/src/runtime/control.js index 87e0dcc2b2c5..d27725429038 100644 --- a/packages/kit/src/runtime/control.js +++ b/packages/kit/src/runtime/control.js @@ -1,4 +1,4 @@ -export let HttpError = class HttpError { +export class HttpError { /** * @param {number} status * @param {{message: string} extends App.Error ? (App.Error | string | undefined) : App.Error} body @@ -17,9 +17,9 @@ export let HttpError = class HttpError { toString() { return JSON.stringify(this.body); } -}; +} -export let Redirect = class Redirect { +export class Redirect { /** * @param {300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308} status * @param {string} location @@ -28,12 +28,12 @@ export let Redirect = class Redirect { this.status = status; this.location = location; } -}; +} /** * @template {Record | undefined} [T=undefined] */ -export let ActionFailure = class ActionFailure { +export class ActionFailure { /** * @param {number} status * @param {T} [data] @@ -42,7 +42,7 @@ export let ActionFailure = class ActionFailure { this.status = status; this.data = data; } -}; +} /** * This is a grotesque hack that, in dev, allows us to replace the implementations @@ -57,7 +57,10 @@ export let ActionFailure = class ActionFailure { * }} implementations */ export function replace_implementations(implementations) { - ActionFailure = implementations.ActionFailure; - HttpError = implementations.HttpError; - Redirect = implementations.Redirect; + // @ts-expect-error + ActionFailure = implementations.ActionFailure; // eslint-disable-line no-class-assign + // @ts-expect-error + HttpError = implementations.HttpError; // eslint-disable-line no-class-assign + // @ts-expect-error + Redirect = implementations.Redirect; // eslint-disable-line no-class-assign } diff --git a/packages/kit/src/runtime/server/ambient.d.ts b/packages/kit/src/runtime/server/ambient.d.ts index cc7b0f428d47..c893c94ff32b 100644 --- a/packages/kit/src/runtime/server/ambient.d.ts +++ b/packages/kit/src/runtime/server/ambient.d.ts @@ -1,8 +1,8 @@ declare module '__SERVER__/internal.js' { export const options: import('types').SSROptions; export const get_hooks: () => Promise<{ - handle?: import('types').Handle; - handleError?: import('types').HandleServerError; - handleFetch?: import('types').HandleFetch; + handle?: import('@sveltejs/kit').Handle; + handleError?: import('@sveltejs/kit').HandleServerError; + handleFetch?: import('@sveltejs/kit').HandleFetch; }>; } diff --git a/packages/kit/src/runtime/server/cookie.js b/packages/kit/src/runtime/server/cookie.js index 33b2bea73c46..644e41b733e3 100644 --- a/packages/kit/src/runtime/server/cookie.js +++ b/packages/kit/src/runtime/server/cookie.js @@ -37,11 +37,11 @@ export function get_cookies(request, url, trailing_slash) { secure: url.hostname === 'localhost' && url.protocol === 'http:' ? false : true }; - /** @type {import('types').Cookies} */ + /** @type {import('@sveltejs/kit').Cookies} */ const cookies = { // The JSDoc param annotations appearing below for get, set and delete // are necessary to expose the `cookie` library types to - // typescript users. `@type {import('types').Cookies}` above is not + // typescript users. `@type {import('@sveltejs/kit').Cookies}` above is not // sufficient to do so. /** diff --git a/packages/kit/src/runtime/server/data/index.js b/packages/kit/src/runtime/server/data/index.js index 8d38b1e10720..472c2c10c479 100644 --- a/packages/kit/src/runtime/server/data/index.js +++ b/packages/kit/src/runtime/server/data/index.js @@ -11,10 +11,10 @@ import { create_async_iterator } from '../../../utils/streaming.js'; const encoder = new TextEncoder(); /** - * @param {import('types').RequestEvent} event + * @param {import('@sveltejs/kit').RequestEvent} event * @param {import('types').SSRRoute} route * @param {import('types').SSROptions} options - * @param {import('types').SSRManifest} manifest + * @param {import('@sveltejs/kit').SSRManifest} manifest * @param {import('types').SSRState} state * @param {boolean[] | undefined} invalidated_data_nodes * @param {import('types').TrailingSlash} trailing_slash @@ -183,7 +183,7 @@ export function redirect_json_response(redirect) { /** * If the serialized data contains promises, `chunks` will be an * async iterable containing their resolutions - * @param {import('types').RequestEvent} event + * @param {import('@sveltejs/kit').RequestEvent} event * @param {import('types').SSROptions} options * @param {Array} nodes * @returns {{ data: string, chunks: AsyncIterable | null }} diff --git a/packages/kit/src/runtime/server/endpoint.js b/packages/kit/src/runtime/server/endpoint.js index a98982536ac5..28e57eb047d5 100644 --- a/packages/kit/src/runtime/server/endpoint.js +++ b/packages/kit/src/runtime/server/endpoint.js @@ -3,7 +3,7 @@ import { Redirect } from '../control.js'; import { method_not_allowed } from './utils.js'; /** - * @param {import('types').RequestEvent} event + * @param {import('@sveltejs/kit').RequestEvent} event * @param {import('types').SSREndpoint} mod * @param {import('types').SSRState} state * @returns {Promise} @@ -40,7 +40,7 @@ export async function render_endpoint(event, mod, state) { try { const response = await handler( - /** @type {import('types').RequestEvent>} */ (event) + /** @type {import('@sveltejs/kit').RequestEvent>} */ (event) ); if (!(response instanceof Response)) { @@ -67,7 +67,7 @@ export async function render_endpoint(event, mod, state) { } /** - * @param {import('types').RequestEvent} event + * @param {import('@sveltejs/kit').RequestEvent} event */ export function is_endpoint_request(event) { const { method, headers } = event.request; diff --git a/packages/kit/src/runtime/server/fetch.js b/packages/kit/src/runtime/server/fetch.js index a679b454bb11..f07fbb19e3eb 100644 --- a/packages/kit/src/runtime/server/fetch.js +++ b/packages/kit/src/runtime/server/fetch.js @@ -4,9 +4,9 @@ import * as paths from '__sveltekit/paths'; /** * @param {{ - * event: import('types').RequestEvent; + * event: import('@sveltejs/kit').RequestEvent; * options: import('types').SSROptions; - * manifest: import('types').SSRManifest; + * manifest: import('@sveltejs/kit').SSRManifest; * state: import('types').SSRState; * get_cookie_header: (url: URL, header: string | null) => string; * set_internal: (name: string, value: string, opts: import('cookie').CookieSerializeOptions) => void; diff --git a/packages/kit/src/runtime/server/index.js b/packages/kit/src/runtime/server/index.js index a20a76cc6f13..9f3a6eb56915 100644 --- a/packages/kit/src/runtime/server/index.js +++ b/packages/kit/src/runtime/server/index.js @@ -7,10 +7,10 @@ export class Server { /** @type {import('types').SSROptions} */ #options; - /** @type {import('types').SSRManifest} */ + /** @type {import('@sveltejs/kit').SSRManifest} */ #manifest; - /** @param {import('types').SSRManifest} manifest */ + /** @param {import('@sveltejs/kit').SSRManifest} manifest */ constructor(manifest) { /** @type {import('types').SSROptions} */ this.#options = options; diff --git a/packages/kit/src/runtime/server/page/actions.js b/packages/kit/src/runtime/server/page/actions.js index 37a72a0c3021..0d656815d83d 100644 --- a/packages/kit/src/runtime/server/page/actions.js +++ b/packages/kit/src/runtime/server/page/actions.js @@ -5,7 +5,7 @@ import { is_form_content_type, negotiate } from '../../../utils/http.js'; import { HttpError, Redirect, ActionFailure } from '../../control.js'; import { handle_error_and_jsonify } from '../utils.js'; -/** @param {import('types').RequestEvent} event */ +/** @param {import('@sveltejs/kit').RequestEvent} event */ export function is_action_json_request(event) { const accept = negotiate(event.request.headers.get('accept') ?? '*/*', [ 'application/json', @@ -16,7 +16,7 @@ export function is_action_json_request(event) { } /** - * @param {import('types').RequestEvent} event + * @param {import('@sveltejs/kit').RequestEvent} event * @param {import('types').SSROptions} options * @param {import('types').SSRNode['server'] | undefined} server */ @@ -97,7 +97,7 @@ function check_incorrect_fail_use(error) { } /** - * @param {import('types').Redirect} redirect + * @param {import('@sveltejs/kit').Redirect} redirect */ export function action_json_redirect(redirect) { return action_json({ @@ -108,7 +108,7 @@ export function action_json_redirect(redirect) { } /** - * @param {import('types').ActionResult} data + * @param {import('@sveltejs/kit').ActionResult} data * @param {ResponseInit} [init] */ function action_json(data, init) { @@ -116,16 +116,16 @@ function action_json(data, init) { } /** - * @param {import('types').RequestEvent} event + * @param {import('@sveltejs/kit').RequestEvent} event */ export function is_action_request(event) { return event.request.method === 'POST'; } /** - * @param {import('types').RequestEvent} event + * @param {import('@sveltejs/kit').RequestEvent} event * @param {import('types').SSRNode['server'] | undefined} server - * @returns {Promise} + * @returns {Promise} */ export async function handle_action_request(event, server) { const actions = server?.actions; @@ -185,7 +185,7 @@ export async function handle_action_request(event, server) { } /** - * @param {import('types').Actions} actions + * @param {import('@sveltejs/kit').Actions} actions */ function check_named_default_separate(actions) { if (actions.default && Object.keys(actions).length > 1) { @@ -196,7 +196,7 @@ function check_named_default_separate(actions) { } /** - * @param {import('types').RequestEvent} event + * @param {import('@sveltejs/kit').RequestEvent} event * @param {NonNullable} actions * @throws {Redirect | ActionFailure | HttpError | Error} */ diff --git a/packages/kit/src/runtime/server/page/index.js b/packages/kit/src/runtime/server/page/index.js index 58299a233b2c..6ba98410d50f 100644 --- a/packages/kit/src/runtime/server/page/index.js +++ b/packages/kit/src/runtime/server/page/index.js @@ -22,10 +22,10 @@ import { get_data_json } from '../data/index.js'; const MAX_DEPTH = 10; /** - * @param {import('types').RequestEvent} event + * @param {import('@sveltejs/kit').RequestEvent} event * @param {import('types').PageNodeIndexes} page * @param {import('types').SSROptions} options - * @param {import('types').SSRManifest} manifest + * @param {import('@sveltejs/kit').SSRManifest} manifest * @param {import('types').SSRState} state * @param {import('types').RequiredResolveOptions} resolve_opts * @returns {Promise} @@ -54,7 +54,7 @@ export async function render_page(event, page, options, manifest, state, resolve let status = 200; - /** @type {import('types').ActionResult | undefined} */ + /** @type {import('@sveltejs/kit').ActionResult | undefined} */ let action_result = undefined; if (is_action_request(event)) { diff --git a/packages/kit/src/runtime/server/page/load_data.js b/packages/kit/src/runtime/server/page/load_data.js index 00d2af56da2b..84cc8f154679 100644 --- a/packages/kit/src/runtime/server/page/load_data.js +++ b/packages/kit/src/runtime/server/page/load_data.js @@ -6,7 +6,7 @@ import { validate_depends } from '../../shared.js'; /** * Calls the user's server `load` function. * @param {{ - * event: import('types').RequestEvent; + * event: import('@sveltejs/kit').RequestEvent; * state: import('types').SSRState; * node: import('types').SSRNode | undefined; * parent: () => Promise>; @@ -143,7 +143,7 @@ export async function load_server_data({ /** * Calls the user's `load` function. * @param {{ - * event: import('types').RequestEvent; + * event: import('@sveltejs/kit').RequestEvent; * fetched: import('./types').Fetched[]; * node: import('types').SSRNode | undefined; * parent: () => Promise>; @@ -190,11 +190,11 @@ export async function load_data({ } /** - * @param {Pick} event - * @param {import("types").SSRState} state - * @param {import("./types").Fetched[]} fetched + * @param {Pick} event + * @param {import('types').SSRState} state + * @param {import('./types').Fetched[]} fetched * @param {boolean} csr - * @param {Pick, 'filterSerializedResponseHeaders'>} resolve_opts + * @param {Pick, 'filterSerializedResponseHeaders'>} resolve_opts */ export function create_universal_fetch(event, state, fetched, csr, resolve_opts) { /** diff --git a/packages/kit/src/runtime/server/page/load_data.spec.js b/packages/kit/src/runtime/server/page/load_data.spec.js index 88785b4a7b98..ec3167c08822 100644 --- a/packages/kit/src/runtime/server/page/load_data.spec.js +++ b/packages/kit/src/runtime/server/page/load_data.spec.js @@ -2,7 +2,7 @@ import { assert, expect, test } from 'vitest'; import { create_universal_fetch } from './load_data.js'; /** - * @param {Partial>} event + * @param {Partial>} event */ function create_fetch(event) { event.fetch = event.fetch || (async () => new Response('foo')); @@ -10,7 +10,7 @@ function create_fetch(event) { event.route = event.route || { id: 'foo' }; event.url = event.url || new URL('https://domain-a.com'); return create_universal_fetch( - /** @type {Pick} */ ( + /** @type {Pick} */ ( event ), { getClientAddress: () => '', error: false, depth: 0 }, diff --git a/packages/kit/src/runtime/server/page/render.js b/packages/kit/src/runtime/server/page/render.js index 4d90d406d6a9..2a3dfc180e68 100644 --- a/packages/kit/src/runtime/server/page/render.js +++ b/packages/kit/src/runtime/server/page/render.js @@ -28,14 +28,14 @@ const encoder = new TextEncoder(); * branch: Array; * fetched: Array; * options: import('types').SSROptions; - * manifest: import('types').SSRManifest; + * manifest: import('@sveltejs/kit').SSRManifest; * state: import('types').SSRState; * page_config: { ssr: boolean; csr: boolean }; * status: number; * error: App.Error | null; - * event: import('types').RequestEvent; + * event: import('@sveltejs/kit').RequestEvent; * resolve_opts: import('types').RequiredResolveOptions; - * action_result?: import('types').ActionResult; + * action_result?: import('@sveltejs/kit').ActionResult; * }} opts */ export async function render_response({ @@ -490,7 +490,7 @@ export async function render_response({ /** * If the serialized data contains promises, `chunks` will be an * async iterable containing their resolutions - * @param {import('types').RequestEvent} event + * @param {import('@sveltejs/kit').RequestEvent} event * @param {import('types').SSROptions} options * @param {Array} nodes * @param {string} global diff --git a/packages/kit/src/runtime/server/page/respond_with_error.js b/packages/kit/src/runtime/server/page/respond_with_error.js index 2567b7e768e8..15148b379bf9 100644 --- a/packages/kit/src/runtime/server/page/respond_with_error.js +++ b/packages/kit/src/runtime/server/page/respond_with_error.js @@ -10,9 +10,9 @@ import { HttpError, Redirect } from '../../control.js'; /** * @param {{ - * event: import('types').RequestEvent; + * event: import('@sveltejs/kit').RequestEvent; * options: import('types').SSROptions; - * manifest: import('types').SSRManifest; + * manifest: import('@sveltejs/kit').SSRManifest; * state: import('types').SSRState; * status: number; * error: unknown; diff --git a/packages/kit/src/runtime/server/respond.js b/packages/kit/src/runtime/server/respond.js index 87dc7d32fe69..1cd9d058ad6b 100644 --- a/packages/kit/src/runtime/server/respond.js +++ b/packages/kit/src/runtime/server/respond.js @@ -45,7 +45,7 @@ const default_preload = ({ type }) => type === 'js' || type === 'css'; /** * @param {Request} request * @param {import('types').SSROptions} options - * @param {import('types').SSRManifest} manifest + * @param {import('@sveltejs/kit').SSRManifest} manifest * @param {import('types').SSRState} state * @returns {Promise} */ @@ -130,7 +130,7 @@ export async function respond(request, options, manifest, state) { /** @type {Record} */ let cookies_to_add = {}; - /** @type {import('types').RequestEvent} */ + /** @type {import('@sveltejs/kit').RequestEvent} */ const event = { // @ts-expect-error `cookies` and `fetch` need to be created after the `event` itself cookies: null, @@ -343,8 +343,8 @@ export async function respond(request, options, manifest, state) { /** * - * @param {import('types').RequestEvent} event - * @param {import('types').ResolveOptions} [opts] + * @param {import('@sveltejs/kit').RequestEvent} event + * @param {import('@sveltejs/kit').ResolveOptions} [opts] */ async function resolve(event, opts) { try { diff --git a/packages/kit/src/runtime/server/utils.js b/packages/kit/src/runtime/server/utils.js index b741d6fff648..25b22720fb4e 100644 --- a/packages/kit/src/runtime/server/utils.js +++ b/packages/kit/src/runtime/server/utils.js @@ -65,7 +65,7 @@ export function static_error_page(options, status, message) { } /** - * @param {import('types').RequestEvent} event + * @param {import('@sveltejs/kit').RequestEvent} event * @param {import('types').SSROptions} options * @param {unknown} error */ @@ -90,7 +90,7 @@ export async function handle_fatal_error(event, options, error) { } /** - * @param {import('types').RequestEvent} event + * @param {import('@sveltejs/kit').RequestEvent} event * @param {import('types').SSROptions} options * @param {any} error * @returns {Promise} @@ -132,7 +132,7 @@ export function redirect_response(status, location) { } /** - * @param {import('types').RequestEvent} event + * @param {import('@sveltejs/kit').RequestEvent} event * @param {Error & { path: string }} error */ export function clarify_devalue_error(event, error) { diff --git a/packages/kit/src/types/ambient-private.d.ts b/packages/kit/src/types/ambient-private.d.ts new file mode 100644 index 000000000000..843cc94d342b --- /dev/null +++ b/packages/kit/src/types/ambient-private.d.ts @@ -0,0 +1,11 @@ +declare global { + const __SVELTEKIT_ADAPTER_NAME__: string; + const __SVELTEKIT_APP_VERSION_FILE__: string; + const __SVELTEKIT_APP_VERSION_POLL_INTERVAL__: number; + const __SVELTEKIT_DEV__: boolean; + const __SVELTEKIT_EMBEDDED__: boolean; + var Bun: object; + var Deno: object; +} + +export {}; diff --git a/packages/kit/src/types/ambient.d.ts b/packages/kit/src/types/ambient.d.ts new file mode 100644 index 000000000000..b7331402a369 --- /dev/null +++ b/packages/kit/src/types/ambient.d.ts @@ -0,0 +1,108 @@ +/** + * It's possible to tell SvelteKit how to type objects inside your app by declaring the `App` namespace. By default, a new project will have a file called `src/app.d.ts` containing the following: + * + * ```ts + * declare global { + * namespace App { + * // interface Error {} + * // interface Locals {} + * // interface PageData {} + * // interface Platform {} + * } + * } + * + * export {}; + * ``` + * + * The `export {}` line exists because without it, the file would be treated as an _ambient module_ which prevents you from adding `import` declarations. + * If you need to add ambient `declare module` declarations, do so in a separate file like `src/ambient.d.ts`. + * + * By populating these interfaces, you will gain type safety when using `event.locals`, `event.platform`, and `data` from `load` functions. + */ +declare namespace App { + /** + * Defines the common shape of expected and unexpected errors. Expected errors are thrown using the `error` function. Unexpected errors are handled by the `handleError` hooks which should return this shape. + */ + export interface Error { + message: string; + } + + /** + * The interface that defines `event.locals`, which can be accessed in [hooks](https://kit.svelte.dev/docs/hooks) (`handle`, and `handleError`), server-only `load` functions, and `+server.js` files. + */ + export interface Locals {} + + /** + * Defines the common shape of the [$page.data store](https://kit.svelte.dev/docs/modules#$app-stores-page) - that is, the data that is shared between all pages. + * The `Load` and `ServerLoad` functions in `./$types` will be narrowed accordingly. + * Use optional properties for data that is only present on specific pages. Do not add an index signature (`[key: string]: any`). + */ + export interface PageData {} + + /** + * If your adapter provides [platform-specific context](https://kit.svelte.dev/docs/adapters#platform-specific-context) via `event.platform`, you can specify it here. + */ + export interface Platform {} +} + +/** + * This module is only available to [service workers](https://kit.svelte.dev/docs/service-workers). + */ +declare module '$service-worker' { + /** + * The `base` path of the deployment. Typically this is equivalent to `config.kit.paths.base`, but it is calculated from `location.pathname` meaning that it will continue to work correctly if the site is deployed to a subdirectory. + * Note that there is a `base` but no `assets`, since service workers cannot be used if `config.kit.paths.assets` is specified. + */ + export const base: string; + /** + * An array of URL strings representing the files generated by Vite, suitable for caching with `cache.addAll(build)`. + * During development, this is an empty array. + */ + export const build: string[]; + /** + * An array of URL strings representing the files in your static directory, or whatever directory is specified by `config.kit.files.assets`. You can customize which files are included from `static` directory using [`config.kit.serviceWorker.files`](https://kit.svelte.dev/docs/configuration) + */ + export const files: string[]; + /** + * An array of pathnames corresponding to prerendered pages and endpoints. + * During development, this is an empty array. + */ + export const prerendered: string[]; + /** + * See [`config.kit.version`](https://kit.svelte.dev/docs/configuration#version). It's useful for generating unique cache names inside your service worker, so that a later deployment of your app can invalidate old caches. + */ + export const version: string; +} + +/** Internal version of $app/environment */ +declare module '__sveltekit/environment' { + /** + * SvelteKit analyses your app during the `build` step by running it. During this process, `building` is `true`. This also applies during prerendering. + */ + export const building: boolean; + /** + * The value of `config.kit.version.name`. + */ + export const version: string; + export function set_building(): void; +} + +/** Internal version of $app/paths */ +declare module '__sveltekit/paths' { + /** + * A string that matches [`config.kit.paths.base`](https://kit.svelte.dev/docs/configuration#paths). + * + * Example usage: `Link` + */ + export let base: '' | `/${string}`; + /** + * An absolute path that matches [`config.kit.paths.assets`](https://kit.svelte.dev/docs/configuration#paths). + * + * > If a value for `config.kit.paths.assets` is specified, it will be replaced with `'/_svelte_kit_assets'` during `vite dev` or `vite preview`, since the assets don't yet live at their eventual URL. + */ + export let assets: '' | `https://${string}` | `http://${string}` | '/_svelte_kit_assets'; + export let relative: boolean | undefined; // TODO in 2.0, make this a `boolean` that defaults to `true` + export function reset(): void; + export function override(paths: { base: string; assets: string }): void; + export function set_assets(path: string): void; +} diff --git a/packages/kit/types/internal.d.ts b/packages/kit/src/types/internal.d.ts similarity index 96% rename from packages/kit/types/internal.d.ts rename to packages/kit/src/types/internal.d.ts index 379328678073..76c4c89c5d85 100644 --- a/packages/kit/types/internal.d.ts +++ b/packages/kit/src/types/internal.d.ts @@ -13,7 +13,7 @@ import { HandleFetch, Actions, HandleClientError -} from './index.js'; +} from '@sveltejs/kit'; import { HttpMethod, MaybePromise, @@ -412,15 +412,5 @@ export type ValidatedConfig = RecursiveRequired; export type ValidatedKitConfig = RecursiveRequired; -export * from './index'; -export * from './private'; - -declare global { - const __SVELTEKIT_ADAPTER_NAME__: string; - const __SVELTEKIT_APP_VERSION_FILE__: string; - const __SVELTEKIT_APP_VERSION_POLL_INTERVAL__: number; - const __SVELTEKIT_DEV__: boolean; - const __SVELTEKIT_EMBEDDED__: boolean; - var Bun: object; - var Deno: object; -} +export * from '../exports/index'; +export * from './private.js'; diff --git a/packages/kit/types/private.d.ts b/packages/kit/src/types/private.d.ts similarity index 96% rename from packages/kit/types/private.d.ts rename to packages/kit/src/types/private.d.ts index ad02da171242..e84cf1644a4f 100644 --- a/packages/kit/types/private.d.ts +++ b/packages/kit/src/types/private.d.ts @@ -2,7 +2,7 @@ // but which cannot be imported from `@sveltejs/kit`. Care should // be taken to avoid breaking changes when editing this file -import { RouteDefinition } from './index.js'; +import { RouteDefinition } from '@sveltejs/kit'; export interface AdapterEntry { /** @@ -233,12 +233,3 @@ export interface RouteSegment { } export type TrailingSlash = 'never' | 'always' | 'ignore'; - -/** - * This doesn't actually exist, it's a way to better distinguish the type - */ -declare const uniqueSymbol: unique symbol; - -export interface UniqueInterface { - readonly [uniqueSymbol]: unknown; -} diff --git a/packages/kit/types/synthetic/$env+dynamic+private.md b/packages/kit/src/types/synthetic/$env+dynamic+private.md similarity index 100% rename from packages/kit/types/synthetic/$env+dynamic+private.md rename to packages/kit/src/types/synthetic/$env+dynamic+private.md diff --git a/packages/kit/types/synthetic/$env+dynamic+public.md b/packages/kit/src/types/synthetic/$env+dynamic+public.md similarity index 100% rename from packages/kit/types/synthetic/$env+dynamic+public.md rename to packages/kit/src/types/synthetic/$env+dynamic+public.md diff --git a/packages/kit/types/synthetic/$env+static+private.md b/packages/kit/src/types/synthetic/$env+static+private.md similarity index 100% rename from packages/kit/types/synthetic/$env+static+private.md rename to packages/kit/src/types/synthetic/$env+static+private.md diff --git a/packages/kit/types/synthetic/$env+static+public.md b/packages/kit/src/types/synthetic/$env+static+public.md similarity index 100% rename from packages/kit/types/synthetic/$env+static+public.md rename to packages/kit/src/types/synthetic/$env+static+public.md diff --git a/packages/kit/types/synthetic/$lib.md b/packages/kit/src/types/synthetic/$lib.md similarity index 100% rename from packages/kit/types/synthetic/$lib.md rename to packages/kit/src/types/synthetic/$lib.md diff --git a/packages/kit/src/utils/routing.js b/packages/kit/src/utils/routing.js index 9803ac7b6acd..17dec1f53f23 100644 --- a/packages/kit/src/utils/routing.js +++ b/packages/kit/src/utils/routing.js @@ -129,7 +129,7 @@ export function get_route_segments(route) { /** * @param {RegExpMatchArray} match * @param {import('types').RouteParam[]} params - * @param {Record} matchers + * @param {Record} matchers */ export function exec(match, params, matchers) { /** @type {Record} */ diff --git a/packages/kit/src/utils/streaming.js b/packages/kit/src/utils/streaming.js index 59606c5ca087..cfb0d6a04f93 100644 --- a/packages/kit/src/utils/streaming.js +++ b/packages/kit/src/utils/streaming.js @@ -1,5 +1,5 @@ /** - * @returns {import("types").Deferred & { promise: Promise }}} + * @returns {import('types').Deferred & { promise: Promise }}} */ function defer() { let fulfil; diff --git a/packages/kit/tsconfig.json b/packages/kit/tsconfig.json index b7eca62d1a3d..461ebb2d8c6c 100644 --- a/packages/kit/tsconfig.json +++ b/packages/kit/tsconfig.json @@ -9,9 +9,10 @@ "moduleResolution": "node", "allowSyntheticDefaultImports": true, "paths": { - "@sveltejs/kit": ["./types/index"], + "@sveltejs/kit": ["./src/exports/public.d.ts"], + "@sveltejs/kit/node": ["./src/exports/node/index.js"], // internal use only - "types": ["./types/internal"] + "types": ["./src/types/internal"] }, "noUnusedLocals": true, "noUnusedParameters": true @@ -19,7 +20,7 @@ "include": [ "scripts/**/*", "src/**/*", - "types/**/*", + "src/types/**/*", "../../sites/kit.svelte.dev/scripts/extract-types.js" ], "exclude": ["./**/write_types/test/**"] diff --git a/packages/kit/types/ambient.d.ts b/packages/kit/types/ambient.d.ts deleted file mode 100644 index 10e3529d238b..000000000000 --- a/packages/kit/types/ambient.d.ts +++ /dev/null @@ -1,486 +0,0 @@ -/** - * It's possible to tell SvelteKit how to type objects inside your app by declaring the `App` namespace. By default, a new project will have a file called `src/app.d.ts` containing the following: - * - * ```ts - * declare global { - * namespace App { - * // interface Error {} - * // interface Locals {} - * // interface PageData {} - * // interface Platform {} - * } - * } - * - * export {}; - * ``` - * - * The `export {}` line exists because without it, the file would be treated as an _ambient module_ which prevents you from adding `import` declarations. - * If you need to add ambient `declare module` declarations, do so in a separate file like `src/ambient.d.ts`. - * - * By populating these interfaces, you will gain type safety when using `event.locals`, `event.platform`, and `data` from `load` functions. - */ -declare namespace App { - /** - * Defines the common shape of expected and unexpected errors. Expected errors are thrown using the `error` function. Unexpected errors are handled by the `handleError` hooks which should return this shape. - */ - export interface Error { - message: string; - } - - /** - * The interface that defines `event.locals`, which can be accessed in [hooks](https://kit.svelte.dev/docs/hooks) (`handle`, and `handleError`), server-only `load` functions, and `+server.js` files. - */ - export interface Locals {} - - /** - * Defines the common shape of the [$page.data store](https://kit.svelte.dev/docs/modules#$app-stores-page) - that is, the data that is shared between all pages. - * The `Load` and `ServerLoad` functions in `./$types` will be narrowed accordingly. - * Use optional properties for data that is only present on specific pages. Do not add an index signature (`[key: string]: any`). - */ - export interface PageData {} - - /** - * If your adapter provides [platform-specific context](https://kit.svelte.dev/docs/adapters#platform-specific-context) via `event.platform`, you can specify it here. - */ - export interface Platform {} -} - -declare module '$app/environment' { - /** - * `true` if the app is running in the browser. - */ - export const browser: boolean; - - /** - * SvelteKit analyses your app during the `build` step by running it. During this process, `building` is `true`. This also applies during prerendering. - */ - export const building: boolean; - - /** - * Whether the dev server is running. This is not guaranteed to correspond to `NODE_ENV` or `MODE`. - */ - export const dev: boolean; - - /** - * The value of `config.kit.version.name`. - */ - export const version: string; -} - -declare module '$app/forms' { - import type { ActionResult } from '@sveltejs/kit'; - - type MaybePromise = T | Promise; - - // this is duplicated in @sveltejs/kit because create-svelte tests fail - // if we use the imported version. See https://github.com/sveltejs/kit/pull/7003#issuecomment-1330921789 - // for why this happens (it's likely a bug in TypeScript, but one that is so rare that it's unlikely to be fixed) - type SubmitFunction< - Success extends Record | undefined = Record, - Invalid extends Record | undefined = Record - > = (input: { - action: URL; - /** - * use `formData` instead of `data` - * @deprecated - */ - data: FormData; - formData: FormData; - /** - * use `formElement` instead of `form` - * @deprecated - */ - form: HTMLFormElement; - formElement: HTMLFormElement; - controller: AbortController; - cancel(): void; - submitter: HTMLElement | null; - }) => MaybePromise< - | void - | ((opts: { - /** - * use `formData` instead of `data` - * @deprecated - */ - data: FormData; - formData: FormData; - /** - * use `formElement` instead of `form` - * @deprecated - */ - form: HTMLFormElement; - formElement: HTMLFormElement; - action: URL; - result: ActionResult; - /** - * Call this to get the default behavior of a form submission response. - * @param options Set `reset: false` if you don't want the `` values to be reset after a successful submission. - */ - update(options?: { reset: boolean }): Promise; - }) => void) - >; - - /** - * This action enhances a `` element that otherwise would work without JavaScript. - * @param form The form element - * @param options Callbacks for different states of the form lifecycle - */ - export function enhance< - Success extends Record | undefined = Record, - Invalid extends Record | undefined = Record - >( - formElement: HTMLFormElement, - /** - * Called upon submission with the given FormData and the `action` that should be triggered. - * If `cancel` is called, the form will not be submitted. - * You can use the abort `controller` to cancel the submission in case another one starts. - * If a function is returned, that function is called with the response from the server. - * If nothing is returned, the fallback will be used. - * - * If this function or its return value isn't set, it - * - falls back to updating the `form` prop with the returned data if the action is one same page as the form - * - updates `$page.status` - * - resets the `` element and invalidates all data in case of successful submission with no redirect response - * - redirects in case of a redirect response - * - redirects to the nearest error page in case of an unexpected error - * - * If you provide a custom function with a callback and want to use the default behavior, invoke `update` in your callback. - */ - submit?: SubmitFunction - ): { destroy(): void }; - - /** - * This action updates the `form` property of the current page with the given data and updates `$page.status`. - * In case of an error, it redirects to the nearest error page. - */ - export function applyAction< - Success extends Record | undefined = Record, - Invalid extends Record | undefined = Record - >(result: ActionResult): Promise; - - /** - * Use this function to deserialize the response from a form submission. - * Usage: - * - * ```js - * import { deserialize } from '$app/forms'; - * - * async function handleSubmit(event) { - * const response = await fetch('/form?/action', { - * method: 'POST', - * body: new FormData(event.target) - * }); - * - * const result = deserialize(await response.text()); - * // ... - * } - * ``` - */ - export function deserialize< - Success extends Record | undefined = Record, - Invalid extends Record | undefined = Record - >(serialized: string): ActionResult; -} - -declare module '$app/navigation' { - import { BeforeNavigate, AfterNavigate } from '@sveltejs/kit'; - - /** - * If called when the page is being updated following a navigation (in `onMount` or `afterNavigate` or an action, for example), this disables SvelteKit's built-in scroll handling. - * This is generally discouraged, since it breaks user expectations. - */ - export function disableScrollHandling(): void; - /** - * Returns a Promise that resolves when SvelteKit navigates (or fails to navigate, in which case the promise rejects) to the specified `url`. - * For external URLs, use `window.location = url` instead of calling `goto(url)`. - * - * @param url Where to navigate to. Note that if you've set [`config.kit.paths.base`](https://kit.svelte.dev/docs/configuration#paths) and the URL is root-relative, you need to prepend the base path if you want to navigate within the app. - * @param opts Options related to the navigation - */ - export function goto( - url: string | URL, - opts?: { - /** - * If `true`, will replace the current `history` entry rather than creating a new one with `pushState` - */ - replaceState?: boolean; - /** - * If `true`, the browser will maintain its scroll position rather than scrolling to the top of the page after navigation - */ - noScroll?: boolean; - /** - * If `true`, the currently focused element will retain focus after navigation. Otherwise, focus will be reset to the body - */ - keepFocus?: boolean; - /** - * The state of the new/updated history entry - */ - state?: any; - /** - * If `true`, all `load` functions of the page will be rerun. See https://kit.svelte.dev/docs/load#rerunning-load-functions for more info on invalidation. - */ - invalidateAll?: boolean; - } - ): Promise; - /** - * Causes any `load` functions belonging to the currently active page to re-run if they depend on the `url` in question, via `fetch` or `depends`. Returns a `Promise` that resolves when the page is subsequently updated. - * - * If the argument is given as a `string` or `URL`, it must resolve to the same URL that was passed to `fetch` or `depends` (including query parameters). - * To create a custom identifier, use a string beginning with `[a-z]+:` (e.g. `custom:state`) — this is a valid URL. - * - * The `function` argument can be used define a custom predicate. It receives the full `URL` and causes `load` to rerun if `true` is returned. - * This can be useful if you want to invalidate based on a pattern instead of a exact match. - * - * ```ts - * // Example: Match '/path' regardless of the query parameters - * import { invalidate } from '$app/navigation'; - * - * invalidate((url) => url.pathname === '/path'); - * ``` - * @param url The invalidated URL - */ - export function invalidate(url: string | URL | ((url: URL) => boolean)): Promise; - /** - * Causes all `load` functions belonging to the currently active page to re-run. Returns a `Promise` that resolves when the page is subsequently updated. - */ - export function invalidateAll(): Promise; - /** - * Programmatically preloads the given page, which means - * 1. ensuring that the code for the page is loaded, and - * 2. calling the page's load function with the appropriate options. - * - * This is the same behaviour that SvelteKit triggers when the user taps or mouses over an `` element with `data-sveltekit-preload-data`. - * If the next navigation is to `href`, the values returned from load will be used, making navigation instantaneous. - * Returns a Promise that resolves when the preload is complete. - * - * @param href Page to preload - */ - export function preloadData(href: string): Promise; - /** - * Programmatically imports the code for routes that haven't yet been fetched. - * Typically, you might call this to speed up subsequent navigation. - * - * You can specify routes by any matching pathname such as `/about` (to match `src/routes/about/+page.svelte`) or `/blog/*` (to match `src/routes/blog/[slug]/+page.svelte`). - * - * Unlike `preloadData`, this won't call `load` functions. - * Returns a Promise that resolves when the modules have been imported. - */ - export function preloadCode(...urls: string[]): Promise; - - /** - * A navigation interceptor that triggers before we navigate to a new URL, whether by clicking a link, calling `goto(...)`, or using the browser back/forward controls. - * Calling `cancel()` will prevent the navigation from completing. If the navigation would have directly unloaded the current page, calling `cancel` will trigger the native - * browser unload confirmation dialog. In these cases, `navigation.willUnload` is `true`. - * - * When a navigation isn't client side, `navigation.to.route.id` will be `null`. - * - * `beforeNavigate` must be called during a component initialization. It remains active as long as the component is mounted. - */ - export function beforeNavigate(callback: (navigation: BeforeNavigate) => void): void; - - /** - * A lifecycle function that runs the supplied `callback` when the current component mounts, and also whenever we navigate to a new URL. - * - * `afterNavigate` must be called during a component initialization. It remains active as long as the component is mounted. - */ - export function afterNavigate(callback: (navigation: AfterNavigate) => void): void; -} - -declare module '$app/paths' { - /** - * A string that matches [`config.kit.paths.base`](https://kit.svelte.dev/docs/configuration#paths). - * - * Example usage: `Link` - */ - export const base: `/${string}`; - /** - * An absolute path that matches [`config.kit.paths.assets`](https://kit.svelte.dev/docs/configuration#paths). - * - * > If a value for `config.kit.paths.assets` is specified, it will be replaced with `'/_svelte_kit_assets'` during `vite dev` or `vite preview`, since the assets don't yet live at their eventual URL. - */ - export const assets: `https://${string}` | `http://${string}`; -} - -/** - * These stores are _contextual_ on the server — they are added to the [context](https://svelte.dev/tutorial/context-api) of your root component. This means that `page` is unique to each request, rather than shared between multiple requests handled by the same server simultaneously. - * - * Because of that, you must subscribe to the stores during component initialization (which happens automatically if you reference the store value, e.g. as `$page`, in a component) before you can use them. - * - * In the browser, we don't need to worry about this, and stores can be accessed from anywhere. Code that will only ever run on the browser can refer to (or subscribe to) any of these stores at any time. - * - * You can read more about client/server differences in the [state management](https://kit.svelte.dev/docs/state-management#using-stores-with-context) documentation. - */ -declare module '$app/stores' { - import { Readable } from 'svelte/store'; - import { Navigation, Page } from '@sveltejs/kit'; - - /** - * A readable store whose value contains page data. - * - * On the server, this store can only be subscribed to during component initialization. In the browser, it can be subscribed to at any time. - */ - export const page: Readable; - /** - * A readable store. - * When navigating starts, its value is a `Navigation` object with `from`, `to`, `type` and (if `type === 'popstate'`) `delta` properties. - * When navigating finishes, its value reverts to `null`. - * - * On the server, this store can only be subscribed to during component initialization. In the browser, it can be subscribed to at any time. - */ - export const navigating: Readable; - /** - * A readable store whose initial value is `false`. If [`version.pollInterval`](https://kit.svelte.dev/docs/configuration#version) is a non-zero value, SvelteKit will poll for new versions of the app and update the store value to `true` when it detects one. `updated.check()` will force an immediate check, regardless of polling. - * - * On the server, this store can only be subscribed to during component initialization. In the browser, it can be subscribed to at any time. - */ - export const updated: Readable & { check(): Promise }; - - /** - * A function that returns all of the contextual stores. On the server, this must be called during component initialization. - * Only use this if you need to defer store subscription until after the component has mounted, for some reason. - */ - export function getStores(): { - navigating: typeof navigating; - page: typeof page; - updated: typeof updated; - }; -} - -/** - * This module is only available to [service workers](https://kit.svelte.dev/docs/service-workers). - */ -declare module '$service-worker' { - /** - * The `base` path of the deployment. Typically this is equivalent to `config.kit.paths.base`, but it is calculated from `location.pathname` meaning that it will continue to work correctly if the site is deployed to a subdirectory. - * Note that there is a `base` but no `assets`, since service workers cannot be used if `config.kit.paths.assets` is specified. - */ - export const base: string; - /** - * An array of URL strings representing the files generated by Vite, suitable for caching with `cache.addAll(build)`. - * During development, this is an empty array. - */ - export const build: string[]; - /** - * An array of URL strings representing the files in your static directory, or whatever directory is specified by `config.kit.files.assets`. You can customize which files are included from `static` directory using [`config.kit.serviceWorker.files`](https://kit.svelte.dev/docs/configuration) - */ - export const files: string[]; - /** - * An array of pathnames corresponding to prerendered pages and endpoints. - * During development, this is an empty array. - */ - export const prerendered: string[]; - /** - * See [`config.kit.version`](https://kit.svelte.dev/docs/configuration#version). It's useful for generating unique cache names inside your service worker, so that a later deployment of your app can invalidate old caches. - */ - export const version: string; -} - -declare module '@sveltejs/kit/hooks' { - import { Handle } from '@sveltejs/kit'; - - /** - * A helper function for sequencing multiple `handle` calls in a middleware-like manner. - * The behavior for the `handle` options is as follows: - * - `transformPageChunk` is applied in reverse order and merged - * - `preload` is applied in forward order, the first option "wins" and no `preload` options after it are called - * - `filterSerializedResponseHeaders` behaves the same as `preload` - * - * ```js - * /// file: src/hooks.server.js - * import { sequence } from '@sveltejs/kit/hooks'; - * - * /// type: import('@sveltejs/kit').Handle - * async function first({ event, resolve }) { - * console.log('first pre-processing'); - * const result = await resolve(event, { - * transformPageChunk: ({ html }) => { - * // transforms are applied in reverse order - * console.log('first transform'); - * return html; - * }, - * preload: () => { - * // this one wins as it's the first defined in the chain - * console.log('first preload'); - * } - * }); - * console.log('first post-processing'); - * return result; - * } - * - * /// type: import('@sveltejs/kit').Handle - * async function second({ event, resolve }) { - * console.log('second pre-processing'); - * const result = await resolve(event, { - * transformPageChunk: ({ html }) => { - * console.log('second transform'); - * return html; - * }, - * preload: () => { - * console.log('second preload'); - * }, - * filterSerializedResponseHeaders: () => { - * // this one wins as it's the first defined in the chain - * console.log('second filterSerializedResponseHeaders'); - * } - * }); - * console.log('second post-processing'); - * return result; - * } - * - * export const handle = sequence(first, second); - * ``` - * - * The example above would print: - * - * ``` - * first pre-processing - * first preload - * second pre-processing - * second filterSerializedResponseHeaders - * second transform - * first transform - * second post-processing - * first post-processing - * ``` - * - * @param handlers The chain of `handle` functions - */ - export function sequence(...handlers: Handle[]): Handle; -} - -/** - * A polyfill for `fetch` and its related interfaces, used by adapters for environments that don't provide a native implementation. - */ -declare module '@sveltejs/kit/node/polyfills' { - /** - * Make various web APIs available as globals: - * - `crypto` - * - `fetch` - * - `Headers` - * - `Request` - * - `Response` - */ - export function installPolyfills(): void; -} - -/** - * Utilities used by adapters for Node-like environments. - */ -declare module '@sveltejs/kit/node' { - export function getRequest(opts: { - base: string; - request: import('http').IncomingMessage; - bodySizeLimit?: number; - }): Promise; - export function setResponse(res: import('http').ServerResponse, response: Response): void; -} - -declare module '@sveltejs/kit/vite' { - import { Plugin } from 'vite'; - - /** - * Returns the SvelteKit Vite plugins. - */ - export function sveltekit(): Promise; - export { vitePreprocess } from '@sveltejs/vite-plugin-svelte'; -} diff --git a/packages/package/test/index.js b/packages/package/test/index.js index 62ca362f630e..03596f6def55 100644 --- a/packages/package/test/index.js +++ b/packages/package/test/index.js @@ -189,13 +189,13 @@ if (!process.env.CI) { compare('index.js'); // processes a .js file - write('src/lib/a.js', 'export const a = "a";'); + write('src/lib/a.js', "export const a = 'a';"); await settled(); compare('a.js'); compare('a.d.ts'); // processes a .ts file - write('src/lib/b.ts', 'export const b = "b";'); + write('src/lib/b.ts', "export const b = 'b';"); await settled(); compare('b.js'); compare('b.d.ts'); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 997c0659fd00..3b5f36a585aa 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -436,6 +436,9 @@ importers: '@types/set-cookie-parser': specifier: ^2.4.2 version: 2.4.2 + dts-buddy: + specifier: ^0.0.9 + version: 0.0.9 marked: specifier: ^4.2.3 version: 4.2.3 @@ -1546,11 +1549,32 @@ packages: engines: {node: '>=8'} dev: true + /@jridgewell/gen-mapping@0.3.3: + resolution: {integrity: sha512-HLhSWOLRi875zjjMG/r+Nv0oCW8umGb0BgEhyX3dDX3egwZtB8PqLnjz3yedt8R5StBrzcg4aBpnh8UA9D1BoQ==} + engines: {node: '>=6.0.0'} + dependencies: + '@jridgewell/set-array': 1.1.2 + '@jridgewell/sourcemap-codec': 1.4.15 + '@jridgewell/trace-mapping': 0.3.17 + dev: true + /@jridgewell/resolve-uri@3.1.0: resolution: {integrity: sha512-F2msla3tad+Mfht5cJq7LSXcdudKTWCVYUgw6pLFOOHSTtZlj6SWNYAp+AhuqLmWdBO2X5hPrLcu8cVP8fy28w==} engines: {node: '>=6.0.0'} dev: true + /@jridgewell/set-array@1.1.2: + resolution: {integrity: sha512-xnkseuNADM0gt2bs+BvhO0p78Mk762YnZdsuzFV018NoG1Sj1SCQvpSqa7XUaTam5vAGasABV9qXASMKnFMwMw==} + engines: {node: '>=6.0.0'} + dev: true + + /@jridgewell/source-map@0.3.3: + resolution: {integrity: sha512-b+fsZXeLYi9fEULmfBrhxn4IrPlINf8fiNarzTof004v3lFdntdwa9PF7vFJqm3mg7s+ScJMxXaE3Acp1irZcg==} + dependencies: + '@jridgewell/gen-mapping': 0.3.3 + '@jridgewell/trace-mapping': 0.3.17 + dev: true + /@jridgewell/sourcemap-codec@1.4.14: resolution: {integrity: sha512-XPSJHWmi394fuUuzDnGz1wiKqWfo1yXecHQMRf2l6hztTO+nPru658AyDngaBe7isIxEkRsPR3FZh+s7iVa4Uw==} @@ -2929,6 +2953,21 @@ packages: engines: {node: '>=12'} dev: true + /dts-buddy@0.0.9: + resolution: {integrity: sha512-T44cc55EgD9J0KEhXa/5Up4E7Cjc45RaGrDdHW/3l/sMu4YQMO77ReehPVweQCDfYwA9XnvxqxhbWLSg2XYQLA==} + hasBin: true + dependencies: + '@jridgewell/source-map': 0.3.3 + '@jridgewell/sourcemap-codec': 1.4.15 + globrex: 0.1.2 + kleur: 4.1.5 + locate-character: 2.0.5 + magic-string: 0.30.0 + sade: 1.8.1 + tiny-glob: 0.2.9 + typescript: 5.0.4 + dev: true + /emoji-regex@8.0.0: resolution: {integrity: sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==} @@ -4181,6 +4220,10 @@ packages: engines: {node: '>=14'} dev: true + /locate-character@2.0.5: + resolution: {integrity: sha512-n2GmejDXtOPBAZdIiEFy5dJ5N38xBCXLNOtw2WpB9kGh6pnrEuKlwYI+Tkpofc4wDtVXHtoAOJaMRlYG/oYaxg==} + dev: true + /locate-path@2.0.0: resolution: {integrity: sha512-NCI2kiDkyR7VeEKm27Kda/iQHyKJe1Bu0FlTbYp3CqJu+9IFe9bLyAjMxf5ZDDbEg+iMPzB5zYyUTSm8wVTKmA==} engines: {node: '>=4'} @@ -5984,6 +6027,12 @@ packages: hasBin: true dev: true + /typescript@5.0.4: + resolution: {integrity: sha512-cW9T5W9xY37cc+jfEnaUvX91foxtHkza3Nw3wkoF4sSlKn0MONdkdEndig/qPBWXNkmplh3NzayQzCiHM4/hqw==} + engines: {node: '>=12.20'} + hasBin: true + dev: true + /ufo@1.1.2: resolution: {integrity: sha512-TrY6DsjTQQgyS3E3dBaOXf0TpPD8u9FVrVYmKVegJuFw51n/YB9XPt+U6ydzFG5ZIN7+DIjPbNmXoBj9esYhgQ==} dev: true diff --git a/sites/kit.svelte.dev/scripts/types/index.js b/sites/kit.svelte.dev/scripts/types/index.js index 365ad50820bc..ae69a8fb4a6c 100644 --- a/sites/kit.svelte.dev/scripts/types/index.js +++ b/sites/kit.svelte.dev/scripts/types/index.js @@ -208,18 +208,7 @@ function read_d_ts_file(file) { } { - const code = read_d_ts_file('types/index.d.ts'); - const node = ts.createSourceFile('index.d.ts', code, ts.ScriptTarget.Latest, true); - - modules.push({ - name: '@sveltejs/kit', - comment: '', - ...get_types(code, node.statements) - }); -} - -{ - const code = read_d_ts_file('types/private.d.ts'); + const code = read_d_ts_file('src/types/private.d.ts'); const node = ts.createSourceFile('private.d.ts', code, ts.ScriptTarget.Latest, true); modules.push({ @@ -230,7 +219,7 @@ function read_d_ts_file(file) { } const dir = fileURLToPath( - new URL('../../../../packages/kit/types/synthetic', import.meta.url).href + new URL('../../../../packages/kit/src/types/synthetic', import.meta.url).href ); for (const file of fs.readdirSync(dir)) { if (!file.endsWith('.md')) continue; @@ -247,8 +236,8 @@ for (const file of fs.readdirSync(dir)) { } { - const code = read_d_ts_file('types/ambient.d.ts'); - const node = ts.createSourceFile('ambient.d.ts', code, ts.ScriptTarget.Latest, true); + const code = read_d_ts_file('types/index.d.ts'); + const node = ts.createSourceFile('index.d.ts', code, ts.ScriptTarget.Latest, true); for (const statement of node.statements) { if (ts.isModuleDeclaration(statement)) { @@ -268,6 +257,22 @@ for (const file of fs.readdirSync(dir)) { } } +// need to do some unfortunate finagling here, hopefully we can remove this one day +const app_paths = modules.find((module) => module.name === '$app/paths'); +const app_environment = modules.find((module) => module.name === '$app/environment'); +const __sveltekit_paths = modules.find((module) => module.name === '__sveltekit/paths'); +const __sveltekit_environment = modules.find((module) => module.name === '__sveltekit/environment'); + +app_paths.exports.push( + __sveltekit_paths.exports.find((e) => e.name === 'assets'), + __sveltekit_paths.exports.find((e) => e.name === 'base') +); + +app_environment.exports.push( + __sveltekit_environment.exports.find((e) => e.name === 'building'), + __sveltekit_environment.exports.find((e) => e.name === 'version') +); + modules.sort((a, b) => (a.name < b.name ? -1 : 1)); mkdirp('docs'); @@ -276,6 +281,10 @@ fs.writeFileSync( ` /* This file is generated by running \`node scripts/extract-types.js\` in the packages/kit directory — do not edit it */ -export const modules = ${JSON.stringify(modules, null, ' ')}; +export const modules = ${JSON.stringify( + modules.filter((m) => !m.name.startsWith('_')), + null, + ' ' + )}; `.trim() ); diff --git a/sites/kit.svelte.dev/src/lib/docs/server/render.js b/sites/kit.svelte.dev/src/lib/docs/server/render.js index 6762c17ce2c3..cfe1c80bbfec 100644 --- a/sites/kit.svelte.dev/src/lib/docs/server/render.js +++ b/sites/kit.svelte.dev/src/lib/docs/server/render.js @@ -66,6 +66,7 @@ export function replace_placeholders(content) { return modules .map((module) => { if (module.exports.length === 0 && !module.exempt) return ''; + if (module.name === 'Private types') return; let import_block = ''; diff --git a/sites/kit.svelte.dev/vercel.json b/sites/kit.svelte.dev/vercel.json index e17f42e185c2..c3c586fb80d1 100644 --- a/sites/kit.svelte.dev/vercel.json +++ b/sites/kit.svelte.dev/vercel.json @@ -5,5 +5,5 @@ }, "trailingSlash": false, "installCommand": "pnpm install --frozen-lockfile --verbose && pnpm rebuild", - "buildCommand": "pnpm build" + "buildCommand": "cd ../../packages/kit && pnpm prepublishOnly && cd ../../sites/kit.svelte.dev && pnpm build" }