@tschk/moonshine-svelte 0.4.4 → 0.4.80

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/kit.ts ADDED
@@ -0,0 +1,1973 @@
1
+ /**
2
+ * Host-free `@sveltejs/kit` server and universal runtime on the Moonshine graph.
3
+ * Provides `error`, `isHttpError`, `HttpError`, `redirect`, `isRedirect`,
4
+ * `Redirect`, `fail`, `isActionFailure`, `ActionFailure`, `json`, `text`,
5
+ * `resolvePath`, `normalizeUrl`, `sequence`, `createKitCookies`, and
6
+ * `createKitRequestEvent`.
7
+ */
8
+ import {
9
+ page,
10
+ setKitPage,
11
+ version as VERSION,
12
+ type ActionResult,
13
+ type AppError,
14
+ type NavigationTarget,
15
+ } from "./navigation";
16
+
17
+ export { VERSION };
18
+ export {
19
+ resolveRoute as resolvePath,
20
+ type ActionResult,
21
+ type AfterNavigate,
22
+ type AppError,
23
+ type BeforeNavigate,
24
+ type GotoOptions,
25
+ type KitLoadEvent as LoadEvent,
26
+ type Navigation,
27
+ type NavigationTarget,
28
+ type NavigationType,
29
+ type OnNavigate,
30
+ type Page,
31
+ type SubmitFunction,
32
+ } from "./navigation";
33
+
34
+ const httpErrorSymbol = Symbol.for("moonshine.sveltekit.httpError");
35
+ const redirectSymbol = Symbol.for("moonshine.sveltekit.redirect");
36
+ const actionFailureSymbol = Symbol.for("moonshine.sveltekit.actionFailure");
37
+
38
+ export class HttpError {
39
+ readonly [httpErrorSymbol] = true;
40
+ readonly status: number;
41
+ readonly body: AppError;
42
+
43
+ constructor(status: number, body?: AppError | string | null) {
44
+ this.status = status;
45
+ if (typeof body === "string") {
46
+ this.body = { message: body };
47
+ } else if (body && typeof body === "object") {
48
+ this.body = body;
49
+ } else {
50
+ this.body = { message: `Error: ${status}` };
51
+ }
52
+ }
53
+
54
+ toString(): string {
55
+ return JSON.stringify(this.body);
56
+ }
57
+ }
58
+
59
+ export class Redirect {
60
+ readonly [redirectSymbol] = true;
61
+ readonly status: number;
62
+ readonly location: string;
63
+
64
+ constructor(status: number, location: string) {
65
+ this.status = status;
66
+ this.location = location;
67
+ }
68
+ }
69
+
70
+ export class ActionFailure<T = undefined> {
71
+ readonly [actionFailureSymbol] = true;
72
+ readonly status: number;
73
+ readonly data: T;
74
+
75
+ constructor(status: number, data?: T) {
76
+ this.status = status;
77
+ this.data = data as T;
78
+ }
79
+ }
80
+
81
+ export function error(status: number, body?: AppError | string): never {
82
+ if (!Number.isInteger(status) || status < 400 || status > 599) {
83
+ throw new RangeError(
84
+ `HTTP error status code must be between 400 and 599 (received ${status})`,
85
+ );
86
+ }
87
+ throw new HttpError(status, body);
88
+ }
89
+
90
+ export function isHttpError<T extends number = number>(
91
+ e: unknown,
92
+ status?: T,
93
+ ): e is HttpError & { status: T } {
94
+ if (
95
+ !(e instanceof HttpError) &&
96
+ (typeof e !== "object" || e === null || !(httpErrorSymbol in e))
97
+ ) {
98
+ return false;
99
+ }
100
+ const err = e as HttpError;
101
+ return status === undefined ? true : err.status === status;
102
+ }
103
+
104
+ export function redirect(
105
+ status: 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308 | (number & {}),
106
+ location: string | URL,
107
+ ): never {
108
+ if (!Number.isInteger(status) || status < 300 || status > 308) {
109
+ throw new RangeError(
110
+ `Redirect status code must be between 300 and 308 (received ${status})`,
111
+ );
112
+ }
113
+ throw new Redirect(
114
+ status,
115
+ typeof location === "string" ? location : location.href,
116
+ );
117
+ }
118
+
119
+ export function isRedirect(e: unknown): e is Redirect {
120
+ return (
121
+ e instanceof Redirect ||
122
+ (typeof e === "object" && e !== null && redirectSymbol in e)
123
+ );
124
+ }
125
+
126
+ export function fail<T extends Record<string, unknown> | undefined = undefined>(
127
+ status: number,
128
+ data?: T,
129
+ ): ActionFailure<T> {
130
+ if (!Number.isInteger(status) || status < 400 || status > 599) {
131
+ throw new RangeError(
132
+ `Action failure status code must be between 400 and 599 (received ${status})`,
133
+ );
134
+ }
135
+ return new ActionFailure(status, data);
136
+ }
137
+
138
+ export function isActionFailure(e: unknown): e is ActionFailure<any> {
139
+ return (
140
+ e instanceof ActionFailure ||
141
+ (typeof e === "object" && e !== null && actionFailureSymbol in e)
142
+ );
143
+ }
144
+
145
+ export function json(data: any, init?: ResponseInit): Response {
146
+ const headers = new Headers(init?.headers);
147
+ if (!headers.has("content-type")) {
148
+ headers.set("content-type", "application/json");
149
+ }
150
+ return new Response(JSON.stringify(data), {
151
+ ...init,
152
+ headers,
153
+ });
154
+ }
155
+
156
+ export function text(body: string, init?: ResponseInit): Response {
157
+ const headers = new Headers(init?.headers);
158
+ if (!headers.has("content-type")) {
159
+ headers.set("content-type", "text/plain;charset=utf-8");
160
+ }
161
+ return new Response(body, {
162
+ ...init,
163
+ headers,
164
+ });
165
+ }
166
+
167
+ export function normalizeUrl(url: URL | string): {
168
+ url: URL;
169
+ wasNormalized: boolean;
170
+ denormalize(target?: URL | string): URL;
171
+ } {
172
+ const original = typeof url === "string" ? new URL(url) : new URL(url.href);
173
+ const hadTrailingSlash =
174
+ original.pathname.length > 1 && original.pathname.endsWith("/");
175
+ const normalized = new URL(original.href);
176
+ let wasNormalized = false;
177
+
178
+ if (hadTrailingSlash) {
179
+ normalized.pathname = normalized.pathname.replace(/\/+$/, "") || "/";
180
+ wasNormalized = true;
181
+ }
182
+ if (normalized.pathname.includes("//")) {
183
+ normalized.pathname = normalized.pathname.replace(/\/+/g, "/");
184
+ wasNormalized = true;
185
+ }
186
+
187
+ return {
188
+ url: normalized,
189
+ wasNormalized,
190
+ denormalize(target?: URL | string): URL {
191
+ const next =
192
+ target === undefined
193
+ ? new URL(normalized.href)
194
+ : typeof target === "string"
195
+ ? new URL(target, normalized)
196
+ : new URL(target.href);
197
+ if (hadTrailingSlash && !next.pathname.endsWith("/")) {
198
+ next.pathname += "/";
199
+ }
200
+ return next;
201
+ },
202
+ };
203
+ }
204
+
205
+ // ============================================================================
206
+ // Cookies & RequestEvent (`createKitCookies`, `createKitRequestEvent`, `sequence`)
207
+ // ============================================================================
208
+
209
+ export interface CookieSerializeOptions {
210
+ domain?: string;
211
+ encode?: (value: string) => string;
212
+ expires?: Date;
213
+ httpOnly?: boolean;
214
+ maxAge?: number;
215
+ path: string;
216
+ priority?: "low" | "medium" | "high";
217
+ sameSite?: boolean | "lax" | "strict" | "none";
218
+ secure?: boolean;
219
+ }
220
+
221
+ export interface Cookies {
222
+ get(
223
+ name: string,
224
+ opts?: { decode?: (value: string) => string },
225
+ ): string | undefined;
226
+ getAll(opts?: {
227
+ decode?: (value: string) => string;
228
+ }): Array<{ name: string; value: string }>;
229
+ set(name: string, value: string, opts: CookieSerializeOptions): void;
230
+ delete(name: string, opts: CookieSerializeOptions): void;
231
+ serialize(name: string, value: string, opts: CookieSerializeOptions): string;
232
+ }
233
+
234
+ export function createKitCookies(
235
+ requestHeaders?: Headers,
236
+ responseHeaders?: Headers,
237
+ ): Cookies {
238
+ const jar = new Map<string, string>();
239
+ const cookieHeader = requestHeaders?.get("cookie") ?? "";
240
+ for (const part of cookieHeader.split(";")) {
241
+ const trimmed = part.trim();
242
+ if (!trimmed) continue;
243
+ const eq = trimmed.indexOf("=");
244
+ if (eq < 0) continue;
245
+ const k = trimmed.slice(0, eq).trim();
246
+ const v = trimmed.slice(eq + 1).trim();
247
+ jar.set(k, v);
248
+ }
249
+
250
+ function serialize(
251
+ name: string,
252
+ value: string,
253
+ opts: CookieSerializeOptions,
254
+ ): string {
255
+ const encode = opts.encode ?? encodeURIComponent;
256
+ const parts = [`${name}=${encode(value)}`];
257
+ if (opts.path) parts.push(`Path=${opts.path}`);
258
+ if (opts.domain) parts.push(`Domain=${opts.domain}`);
259
+ if (opts.maxAge !== undefined)
260
+ parts.push(`Max-Age=${Math.floor(opts.maxAge)}`);
261
+ if (opts.expires) parts.push(`Expires=${opts.expires.toUTCString()}`);
262
+ if (opts.httpOnly !== false) parts.push("HttpOnly");
263
+ if (opts.secure) parts.push("Secure");
264
+ if (opts.sameSite) {
265
+ const s =
266
+ opts.sameSite === true
267
+ ? "Strict"
268
+ : opts.sameSite.charAt(0).toUpperCase() + opts.sameSite.slice(1);
269
+ parts.push(`SameSite=${s}`);
270
+ }
271
+ if (opts.priority) {
272
+ const p = opts.priority.charAt(0).toUpperCase() + opts.priority.slice(1);
273
+ parts.push(`Priority=${p}`);
274
+ }
275
+ return parts.join("; ");
276
+ }
277
+
278
+ return {
279
+ get(name: string, opts?: { decode?: (value: string) => string }) {
280
+ const raw = jar.get(name);
281
+ if (raw === undefined) return undefined;
282
+ const decode = opts?.decode ?? decodeURIComponent;
283
+ return decode(raw);
284
+ },
285
+ getAll(opts?: { decode?: (value: string) => string }) {
286
+ const decode = opts?.decode ?? decodeURIComponent;
287
+ return Array.from(jar.entries(), ([name, val]) => ({
288
+ name,
289
+ value: decode(val),
290
+ }));
291
+ },
292
+ set(name: string, value: string, opts: CookieSerializeOptions) {
293
+ const encode = opts.encode ?? encodeURIComponent;
294
+ jar.set(name, encode(value));
295
+ responseHeaders?.append("set-cookie", serialize(name, value, opts));
296
+ },
297
+ delete(name: string, opts: CookieSerializeOptions) {
298
+ jar.delete(name);
299
+ responseHeaders?.append(
300
+ "set-cookie",
301
+ serialize(name, "", {
302
+ ...opts,
303
+ maxAge: 0,
304
+ expires: new Date(0),
305
+ }),
306
+ );
307
+ },
308
+ serialize,
309
+ };
310
+ }
311
+
312
+ export interface RequestEvent<
313
+ Params extends Record<string, string> = Record<string, string>,
314
+ RouteId extends string | null = string | null,
315
+ > {
316
+ cookies: Cookies;
317
+ fetch: typeof globalThis.fetch;
318
+ getClientAddress(): string;
319
+ locals: Record<string, any>;
320
+ params: Params;
321
+ platform: Readonly<Record<string, any>> | undefined;
322
+ request: Request;
323
+ route: { id: RouteId };
324
+ setHeaders(headers: Record<string, string>): void;
325
+ url: URL;
326
+ isDataRequest: boolean;
327
+ isSubRequest: boolean;
328
+ }
329
+
330
+ export interface KitRequestEventInit<
331
+ Params extends Record<string, string> = Record<string, string>,
332
+ RouteId extends string | null = string | null,
333
+ > {
334
+ request?: Request;
335
+ method?: string;
336
+ url?: string | URL;
337
+ params?: Params;
338
+ routeId?: RouteId;
339
+ locals?: Record<string, any>;
340
+ platform?: Record<string, any>;
341
+ clientAddress?: string;
342
+ responseHeaders?: Headers;
343
+ }
344
+
345
+ export function createKitRequestEvent<
346
+ Params extends Record<string, string> = Record<string, string>,
347
+ RouteId extends string | null = string | null,
348
+ >(
349
+ init: KitRequestEventInit<Params, RouteId> = {},
350
+ ): RequestEvent<Params, RouteId> {
351
+ const url =
352
+ init.url instanceof URL
353
+ ? new URL(init.url.href)
354
+ : typeof init.url === "string"
355
+ ? new URL(init.url, "http://localhost")
356
+ : init.request
357
+ ? new URL(init.request.url)
358
+ : new URL("http://localhost/");
359
+ const request =
360
+ init.request ??
361
+ new Request(url.href, init.method ? { method: init.method } : undefined);
362
+ const responseHeaders = init.responseHeaders ?? new Headers();
363
+ const cookies = createKitCookies(request.headers, responseHeaders);
364
+
365
+ return {
366
+ cookies,
367
+ fetch: globalThis.fetch.bind(globalThis),
368
+ getClientAddress() {
369
+ return (
370
+ init.clientAddress ??
371
+ request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ??
372
+ "127.0.0.1"
373
+ );
374
+ },
375
+ locals: init.locals ?? {},
376
+ params: (init.params ?? {}) as Params,
377
+ platform: init.platform,
378
+ request,
379
+ route: { id: (init.routeId ?? (url.pathname as RouteId)) as RouteId },
380
+ setHeaders(headers: Record<string, string>) {
381
+ for (const [k, v] of Object.entries(headers)) {
382
+ responseHeaders.set(k, v);
383
+ }
384
+ },
385
+ url,
386
+ isDataRequest: url.pathname.endsWith("/__data.json"),
387
+ isSubRequest: false,
388
+ };
389
+ }
390
+
391
+ export interface ResolveOptions {
392
+ transformPageChunk?: (input: {
393
+ html: string;
394
+ done: boolean;
395
+ }) => Promise<string | undefined> | string | undefined;
396
+ filterSerializedResponseHeaders?: (name: string, value: string) => boolean;
397
+ preload?: (input: {
398
+ type: "font" | "css" | "js" | "asset";
399
+ path: string;
400
+ }) => boolean;
401
+ }
402
+
403
+ export type Handle = (input: {
404
+ event: RequestEvent;
405
+ resolve: (
406
+ event: RequestEvent,
407
+ options?: ResolveOptions,
408
+ ) => Promise<Response> | Response;
409
+ }) => Promise<Response> | Response;
410
+
411
+ export function sequence(...handlers: Handle[]): Handle {
412
+ const length = handlers.length;
413
+ if (length === 0) {
414
+ return ({ event, resolve }) => resolve(event);
415
+ }
416
+
417
+ return ({ event, resolve }) => {
418
+ function applyHandle(
419
+ i: number,
420
+ currentEvent: RequestEvent,
421
+ parentOptions?: ResolveOptions,
422
+ ): Promise<Response> | Response {
423
+ const handle = handlers[i]!;
424
+ return handle({
425
+ event: currentEvent,
426
+ resolve: (nextEvent, options) => {
427
+ const mergedOptions: ResolveOptions = {
428
+ transformPageChunk: options?.transformPageChunk
429
+ ? async ({ html, done }) => {
430
+ const parentHtml = parentOptions?.transformPageChunk
431
+ ? ((await parentOptions.transformPageChunk({
432
+ html,
433
+ done,
434
+ })) ?? html)
435
+ : html;
436
+ return (
437
+ (await options.transformPageChunk!({
438
+ html: parentHtml,
439
+ done,
440
+ })) ?? parentHtml
441
+ );
442
+ }
443
+ : parentOptions?.transformPageChunk,
444
+ filterSerializedResponseHeaders:
445
+ options?.filterSerializedResponseHeaders ??
446
+ parentOptions?.filterSerializedResponseHeaders,
447
+ preload: options?.preload ?? parentOptions?.preload,
448
+ };
449
+
450
+ if (i < length - 1) {
451
+ return applyHandle(i + 1, nextEvent, mergedOptions);
452
+ }
453
+ return resolve(nextEvent, mergedOptions);
454
+ },
455
+ });
456
+ }
457
+
458
+ return applyHandle(0, event, undefined);
459
+ };
460
+ }
461
+
462
+ // ============================================================================
463
+ // `$env/dynamic/public`, `$env/dynamic/private`, `$env/static/public`, `$env/static/private`
464
+ // ============================================================================
465
+
466
+ export interface KitEnvConfig {
467
+ publicPrefix?: string;
468
+ privatePrefix?: string;
469
+ env?: Record<string, string | undefined>;
470
+ values?: Record<string, string | undefined>;
471
+ }
472
+
473
+ let envPublicPrefix = "PUBLIC_";
474
+ let envPrivatePrefix = "";
475
+ const customEnvStore = new Map<string, string>();
476
+
477
+ function readProcessEnv(): Record<string, string | undefined> {
478
+ if (
479
+ typeof process !== "undefined" &&
480
+ process !== null &&
481
+ typeof process.env === "object" &&
482
+ process.env !== null
483
+ ) {
484
+ return process.env as Record<string, string | undefined>;
485
+ }
486
+ return {};
487
+ }
488
+
489
+ function collectEnvEntries(
490
+ mode: "all" | "public" | "private",
491
+ ): Record<string, string> {
492
+ const result: Record<string, string> = Object.create(null);
493
+ const procEnv = readProcessEnv();
494
+ const assignIfMatch = (key: string, val: string | undefined) => {
495
+ if (val === undefined) return;
496
+ const isPub = envPublicPrefix ? key.startsWith(envPublicPrefix) : false;
497
+ const isPriv = envPrivatePrefix
498
+ ? !isPub && key.startsWith(envPrivatePrefix)
499
+ : true;
500
+ if (
501
+ mode === "all" ||
502
+ (mode === "public" && isPub) ||
503
+ (mode === "private" && isPriv)
504
+ ) {
505
+ result[key] = String(val);
506
+ }
507
+ };
508
+ for (const [k, v] of Object.entries(procEnv)) {
509
+ assignIfMatch(k, v);
510
+ }
511
+ for (const [k, v] of customEnvStore.entries()) {
512
+ assignIfMatch(k, v);
513
+ }
514
+ return result;
515
+ }
516
+
517
+ function createEnvProxy(
518
+ mode: "all" | "public" | "private",
519
+ ): Record<string, string | undefined> {
520
+ return new Proxy(Object.create(null) as Record<string, string | undefined>, {
521
+ get(_target, prop) {
522
+ if (typeof prop !== "string") return undefined;
523
+ const entries = collectEnvEntries(mode);
524
+ return entries[prop];
525
+ },
526
+ has(_target, prop) {
527
+ if (typeof prop !== "string") return false;
528
+ const entries = collectEnvEntries(mode);
529
+ return prop in entries;
530
+ },
531
+ ownKeys() {
532
+ return Object.keys(collectEnvEntries(mode));
533
+ },
534
+ getOwnPropertyDescriptor(_target, prop) {
535
+ if (typeof prop !== "string") return undefined;
536
+ const entries = collectEnvEntries(mode);
537
+ if (!(prop in entries)) return undefined;
538
+ return {
539
+ value: entries[prop],
540
+ writable: false,
541
+ enumerable: true,
542
+ configurable: true,
543
+ };
544
+ },
545
+ set() {
546
+ throw new TypeError("Cannot mutate read-only SvelteKit $env object");
547
+ },
548
+ deleteProperty() {
549
+ throw new TypeError("Cannot mutate read-only SvelteKit $env object");
550
+ },
551
+ });
552
+ }
553
+
554
+ export const publicEnv: Record<string, string | undefined> =
555
+ createEnvProxy("public");
556
+ export const privateEnv: Record<string, string | undefined> =
557
+ createEnvProxy("private");
558
+ export const env: Record<string, string | undefined> = publicEnv;
559
+
560
+ export function configureKitEnv(
561
+ config: KitEnvConfig | Record<string, string | undefined>,
562
+ ): void {
563
+ if (
564
+ "env" in config ||
565
+ "values" in config ||
566
+ "publicPrefix" in config ||
567
+ "privatePrefix" in config
568
+ ) {
569
+ const typed = config as KitEnvConfig;
570
+ if (typeof typed.publicPrefix === "string") {
571
+ envPublicPrefix = typed.publicPrefix;
572
+ }
573
+ if (typeof typed.privatePrefix === "string") {
574
+ envPrivatePrefix = typed.privatePrefix;
575
+ }
576
+ const sourceMap = typed.env ?? typed.values;
577
+ if (sourceMap && typeof sourceMap === "object") {
578
+ for (const [k, v] of Object.entries(sourceMap)) {
579
+ if (v === undefined) {
580
+ customEnvStore.delete(k);
581
+ } else {
582
+ customEnvStore.set(k, String(v));
583
+ }
584
+ }
585
+ }
586
+ } else {
587
+ for (const [k, v] of Object.entries(
588
+ config as Record<string, string | undefined>,
589
+ )) {
590
+ if (v === undefined) {
591
+ customEnvStore.delete(k);
592
+ } else {
593
+ customEnvStore.set(k, String(v));
594
+ }
595
+ }
596
+ }
597
+ }
598
+
599
+ export function resetKitEnv(): void {
600
+ envPublicPrefix = "PUBLIC_";
601
+ envPrivatePrefix = "";
602
+ customEnvStore.clear();
603
+ }
604
+
605
+ // ============================================================================
606
+ // `$service-worker`
607
+ // ============================================================================
608
+
609
+ export interface KitServiceWorkerConfig {
610
+ build?: string[];
611
+ files?: string[];
612
+ prerendered?: string[];
613
+ version?: string;
614
+ base?: string;
615
+ }
616
+
617
+ export let build: string[] = [];
618
+ export let files: string[] = [];
619
+ export let prerendered: string[] = [];
620
+ export let version: string = VERSION;
621
+ export let base = "";
622
+
623
+ export function configureKitServiceWorker(
624
+ config: KitServiceWorkerConfig,
625
+ ): void {
626
+ if (Array.isArray(config.build)) {
627
+ build = [...config.build];
628
+ }
629
+ if (Array.isArray(config.files)) {
630
+ files = [...config.files];
631
+ }
632
+ if (Array.isArray(config.prerendered)) {
633
+ prerendered = [...config.prerendered];
634
+ }
635
+ if (typeof config.version === "string") {
636
+ version = config.version;
637
+ }
638
+ if (typeof config.base === "string") {
639
+ base = config.base === "/" ? "" : config.base.replace(/\/+$/, "");
640
+ }
641
+ }
642
+
643
+ export function resetKitServiceWorker(): void {
644
+ build = [];
645
+ files = [];
646
+ prerendered = [];
647
+ version = VERSION;
648
+ base = "";
649
+ }
650
+
651
+ // ============================================================================
652
+ // `$app/server` (`getRequestEvent`, `withKitRequestEvent`, `read`, `query`, `prerender`, `command`, `form`)
653
+ // ============================================================================
654
+
655
+ const requestEventStack: RequestEvent<any, any>[] = [];
656
+
657
+ export function withKitRequestEvent<
658
+ T,
659
+ Params extends Record<string, string> = Record<string, string>,
660
+ RouteId extends string | null = string | null,
661
+ >(
662
+ eventOrInit:
663
+ RequestEvent<Params, RouteId> | KitRequestEventInit<Params, RouteId>,
664
+ fn: (event: RequestEvent<Params, RouteId>) => T,
665
+ ): T {
666
+ const event =
667
+ "cookies" in eventOrInit &&
668
+ "request" in eventOrInit &&
669
+ "url" in eventOrInit &&
670
+ typeof eventOrInit.getClientAddress === "function"
671
+ ? (eventOrInit as RequestEvent<Params, RouteId>)
672
+ : createKitRequestEvent<Params, RouteId>(
673
+ eventOrInit as KitRequestEventInit<Params, RouteId>,
674
+ );
675
+ requestEventStack.push(event);
676
+ let isAsync = false;
677
+ try {
678
+ const result = fn(event);
679
+ if (
680
+ result !== null &&
681
+ typeof result === "object" &&
682
+ typeof (result as any).then === "function"
683
+ ) {
684
+ isAsync = true;
685
+ return (result as unknown as Promise<any>).finally(() => {
686
+ const idx = requestEventStack.lastIndexOf(event);
687
+ if (idx !== -1) {
688
+ requestEventStack.splice(idx, 1);
689
+ }
690
+ }) as unknown as T;
691
+ }
692
+ return result;
693
+ } finally {
694
+ if (!isAsync) {
695
+ const idx = requestEventStack.lastIndexOf(event);
696
+ if (idx !== -1) {
697
+ requestEventStack.splice(idx, 1);
698
+ }
699
+ }
700
+ }
701
+ }
702
+
703
+ export function getRequestEvent<
704
+ Params extends Record<string, string> = Record<string, string>,
705
+ RouteId extends string | null = string | null,
706
+ >(): RequestEvent<Params, RouteId> {
707
+ const current = requestEventStack[requestEventStack.length - 1];
708
+ if (!current) {
709
+ throw new Error(
710
+ "getRequestEvent() cannot be called outside of an active RequestEvent context (`withKitRequestEvent`, `load`, `actions`, or remote functions)",
711
+ );
712
+ }
713
+ return current as RequestEvent<Params, RouteId>;
714
+ }
715
+
716
+ export interface KitServerAssetEntry {
717
+ body: Uint8Array | string;
718
+ headers?: HeadersInit;
719
+ type?: string;
720
+ status?: number;
721
+ }
722
+
723
+ const serverAssetStore = new Map<string, KitServerAssetEntry>();
724
+
725
+ function inferMimeType(assetPath: string): string {
726
+ const clean = assetPath.split("?")[0]?.split("#")[0]?.toLowerCase() ?? "";
727
+ if (clean.endsWith(".json")) return "application/json; charset=utf-8";
728
+ if (clean.endsWith(".html") || clean.endsWith(".htm"))
729
+ return "text/html; charset=utf-8";
730
+ if (clean.endsWith(".css")) return "text/css; charset=utf-8";
731
+ if (clean.endsWith(".js") || clean.endsWith(".mjs"))
732
+ return "text/javascript; charset=utf-8";
733
+ if (clean.endsWith(".svg")) return "image/svg+xml";
734
+ if (clean.endsWith(".png")) return "image/png";
735
+ if (clean.endsWith(".jpg") || clean.endsWith(".jpeg")) return "image/jpeg";
736
+ if (clean.endsWith(".webp")) return "image/webp";
737
+ if (clean.endsWith(".gif")) return "image/gif";
738
+ if (clean.endsWith(".wasm")) return "application/wasm";
739
+ if (clean.endsWith(".xml")) return "application/xml; charset=utf-8";
740
+ if (clean.endsWith(".csv")) return "text/csv; charset=utf-8";
741
+ if (clean.endsWith(".txt") || clean.endsWith(".md"))
742
+ return "text/plain; charset=utf-8";
743
+ return "application/octet-stream";
744
+ }
745
+
746
+ export function registerKitServerAsset(
747
+ assetPath: string,
748
+ body: Uint8Array | string,
749
+ init?: { headers?: HeadersInit; type?: string; status?: number },
750
+ ): void {
751
+ serverAssetStore.set(assetPath, {
752
+ body: typeof body === "string" ? body : new Uint8Array(body),
753
+ headers: init?.headers,
754
+ type: init?.type,
755
+ status: init?.status,
756
+ });
757
+ }
758
+
759
+ export function clearKitServerAssets(): void {
760
+ serverAssetStore.clear();
761
+ }
762
+
763
+ export function read(asset: string): Response {
764
+ const registered =
765
+ serverAssetStore.get(asset) ??
766
+ serverAssetStore.get(asset.startsWith("/") ? asset.slice(1) : `/${asset}`);
767
+ if (registered) {
768
+ const headers = new Headers(registered.headers);
769
+ if (!headers.has("content-type")) {
770
+ headers.set("content-type", registered.type ?? inferMimeType(asset));
771
+ }
772
+ const bodyBytes =
773
+ typeof registered.body === "string"
774
+ ? new TextEncoder().encode(registered.body)
775
+ : new Uint8Array(registered.body);
776
+ if (!headers.has("content-length")) {
777
+ headers.set("content-length", String(bodyBytes.byteLength));
778
+ }
779
+ return new Response(bodyBytes as unknown as BodyInit, {
780
+ status: registered.status ?? 200,
781
+ headers,
782
+ });
783
+ }
784
+ throw new Error(
785
+ `SvelteKit server asset "${asset}" was not found. Register virtual assets via registerKitServerAsset("${asset}", content) before calling read("${asset}").`,
786
+ );
787
+ }
788
+
789
+ export type RemoteSchema<Input = any, Output = Input> =
790
+ | "unchecked"
791
+ | ((input: unknown) => Output | Promise<Output>)
792
+ | { parse(input: unknown): Output | Promise<Output> }
793
+ | {
794
+ safeParse(
795
+ input: unknown,
796
+ ): { success: true; data: Output } | { success: false; error: any };
797
+ }
798
+ | {
799
+ "~standard": {
800
+ validate(
801
+ input: unknown,
802
+ ):
803
+ | { value: Output; issues?: undefined }
804
+ | { issues: ReadonlyArray<{ message: string }> }
805
+ | Promise<
806
+ | { value: Output; issues?: undefined }
807
+ | { issues: ReadonlyArray<{ message: string }> }
808
+ >;
809
+ };
810
+ };
811
+
812
+ async function validateRemoteInput<Input, Output>(
813
+ schema: RemoteSchema<Input, Output> | undefined,
814
+ raw: Input,
815
+ ): Promise<Output> {
816
+ if (!schema || schema === "unchecked") {
817
+ return raw as unknown as Output;
818
+ }
819
+ if (typeof schema === "function") {
820
+ return await schema(raw);
821
+ }
822
+ if ("~standard" in schema && schema["~standard"]) {
823
+ const res = await schema["~standard"].validate(raw);
824
+ if (res.issues && res.issues.length > 0) {
825
+ error(
826
+ 400,
827
+ res.issues.map((i) => i.message).join("; ") || "Invalid input",
828
+ );
829
+ }
830
+ return (res as { value: Output }).value;
831
+ }
832
+ if ("safeParse" in schema && typeof schema.safeParse === "function") {
833
+ const res = schema.safeParse(raw);
834
+ if (!res.success) {
835
+ error(
836
+ 400,
837
+ res.error?.message ? String(res.error.message) : "Validation failed",
838
+ );
839
+ }
840
+ return res.data;
841
+ }
842
+ if ("parse" in schema && typeof schema.parse === "function") {
843
+ try {
844
+ return await schema.parse(raw);
845
+ } catch (err: any) {
846
+ error(400, err?.message ? String(err.message) : "Validation failed");
847
+ }
848
+ }
849
+ return raw as unknown as Output;
850
+ }
851
+
852
+ export interface RemoteQuery<T> extends Promise<T> {
853
+ readonly current: T | undefined;
854
+ readonly loading: boolean;
855
+ readonly error: any;
856
+ readonly ready: boolean;
857
+ refresh(): Promise<T>;
858
+ set(value: T): void;
859
+ withOverride(updater: (current: T) => T): () => void;
860
+ }
861
+
862
+ export interface RemoteQueryFunction<Input = void, Output = any> {
863
+ (arg: Input): RemoteQuery<Output>;
864
+ refresh(arg?: Input): Promise<Output>;
865
+ set(arg: Input, value: Output): void;
866
+ peek(arg?: Input): Output | undefined;
867
+ }
868
+
869
+ export interface RemoteBatchQueryFunction<Input = any, Output = any> {
870
+ (arg: Input): RemoteQuery<Output>;
871
+ }
872
+
873
+ const remoteQueryCache = new Map<string, any>();
874
+
875
+ export function clearKitRemoteCache(): void {
876
+ remoteQueryCache.clear();
877
+ }
878
+
879
+ function createRemoteQueryHandle<T>(
880
+ runner: () => Promise<T>,
881
+ initialCached?: { hasValue: boolean; value?: T },
882
+ onSet?: (value: T) => void,
883
+ ): RemoteQuery<T> {
884
+ let currentVal: T | undefined = initialCached?.value;
885
+ let isReady = Boolean(initialCached?.hasValue);
886
+ let isLoading = !isReady;
887
+ let currentErr: any = undefined;
888
+ let overrideStack: T[] = [];
889
+
890
+ const execute = (): Promise<T> => {
891
+ isLoading = true;
892
+ currentErr = undefined;
893
+ return Promise.resolve()
894
+ .then(runner)
895
+ .then(
896
+ (val) => {
897
+ currentVal = val;
898
+ isReady = true;
899
+ isLoading = false;
900
+ onSet?.(val);
901
+ return val;
902
+ },
903
+ (err) => {
904
+ currentErr = err;
905
+ isLoading = false;
906
+ throw err;
907
+ },
908
+ );
909
+ };
910
+
911
+ const basePromise = initialCached?.hasValue
912
+ ? Promise.resolve(initialCached.value as T)
913
+ : execute();
914
+
915
+ const handle = Object.defineProperties(
916
+ basePromise,
917
+ Object.getOwnPropertyDescriptors({
918
+ get current(): T | undefined {
919
+ return overrideStack.length > 0
920
+ ? overrideStack[overrideStack.length - 1]
921
+ : currentVal;
922
+ },
923
+ get loading(): boolean {
924
+ return isLoading;
925
+ },
926
+ get error(): any {
927
+ return currentErr;
928
+ },
929
+ get ready(): boolean {
930
+ return isReady;
931
+ },
932
+ async refresh(): Promise<T> {
933
+ return execute();
934
+ },
935
+ set(value: T): void {
936
+ currentVal = value;
937
+ isReady = true;
938
+ isLoading = false;
939
+ currentErr = undefined;
940
+ onSet?.(value);
941
+ },
942
+ withOverride(updater: (current: T) => T): () => void {
943
+ const next = updater(
944
+ (overrideStack.length > 0
945
+ ? overrideStack[overrideStack.length - 1]
946
+ : currentVal) as T,
947
+ );
948
+ overrideStack.push(next);
949
+ return () => {
950
+ const idx = overrideStack.lastIndexOf(next);
951
+ if (idx !== -1) {
952
+ overrideStack.splice(idx, 1);
953
+ }
954
+ };
955
+ },
956
+ }),
957
+ ) as RemoteQuery<T>;
958
+
959
+ return handle;
960
+ }
961
+
962
+ let remoteQueryIdCounter = 0;
963
+
964
+ function createQueryImpl<Input = void, Output = any>(
965
+ schemaOrFn:
966
+ RemoteSchema<Input, any> | ((arg: Input) => Output | Promise<Output>),
967
+ maybeFn?: (arg: any) => Output | Promise<Output>,
968
+ ): RemoteQueryFunction<Input, Output> {
969
+ const hasSchema = typeof maybeFn === "function";
970
+ const schema = hasSchema
971
+ ? (schemaOrFn as RemoteSchema<Input, any>)
972
+ : undefined;
973
+ const fn = (hasSchema ? maybeFn! : schemaOrFn) as (
974
+ arg: any,
975
+ ) => Output | Promise<Output>;
976
+ const queryId = `query_${++remoteQueryIdCounter}`;
977
+ const handles = new Map<string, RemoteQuery<Output>>();
978
+
979
+ const keyFor = (arg: Input): string => {
980
+ try {
981
+ return `${queryId}:${JSON.stringify(arg ?? null)}`;
982
+ } catch {
983
+ return `${queryId}:${String(arg)}`;
984
+ }
985
+ };
986
+
987
+ const runFor = async (arg: Input): Promise<Output> => {
988
+ const validated = await validateRemoteInput(schema, arg);
989
+ const value = await fn(validated);
990
+ remoteQueryCache.set(keyFor(arg), value);
991
+ return value;
992
+ };
993
+
994
+ const queryFn = ((arg: Input): RemoteQuery<Output> => {
995
+ const key = keyFor(arg);
996
+ const existing = handles.get(key);
997
+ if (existing && remoteQueryCache.has(key)) {
998
+ return existing;
999
+ }
1000
+ const hasCached = remoteQueryCache.has(key);
1001
+ const cachedValue = remoteQueryCache.get(key) as Output | undefined;
1002
+ const handle = createRemoteQueryHandle<Output>(
1003
+ () => runFor(arg),
1004
+ hasCached ? { hasValue: true, value: cachedValue } : undefined,
1005
+ (val) => {
1006
+ remoteQueryCache.set(key, val);
1007
+ },
1008
+ );
1009
+ handles.set(key, handle);
1010
+ return handle;
1011
+ }) as RemoteQueryFunction<Input, Output>;
1012
+
1013
+ queryFn.refresh = async (arg?: Input): Promise<Output> => {
1014
+ const key = keyFor(arg as Input);
1015
+ const existing = handles.get(key);
1016
+ if (existing) {
1017
+ return existing.refresh();
1018
+ }
1019
+ return runFor(arg as Input);
1020
+ };
1021
+
1022
+ queryFn.set = (arg: Input, value: Output): void => {
1023
+ const key = keyFor(arg);
1024
+ remoteQueryCache.set(key, value);
1025
+ handles.get(key)?.set(value);
1026
+ };
1027
+
1028
+ queryFn.peek = (arg?: Input): Output | undefined => {
1029
+ const key = keyFor(arg as Input);
1030
+ const existing = handles.get(key);
1031
+ if (existing && existing.ready && remoteQueryCache.has(key)) {
1032
+ return existing.current;
1033
+ }
1034
+ return remoteQueryCache.get(key) as Output | undefined;
1035
+ };
1036
+
1037
+ return queryFn;
1038
+ }
1039
+
1040
+ function createBatchQueryImpl<Input = any, Output = any>(
1041
+ schemaOrFn: any,
1042
+ maybeFn?: any,
1043
+ ): RemoteBatchQueryFunction<Input, Output> {
1044
+ const hasSchema = typeof maybeFn === "function";
1045
+ const schema = hasSchema
1046
+ ? (schemaOrFn as RemoteSchema<Input, any>)
1047
+ : undefined;
1048
+ const fn = (hasSchema ? maybeFn! : schemaOrFn) as (
1049
+ args: any[],
1050
+ ) =>
1051
+ | Promise<((input: any, idx: number) => Output) | Output[]>
1052
+ | ((input: any, idx: number) => Output)
1053
+ | Output[];
1054
+
1055
+ let pendingQueue: Array<{
1056
+ arg: Input;
1057
+ resolve: (value: Output) => void;
1058
+ reject: (reason: any) => void;
1059
+ }> = [];
1060
+ let flushScheduled = false;
1061
+
1062
+ const flush = async () => {
1063
+ flushScheduled = false;
1064
+ const batchItems = pendingQueue;
1065
+ pendingQueue = [];
1066
+ try {
1067
+ const validatedArgs: any[] = [];
1068
+ for (const item of batchItems) {
1069
+ validatedArgs.push(await validateRemoteInput(schema, item.arg));
1070
+ }
1071
+ const resolverOrArray = await fn(validatedArgs);
1072
+ for (let i = 0; i < batchItems.length; i++) {
1073
+ const item = batchItems[i]!;
1074
+ const val =
1075
+ typeof resolverOrArray === "function"
1076
+ ? (resolverOrArray as (input: any, idx: number) => Output)(
1077
+ validatedArgs[i],
1078
+ i,
1079
+ )
1080
+ : (resolverOrArray as Output[])[i]!;
1081
+ item.resolve(val);
1082
+ }
1083
+ } catch (err) {
1084
+ for (const item of batchItems) {
1085
+ item.reject(err);
1086
+ }
1087
+ }
1088
+ };
1089
+
1090
+ return ((arg: Input): RemoteQuery<Output> => {
1091
+ return createRemoteQueryHandle<Output>(() => {
1092
+ return new Promise<Output>((resolve, reject) => {
1093
+ pendingQueue.push({ arg, resolve, reject });
1094
+ if (!flushScheduled) {
1095
+ flushScheduled = true;
1096
+ queueMicrotask(flush);
1097
+ }
1098
+ });
1099
+ });
1100
+ }) as RemoteBatchQueryFunction<Input, Output>;
1101
+ }
1102
+
1103
+ export const query: {
1104
+ <Output>(
1105
+ fn: () => Output | Promise<Output>,
1106
+ ): RemoteQueryFunction<void, Output>;
1107
+ <Input, Output>(
1108
+ fn: (arg: Input) => Output | Promise<Output>,
1109
+ ): RemoteQueryFunction<Input, Output>;
1110
+ <Input, Validated, Output>(
1111
+ schema: RemoteSchema<Input, Validated>,
1112
+ fn: (arg: Validated) => Output | Promise<Output>,
1113
+ ): RemoteQueryFunction<Input, Output>;
1114
+ batch: {
1115
+ <Input, Output>(
1116
+ fn: (
1117
+ args: Input[],
1118
+ ) =>
1119
+ | Promise<((input: Input, idx: number) => Output) | Output[]>
1120
+ | ((input: Input, idx: number) => Output)
1121
+ | Output[],
1122
+ ): RemoteBatchQueryFunction<Input, Output>;
1123
+ <Input, Validated, Output>(
1124
+ schema: RemoteSchema<Input, Validated>,
1125
+ fn: (
1126
+ args: Validated[],
1127
+ ) =>
1128
+ | Promise<((input: Validated, idx: number) => Output) | Output[]>
1129
+ | ((input: Validated, idx: number) => Output)
1130
+ | Output[],
1131
+ ): RemoteBatchQueryFunction<Input, Output>;
1132
+ };
1133
+ } = Object.assign(createQueryImpl, {
1134
+ batch: createBatchQueryImpl,
1135
+ }) as any;
1136
+
1137
+ export interface RemotePrerenderOptions<Input = any> {
1138
+ inputs?: () => Iterable<Input> | Promise<Iterable<Input>>;
1139
+ dynamic?: boolean;
1140
+ }
1141
+
1142
+ export interface RemotePrerenderFunction<Input = void, Output = any> {
1143
+ (arg: Input): RemoteQuery<Output>;
1144
+ readonly options: RemotePrerenderOptions<Input>;
1145
+ }
1146
+
1147
+ let remotePrerenderIdCounter = 0;
1148
+
1149
+ export function prerender<Output>(
1150
+ fn: () => Output | Promise<Output>,
1151
+ options?: RemotePrerenderOptions<void>,
1152
+ ): RemotePrerenderFunction<void, Output>;
1153
+ export function prerender<Input, Output>(
1154
+ fn: (arg: Input) => Output | Promise<Output>,
1155
+ options?: RemotePrerenderOptions<Input>,
1156
+ ): RemotePrerenderFunction<Input, Output>;
1157
+ export function prerender<Input, Validated, Output>(
1158
+ schema: RemoteSchema<Input, Validated>,
1159
+ fn: (arg: Validated) => Output | Promise<Output>,
1160
+ options?: RemotePrerenderOptions<Input>,
1161
+ ): RemotePrerenderFunction<Input, Output>;
1162
+ export function prerender<Input = any, Output = any>(
1163
+ schemaOrFn: any,
1164
+ fnOrOptions?: any,
1165
+ maybeOptions?: RemotePrerenderOptions<Input>,
1166
+ ): RemotePrerenderFunction<Input, Output> {
1167
+ const hasSchema = typeof fnOrOptions === "function";
1168
+ const schema = hasSchema
1169
+ ? (schemaOrFn as RemoteSchema<Input, any>)
1170
+ : undefined;
1171
+ const fn = (hasSchema ? fnOrOptions : schemaOrFn) as (
1172
+ arg: any,
1173
+ ) => Output | Promise<Output>;
1174
+ const options = (hasSchema ? maybeOptions : fnOrOptions) ?? {};
1175
+ const prerenderId = `prerender_${++remotePrerenderIdCounter}`;
1176
+
1177
+ const keyFor = (arg: Input): string => {
1178
+ try {
1179
+ return `${prerenderId}:${JSON.stringify(arg ?? null)}`;
1180
+ } catch {
1181
+ return `${prerenderId}:${String(arg)}`;
1182
+ }
1183
+ };
1184
+
1185
+ const runFor = async (arg: Input): Promise<Output> => {
1186
+ const key = keyFor(arg);
1187
+ if (remoteQueryCache.has(key)) {
1188
+ return remoteQueryCache.get(key) as Output;
1189
+ }
1190
+ const validated = await validateRemoteInput(schema, arg);
1191
+ const val = await fn(validated);
1192
+ remoteQueryCache.set(key, val);
1193
+ return val;
1194
+ };
1195
+
1196
+ const prerenderFn = ((arg: Input): RemoteQuery<Output> => {
1197
+ const key = keyFor(arg);
1198
+ const hasCached = remoteQueryCache.has(key);
1199
+ const cachedValue = remoteQueryCache.get(key) as Output | undefined;
1200
+ return createRemoteQueryHandle<Output>(
1201
+ () => runFor(arg),
1202
+ hasCached ? { hasValue: true, value: cachedValue } : undefined,
1203
+ );
1204
+ }) as RemotePrerenderFunction<Input, Output>;
1205
+
1206
+ Object.defineProperty(prerenderFn, "options", {
1207
+ value: options,
1208
+ enumerable: true,
1209
+ writable: false,
1210
+ });
1211
+
1212
+ return prerenderFn;
1213
+ }
1214
+
1215
+ export interface RemoteCommandFunction<Input = void, Output = any> {
1216
+ (arg: Input): Promise<Output> & {
1217
+ updates(
1218
+ ...queries: Array<RemoteQuery<any> | (() => Promise<any>)>
1219
+ ): Promise<Output>;
1220
+ };
1221
+ readonly pending: number;
1222
+ }
1223
+
1224
+ export function command<Output>(
1225
+ fn: () => Output | Promise<Output>,
1226
+ ): RemoteCommandFunction<void, Output>;
1227
+ export function command<Input, Output>(
1228
+ fn: (arg: Input) => Output | Promise<Output>,
1229
+ ): RemoteCommandFunction<Input, Output>;
1230
+ export function command<Input, Validated, Output>(
1231
+ schema: RemoteSchema<Input, Validated>,
1232
+ fn: (arg: Validated) => Output | Promise<Output>,
1233
+ ): RemoteCommandFunction<Input, Output>;
1234
+ export function command<Input = any, Output = any>(
1235
+ schemaOrFn: any,
1236
+ maybeFn?: any,
1237
+ ): RemoteCommandFunction<Input, Output> {
1238
+ const hasSchema = typeof maybeFn === "function";
1239
+ const schema = hasSchema
1240
+ ? (schemaOrFn as RemoteSchema<Input, any>)
1241
+ : undefined;
1242
+ const fn = (hasSchema ? maybeFn : schemaOrFn) as (
1243
+ arg: any,
1244
+ ) => Output | Promise<Output>;
1245
+ let pendingCount = 0;
1246
+
1247
+ const invoke = (arg: Input) => {
1248
+ pendingCount++;
1249
+ const extraUpdates: Array<RemoteQuery<any> | (() => Promise<any>)> = [];
1250
+ const promise = (async () => {
1251
+ try {
1252
+ const validated = await validateRemoteInput(schema, arg);
1253
+ const result = await fn(validated);
1254
+ for (const q of extraUpdates) {
1255
+ if (q && typeof (q as RemoteQuery<any>).refresh === "function") {
1256
+ await (q as RemoteQuery<any>).refresh();
1257
+ } else if (typeof q === "function") {
1258
+ await q();
1259
+ }
1260
+ }
1261
+ return result;
1262
+ } finally {
1263
+ pendingCount = Math.max(0, pendingCount - 1);
1264
+ }
1265
+ })();
1266
+
1267
+ return Object.assign(promise, {
1268
+ updates(...queries: Array<RemoteQuery<any> | (() => Promise<any>)>) {
1269
+ extraUpdates.push(...queries);
1270
+ return promise;
1271
+ },
1272
+ });
1273
+ };
1274
+
1275
+ Object.defineProperty(invoke, "pending", {
1276
+ get() {
1277
+ return pendingCount;
1278
+ },
1279
+ enumerable: true,
1280
+ });
1281
+
1282
+ return invoke as RemoteCommandFunction<Input, Output>;
1283
+ }
1284
+
1285
+ export interface RemoteFormFieldDescriptor {
1286
+ readonly name: string;
1287
+ as(
1288
+ type: string,
1289
+ value?: string | number | boolean,
1290
+ ): {
1291
+ name: string;
1292
+ type: string;
1293
+ value?: string | number | boolean;
1294
+ checked?: boolean;
1295
+ };
1296
+ value(): any;
1297
+ issues(): Array<{ message: string }>;
1298
+ }
1299
+
1300
+ export interface RemoteForm<Input = Record<string, any>, Output = any> {
1301
+ (data?: Input | FormData): Promise<Output>;
1302
+ readonly method: "POST";
1303
+ readonly action: string;
1304
+ readonly result: Output | undefined;
1305
+ readonly pending: number;
1306
+ readonly fields: Record<string, RemoteFormFieldDescriptor> & {
1307
+ allIssues(): Array<{ message: string }>;
1308
+ set(values: Partial<Input>): void;
1309
+ value(): Input;
1310
+ };
1311
+ enhance(
1312
+ callback: (opts: {
1313
+ form: HTMLFormElement;
1314
+ data: Input;
1315
+ submit: () => Promise<Output>;
1316
+ }) => void | Promise<void>,
1317
+ ): { method: "POST"; action: string; onsubmit: (ev: Event) => Promise<void> };
1318
+ for(id: string | number): RemoteForm<Input, Output>;
1319
+ validate(opts?: { includeUntouched?: boolean }): Promise<boolean>;
1320
+ }
1321
+
1322
+ let remoteFormIdCounter = 0;
1323
+
1324
+ export function form<Output>(
1325
+ fn: (data: Record<string, any>) => Output | Promise<Output>,
1326
+ ): RemoteForm<Record<string, any>, Output>;
1327
+ export function form<Input extends Record<string, any>, Output>(
1328
+ schema: RemoteSchema<Input, Input>,
1329
+ fn: (data: Input) => Output | Promise<Output>,
1330
+ ): RemoteForm<Input, Output>;
1331
+ export function form<
1332
+ Input extends Record<string, any> = Record<string, any>,
1333
+ Output = any,
1334
+ >(schemaOrFn: any, maybeFn?: any): RemoteForm<Input, Output> {
1335
+ const hasSchema = typeof maybeFn === "function";
1336
+ const schema = hasSchema
1337
+ ? (schemaOrFn as RemoteSchema<Input, any>)
1338
+ : undefined;
1339
+ const fn = (hasSchema ? maybeFn : schemaOrFn) as (
1340
+ data: any,
1341
+ ) => Output | Promise<Output>;
1342
+ const formId = `remote_form_${++remoteFormIdCounter}`;
1343
+
1344
+ const createFormInstance = (
1345
+ instanceKey = formId,
1346
+ scopedId?: string | number,
1347
+ ): RemoteForm<Input, Output> => {
1348
+ let lastResult: Output | undefined = undefined;
1349
+ let pendingCount = 0;
1350
+ let fieldValues: Record<string, any> = {};
1351
+ let fieldIssues: Array<{ message: string }> = [];
1352
+ const scopedInstances = new Map<
1353
+ string | number,
1354
+ RemoteForm<Input, Output>
1355
+ >();
1356
+
1357
+ const normalizeFormData = (raw?: Input | FormData): Input => {
1358
+ if (!raw) return { ...fieldValues } as Input;
1359
+ if (typeof FormData !== "undefined" && raw instanceof FormData) {
1360
+ const obj: Record<string, any> = {};
1361
+ for (const [k, v] of raw.entries()) {
1362
+ obj[k] = v;
1363
+ }
1364
+ return obj as Input;
1365
+ }
1366
+ return raw as Input;
1367
+ };
1368
+
1369
+ const submitForm = async (raw?: Input | FormData): Promise<Output> => {
1370
+ pendingCount++;
1371
+ fieldIssues = [];
1372
+ try {
1373
+ const inputObj = normalizeFormData(raw);
1374
+ fieldValues = { ...inputObj };
1375
+ const validated = await validateRemoteInput(schema, inputObj);
1376
+ const out = await fn(validated);
1377
+ lastResult = out;
1378
+ return out;
1379
+ } catch (err: any) {
1380
+ const msg = err?.body?.message ?? err?.message ?? String(err);
1381
+ fieldIssues = [{ message: String(msg) }];
1382
+ throw err;
1383
+ } finally {
1384
+ pendingCount = Math.max(0, pendingCount - 1);
1385
+ }
1386
+ };
1387
+
1388
+ const fieldsProxy = new Proxy(
1389
+ {
1390
+ allIssues: () => fieldIssues,
1391
+ set: (values: Partial<Input>) => {
1392
+ fieldValues = { ...fieldValues, ...values };
1393
+ },
1394
+ value: () => ({ ...fieldValues }) as Input,
1395
+ },
1396
+ {
1397
+ get(target, prop) {
1398
+ if (prop in target) {
1399
+ return (target as any)[prop];
1400
+ }
1401
+ if (typeof prop !== "string") return undefined;
1402
+ const fieldDescriptor: RemoteFormFieldDescriptor = {
1403
+ name: prop,
1404
+ as(type: string, val?: string | number | boolean) {
1405
+ if (type === "checkbox") {
1406
+ return {
1407
+ name: prop,
1408
+ type,
1409
+ checked: Boolean(val ?? fieldValues[prop]),
1410
+ };
1411
+ }
1412
+ if (type === "radio") {
1413
+ return {
1414
+ name: prop,
1415
+ type,
1416
+ value: val,
1417
+ checked: fieldValues[prop] === val,
1418
+ };
1419
+ }
1420
+ return {
1421
+ name: prop,
1422
+ type,
1423
+ value: (val ?? fieldValues[prop] ?? "") as
1424
+ string | number | boolean,
1425
+ };
1426
+ },
1427
+ value: () => fieldValues[prop],
1428
+ issues: () => fieldIssues,
1429
+ };
1430
+ return fieldDescriptor;
1431
+ },
1432
+ },
1433
+ ) as RemoteForm<Input, Output>["fields"];
1434
+
1435
+ const actionPath =
1436
+ scopedId !== undefined
1437
+ ? `?/${instanceKey}&id=${encodeURIComponent(JSON.stringify(scopedId))}`
1438
+ : `?/${instanceKey}`;
1439
+
1440
+ const instance = Object.defineProperties(
1441
+ submitForm,
1442
+ Object.getOwnPropertyDescriptors({
1443
+ method: "POST" as const,
1444
+ action: actionPath,
1445
+ get result(): Output | undefined {
1446
+ return lastResult;
1447
+ },
1448
+ get pending(): number {
1449
+ return pendingCount;
1450
+ },
1451
+ fields: fieldsProxy,
1452
+ enhance(
1453
+ callback: (opts: {
1454
+ form: HTMLFormElement;
1455
+ data: Input;
1456
+ submit: () => Promise<Output>;
1457
+ }) => void | Promise<void>,
1458
+ ) {
1459
+ return {
1460
+ method: "POST" as const,
1461
+ action: actionPath,
1462
+ onsubmit: async (ev: Event) => {
1463
+ if (typeof ev?.preventDefault === "function") {
1464
+ ev.preventDefault();
1465
+ }
1466
+ const formEl = (ev?.currentTarget ??
1467
+ ev?.target) as HTMLFormElement;
1468
+ const data =
1469
+ formEl && typeof FormData !== "undefined"
1470
+ ? normalizeFormData(new FormData(formEl))
1471
+ : ({ ...fieldValues } as Input);
1472
+ await callback({
1473
+ form: formEl,
1474
+ data,
1475
+ submit: () => submitForm(data),
1476
+ });
1477
+ },
1478
+ };
1479
+ },
1480
+ for(id: string | number): RemoteForm<Input, Output> {
1481
+ let scoped = scopedInstances.get(id);
1482
+ if (!scoped) {
1483
+ scoped = createFormInstance(instanceKey, id);
1484
+ scopedInstances.set(id, scoped);
1485
+ }
1486
+ return scoped;
1487
+ },
1488
+ async validate(): Promise<boolean> {
1489
+ try {
1490
+ await validateRemoteInput(schema, { ...fieldValues } as Input);
1491
+ fieldIssues = [];
1492
+ return true;
1493
+ } catch (err: any) {
1494
+ const msg = err?.body?.message ?? err?.message ?? String(err);
1495
+ fieldIssues = [{ message: String(msg) }];
1496
+ return false;
1497
+ }
1498
+ },
1499
+ }),
1500
+ ) as RemoteForm<Input, Output>;
1501
+
1502
+ return instance;
1503
+ };
1504
+
1505
+ return createFormInstance();
1506
+ }
1507
+
1508
+ export type RemoteFormFunction<
1509
+ Input extends Record<string, any> = Record<string, any>,
1510
+ Output = any,
1511
+ > = RemoteForm<Input, Output>;
1512
+
1513
+ // ============================================================================
1514
+ // `@sveltejs/kit` Universal / Server Data Loading & Form Actions Runtime & Types
1515
+ // ============================================================================
1516
+
1517
+ export type ParamMatcher = (param: string) => boolean;
1518
+
1519
+ export type RequestHandler<
1520
+ Params extends Record<string, string> = Record<string, string>,
1521
+ RouteId extends string | null = string | null,
1522
+ > = (event: RequestEvent<Params, RouteId>) => Response | Promise<Response>;
1523
+
1524
+ export interface ServerLoadEvent<
1525
+ Params extends Record<string, string> = Record<string, string>,
1526
+ ParentData extends Record<string, any> = Record<string, any>,
1527
+ RouteId extends string | null = string | null,
1528
+ > extends RequestEvent<Params, RouteId> {
1529
+ parent(): Promise<ParentData>;
1530
+ depends(...deps: string[]): void;
1531
+ untrack<T>(fn: () => T): T;
1532
+ tracing: {
1533
+ enabled: boolean;
1534
+ root: any;
1535
+ current: any;
1536
+ };
1537
+ }
1538
+
1539
+ export type ServerLoad<
1540
+ Params extends Record<string, string> = Record<string, string>,
1541
+ ParentData extends Record<string, any> = Record<string, any>,
1542
+ OutputData extends Record<string, any> | void = Record<string, any> | void,
1543
+ RouteId extends string | null = string | null,
1544
+ > = (
1545
+ event: ServerLoadEvent<Params, ParentData, RouteId>,
1546
+ ) => OutputData | Promise<OutputData>;
1547
+
1548
+ export type PageServerLoad<
1549
+ Params extends Record<string, string> = Record<string, string>,
1550
+ ParentData extends Record<string, any> = Record<string, any>,
1551
+ OutputData extends Record<string, any> | void = Record<string, any> | void,
1552
+ RouteId extends string | null = string | null,
1553
+ > = ServerLoad<Params, ParentData, OutputData, RouteId>;
1554
+
1555
+ export type LayoutServerLoad<
1556
+ Params extends Record<string, string> = Record<string, string>,
1557
+ ParentData extends Record<string, any> = Record<string, any>,
1558
+ OutputData extends Record<string, any> | void = Record<string, any> | void,
1559
+ RouteId extends string | null = string | null,
1560
+ > = ServerLoad<Params, ParentData, OutputData, RouteId>;
1561
+
1562
+ export type Load<
1563
+ Params extends Record<string, string> = Record<string, string>,
1564
+ InputData extends Record<string, any> | null = Record<string, any> | null,
1565
+ ParentData extends Record<string, any> = Record<string, any>,
1566
+ OutputData extends Record<string, any> | void = Record<string, any> | void,
1567
+ RouteId extends string | null = string | null,
1568
+ > = (event: {
1569
+ url: URL;
1570
+ params: Params;
1571
+ data: InputData;
1572
+ route: { id: RouteId };
1573
+ fetch: typeof globalThis.fetch;
1574
+ setHeaders(headers: Record<string, string>): void;
1575
+ parent(): Promise<ParentData>;
1576
+ depends(...deps: string[]): void;
1577
+ untrack<T>(fn: () => T): T;
1578
+ }) => OutputData | Promise<OutputData>;
1579
+
1580
+ export type PageLoad<
1581
+ Params extends Record<string, string> = Record<string, string>,
1582
+ InputData extends Record<string, any> | null = Record<string, any> | null,
1583
+ ParentData extends Record<string, any> = Record<string, any>,
1584
+ OutputData extends Record<string, any> | void = Record<string, any> | void,
1585
+ RouteId extends string | null = string | null,
1586
+ > = Load<Params, InputData, ParentData, OutputData, RouteId>;
1587
+
1588
+ export type LayoutLoad<
1589
+ Params extends Record<string, string> = Record<string, string>,
1590
+ InputData extends Record<string, any> | null = Record<string, any> | null,
1591
+ ParentData extends Record<string, any> = Record<string, any>,
1592
+ OutputData extends Record<string, any> | void = Record<string, any> | void,
1593
+ RouteId extends string | null = string | null,
1594
+ > = Load<Params, InputData, ParentData, OutputData, RouteId>;
1595
+
1596
+ export type LoadProperties<T> = T extends void | undefined
1597
+ ? Record<string, never>
1598
+ : T;
1599
+
1600
+ export type Action<
1601
+ Params extends Record<string, string> = Record<string, string>,
1602
+ OutputData extends Record<string, any> | void = Record<string, any> | void,
1603
+ RouteId extends string | null = string | null,
1604
+ > = (
1605
+ event: RequestEvent<Params, RouteId>,
1606
+ ) => OutputData | ActionFailure<any> | Promise<OutputData | ActionFailure<any>>;
1607
+
1608
+ export type Actions<
1609
+ Params extends Record<string, string> = Record<string, string>,
1610
+ OutputData extends Record<string, any> | void = Record<string, any> | void,
1611
+ RouteId extends string | null = string | null,
1612
+ > = Record<string, Action<Params, OutputData, RouteId>>;
1613
+
1614
+ export type HandleFetch = (input: {
1615
+ event: RequestEvent;
1616
+ request: Request;
1617
+ fetch: typeof globalThis.fetch;
1618
+ }) => Promise<Response> | Response;
1619
+
1620
+ export type HandleServerError = (input: {
1621
+ error: unknown;
1622
+ event: RequestEvent;
1623
+ status: number;
1624
+ message: string;
1625
+ }) => Promise<AppError | void> | AppError | void;
1626
+
1627
+ export type HandleClientError = (input: {
1628
+ error: unknown;
1629
+ event: NavigationTarget;
1630
+ status: number;
1631
+ message: string;
1632
+ }) => Promise<AppError | void> | AppError | void;
1633
+
1634
+ export type HandleValidationError<Issue = any> = (input: {
1635
+ issues: Issue[];
1636
+ event: RequestEvent;
1637
+ }) => Promise<AppError> | AppError;
1638
+
1639
+ export type Reroute = (input: {
1640
+ url: URL;
1641
+ fetch: typeof globalThis.fetch;
1642
+ }) => Promise<string | void> | string | void;
1643
+
1644
+ export type Transport = Record<
1645
+ string,
1646
+ {
1647
+ encode: (value: any) => any;
1648
+ decode: (data: any) => any;
1649
+ }
1650
+ >;
1651
+
1652
+ export interface KitServerLoadEventInit<
1653
+ Params extends Record<string, string> = Record<string, string>,
1654
+ ParentData extends Record<string, any> = Record<string, any>,
1655
+ RouteId extends string | null = string | null,
1656
+ > extends KitRequestEventInit<Params, RouteId> {
1657
+ parentData?: ParentData;
1658
+ parent?: () => Promise<ParentData> | ParentData;
1659
+ dependencies?: Set<string>;
1660
+ }
1661
+
1662
+ export function createServerLoadEvent<
1663
+ Params extends Record<string, string> = Record<string, string>,
1664
+ ParentData extends Record<string, any> = Record<string, any>,
1665
+ RouteId extends string | null = string | null,
1666
+ >(
1667
+ init: KitServerLoadEventInit<Params, ParentData, RouteId> = {},
1668
+ ): ServerLoadEvent<Params, ParentData, RouteId> & {
1669
+ readonly dependencies: ReadonlySet<string>;
1670
+ readonly responseHeaders: Headers;
1671
+ } {
1672
+ const responseHeaders = init.responseHeaders ?? new Headers();
1673
+ const baseEvent = createKitRequestEvent<Params, RouteId>({
1674
+ ...init,
1675
+ responseHeaders,
1676
+ });
1677
+ const deps = init.dependencies ?? new Set<string>();
1678
+ return {
1679
+ ...baseEvent,
1680
+ async parent(): Promise<ParentData> {
1681
+ if (init.parent) return await init.parent();
1682
+ return (init.parentData ?? {}) as ParentData;
1683
+ },
1684
+ depends(...urls: string[]): void {
1685
+ for (const u of urls) {
1686
+ deps.add(u);
1687
+ }
1688
+ },
1689
+ untrack<T>(fn: () => T): T {
1690
+ return fn();
1691
+ },
1692
+ tracing: {
1693
+ enabled: false,
1694
+ root: null,
1695
+ current: null,
1696
+ },
1697
+ get dependencies(): ReadonlySet<string> {
1698
+ return deps;
1699
+ },
1700
+ get responseHeaders(): Headers {
1701
+ return responseHeaders;
1702
+ },
1703
+ };
1704
+ }
1705
+
1706
+ export interface KitUniversalLoadEventInit<
1707
+ Params extends Record<string, string> = Record<string, string>,
1708
+ InputData extends Record<string, any> | null = Record<string, any> | null,
1709
+ ParentData extends Record<string, any> = Record<string, any>,
1710
+ RouteId extends string | null = string | null,
1711
+ > {
1712
+ url?: string | URL;
1713
+ params?: Params;
1714
+ data?: InputData;
1715
+ parentData?: ParentData;
1716
+ routeId?: RouteId;
1717
+ fetch?: typeof globalThis.fetch;
1718
+ parent?: () => Promise<ParentData> | ParentData;
1719
+ responseHeaders?: Headers;
1720
+ dependencies?: Set<string>;
1721
+ }
1722
+
1723
+ export function createLoadEvent<
1724
+ Params extends Record<string, string> = Record<string, string>,
1725
+ InputData extends Record<string, any> | null = Record<string, any> | null,
1726
+ ParentData extends Record<string, any> = Record<string, any>,
1727
+ RouteId extends string | null = string | null,
1728
+ >(
1729
+ init: KitUniversalLoadEventInit<Params, InputData, ParentData, RouteId> = {},
1730
+ ) {
1731
+ const url =
1732
+ init.url instanceof URL
1733
+ ? new URL(init.url.href)
1734
+ : typeof init.url === "string"
1735
+ ? new URL(init.url, "http://localhost")
1736
+ : new URL("http://localhost/");
1737
+ const responseHeaders = init.responseHeaders ?? new Headers();
1738
+ const deps = init.dependencies ?? new Set<string>();
1739
+ return {
1740
+ url,
1741
+ params: (init.params ?? {}) as Params,
1742
+ data: (init.data ?? null) as InputData,
1743
+ route: { id: (init.routeId ?? (url.pathname as RouteId)) as RouteId },
1744
+ fetch: init.fetch ?? globalThis.fetch.bind(globalThis),
1745
+ setHeaders(headers: Record<string, string>): void {
1746
+ for (const [k, v] of Object.entries(headers)) {
1747
+ responseHeaders.set(k, v);
1748
+ }
1749
+ },
1750
+ async parent(): Promise<ParentData> {
1751
+ if (init.parent) return await init.parent();
1752
+ return (init.parentData ?? {}) as ParentData;
1753
+ },
1754
+ depends(...urls: string[]): void {
1755
+ for (const u of urls) {
1756
+ deps.add(u);
1757
+ }
1758
+ },
1759
+ untrack<T>(fn: () => T): T {
1760
+ return fn();
1761
+ },
1762
+ get dependencies(): ReadonlySet<string> {
1763
+ return deps;
1764
+ },
1765
+ get responseHeaders(): Headers {
1766
+ return responseHeaders;
1767
+ },
1768
+ };
1769
+ }
1770
+
1771
+ export async function executeKitServerLoad<
1772
+ OutputData extends Record<string, any> | void = Record<string, any>,
1773
+ Params extends Record<string, string> = Record<string, string>,
1774
+ ParentData extends Record<string, any> = Record<string, any>,
1775
+ RouteId extends string | null = string | null,
1776
+ >(
1777
+ loadFn: ServerLoad<Params, ParentData, OutputData, RouteId>,
1778
+ init: KitServerLoadEventInit<Params, ParentData, RouteId> = {},
1779
+ ): Promise<{
1780
+ data: OutputData;
1781
+ dependencies: string[];
1782
+ headers: Headers;
1783
+ event: ServerLoadEvent<Params, ParentData, RouteId> & {
1784
+ readonly dependencies: ReadonlySet<string>;
1785
+ readonly responseHeaders: Headers;
1786
+ };
1787
+ }> {
1788
+ const responseHeaders = init.responseHeaders ?? new Headers();
1789
+ const event = createServerLoadEvent<Params, ParentData, RouteId>({
1790
+ ...init,
1791
+ responseHeaders,
1792
+ });
1793
+ const data = await withKitRequestEvent(event, () => loadFn(event));
1794
+ setKitPage({
1795
+ url: event.url,
1796
+ params: event.params,
1797
+ route: event.route,
1798
+ data:
1799
+ data && typeof data === "object"
1800
+ ? { ...page.data, ...(data as Record<string, any>) }
1801
+ : page.data,
1802
+ });
1803
+ return {
1804
+ data,
1805
+ dependencies: Array.from(event.dependencies),
1806
+ headers: responseHeaders,
1807
+ event,
1808
+ };
1809
+ }
1810
+
1811
+ export async function executeKitUniversalLoad<
1812
+ OutputData extends Record<string, any> | void = Record<string, any>,
1813
+ Params extends Record<string, string> = Record<string, string>,
1814
+ InputData extends Record<string, any> | null = Record<string, any> | null,
1815
+ ParentData extends Record<string, any> = Record<string, any>,
1816
+ RouteId extends string | null = string | null,
1817
+ >(
1818
+ loadFn: Load<Params, InputData, ParentData, OutputData, RouteId>,
1819
+ init: KitUniversalLoadEventInit<Params, InputData, ParentData, RouteId> = {},
1820
+ ): Promise<{
1821
+ data: OutputData;
1822
+ dependencies: string[];
1823
+ headers: Headers;
1824
+ event: ReturnType<
1825
+ typeof createLoadEvent<Params, InputData, ParentData, RouteId>
1826
+ >;
1827
+ }> {
1828
+ const event = createLoadEvent<Params, InputData, ParentData, RouteId>(init);
1829
+ const data = await loadFn(event);
1830
+ setKitPage({
1831
+ url: event.url,
1832
+ params: event.params,
1833
+ route: event.route,
1834
+ data:
1835
+ data && typeof data === "object"
1836
+ ? { ...page.data, ...(data as Record<string, any>) }
1837
+ : page.data,
1838
+ });
1839
+ return {
1840
+ data,
1841
+ dependencies: Array.from(event.dependencies),
1842
+ headers: event.responseHeaders,
1843
+ event,
1844
+ };
1845
+ }
1846
+
1847
+ export interface KitActionExecutionInit<
1848
+ Params extends Record<string, string> = Record<string, string>,
1849
+ RouteId extends string | null = string | null,
1850
+ > extends KitRequestEventInit<Params, RouteId> {
1851
+ formData?: FormData;
1852
+ }
1853
+
1854
+ export async function executeKitAction<
1855
+ Success extends Record<string, unknown> | undefined = Record<string, any>,
1856
+ Failure extends Record<string, unknown> | undefined = Record<string, any>,
1857
+ Params extends Record<string, string> = Record<string, string>,
1858
+ RouteId extends string | null = string | null,
1859
+ >(
1860
+ actionsOrAction: Actions<Params, any, RouteId> | Action<Params, any, RouteId>,
1861
+ nameOrInit: string | KitActionExecutionInit<Params, RouteId> = {},
1862
+ maybeInit?: KitActionExecutionInit<Params, RouteId> | string,
1863
+ ): Promise<ActionResult<Success, Failure>> {
1864
+ const actionName =
1865
+ typeof nameOrInit === "string"
1866
+ ? nameOrInit
1867
+ : typeof maybeInit === "string"
1868
+ ? maybeInit
1869
+ : undefined;
1870
+ const rawInit: KitActionExecutionInit<Params, RouteId> =
1871
+ typeof nameOrInit === "object" && nameOrInit !== null
1872
+ ? nameOrInit
1873
+ : typeof maybeInit === "object" && maybeInit !== null
1874
+ ? maybeInit
1875
+ : {};
1876
+
1877
+ let request = rawInit.request;
1878
+ if (!request && rawInit.formData) {
1879
+ const resolvedUrl =
1880
+ rawInit.url instanceof URL
1881
+ ? rawInit.url.href
1882
+ : typeof rawInit.url === "string"
1883
+ ? new URL(rawInit.url, "http://localhost").href
1884
+ : "http://localhost/";
1885
+ request = new Request(resolvedUrl, {
1886
+ method: "POST",
1887
+ body: rawInit.formData,
1888
+ });
1889
+ }
1890
+
1891
+ const event = createKitRequestEvent<Params, RouteId>({
1892
+ ...rawInit,
1893
+ request,
1894
+ method: rawInit.method ?? "POST",
1895
+ });
1896
+ let targetAction: Action<Params, any, RouteId> | undefined;
1897
+
1898
+ if (typeof actionsOrAction === "function") {
1899
+ targetAction = actionsOrAction;
1900
+ } else {
1901
+ let resolvedName = actionName;
1902
+ if (!resolvedName) {
1903
+ for (const [key] of event.url.searchParams.entries()) {
1904
+ if (key.startsWith("/")) {
1905
+ resolvedName = key.slice(1);
1906
+ break;
1907
+ }
1908
+ }
1909
+ }
1910
+ if (!resolvedName) {
1911
+ resolvedName = "default";
1912
+ }
1913
+ targetAction = actionsOrAction[resolvedName];
1914
+ if (!targetAction) {
1915
+ return {
1916
+ type: "error",
1917
+ status: 404,
1918
+ error: { message: `Action "${resolvedName}" not found` },
1919
+ };
1920
+ }
1921
+ }
1922
+
1923
+ try {
1924
+ const out = await withKitRequestEvent(event, () => targetAction(event));
1925
+ if (isActionFailure(out)) {
1926
+ setKitPage({
1927
+ status: out.status,
1928
+ form: out.data,
1929
+ });
1930
+ return {
1931
+ type: "failure",
1932
+ status: out.status,
1933
+ data: out.data as Failure,
1934
+ };
1935
+ }
1936
+ setKitPage({
1937
+ status: 200,
1938
+ form: out ?? null,
1939
+ });
1940
+ return {
1941
+ type: "success",
1942
+ status: 200,
1943
+ data: out as Success,
1944
+ };
1945
+ } catch (err) {
1946
+ if (isRedirect(err)) {
1947
+ return {
1948
+ type: "redirect",
1949
+ status: err.status,
1950
+ location: err.location,
1951
+ };
1952
+ }
1953
+ if (isHttpError(err)) {
1954
+ setKitPage({
1955
+ status: err.status,
1956
+ error: err.body,
1957
+ });
1958
+ return {
1959
+ type: "error",
1960
+ status: err.status,
1961
+ error: err.body,
1962
+ };
1963
+ }
1964
+ return {
1965
+ type: "error",
1966
+ status: 500,
1967
+ error:
1968
+ err instanceof Error
1969
+ ? { message: err.message }
1970
+ : { message: String(err) },
1971
+ };
1972
+ }
1973
+ }