import 'svelte'; // pick up `declare module "*.svelte"` import 'vite/client'; // pick up `declare module "*.jpg"`, etc. import '../types/ambient.js'; import { CompileOptions } from 'svelte/compiler'; import { AdapterEntry, CspDirectives, HttpMethod, Logger, MaybePromise, Prerendered, PrerenderEntryGeneratorMismatchHandlerValue, PrerenderHttpErrorHandlerValue, PrerenderMissingIdHandlerValue, PrerenderOption, RequestOptions, RouteSegment } from '../types/private.js'; import { BuildData, SSRNodeLoader, SSRRoute, ValidatedConfig } from 'types'; import type { PluginOptions } from '@sveltejs/vite-plugin-svelte'; export { PrerenderOption } from '../types/private.js'; /** * [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. */ export interface Adapter { /** * The name of the adapter, using for logging. Will typically correspond to the package name. */ name: string; /** * This function is called after SvelteKit has built your app. * @param builder An object provided by SvelteKit that contains methods for adapting the app */ adapt(builder: Builder): MaybePromise; /** * Checks called during dev and build to determine whether specific features will work in production with this adapter */ supports?: { /** * Test support for `read` from `$app/server` * @param config The merged route config */ read?: (details: { config: any; route: { id: string } }) => boolean; }; /** * Creates an `Emulator`, which allows the adapter to influence the environment * during dev, build and prerendering */ emulate?(): MaybePromise; } export type LoadProperties | void> = input extends void ? undefined // needs to be undefined, because void will break intellisense : input extends Record ? input : unknown; export type AwaitedActions any>> = OptionalUnion< { [Key in keyof T]: UnpackValidationError>>; }[keyof T] >; // Takes a union type and returns a union type where each type also has all properties // of all possible types (typed as undefined), making accessing them more ergonomic type OptionalUnion< U extends Record, // not unknown, else interfaces don't satisfy this constraint A extends keyof U = U extends U ? keyof U : never > = U extends unknown ? { [P in Exclude]?: never } & U : never; declare const uniqueSymbol: unique symbol; export interface ActionFailure | undefined = undefined> { status: number; data: T; [uniqueSymbol]: true; // necessary or else UnpackValidationError could wrongly unpack objects with the same shape as ActionFailure } type UnpackValidationError = T extends ActionFailure ? X : T extends void ? undefined // needs to be undefined, because void will corrupt union type : T; /** * This object is passed to the `adapt` function of adapters. * It contains various methods and properties that are useful for adapting the app. */ export interface Builder { /** Print messages to the console. `log.info` and `log.minor` are silent unless Vite's `logLevel` is `info`. */ log: Logger; /** Remove `dir` and all its contents. */ rimraf(dir: string): void; /** Create `dir` and any required parent directories. */ mkdirp(dir: string): void; /** The fully resolved `svelte.config.js`. */ config: ValidatedConfig; /** Information about prerendered pages and assets, if any. */ prerendered: Prerendered; /** An array of all routes (including prerendered) */ routes: RouteDefinition[]; // TODO 3.0 remove this method /** * Create separate functions that map to one or more routes of your app. * @param fn A function that groups a set of routes into an entry point * @deprecated Use `builder.routes` instead */ createEntries(fn: (route: RouteDefinition) => AdapterEntry): Promise; /** * Find all the assets imported by server files belonging to `routes` */ findServerAssets(routes: RouteDefinition[]): string[]; /** * Generate a fallback page for a static webserver to use when no route is matched. Useful for single-page apps. */ generateFallback(dest: string): Promise; /** * Generate a module exposing build-time environment variables as `$env/dynamic/public`. */ generateEnvModule(): void; /** * Generate a server-side manifest to initialise the SvelteKit [server](https://kit.svelte.dev/docs/types#public-types-server) with. * @param opts a relative path to the base directory of the app and optionally in which format (esm or cjs) the manifest should be generated */ generateManifest(opts: { relativePath: string; routes?: RouteDefinition[] }): string; /** * Resolve a path to the `name` directory inside `outDir`, e.g. `/path/to/.svelte-kit/my-adapter`. * @param name path to the file, relative to the build directory */ getBuildDirectory(name: string): string; /** Get the fully resolved path to the directory containing client-side assets, including the contents of your `static` directory. */ getClientDirectory(): string; /** Get the fully resolved path to the directory containing server-side code. */ getServerDirectory(): string; /** Get the application path including any configured `base` path, e.g. `my-base-path/_app`. */ getAppPath(): string; /** * Write client assets to `dest`. * @param dest the destination folder * @returns an array of files written to `dest` */ writeClient(dest: string): string[]; /** * Write prerendered files to `dest`. * @param dest the destination folder * @returns an array of files written to `dest` */ writePrerendered(dest: string): string[]; /** * Write server-side code to `dest`. * @param dest the destination folder * @returns an array of files written to `dest` */ writeServer(dest: string): string[]; /** * Copy a file or directory. * @param from the source file or directory * @param to the destination file or directory * @param opts.filter a function to determine whether a file or directory should be copied * @param opts.replace a map of strings to replace * @returns an array of files that were copied */ copy( from: string, to: string, opts?: { filter?(basename: string): boolean; replace?: Record; } ): string[]; /** * Compress files in `directory` with gzip and brotli, where appropriate. Generates `.gz` and `.br` files alongside the originals. * @param {string} directory The directory containing the files to be compressed */ compress(directory: string): Promise; } export interface Config { /** * Options passed to [`svelte.compile`](https://svelte.dev/docs#compile-time-svelte-compile). * @default {} */ compilerOptions?: CompileOptions; /** * List of file extensions that should be treated as Svelte files. * @default [".svelte"] */ extensions?: string[]; /** SvelteKit options */ kit?: KitConfig; /** Preprocessor options, if any. Preprocessing can alternatively also be done through Vite's preprocessor capabilities. */ preprocess?: any; /** `vite-plugin-svelte` plugin options. */ vitePlugin?: PluginOptions; /** Any additional options required by tooling that integrates with Svelte. */ [key: string]: any; } export interface Cookies { /** * Gets a cookie that was previously set with `cookies.set`, or from the request headers. * @param name the name of the cookie * @param opts the options, passed directly to `cookie.parse`. See documentation [here](https://github.com/jshttp/cookie#cookieparsestr-options) */ get(name: string, opts?: import('cookie').CookieParseOptions): string | undefined; /** * Gets all cookies that were previously set with `cookies.set`, or from the request headers. * @param opts the options, passed directly to `cookie.parse`. See documentation [here](https://github.com/jshttp/cookie#cookieparsestr-options) */ getAll(opts?: import('cookie').CookieParseOptions): Array<{ name: string; value: string }>; /** * Sets a cookie. This will add a `set-cookie` header to the response, but also make the cookie available via `cookies.get` or `cookies.getAll` during the current request. * * The `httpOnly` and `secure` options are `true` by default (except on http://localhost, where `secure` is `false`), and must be explicitly disabled if you want cookies to be readable by client-side JavaScript and/or transmitted over HTTP. The `sameSite` option defaults to `lax`. * * You must specify a `path` for the cookie. In most cases you should explicitly set `path: '/'` to make the cookie available throughout your app. You can use relative paths, or set `path: ''` to make the cookie only available on the current path and its children * @param name the name of the cookie * @param value the cookie value * @param opts the options, passed directly to `cookie.serialize`. See documentation [here](https://github.com/jshttp/cookie#cookieserializename-value-options) */ set( name: string, value: string, opts: import('cookie').CookieSerializeOptions & { path: string } ): void; /** * Deletes a cookie by setting its value to an empty string and setting the expiry date in the past. * * You must specify a `path` for the cookie. In most cases you should explicitly set `path: '/'` to make the cookie available throughout your app. You can use relative paths, or set `path: ''` to make the cookie only available on the current path and its children * @param name the name of the cookie * @param opts the options, passed directly to `cookie.serialize`. The `path` must match the path of the cookie you want to delete. See documentation [here](https://github.com/jshttp/cookie#cookieserializename-value-options) */ delete(name: string, opts: import('cookie').CookieSerializeOptions & { path: string }): void; /** * Serialize a cookie name-value pair into a `Set-Cookie` header string, but don't apply it to the response. * * The `httpOnly` and `secure` options are `true` by default (except on http://localhost, where `secure` is `false`), and must be explicitly disabled if you want cookies to be readable by client-side JavaScript and/or transmitted over HTTP. The `sameSite` option defaults to `lax`. * * You must specify a `path` for the cookie. In most cases you should explicitly set `path: '/'` to make the cookie available throughout your app. You can use relative paths, or set `path: ''` to make the cookie only available on the current path and its children * * @param name the name of the cookie * @param value the cookie value * @param opts the options, passed directly to `cookie.serialize`. See documentation [here](https://github.com/jshttp/cookie#cookieserializename-value-options) */ serialize( name: string, value: string, opts: import('cookie').CookieSerializeOptions & { path: string } ): string; } /** * A collection of functions that influence the environment during dev, build and prerendering */ export interface Emulator { /** * A function that is called with the current route `config` and `prerender` option * and returns an `App.Platform` object */ platform?(details: { config: any; prerender: PrerenderOption }): MaybePromise; } export interface KitConfig { /** * Your [adapter](https://kit.svelte.dev/docs/adapters) is run when executing `vite build`. It determines how the output is converted for different platforms. * @default undefined */ adapter?: Adapter; /** * An object containing zero or more aliases used to replace values in `import` statements. These aliases are automatically passed to Vite and TypeScript. * * ```js * /// file: svelte.config.js * /// type: import('@sveltejs/kit').Config * const config = { * kit: { * alias: { * // this will match a file * 'my-file': 'path/to/my-file.js', * * // this will match a directory and its contents * // (`my-directory/x` resolves to `path/to/my-directory/x`) * 'my-directory': 'path/to/my-directory', * * // an alias ending /* will only match * // the contents of a directory, not the directory itself * 'my-directory/*': 'path/to/my-directory/*' * } * } * }; * ``` * * > The built-in `$lib` alias is controlled by `config.kit.files.lib` as it is used for packaging. * * > You will need to run `npm run dev` to have SvelteKit automatically generate the required alias configuration in `jsconfig.json` or `tsconfig.json`. * @default {} */ alias?: Record; /** * The directory where SvelteKit keeps its stuff, including static assets (such as JS and CSS) and internally-used routes. * * If `paths.assets` is specified, there will be two app directories — `${paths.assets}/${appDir}` and `${paths.base}/${appDir}`. * @default "_app" */ appDir?: string; /** * [Content Security Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy) configuration. CSP helps to protect your users against cross-site scripting (XSS) attacks, by limiting the places resources can be loaded from. For example, a configuration like this... * * ```js * /// file: svelte.config.js * /// type: import('@sveltejs/kit').Config * const config = { * kit: { * csp: { * directives: { * 'script-src': ['self'] * }, * reportOnly: { * 'script-src': ['self'] * } * } * } * }; * * export default config; * ``` * * ...would prevent scripts loading from external sites. SvelteKit will augment the specified directives with nonces or hashes (depending on `mode`) for any inline styles and scripts it generates. * * To add a nonce for scripts and links manually included in `src/app.html`, you may use the placeholder `%sveltekit.nonce%` (for example ` * ``` * * If you set `pollInterval` to a non-zero value, SvelteKit will poll for new versions in the background and set the value of the [`updated`](/docs/modules#$app-stores-updated) store to `true` when it detects one. */ version?: { /** * The current app version string. If specified, this must be deterministic (e.g. a commit ref rather than `Math.random()` or `Date.now().toString()`), otherwise defaults to a timestamp of the build. * * For example, to use the current commit hash, you could do use `git rev-parse HEAD`: * * ```js * /// file: svelte.config.js * import * as child_process from 'node:child_process'; * * export default { * kit: { * version: { * name: child_process.execSync('git rev-parse HEAD').toString().trim() * } * } * }; * ``` */ name?: string; /** * The interval in milliseconds to poll for version changes. If this is `0`, no polling occurs. * @default 0 */ pollInterval?: number; }; } /** * The [`handle`](https://kit.svelte.dev/docs/hooks#server-hooks-handle) hook runs every time the SvelteKit server receives a [request](https://kit.svelte.dev/docs/web-standards#fetch-apis-request) and * determines the [response](https://kit.svelte.dev/docs/web-standards#fetch-apis-response). * 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 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. * * 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 type HandleServerError = (input: { error: unknown; event: RequestEvent; status: number; message: string; }) => MaybePromise; /** * The client-side [`handleError`](https://kit.svelte.dev/docs/hooks#shared-hooks-handleerror) hook runs when an unexpected error is thrown while navigating. * * 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 type HandleClientError = (input: { error: unknown; event: NavigationEvent; status: number; message: string; }) => 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 type HandleFetch = (input: { event: RequestEvent; request: Request; fetch: typeof fetch; }) => MaybePromise; /** * The [`reroute`](https://kit.svelte.dev/docs/hooks#universal-hooks-reroute) hook allows you to modify the URL before it is used to determine which route to render. * @since 2.3.0 */ export type Reroute = (event: { url: URL }) => void | string; /** * 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 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; /** * The generic form of `PageLoadEvent` and `LayoutLoadEvent`. You should import those from `./$types` (see [generated types](https://kit.svelte.dev/docs/types#generated-types)) * rather than using `LoadEvent` directly. */ export interface LoadEvent< Params extends Partial> = Partial>, Data extends Record | null = Record | null, ParentData extends Record = Record, RouteId extends string | null = string | null > extends NavigationEvent { /** * `fetch` is equivalent to the [native `fetch` web API](https://developer.mozilla.org/en-US/docs/Web/API/fetch), with a few additional features: * * - It can be used to make credentialed requests on the server, as it inherits the `cookie` and `authorization` headers for the page request. * - It can make relative requests on the server (ordinarily, `fetch` requires a URL with an origin when used in a server context). * - Internal requests (e.g. for `+server.js` routes) go directly to the handler function when running on the server, without the overhead of an HTTP call. * - During server-side rendering, the response will be captured and inlined into the rendered HTML by hooking into the `text` and `json` methods of the `Response` object. Note that headers will _not_ be serialized, unless explicitly included via [`filterSerializedResponseHeaders`](https://kit.svelte.dev/docs/hooks#server-hooks-handle) * - During hydration, the response will be read from the HTML, guaranteeing consistency and preventing an additional network request. * * You can learn more about making credentialed requests with cookies [here](https://kit.svelte.dev/docs/load#cookies) */ fetch: typeof fetch; /** * Contains the data returned by the route's server `load` function (in `+layout.server.js` or `+page.server.js`), if any. */ data: Data; /** * If you need to set headers for the response, you can do so using the this method. This is useful if you want the page to be cached, for example: * * ```js * /// file: src/routes/blog/+page.js * export async function load({ fetch, setHeaders }) { * const url = `https://cms.example.com/articles.json`; * const response = await fetch(url); * * setHeaders({ * age: response.headers.get('age'), * 'cache-control': response.headers.get('cache-control') * }); * * return response.json(); * } * ``` * * Setting the same header multiple times (even in separate `load` functions) is an error — you can only set a given header once. * * You cannot add a `set-cookie` header with `setHeaders` — use the [`cookies`](https://kit.svelte.dev/docs/types#public-types-cookies) API in a server-only `load` function instead. * * `setHeaders` has no effect when a `load` function runs in the browser. */ setHeaders(headers: Record): void; /** * `await parent()` returns data from parent `+layout.js` `load` functions. * Implicitly, a missing `+layout.js` is treated as a `({ data }) => data` function, meaning that it will return and forward data from parent `+layout.server.js` files. * * Be careful not to introduce accidental waterfalls when using `await parent()`. If for example you only want to merge parent data into the returned output, call it _after_ fetching your other data. */ parent(): Promise; /** * This function declares that the `load` function has a _dependency_ on one or more URLs or custom identifiers, which can subsequently be used with [`invalidate()`](/docs/modules#$app-navigation-invalidate) to cause `load` to rerun. * * Most of the time you won't need this, as `fetch` calls `depends` on your behalf — it's only necessary if you're using a custom API client that bypasses `fetch`. * * URLs can be absolute or relative to the page being loaded, and must be [encoded](https://developer.mozilla.org/en-US/docs/Glossary/percent-encoding). * * Custom identifiers have to be prefixed with one or more lowercase letters followed by a colon to conform to the [URI specification](https://www.rfc-editor.org/rfc/rfc3986.html). * * The following example shows how to use `depends` to register a dependency on a custom identifier, which is `invalidate`d after a button click, making the `load` function rerun. * * ```js * /// file: src/routes/+page.js * let count = 0; * export async function load({ depends }) { * depends('increase:count'); * * return { count: count++ }; * } * ``` * * ```html * /// file: src/routes/+page.svelte * * *

{data.count}

* * ``` */ depends(...deps: Array<`${string}:${string}`>): void; /** * Use this function to opt out of dependency tracking for everything that is synchronously called within the callback. Example: * * ```js * /// file: src/routes/+page.server.js * export async function load({ untrack, url }) { * // Untrack url.pathname so that path changes don't trigger a rerun * if (untrack(() => url.pathname === '/')) { * return { message: 'Welcome!' }; * } * } * ``` */ untrack(fn: () => T): T; } export interface NavigationEvent< Params extends Partial> = Partial>, RouteId extends string | null = string | null > { /** * The parameters of the current page - e.g. for a route like `/blog/[slug]`, a `{ slug: string }` object */ params: Params; /** * Info about the current route */ route: { /** * The ID of the current route - e.g. for `src/routes/blog/[slug]`, it would be `/blog/[slug]` */ id: RouteId; }; /** * The URL of the current page */ url: URL; } /** * Information about the target of a specific navigation. */ export interface NavigationTarget { /** * Parameters of the target page - e.g. for a route like `/blog/[slug]`, a `{ slug: string }` object. * Is `null` if the target is not part of the SvelteKit app (could not be resolved to a route). */ params: Record | null; /** * Info about the target route */ route: { id: string | null }; /** * The URL that is navigated to */ url: URL; } /** * - `enter`: The app has hydrated * - `form`: The user submitted a `

` with a GET method * - `leave`: The user is leaving the app by closing the tab or using the back/forward buttons to go to a different document * - `link`: Navigation was triggered by a link click * - `goto`: Navigation was triggered by a `goto(...)` call or a redirect * - `popstate`: Navigation was triggered by back/forward navigation */ export type NavigationType = 'enter' | 'form' | 'leave' | 'link' | 'goto' | 'popstate'; export interface Navigation { /** * Where navigation was triggered from */ from: NavigationTarget | null; /** * Where navigation is going to/has gone to */ to: NavigationTarget | null; /** * The type of navigation: * - `form`: The user submitted a `` * - `leave`: The app is being left either because the tab is being closed or a navigation to a different document is occurring * - `link`: Navigation was triggered by a link click * - `goto`: Navigation was triggered by a `goto(...)` call or a redirect * - `popstate`: Navigation was triggered by back/forward navigation */ type: Exclude; /** * Whether or not the navigation will result in the page being unloaded (i.e. not a client-side navigation) */ willUnload: boolean; /** * In case of a history back/forward navigation, the number of steps to go back/forward */ delta?: number; /** * A promise that resolves once the navigation is complete, and rejects if the navigation * fails or is aborted. In the case of a `willUnload` navigation, the promise will never resolve */ complete: Promise; } /** * The argument passed to [`beforeNavigate`](https://kit.svelte.dev/docs/modules#$app-navigation-beforenavigate) callbacks. */ export interface BeforeNavigate extends Navigation { /** * Call this to prevent the navigation from starting. */ cancel(): void; } /** * The argument passed to [`onNavigate`](https://kit.svelte.dev/docs/modules#$app-navigation-onnavigate) callbacks. */ export interface OnNavigate extends Navigation { /** * The type of navigation: * - `form`: The user submitted a `` * - `link`: Navigation was triggered by a link click * - `goto`: Navigation was triggered by a `goto(...)` call or a redirect * - `popstate`: Navigation was triggered by back/forward navigation */ type: Exclude; /** * Since `onNavigate` callbacks are called immediately before a client-side navigation, they will never be called with a navigation that unloads the page. */ willUnload: false; } /** * The argument passed to [`afterNavigate`](https://kit.svelte.dev/docs/modules#$app-navigation-afternavigate) callbacks. */ export interface AfterNavigate extends Omit { /** * The type of navigation: * - `enter`: The app has hydrated * - `form`: The user submitted a `` * - `link`: Navigation was triggered by a link click * - `goto`: Navigation was triggered by a `goto(...)` call or a redirect * - `popstate`: Navigation was triggered by back/forward navigation */ type: Exclude; /** * Since `afterNavigate` callbacks are called after a navigation completes, they will never be called with a navigation that unloads the page. */ willUnload: false; } /** * The shape of the `$page` store */ export interface Page< Params extends Record = Record, RouteId extends string | null = string | null > { /** * The URL of the current page */ url: URL; /** * The parameters of the current page - e.g. for a route like `/blog/[slug]`, a `{ slug: string }` object */ params: Params; /** * Info about the current route */ route: { /** * The ID of the current route - e.g. for `src/routes/blog/[slug]`, it would be `/blog/[slug]` */ id: RouteId; }; /** * Http status code of the current page */ status: number; /** * The error object of the current page, if any. Filled from the `handleError` hooks. */ error: App.Error | null; /** * The merged result of all data from all `load` functions on the current page. You can type a common denominator through `App.PageData`. */ data: App.PageData & Record; /** * The page state, which can be manipulated using the [`pushState`](https://kit.svelte.dev/docs/modules#$app-navigation-pushstate) and [`replaceState`](https://kit.svelte.dev/docs/modules#$app-navigation-replacestate) functions from `$app/navigation`. */ state: App.PageState; /** * Filled only after a form submission. See [form actions](https://kit.svelte.dev/docs/form-actions) for more info. */ form: any; } /** * The shape of a param matcher. See [matching](https://kit.svelte.dev/docs/advanced-routing#matching) for more info. */ export type ParamMatcher = (param: string) => boolean; export interface RequestEvent< Params extends Partial> = Partial>, RouteId extends string | null = string | null > { /** * Get or set cookies related to the current request */ cookies: Cookies; /** * `fetch` is equivalent to the [native `fetch` web API](https://developer.mozilla.org/en-US/docs/Web/API/fetch), with a few additional features: * * - It can be used to make credentialed requests on the server, as it inherits the `cookie` and `authorization` headers for the page request. * - It can make relative requests on the server (ordinarily, `fetch` requires a URL with an origin when used in a server context). * - Internal requests (e.g. for `+server.js` routes) go directly to the handler function when running on the server, without the overhead of an HTTP call. * - During server-side rendering, the response will be captured and inlined into the rendered HTML by hooking into the `text` and `json` methods of the `Response` object. Note that headers will _not_ be serialized, unless explicitly included via [`filterSerializedResponseHeaders`](https://kit.svelte.dev/docs/hooks#server-hooks-handle) * - During hydration, the response will be read from the HTML, guaranteeing consistency and preventing an additional network request. * * You can learn more about making credentialed requests with cookies [here](https://kit.svelte.dev/docs/load#cookies) */ fetch: typeof fetch; /** * The client's IP address, set by the adapter. */ getClientAddress(): string; /** * Contains custom data that was added to the request within the [`handle hook`](https://kit.svelte.dev/docs/hooks#server-hooks-handle). */ locals: App.Locals; /** * The parameters of the current route - e.g. for a route like `/blog/[slug]`, a `{ slug: string }` object */ params: Params; /** * Additional data made available through the adapter. */ platform: Readonly | undefined; /** * The original request object */ request: Request; /** * Info about the current route */ route: { /** * The ID of the current route - e.g. for `src/routes/blog/[slug]`, it would be `/blog/[slug]` */ id: RouteId; }; /** * If you need to set headers for the response, you can do so using the this method. This is useful if you want the page to be cached, for example: * * ```js * /// file: src/routes/blog/+page.js * export async function load({ fetch, setHeaders }) { * const url = `https://cms.example.com/articles.json`; * const response = await fetch(url); * * setHeaders({ * age: response.headers.get('age'), * 'cache-control': response.headers.get('cache-control') * }); * * return response.json(); * } * ``` * * Setting the same header multiple times (even in separate `load` functions) is an error — you can only set a given header once. * * You cannot add a `set-cookie` header with `setHeaders` — use the [`cookies`](https://kit.svelte.dev/docs/types#public-types-cookies) API instead. */ setHeaders(headers: Record): void; /** * The requested URL. */ url: URL; /** * `true` if the request comes from the client asking for `+page/layout.server.js` data. The `url` property will be stripped of the internal information * related to the data request in this case. Use this property instead if the distinction is important to you. */ isDataRequest: boolean; /** * `true` for `+server.js` calls coming from SvelteKit without the overhead of actually making an HTTP request. This happens when you make same-origin `fetch` requests on the server. */ isSubRequest: boolean; } /** * A `(event: RequestEvent) => Response` function exported from a `+server.js` file that corresponds to an HTTP verb (`GET`, `PUT`, `PATCH`, etc) and handles requests with that method. * * 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 type RequestHandler< Params extends Partial> = Partial>, RouteId extends string | null = string | null > = (event: RequestEvent) => MaybePromise; export interface ResolveOptions { /** * Applies custom transforms to HTML. If `done` is true, it's the final chunk. Chunks are not guaranteed to be well-formed HTML * (they could include an element's opening tag but not its closing tag, for example) * but they will always be split at sensible boundaries such as `%sveltekit.head%` or layout/page components. * @param input the html chunk and the info if this is the last chunk */ transformPageChunk?(input: { html: string; done: boolean }): MaybePromise; /** * Determines which headers should be included in serialized responses when a `load` function loads a resource with `fetch`. * By default, none will be included. * @param name header name * @param value header value */ filterSerializedResponseHeaders?(name: string, value: string): boolean; /** * Determines what should be added to the `` tag to preload it. * By default, `js` and `css` files will be preloaded. * @param input the type of the file and its path */ preload?(input: { type: 'font' | 'css' | 'js' | 'asset'; path: string }): boolean; } export interface RouteDefinition { id: string; api: { methods: Array; }; page: { methods: Array>; }; pattern: RegExp; prerender: PrerenderOption; segments: RouteSegment[]; methods: Array; config: Config; } export class Server { constructor(manifest: SSRManifest); init(options: ServerInitOptions): Promise; respond(request: Request, options: RequestOptions): Promise; } export interface ServerInitOptions { /** A map of environment variables */ env: Record; /** A function that turns an asset filename into a `ReadableStream`. Required for the `read` export from `$app/server` to work */ read?: (file: string) => ReadableStream; } export interface SSRManifest { appDir: string; appPath: string; assets: Set; mimeTypes: Record; /** private fields */ _: { client: NonNullable; nodes: SSRNodeLoader[]; routes: SSRRoute[]; matchers(): Promise>; /** A `[file]: size` map of all assets imported by server code */ server_assets: Record; }; } /** * 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 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; export interface ServerLoadEvent< Params extends Partial> = Partial>, ParentData extends Record = Record, RouteId extends string | null = string | null > extends RequestEvent { /** * `await parent()` returns data from parent `+layout.server.js` `load` functions. * * Be careful not to introduce accidental waterfalls when using `await parent()`. If for example you only want to merge parent data into the returned output, call it _after_ fetching your other data. */ parent(): Promise; /** * This function declares that the `load` function has a _dependency_ on one or more URLs or custom identifiers, which can subsequently be used with [`invalidate()`](/docs/modules#$app-navigation-invalidate) to cause `load` to rerun. * * Most of the time you won't need this, as `fetch` calls `depends` on your behalf — it's only necessary if you're using a custom API client that bypasses `fetch`. * * URLs can be absolute or relative to the page being loaded, and must be [encoded](https://developer.mozilla.org/en-US/docs/Glossary/percent-encoding). * * Custom identifiers have to be prefixed with one or more lowercase letters followed by a colon to conform to the [URI specification](https://www.rfc-editor.org/rfc/rfc3986.html). * * The following example shows how to use `depends` to register a dependency on a custom identifier, which is `invalidate`d after a button click, making the `load` function rerun. * * ```js * /// file: src/routes/+page.js * let count = 0; * export async function load({ depends }) { * depends('increase:count'); * * return { count: count++ }; * } * ``` * * ```html * /// file: src/routes/+page.svelte * * *

{data.count}

* * ``` */ depends(...deps: string[]): void; /** * Use this function to opt out of dependency tracking for everything that is synchronously called within the callback. Example: * * ```js * /// file: src/routes/+page.js * export async function load({ untrack, url }) { * // Untrack url.pathname so that path changes don't trigger a rerun * if (untrack(() => url.pathname === '/')) { * return { message: 'Welcome!' }; * } * } * ``` */ untrack(fn: () => T): T; } /** * 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 type Action< Params extends Partial> = Partial>, OutputData extends Record | void = Record | void, RouteId extends string | null = string | null > = (event: RequestEvent) => MaybePromise; /** * Shape of the `export const actions = {..}` object in `+page.server.js`. * See [form actions](https://kit.svelte.dev/docs/form-actions) for more information. */ export type Actions< Params extends Partial> = Partial>, OutputData extends Record | void = Record | void, RouteId extends string | null = string | null > = Record>; /** * When calling a form action via fetch, the response will be one of these shapes. * ```svelte * { * return ({ result }) => { * // result is of type ActionResult * }; * }} * ``` */ export type ActionResult< Success extends Record | undefined = Record, Failure extends Record | undefined = Record > = | { type: 'success'; status: number; data?: Success } | { type: 'failure'; status: number; data?: Failure } | { type: 'redirect'; status: number; location: string } | { type: 'error'; status?: number; error: any }; /** * The object returned by the [`error`](https://kit.svelte.dev/docs/modules#sveltejs-kit-error) function. */ export interface HttpError { /** The [HTTP status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#client_error_responses), in the range 400-599. */ status: number; /** The content of the error. */ body: App.Error; } /** * The object returned by the [`redirect`](https://kit.svelte.dev/docs/modules#sveltejs-kit-redirect) function */ export interface Redirect { /** The [HTTP status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#redirection_messages), in the range 300-308. */ status: 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308; /** The location to redirect to. */ location: string; } export type SubmitFunction< Success extends Record | undefined = Record, Failure extends Record | undefined = Record > = (input: { action: URL; formData: FormData; formElement: HTMLFormElement; controller: AbortController; submitter: HTMLElement | null; cancel(): void; }) => MaybePromise< | void | ((opts: { formData: FormData; 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. * @param invalidateAll Set `invalidateAll: false` if you don't want the action to call `invalidateAll` after submission. */ update(options?: { reset?: boolean; invalidateAll?: boolean }): Promise; }) => void) >; /** * The type of `export const snapshot` exported from a page or layout component. */ export interface Snapshot { capture: () => T; restore: (snapshot: T) => void; } export * from './index.js';