-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
index.d.ts
1170 lines (1113 loc) · 45.9 KB
/
index.d.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/// <reference types="svelte" />
/// <reference types="vite/client" />
import './ambient.js';
import { CompileOptions } from 'svelte/types/compiler/interfaces';
import {
AdapterEntry,
CspDirectives,
Logger,
MaybePromise,
Prerendered,
PrerenderHttpErrorHandlerValue,
PrerenderMissingIdHandlerValue,
RequestOptions,
RouteDefinition,
UniqueInterface
} from './private.js';
import { SSRNodeLoader, SSRRoute, ValidatedConfig } from './internal.js';
export { PrerenderOption } from './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<void>;
}
type AwaitedPropertiesUnion<input extends Record<string, any> | void> = input extends void
? undefined // needs to be undefined, because void will break intellisense
: input extends Record<string, any>
? {
[key in keyof input]: Awaited<input[key]>;
}
: {} extends input // handles the any case
? input
: unknown;
export type AwaitedProperties<input extends Record<string, any> | void> =
AwaitedPropertiesUnion<input> extends Record<string, any>
? OptionalUnion<AwaitedPropertiesUnion<input>>
: AwaitedPropertiesUnion<input>;
export type AwaitedActions<T extends Record<string, (...args: any) => any>> = {
[Key in keyof T]: OptionalUnion<UnpackValidationError<Awaited<ReturnType<T[Key]>>>>;
}[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<string, any>, // 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<A, keyof U>]?: never } & U : never;
type UnpackValidationError<T> = T extends ValidationError<infer X>
? 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;
/**
* 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
*/
createEntries(fn: (route: RouteDefinition) => AdapterEntry): Promise<void>;
/**
* Generate a fallback page for a static webserver to use when no route is matched. Useful for single-page apps.
*/
generateFallback(dest: string): Promise<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 }): 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, string>;
}
): 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<void>;
}
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;
/** [`@sveltejs/package`](/docs/packaging) options. */
package?: {
source?: string;
dir?: string;
emitTypes?: boolean;
exports?(filepath: string): boolean;
files?(filepath: string): boolean;
};
/** Preprocessor options, if any. Preprocessing can alternatively also be done through Vite's preprocessor capabilities. */
preprocess?: any;
/** 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;
/**
* Sets a cookie. This will add a `set-cookie` header to the response, but also make the cookie available via `cookies.get` 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`.
*
* By default, the `path` of a cookie is the 'directory' of the current pathname. In most cases you should explicitly set `path: '/'` to make the cookie available throughout your app.
* @param name the name of the cookie
* @param value the cookie value
* @param opts the options, passed directory to `cookie.serialize`. See documentation [here](https://github.com/jshttp/cookie#cookieserializename-value-options)
*/
set(name: string, value: string, opts?: import('cookie').CookieSerializeOptions): void;
/**
* Deletes a cookie by setting its value to an empty string and setting the expiry date in the past.
*
* By default, the `path` of a cookie is the 'directory' of the current pathname. In most cases you should explicitly set `path: '/'` to make the cookie available throughout your app.
* @param name the name of the cookie
* @param opts the options, passed directory 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): 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`.
*
* By default, the `path` of a cookie is the current pathname. In most cases you should explicitly set `path: '/'` to make the cookie available throughout your app.
*
* @param name the name of the cookie
* @param value the cookie value
* @param opts the options, passed directory to `cookie.serialize`. See documentation [here](https://github.com/jshttp/cookie#cookieserializename-value-options)
*/
serialize(name: string, value: string, opts?: import('cookie').CookieSerializeOptions): string;
}
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<string, string>;
/**
* The directory relative to `paths.assets` where the built JS and CSS (and imported assets) are served from. (The filenames therein contain content-based hashes, meaning they can be cached indefinitely). Must not start or end with `/`.
* @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 `<script nonce="%sveltekit.nonce%">`).
*
* When pages are prerendered, the CSP header is added via a `<meta http-equiv>` tag (note that in this case, `frame-ancestors`, `report-uri` and `sandbox` directives will be ignored).
*
* > When `mode` is `'auto'`, SvelteKit will use nonces for dynamically rendered pages and hashes for prerendered pages. Using nonces with prerendered pages is insecure and therefore forbidden.
*
* > Note that most [Svelte transitions](https://svelte.dev/tutorial/transition) work by creating an inline `<style>` element. If you use these in your app, you must either leave the `style-src` directive unspecified or add `unsafe-inline`.
*/
csp?: {
/**
* Whether to use hashes or nonces to restrict `<script>` and `<style>` elements. `'auto'` will use hashes for prerendered pages, and nonces for dynamically rendered pages.
*/
mode?: 'hash' | 'nonce' | 'auto';
/**
* Directives that will be added to `Content-Security-Policy` headers.
*/
directives?: CspDirectives;
/**
* Directives that will be added to `Content-Security-Policy-Report-Only` headers.
*/
reportOnly?: CspDirectives;
};
/**
* Protection against [cross-site request forgery](https://owasp.org/www-community/attacks/csrf) attacks.
*/
csrf?: {
/**
* Whether to check the incoming `origin` header for `POST` form submissions and verify that it matches the server's origin.
*
* To allow people to make `POST` form submissions to your app from other origins, you will need to disable this option. Be careful!
* @default true
*/
checkOrigin?: boolean;
};
/**
* Whether or not the app is embedded inside a larger app. If `true`, SvelteKit will add its event listeners related to navigation etc on the parent of `%sveltekit.body%` instead of `window`, and will pass `params` from the server rather than inferring them from `location.pathname`.
* @default false
*/
embedded?: boolean;
/**
* Environment variable configuration
*/
env?: {
/**
* The directory to search for `.env` files.
* @default "."
*/
dir?: string;
/**
* A prefix that signals that an environment variable is safe to expose to client-side code. See [`$env/static/public`](/docs/modules#$env-static-public) and [`$env/dynamic/public`](/docs/modules#$env-dynamic-public). Note that Vite's [`envPrefix`](https://vitejs.dev/config/shared-options.html#envprefix) must be set separately if you are using Vite's environment variable handling - though use of that feature should generally be unnecessary.
* @default "PUBLIC_"
*/
publicPrefix?: string;
};
/**
* Where to find various files within your project.
*/
files?: {
/**
* a place to put static files that should have stable URLs and undergo no processing, such as `favicon.ico` or `manifest.json`
* @default "static"
*/
assets?: string;
hooks?: {
/**
* The location of your client [hooks](https://kit.svelte.dev/docs/hooks).
* @default "src/hooks.client"
*/
client?: string;
/**
* The location of your server [hooks](https://kit.svelte.dev/docs/hooks).
* @default "src/hooks.server"
*/
server?: string;
};
/**
* your app's internal library, accessible throughout the codebase as `$lib`
* @default "src/lib"
*/
lib?: string;
/**
* a directory containing [parameter matchers](https://kit.svelte.dev/docs/advanced-routing#matching)
* @default "src/params"
*/
params?: string;
/**
* the files that define the structure of your app (see [Routing](https://kit.svelte.dev/docs/routing))
* @default "src/routes"
*/
routes?: string;
/**
* the location of your service worker's entry point (see [Service workers](https://kit.svelte.dev/docs/service-workers))
* @default "src/service-worker"
*/
serviceWorker?: string;
/**
* the location of the template for HTML responses
* @default "src/app.html"
*/
appTemplate?: string;
/**
* the location of the template for fallback error responses
* @default "src/error.html"
*/
errorTemplate?: string;
};
/**
* Inline CSS inside a `<style>` block at the head of the HTML. This option is a number that specifies the maximum length of a CSS file to be inlined. All CSS files needed for the page and smaller than this value are merged and inlined in a `<style>` block.
*
* > This results in fewer initial requests and can improve your [First Contentful Paint](https://web.dev/first-contentful-paint) score. However, it generates larger HTML output and reduces the effectiveness of browser caches. Use it advisedly.
* @default 0
*/
inlineStyleThreshold?: number;
/**
* An array of file extensions that SvelteKit will treat as modules. Files with extensions that match neither `config.extensions` nor `config.kit.moduleExtensions` will be ignored by the router.
* @default [".js", ".ts"]
*/
moduleExtensions?: string[];
/**
* The directory that SvelteKit writes files to during `dev` and `build`. You should exclude this directory from version control.
* @default ".svelte-kit"
*/
outDir?: string;
paths?: {
/**
* An absolute path that your app's files are served from. This is useful if your files are served from a storage bucket of some kind.
* @default ""
*/
assets?: string;
/**
* A root-relative path that must start, but not end with `/` (e.g. `/base-path`), unless it is the empty string. This specifies where your app is served from and allows the app to live on a non-root path. Note that you need to prepend all your root-relative links with the base value or they will point to the root of your domain, not your `base` (this is how the browser works). You can use [`base` from `$app/paths`](/docs/modules#$app-paths-base) for that: `<a href="{base}/your-page">Link</a>`. If you find yourself writing this often, it may make sense to extract this into a reusable component.
* @default ""
*/
base?: string;
};
/**
* See [Prerendering](https://kit.svelte.dev/docs/page-options#prerender).
*/
prerender?: {
/**
* How many pages can be prerendered simultaneously. JS is single-threaded, but in cases where prerendering performance is network-bound (for example loading content from a remote CMS) this can speed things up by processing other tasks while waiting on the network response.
* @default 1
*/
concurrency?: number;
/**
* Whether SvelteKit should find pages to prerender by following links from `entries`.
* @default true
*/
crawl?: boolean;
/**
* An array of pages to prerender, or start crawling from (if `crawl: true`). The `*` string includes all non-dynamic routes (i.e. pages with no `[parameters]`, because SvelteKit doesn't know what value the parameters should have).
* @default ["*"]
*/
entries?: Array<'*' | `/${string}`>;
/**
* How to respond to HTTP errors encountered while prerendering the app.
*
* - `'fail'` — fail the build
* - `'ignore'` - silently ignore the failure and continue
* - `'warn'` — continue, but print a warning
* - `(details) => void` — a custom error handler that takes a `details` object with `status`, `path`, `referrer`, `referenceType` and `message` properties. If you `throw` from this function, the build will fail
*
* ```js
* /// type: import('@sveltejs/kit').Config
* const config = {
* kit: {
* prerender: {
* handleHttpError: ({ path, referrer, message }) => {
* // ignore deliberate link to shiny 404 page
* if (path === '/not-found' && referrer === '/blog/how-we-built-our-404-page') {
* return;
* }
*
* // otherwise fail the build
* throw new Error(message);
* }
* }
* }
* }
* };
* ```
*
* @default "fail"
*/
handleHttpError?: PrerenderHttpErrorHandlerValue;
/**
* How to respond to hash links from one prerendered page to another that don't correspond to an `id` on the destination page
*
* - `'fail'` — fail the build
* - `'ignore'` - silently ignore the failure and continue
* - `'warn'` — continue, but print a warning
* - `(details) => void` — a custom error handler that takes a `details` object with `path`, `id`, `referrers` and `message` properties. If you `throw` from this function, the build will fail
*
* @default "fail"
*/
handleMissingId?: PrerenderMissingIdHandlerValue;
/**
* The value of `url.origin` during prerendering; useful if it is included in rendered content.
* @default "http://sveltekit-prerender"
*/
origin?: string;
};
serviceWorker?: {
/**
* Whether to automatically register the service worker, if it exists.
* @default true
*/
register?: boolean;
/**
* Determine which files in your `static` directory will be available in `$service-worker.files`.
* @default (filename) => !/\.DS_Store/.test(filename)
*/
files?(filepath: string): boolean;
};
/**
* Client-side navigation can be buggy if you deploy a new version of your app while people are using it. If the code for the new page is already loaded, it may have stale content; if it isn't, the app's route manifest may point to a JavaScript file that no longer exists. SvelteKit solves this problem by falling back to traditional full-page navigation if it detects that a new version has been deployed, using the `name` specified here (which defaults to a timestamp of the build).
*
* 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.
* @default Date.now().toString()
*/
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 interface Handle {
(input: {
event: RequestEvent;
resolve(event: RequestEvent, opts?: ResolveOptions): MaybePromise<Response>;
}): MaybePromise<Response>;
}
/**
* 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 interface HandleServerError {
(input: { error: unknown; event: RequestEvent }): MaybePromise<void | App.Error>;
}
/**
* 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 interface HandleClientError {
(input: { error: unknown; event: NavigationEvent }): MaybePromise<void | App.Error>;
}
/**
* 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<Response>;
}
/**
* 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<
Params extends Partial<Record<string, string>> = Partial<Record<string, string>>,
InputData extends Record<string, unknown> | null = Record<string, any> | null,
ParentData extends Record<string, unknown> = Record<string, any>,
OutputData extends Record<string, unknown> | void = Record<string, any> | void,
RouteId extends string | null = string | null
> {
(event: LoadEvent<Params, InputData, ParentData, RouteId>): MaybePromise<OutputData>;
}
/**
* 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<Record<string, string>> = Partial<Record<string, string>>,
Data extends Record<string, unknown> | null = Record<string, any> | null,
ParentData extends Record<string, unknown> = Record<string, any>,
RouteId extends string | null = string | null
> extends NavigationEvent<Params, RouteId> {
/**
* `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. 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
*
* > Cookies will only be passed through if the target host is the same as the SvelteKit application or a more specific subdomain of it.
*/
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<string, string>): 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<ParentData>;
/**
* 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
* <script>
* import { invalidate } from '$app/navigation';
*
* export let data;
*
* const increase = async () => {
* await invalidate('increase:count');
* }
* </script>
*
* <p>{data.count}<p>
* <button on:click={increase}>Increase Count</button>
* ```
*/
depends(...deps: string[]): void;
}
export interface NavigationEvent<
Params extends Partial<Record<string, string>> = Partial<Record<string, string>>,
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<string, string> | 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 `<form>`
* - `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 `<form>`
* - `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
*/
type: Omit<NavigationType, 'enter'>;
/**
* 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;
}
/**
* 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 [`afterNavigate`](https://kit.svelte.dev/docs/modules#$app-navigation-afternavigate) callbacks.
*/
export interface AfterNavigate extends Navigation {
/**
* The type of navigation:
* - `enter`: The app has hydrated
* - `form`: The user submitted a `<form>`
* - `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: Omit<NavigationType, 'leave'>;
/**
* Since `afterNavigate` is called after a navigation completes, it 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<string, string> = Record<string, string>,
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<string, any>;
/**
* 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 interface ParamMatcher {
(param: string): boolean;
}
export interface RequestEvent<
Params extends Partial<Record<string, string>> = Partial<Record<string, string>>,
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
*
* > Cookies will only be passed through if the target host is the same as the SvelteKit application or a more specific subdomain of it.
*/
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 page or endpoint - e.g. for a route like `/blog/[slug]`, a `{ slug: string }` object
*/
params: Params;
/**
* Additional data made available through the adapter.
*/
platform: Readonly<App.Platform>;
/**
* 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<string, string>): void;
/**
* The URL of the current page or endpoint.
*/
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;
}
/**
* 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 interface RequestHandler<
Params extends Partial<Record<string, string>> = Partial<Record<string, string>>,
RouteId extends string | null = string | null
> {
(event: RequestEvent<Params, RouteId>): MaybePromise<Response>;
}
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<string | undefined>;
/**
* 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 `<head>` tag to preload it.
* By default, `js`, `css` and `font` 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 class Server {
constructor(manifest: SSRManifest);
init(options: ServerInitOptions): Promise<void>;
respond(request: Request, options: RequestOptions): Promise<Response>;
}
export interface ServerInitOptions {
env: Record<string, string>;
}
export interface SSRManifest {
appDir: string;
appPath: string;
assets: Set<string>;
mimeTypes: Record<string, string>;
/** private fields */
_: {
entry: {
file: string;
imports: string[];
stylesheets: string[];
fonts: string[];
};
nodes: SSRNodeLoader[];
routes: SSRRoute[];
matchers(): Promise<Record<string, ParamMatcher>>;
};
}
/**
* 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<
Params extends Partial<Record<string, string>> = Partial<Record<string, string>>,
ParentData extends Record<string, any> = Record<string, any>,
OutputData extends Record<string, any> | void = Record<string, any> | void,
RouteId extends string | null = string | null
> {
(event: ServerLoadEvent<Params, ParentData, RouteId>): MaybePromise<OutputData>;
}
export interface ServerLoadEvent<
Params extends Partial<Record<string, string>> = Partial<Record<string, string>>,
ParentData extends Record<string, any> = Record<string, any>,
RouteId extends string | null = string | null
> extends RequestEvent<Params, RouteId> {
/**