@aklinker1/zeta 1.0.0

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/types.ts ADDED
@@ -0,0 +1,1111 @@
1
+ /**
2
+ * Types used internally by Zeta to build the type system. You probably don't
3
+ * need to use these, and there is no guarantee that they will remain stable
4
+ * between non-major versions.
5
+ *
6
+ * @internal Subject to breaking changes outside of major versions.
7
+ * @module
8
+ */
9
+ import type { StandardSchemaV1 } from "@standard-schema/spec";
10
+ import type { OpenAPI } from "openapi-types";
11
+ import type { IsStatusResult } from "./internal/utils";
12
+ import type { HttpStatus } from "./status";
13
+
14
+ //
15
+ // APP
16
+ //
17
+
18
+ /**
19
+ * Represents an App object. TAppData represents additional type information not
20
+ * always stored on the app object itself.
21
+ */
22
+ export interface App<TAppData extends AppData = AppData> {
23
+ /**
24
+ * Internal references for implementing routing and calling registered
25
+ * handlers. Subject to breaking changes outside of major versions.
26
+ * @internal
27
+ */
28
+ "~zeta": {
29
+ /**
30
+ * Used for deduplication of hooks.
31
+ */
32
+ id: string;
33
+
34
+ /**
35
+ * When true, hooks defined on this app should be added to any app that
36
+ * imports this app.
37
+ */
38
+ exported?: boolean;
39
+
40
+ /**
41
+ * Path prefix from `CreateAppOptions.prefix`.
42
+ */
43
+ prefix: string;
44
+
45
+ /**
46
+ * List of routes registered with the app.
47
+ */
48
+ routes: { [method: string]: { [path: string]: RouterData } };
49
+
50
+ /**
51
+ * Stores arrays of hooks registered on the app.
52
+ */
53
+ hooks: LifeCycleHooks;
54
+ };
55
+
56
+ /**
57
+ * Merge and simplify all the app routes into a single fetch function.
58
+ */
59
+ build: () => ServerSideFetch;
60
+
61
+ /**
62
+ * Returns your application's OpenAPI spec. You do not need to listen to a
63
+ * port to call this method.
64
+ */
65
+ getOpenApiSpec: () => OpenAPI.Document;
66
+
67
+ /**
68
+ * Mark the app as "exported". When an exported app is `use`d by a
69
+ * parent app, the parent app will inherit all of it's hooks and modifiers.
70
+ *
71
+ * Regular, non-exported apps isolate their hooks and modifiers from the
72
+ * parent app (except for the global hooks, `onGlobalRequest`, `onGlobalError`, and
73
+ * `onGlobalAfterResponse`, which are always inherited by the parent app).
74
+ *
75
+ * The basic example is you can't access a decorated value from a parent app
76
+ * unless the child app is exported.
77
+ *
78
+ * @example
79
+ * ```ts
80
+ * const child = createApp()
81
+ * .decorate("a", "A");
82
+ *
83
+ * const bad = createApp()
84
+ * .use(child)
85
+ * .get("/", ({ a }) => {
86
+ * console.log(a); // => undefined
87
+ * });
88
+ *
89
+ * const good = createApp()
90
+ * .use(child.export())
91
+ * .get("/", ({ a }) => {
92
+ * console.log(a); // => "A"
93
+ * });
94
+ * ```
95
+ */
96
+ export: () => App<MergeAppData<TAppData, { exported: true }>>;
97
+
98
+ /**
99
+ * Detect the current environment and use `Bun.serve` or `Deno.serve` to serve the app over a port.
100
+ * @param port The port to listen on.
101
+ * @param cb Optional callback to be called when the server is ready.
102
+ */
103
+ listen: (port: number, cb?: () => void) => this;
104
+
105
+ /**
106
+ * Add a static value to the handler context.
107
+ */
108
+ decorate<TKey extends string, TValue>(
109
+ key: TKey,
110
+ value: TValue,
111
+ ): App<
112
+ Simplify<
113
+ MergeAppData<TAppData, { ctx: { [key in TKey]: Readonly<TValue> } }>
114
+ >
115
+ >;
116
+ /**
117
+ * Add multiple static values to the handler context.
118
+ */
119
+ decorate<TValues extends Record<string, any>>(
120
+ values: TValues,
121
+ ): App<Simplify<MergeAppData<TAppData, { ctx: TValues }>>>;
122
+
123
+ /**
124
+ * Add a callback that is called before the route is matched. If the callback
125
+ * returns a value, it will be merged into the `ctx` object. If the callback
126
+ * returns a `Response`, it will be returned immediately.
127
+ *
128
+ * @param callback The function to call.
129
+ */
130
+ onGlobalRequest(
131
+ callback: (
132
+ ctx: OnGlobalRequestContext<GetAppDataCtx<TAppData>>,
133
+ ) => MaybePromise<void>,
134
+ ): this;
135
+ onGlobalRequest(
136
+ callback: (
137
+ ctx: OnGlobalRequestContext<GetAppDataCtx<TAppData>>,
138
+ ) => MaybePromise<Response>,
139
+ ): this;
140
+ onGlobalRequest<TNewCtx extends Record<string, any>>(
141
+ callback: (
142
+ ctx: OnGlobalRequestContext<GetAppDataCtx<TAppData>>,
143
+ ) => MaybePromise<TNewCtx>,
144
+ ): App<MergeAppData<TAppData, { ctx: TNewCtx }>>;
145
+
146
+ /**
147
+ * Add a callback that is called after the route is matched and before the
148
+ * inputs are validated. If the callback returns a value, it will be merged
149
+ * into the `ctx` object. If the callback returns a `Response`, it will be
150
+ * returned immediately.
151
+ *
152
+ * @param callback The function to call.
153
+ */
154
+ onTransform(
155
+ callback: (
156
+ ctx: OnTransformContext<GetAppDataCtx<TAppData>>,
157
+ ) => MaybePromise<void>,
158
+ ): this;
159
+ onTransform(
160
+ callback: (
161
+ ctx: OnTransformContext<GetAppDataCtx<TAppData>>,
162
+ ) => MaybePromise<Response>,
163
+ ): this;
164
+ onTransform<TNewCtx extends Record<string, any>>(
165
+ callback: (
166
+ ctx: OnTransformContext<GetAppDataCtx<TAppData>>,
167
+ ) => MaybePromise<TNewCtx>,
168
+ ): App<MergeAppData<TAppData, { ctx: TNewCtx }>>;
169
+
170
+ /**
171
+ * Add a callback that is called after inputs are validated and before the
172
+ * handler is called. If the callback returns a value, it will be merged into
173
+ * the `ctx` object. If the callback returns a `Response`, it will be returned
174
+ * immediately.
175
+ *
176
+ * @param callback The function to call.
177
+ */
178
+ onBeforeHandle(
179
+ callback: (
180
+ ctx: OnBeforeHandleContext<GetAppDataCtx<TAppData>>,
181
+ ) => MaybePromise<void>,
182
+ ): this;
183
+ onBeforeHandle(
184
+ callback: (
185
+ ctx: OnBeforeHandleContext<GetAppDataCtx<TAppData>>,
186
+ ) => MaybePromise<Response>,
187
+ ): this;
188
+ onBeforeHandle<TNewCtx extends Record<string, any>>(
189
+ callback: (
190
+ ctx: OnBeforeHandleContext<GetAppDataCtx<TAppData>>,
191
+ ) => MaybePromise<TNewCtx>,
192
+ ): App<MergeAppData<TAppData, { ctx: TNewCtx }>>;
193
+
194
+ /**
195
+ * Add a callback that is called after the handler is called and before the
196
+ * response is validated. If the callback returns a value, it replaces the
197
+ * response with it.
198
+ *
199
+ * @param callback The function to call.
200
+ */
201
+ onAfterHandle(
202
+ callback: (
203
+ ctx: AfterHandleContext<GetAppDataCtx<TAppData>>,
204
+ ) => MaybePromise<unknown | void>,
205
+ ): this;
206
+
207
+ /**
208
+ * Add a callback that is called after the response is validated and before it
209
+ * is sent to the client. The callback can return a `Response` if you want to
210
+ * change how the response is built.
211
+ *
212
+ * @param callback The function to call.
213
+ */
214
+ onMapResponse(
215
+ callback: (
216
+ ctx: AfterHandleContext<GetAppDataCtx<TAppData>>,
217
+ ) => MaybePromise<unknown | void>,
218
+ ): this;
219
+
220
+ /**
221
+ * Add a callback that is called when an error is thrown. The callback can
222
+ * optionally return a `Response`, which will be used to respond to the
223
+ * client.
224
+ *
225
+ * @param callback The function to call.
226
+ */
227
+ onGlobalError(
228
+ callback: (
229
+ ctx: OnGlobalErrorContext<GetAppDataCtx<TAppData>>,
230
+ ) => MaybePromise<void>,
231
+ ): this;
232
+
233
+ /**
234
+ * Add a callback that is called after the response is sent.
235
+ * @param callback The function to call.
236
+ */
237
+ onGlobalAfterResponse(
238
+ callback: (
239
+ ctx: AfterResponseContext<GetAppDataCtx<TAppData>>,
240
+ ) => MaybePromise<void>,
241
+ ): this;
242
+
243
+ /**
244
+ * Add an undocumented GET route to the app.
245
+ */
246
+ get<TPath extends BasePath>(
247
+ path: TPath,
248
+ handler: RouteHandler<TAppData, TPath, AnyDef>,
249
+ ): App<
250
+ MergeAppData<TAppData, { routes: { GET: { [path in TPath]: AnyDef } } }>
251
+ >;
252
+ /**
253
+ * Add a documented GET route to the app.
254
+ */
255
+ get<TPath extends BasePath, TRouteDef extends RouteDef>(
256
+ path: TPath,
257
+ def: TRouteDef,
258
+ handler: RouteHandler<TAppData, TPath, TRouteDef>,
259
+ ): App<
260
+ MergeAppData<TAppData, { routes: { GET: { [path in TPath]: TRouteDef } } }>
261
+ >;
262
+
263
+ /**
264
+ * Add an undocumented POST route to the app.
265
+ */
266
+ post<TPath extends BasePath>(
267
+ path: TPath,
268
+ handler: RouteHandler<TAppData, TPath, AnyDef>,
269
+ ): App<
270
+ MergeAppData<TAppData, { routes: { POST: { [path in TPath]: AnyDef } } }>
271
+ >;
272
+ /**
273
+ * Add a documented POST route to the app.
274
+ */
275
+ post<TPath extends BasePath, TRouteDef extends RouteDef>(
276
+ path: TPath,
277
+ def: TRouteDef,
278
+ handler: RouteHandler<TAppData, TPath, TRouteDef>,
279
+ ): App<
280
+ MergeAppData<TAppData, { routes: { POST: { [path in TPath]: TRouteDef } } }>
281
+ >;
282
+
283
+ /**
284
+ * Add an undocumented PUT route to the app.
285
+ */
286
+ put<TPath extends BasePath>(
287
+ path: TPath,
288
+ handler: RouteHandler<TAppData, TPath, AnyDef>,
289
+ ): App<
290
+ MergeAppData<TAppData, { routes: { PUT: { [path in TPath]: AnyDef } } }>
291
+ >;
292
+ /**
293
+ * Add a documented PUT route to the app.
294
+ */
295
+ put<TPath extends BasePath, TRouteDef extends RouteDef>(
296
+ path: TPath,
297
+ def: TRouteDef,
298
+ handler: RouteHandler<TAppData, TPath, TRouteDef>,
299
+ ): App<
300
+ MergeAppData<TAppData, { routes: { PUT: { [path in TPath]: TRouteDef } } }>
301
+ >;
302
+
303
+ /**
304
+ * Add an undocumented DELETE route to the app.
305
+ */
306
+ delete<TPath extends BasePath>(
307
+ path: TPath,
308
+ handler: RouteHandler<TAppData, TPath, AnyDef>,
309
+ ): App<
310
+ MergeAppData<TAppData, { routes: { DELETE: { [path in TPath]: AnyDef } } }>
311
+ >;
312
+ /**
313
+ * Add a documented DELETE route to the app.
314
+ */
315
+ delete<TPath extends BasePath, TRouteDef extends RouteDef>(
316
+ path: TPath,
317
+ def: TRouteDef,
318
+ handler: RouteHandler<TAppData, TPath, TRouteDef>,
319
+ ): App<
320
+ MergeAppData<
321
+ TAppData,
322
+ { routes: { DELETE: { [path in TPath]: TRouteDef } } }
323
+ >
324
+ >;
325
+
326
+ /**
327
+ * Add an undocumented route to the app that responds to any method used.
328
+ */
329
+ any<TPath extends BasePath>(
330
+ path: TPath,
331
+ handler: RouteHandler<TAppData, TPath, AnyDef>,
332
+ ): App<
333
+ MergeAppData<TAppData, { routes: { ANY: { [path in TPath]: AnyDef } } }>
334
+ >;
335
+
336
+ /**
337
+ * Add an documented route to the app that responds to any method used.
338
+ */
339
+ any<TPath extends BasePath, TRouteDef extends RouteDef>(
340
+ path: TPath,
341
+ def: TRouteDef,
342
+ handler: RouteHandler<TAppData, TPath, AnyDef>,
343
+ ): App<
344
+ MergeAppData<TAppData, { routes: { ANY: { [path in TPath]: TRouteDef } } }>
345
+ >;
346
+
347
+ /**
348
+ * Add an undocumented route to the app using a custom method.
349
+ */
350
+ method<TMethod extends string, TPath extends BasePath>(
351
+ method: TMethod,
352
+ path: TPath,
353
+ handler: RouteHandler<TAppData, TPath, AnyDef>,
354
+ ): App<
355
+ MergeAppData<
356
+ TAppData,
357
+ { routes: { [method in TMethod]: { [path in TPath]: AnyDef } } }
358
+ >
359
+ >;
360
+ /**
361
+ * Add a documented route to the app using a custom method.
362
+ */
363
+ method<
364
+ TMethod extends string,
365
+ TPath extends BasePath,
366
+ TRouteDef extends RouteDef,
367
+ >(
368
+ method: TMethod,
369
+ path: TPath,
370
+ def: TRouteDef,
371
+ handler: RouteHandler<TAppData, TPath, TRouteDef>,
372
+ ): App<
373
+ MergeAppData<
374
+ TAppData,
375
+ { routes: { [method in TMethod]: { [path in TPath]: TRouteDef } } }
376
+ >
377
+ >;
378
+
379
+ /**
380
+ * Mount another fetch function at `/**`.
381
+ */
382
+ mount(
383
+ fetch: ServerSideFetch,
384
+ ): App<MergeAppData<TAppData, { routes: { ANY: { "/**": AnyDef } } }>>;
385
+ /**
386
+ * Mount another fetch function at `${path}/**`.
387
+ */
388
+ mount<TPath extends BasePath>(
389
+ path: TPath,
390
+ fetch: ServerSideFetch,
391
+ ): App<
392
+ MergeAppData<
393
+ TAppData,
394
+ { routes: { ANY: { [path in `${TPath}/**`]: AnyDef } } }
395
+ >
396
+ >;
397
+ /**
398
+ * Mount another fetch function at `${path}/**`.
399
+ */
400
+ mount<TPath extends BasePath, TRouteDef extends RouteDef>(
401
+ path: TPath,
402
+ def: TRouteDef,
403
+ fetch: ServerSideFetch,
404
+ ): App<
405
+ MergeAppData<
406
+ TAppData,
407
+ { routes: { ANY: { [path in `${TPath}/**`]: TRouteDef } } }
408
+ >
409
+ >;
410
+
411
+ /**
412
+ * Add a subapp to the app.
413
+ */
414
+ use<TNewApp extends App>(
415
+ app: TNewApp,
416
+ ): App<UseAppData<TAppData, GetAppData<TNewApp>>>;
417
+ }
418
+
419
+ /**
420
+ * Given an `App`, return it's `AppData`.
421
+ */
422
+ export type GetAppData<TApp extends App> =
423
+ TApp extends App<infer TAppData> ? TAppData : never;
424
+
425
+ /**
426
+ * Given an `App`, return the routes defined on it.
427
+ */
428
+ export type GetAppRoutes<TApp extends App> = GetAppData<TApp>["routes"];
429
+
430
+ /**
431
+ * Data stored internally for each route inside the `rou3` router.
432
+ */
433
+ export type RouterData = {
434
+ def?: RouteDef;
435
+ route: string;
436
+ hooks: LifeCycleHooks;
437
+ } & (
438
+ | { fetch: ServerSideFetch }
439
+ | { handler: (ctx: OnBeforeHandleContext) => Promise<any> }
440
+ );
441
+
442
+ //
443
+ // HANDLERS
444
+ //
445
+
446
+ /**
447
+ * Type of the callback function used for each route.
448
+ */
449
+ export type RouteHandler<
450
+ TAppData extends AppData,
451
+ TPath extends BasePath,
452
+ TRouteDef extends RouteDef,
453
+ > = (
454
+ ctx: BuildHandlerContext<TAppData, TPath, TRouteDef>,
455
+ ) => MaybePromise<GetRouteHandlerReturnType<TRouteDef>>;
456
+
457
+ export type GetRouteHandlerReturnType<TRouteDef extends RouteDef> =
458
+ TRouteDef extends { responses: symbol } // is any check
459
+ ? any
460
+ : TRouteDef extends { responses: infer TResponses }
461
+ ? TResponses extends StandardSchemaV1<infer TResponse>
462
+ ? TResponse
463
+ : TRouteDef["responses"] extends Record<number, StandardSchemaV1<any>>
464
+ ? StatusResult
465
+ : never
466
+ : void;
467
+
468
+ /**
469
+ * Given an `App`, a method, and a route, return the handler function's type.
470
+ */
471
+ export type GetRouteHandler<
472
+ TApp extends App,
473
+ TMethod extends keyof GetAppRoutes<TApp>,
474
+ TRoute extends keyof GetAppRoutes<TApp>[TMethod],
475
+ > = TRoute extends BasePath
476
+ ? GetAppRoutes<TApp>[TMethod][TRoute] extends RouteDef
477
+ ? RouteHandler<
478
+ GetAppData<TApp>,
479
+ TRoute,
480
+ GetAppRoutes<TApp>[TMethod][TRoute]
481
+ >
482
+ : never
483
+ : never;
484
+
485
+ //
486
+ // LIFECYCLE HOOKS
487
+ //
488
+
489
+ /**
490
+ * Internal type used to store a hook on an app.
491
+ */
492
+ export type LifeCycleHook<TCallback extends Function> = {
493
+ /**
494
+ * Used for deducplication.
495
+ */
496
+ id: string;
497
+ /**
498
+ * Where this plugin should be applied.
499
+ * - `global`: Global plugins are hoisted to the top-level app.
500
+ * - `local`: Local plugins are applied to the app they were added to.
501
+ * @default "local"
502
+ */
503
+ applyTo: "global" | "local";
504
+ /**
505
+ * The function called when the hook is triggered.
506
+ */
507
+ callback: TCallback;
508
+ };
509
+
510
+ /**
511
+ * Called immediately after receiving the request. Returned record is merged
512
+ * into the handler context.
513
+ */
514
+ export type OnGlobalRequestHook = LifeCycleHook<
515
+ (
516
+ ctx: Simplify<OnGlobalRequestContext>,
517
+ ) => MaybePromise<Record<string, any> | void>
518
+ >;
519
+
520
+ /**
521
+ * Called before validating the request inputs. Returned record is merged into
522
+ * the handler context.
523
+ */
524
+ export type OnTransformHook = LifeCycleHook<
525
+ (
526
+ ctx: Simplify<OnTransformContext>,
527
+ ) => MaybePromise<Record<string, any> | void>
528
+ >;
529
+
530
+ /**
531
+ * Called before calling the route handler. Returned record is merged into the
532
+ * handler context.
533
+ */
534
+ export type OnBeforeHandleHook = LifeCycleHook<
535
+ (
536
+ ctx: Simplify<OnBeforeHandleContext>,
537
+ ) => MaybePromise<Record<string, any> | void>
538
+ >;
539
+
540
+ /**
541
+ * Called after calling the route handler. If there is a return value, it
542
+ * replaces the return value from the handler. Similar to the `onTransform` hook,
543
+ * but for the response.
544
+ */
545
+ export type OnAfterHandleHook = LifeCycleHook<
546
+ (ctx: Simplify<AfterHandleContext>) => MaybePromise<unknown | void>
547
+ >;
548
+
549
+ /**
550
+ * Called after validating the handler return value. Used to transform the
551
+ * return value into a `Response`.
552
+ */
553
+ export type OnMapResponseHook = LifeCycleHook<
554
+ (ctx: Simplify<OnMapResponseContext>) => MaybePromise<Response | void>
555
+ >;
556
+
557
+ /**
558
+ * Called if an error is thrown in any other hook other than `onGlobalAfterResponse`.
559
+ *
560
+ * Zeta will handle any `HttpError`s thrown, but you can handle your own errors
561
+ * here.
562
+ */
563
+ export type OnGlobalErrorHooks = LifeCycleHook<
564
+ (ctx: Simplify<OnGlobalErrorContext>) => MaybePromise<void>
565
+ >;
566
+
567
+ /**
568
+ * Called after the response is sent back to the client.
569
+ */
570
+ export type OnGlobalAfterResponseHook = LifeCycleHook<
571
+ (ctx: Simplify<AfterResponseContext>) => MaybePromise<void>
572
+ >;
573
+
574
+ export type LifeCycleHooks = {
575
+ onGlobalRequest: OnGlobalRequestHook[];
576
+ onTransform: OnTransformHook[];
577
+ onBeforeHandle: OnBeforeHandleHook[];
578
+ onAfterHandle: OnAfterHandleHook[];
579
+ onMapResponse: OnMapResponseHook[];
580
+ onGlobalError: OnGlobalErrorHooks[];
581
+ onGlobalAfterResponse: OnGlobalAfterResponseHook[];
582
+ };
583
+
584
+ //
585
+ // BASE TYPES
586
+ //
587
+
588
+ /**
589
+ * Base data type associated with each app.
590
+ */
591
+ export type AppData = {
592
+ exported: boolean;
593
+ prefix: BasePrefix;
594
+ ctx: BaseCtx;
595
+ routes: BaseRoutes;
596
+ };
597
+
598
+ /**
599
+ * Minimal data type that works with `AppData`.
600
+ */
601
+ export type DefaultAppData = {
602
+ exported: false;
603
+ prefix: "";
604
+ ctx: {};
605
+ routes: {};
606
+ };
607
+
608
+ /**
609
+ * Minimal data type that matches `AppData["ctx"]`.
610
+ */
611
+ export type BaseCtx = Record<string, any>;
612
+
613
+ /**
614
+ * Minimal data type that matches `AppData["routes"]`.
615
+ */
616
+ export type BaseRoutes = {
617
+ [method: string]: {
618
+ [path: BasePath]: RouteDef;
619
+ };
620
+ };
621
+
622
+ /**
623
+ * Minimal data type that matches `AppData["routes"][method][path]`, containing information about the route.
624
+ */
625
+ export type RouteDef = Simplify<
626
+ Omit<OpenAPI.Operation, "parameters" | "responses"> & {
627
+ headers?: StandardSchemaV1<Record<string, any>>;
628
+ params?: StandardSchemaV1<Record<string, any>>;
629
+ query?: StandardSchemaV1<Record<string, any>>;
630
+ body?: StandardSchemaV1;
631
+ responses?: StandardSchemaV1 | Record<number, StandardSchemaV1>;
632
+ }
633
+ >;
634
+
635
+ /**
636
+ * Used for `TDef` when a route definition is not passed. Essentially removes type-safety from a route.
637
+ */
638
+ export type AnyDef = {
639
+ headers: StandardSchemaV1<Record<string, string>>;
640
+ params: StandardSchemaV1<Record<string, string>>;
641
+ query: StandardSchemaV1<Record<string, string>>;
642
+ body: StandardSchemaV1<any>;
643
+ responses: any;
644
+ };
645
+
646
+ /**
647
+ * Base type representing what strings can be passed as a `prefix` when creating an app.
648
+ */
649
+ export type BasePrefix = BasePath | "";
650
+
651
+ /**
652
+ * Base type representing what a route's string must look like.
653
+ */
654
+ export type BasePath = `/${string}`;
655
+
656
+ //
657
+ // CONTEXT OBJECTS
658
+ //
659
+
660
+ /**
661
+ * `ctx` type used in the `onGlobalRequest` hook.
662
+ */
663
+ export type OnGlobalRequestContext<TCtx extends BaseCtx = {}> = TCtx & {
664
+ request: Request;
665
+ url: URL;
666
+ path: string;
667
+ method: string;
668
+ set: Setter;
669
+ };
670
+
671
+ /**
672
+ * `ctx` type used in the `onTransform` hook.
673
+ */
674
+ export type OnTransformContext<TCtx extends BaseCtx = {}> =
675
+ OnGlobalRequestContext<TCtx> & {
676
+ route: string;
677
+ params?: Record<string, string>;
678
+ query?: Record<string, string>;
679
+ headers?: Record<string, string>;
680
+ body?: any;
681
+ };
682
+
683
+ /**
684
+ * `ctx` type used in the `onBeforeHandle` hook.
685
+ */
686
+ export type OnBeforeHandleContext<TCtx extends BaseCtx = {}> =
687
+ OnTransformContext<TCtx>;
688
+
689
+ /**
690
+ * `ctx` type used in the `onAfterHandle` hook.
691
+ */
692
+ export type AfterHandleContext<TCtx extends BaseCtx = {}> =
693
+ OnTransformContext<TCtx> & {
694
+ response?: unknown;
695
+ };
696
+
697
+ /**
698
+ * `ctx` type used in the `onMapResponse` hook.
699
+ */
700
+ export type OnMapResponseContext<TCtx extends BaseCtx = {}> =
701
+ AfterHandleContext<TCtx> & {};
702
+
703
+ /**
704
+ * `ctx` type used in the `onGlobalError` hook.
705
+ */
706
+ export type OnGlobalErrorContext<TCtx extends BaseCtx = {}> =
707
+ OnGlobalRequestContext<TCtx> &
708
+ Partial<OnMapResponseContext> & { error: unknown };
709
+
710
+ /**
711
+ * `ctx` type used in the `onGlobalAfterResponse` hook.
712
+ */
713
+ export type AfterResponseContext<TCtx extends BaseCtx = {}> =
714
+ OnGlobalRequestContext<TCtx> &
715
+ Partial<OnMapResponseContext> & { response: Response };
716
+
717
+ /**
718
+ * Given an `AppData` type, return the type of it's `ctx`.
719
+ */
720
+ export type GetAppDataCtx<TAppData extends AppData> = TAppData extends {
721
+ ctx: infer TCtx;
722
+ }
723
+ ? TCtx
724
+ : never;
725
+
726
+ export type StatusFn<TMap extends Record<any, any>> = TMap extends never
727
+ ? never
728
+ : <TStatus extends keyof TMap>(
729
+ status: TStatus,
730
+ body: StandardSchemaV1.InferInput<TMap[TStatus]>,
731
+ ) => StatusResult;
732
+
733
+ export type GetResponseStatusMap<TRouteDef extends RouteDef> =
734
+ TRouteDef extends { responses: unknown }
735
+ ? TRouteDef["responses"] extends symbol // is any check
736
+ ? Record<number, StandardSchemaV1<any, any>>
737
+ : TRouteDef["responses"] extends StandardSchemaV1
738
+ ? { 200: TRouteDef["responses"] }
739
+ : TRouteDef["responses"] extends Record<
740
+ number | string,
741
+ StandardSchemaV1
742
+ >
743
+ ? TRouteDef["responses"]
744
+ : any
745
+ : never;
746
+
747
+ export type StatusResult = {
748
+ [IsStatusResult]: true;
749
+ status: number;
750
+ body: unknown;
751
+ };
752
+
753
+ /**
754
+ * Build the `ctx` type used for request handlers.
755
+ */
756
+ export type BuildHandlerContext<
757
+ TAppData extends AppData,
758
+ TPath extends BasePath,
759
+ TRouteDef extends RouteDef,
760
+ > = Simplify<
761
+ Omit<OnBeforeHandleContext<GetAppDataCtx<TAppData>>, InputParams> & {
762
+ route: TPath;
763
+ } & GetRequestParamsOutputFromDef<TRouteDef> & {
764
+ status: StatusFn<GetResponseStatusMap<TRouteDef>>;
765
+ }
766
+ >;
767
+
768
+ //
769
+ // MERGING OBJECTS
770
+ //
771
+
772
+ /**
773
+ * Given two `App`s, merge their data to match the behavior of `TParent.use(TChild)`.
774
+ */
775
+ export type UseApp<TParent extends App, TChild extends App> = App<
776
+ Simplify<UseAppData<GetAppData<TParent>, GetAppData<TChild>>>
777
+ >;
778
+
779
+ /**
780
+ * Same as `UseApp`, but instead of app instances, it merges the `AppData` of each.
781
+ */
782
+ export type UseAppData<
783
+ TParentData extends AppData,
784
+ TChildData extends AppData,
785
+ > = TChildData extends { exported: true }
786
+ ? MergeAppData<
787
+ TParentData,
788
+ Pick<ApplyAppDataPrefix<TChildData>, "ctx" | "routes">
789
+ >
790
+ : MergeAppData<TParentData, Pick<ApplyAppDataPrefix<TChildData>, "routes">>;
791
+
792
+ /**
793
+ * Merge two `App` types together. See `MergeAppData` for details.
794
+ */
795
+ export type MergeApp<T1, T2> =
796
+ T1 extends App<infer D1>
797
+ ? T2 extends App<infer D2>
798
+ ? App<Simplify<MergeAppData<D1, D2>>>
799
+ : never
800
+ : never;
801
+
802
+ /**
803
+ * Merge two `AppData` types together.
804
+ * - `prefix`: The second app's prefix overrides the first if present.
805
+ * - `ctx`: The second app's context gets merged with the first if present. Any
806
+ * existing keys are overwritten to match the second app's context.
807
+ * - `exported`: The second app's exported status overrides the first if
808
+ * present.
809
+ * - `routes`: See `MergeRoutes` for details.
810
+ */
811
+ export type MergeAppData<
812
+ T1 extends AppData,
813
+ T2 extends Partial<AppData>,
814
+ > = Simplify<{
815
+ prefix: T2["prefix"] extends string ? T2["prefix"] : T1["prefix"];
816
+ ctx: T2["ctx"] extends BaseCtx
817
+ ? Simplify<Spread<T1["ctx"], T2["ctx"]>>
818
+ : T1["ctx"];
819
+ exported: T2["exported"] extends boolean ? T2["exported"] : T1["exported"];
820
+ routes: T2["routes"] extends BaseRoutes
821
+ ? Simplify<MergeRoutes<T1["routes"], T2["routes"]>>
822
+ : T1["routes"];
823
+ }>;
824
+
825
+ /**
826
+ * Merges two route objects together, 2 levels deep. If the same method/path
827
+ * combination exists in both apps, the second app's route overrides the first.
828
+ */
829
+ export type MergeRoutes<
830
+ A extends Record<string, any>,
831
+ B extends Record<string, any>,
832
+ > = Simplify<Merge<A, B>>;
833
+
834
+ //
835
+ // APPLY PREFIX
836
+ //
837
+
838
+ /**
839
+ * Given an app and a new prefix, return a new app type with app's original
840
+ * prefix applied to each route, and with the new prefix stored in the
841
+ * `AppData`.
842
+ */
843
+ export type ApplyAppPrefix<
844
+ TApp extends App,
845
+ TNewPrefix extends BasePrefix = "",
846
+ > = App<Simplify<ApplyAppDataPrefix<GetAppData<TApp>, TNewPrefix>>>;
847
+
848
+ /**
849
+ * Same as `ApplyAppPrefix`, but at the `AppData` level.
850
+ */
851
+ export type ApplyAppDataPrefix<
852
+ TAppData extends AppData,
853
+ TNewPrefix extends BasePrefix = "",
854
+ > = {
855
+ ctx: TAppData["ctx"];
856
+ exported: TAppData["exported"];
857
+ prefix: TNewPrefix;
858
+ routes: TAppData["prefix"] extends BasePath
859
+ ? {
860
+ [TMethod in keyof TAppData["routes"]]: Simplify<
861
+ PrefixObjectKeys<TAppData["prefix"], TAppData["routes"][TMethod]>
862
+ >;
863
+ }
864
+ : TAppData["routes"];
865
+ };
866
+
867
+ //
868
+ // SCHEMA CONVERSION
869
+ //
870
+
871
+ /**
872
+ * Given a route definition, return the input types of all the params.
873
+ */
874
+ export type GetRequestParamsInputFromDef<TRouteDef extends RouteDef> =
875
+ TRouteDef extends AnyDef
876
+ ? {
877
+ headers?: Record<string, string>;
878
+ params?: Record<string, string>;
879
+ query?: Record<string, string>;
880
+ body?: any;
881
+ }
882
+ : Simplify<{
883
+ [key in keyof GetDefParams<TRouteDef>]: TRouteDef[key] extends StandardSchemaV1
884
+ ? StandardSchemaV1.InferInput<TRouteDef[key]>
885
+ : never;
886
+ }>;
887
+
888
+ /**
889
+ * Given a set of routes, a method, and a route, return the input types of all
890
+ * the schemas in the route definition.
891
+ */
892
+ export type GetRequestParamsInput<
893
+ TRoutes extends BaseRoutes,
894
+ TMethod extends keyof TRoutes,
895
+ TRoute extends keyof TRoutes[TMethod],
896
+ > = TRoute extends BasePath
897
+ ? GetRequestParamsInputFromDef<TRoutes[TMethod][TRoute]>
898
+ : never;
899
+
900
+ /**
901
+ * Given a route definition, return the input type of the response schema.
902
+ */
903
+ export type GetResponseInputFromDef<TRouteDef extends RouteDef> =
904
+ TRouteDef["responses"] extends undefined
905
+ ? undefined
906
+ : TRouteDef["responses"] extends StandardSchemaV1
907
+ ? StandardSchemaV1.InferInput<TRouteDef["responses"]>
908
+ : never;
909
+
910
+ /**
911
+ * Given a set of routes, a method, and a route, return the input type of the
912
+ * response schema in the route definition.
913
+ */
914
+ export type GetResponseInput<
915
+ TRoutes extends BaseRoutes,
916
+ TMethod extends keyof TRoutes,
917
+ TPath extends keyof TRoutes[TMethod],
918
+ > = TPath extends BasePath
919
+ ? GetResponseInputFromDef<TRoutes[TMethod][TPath]>
920
+ : never;
921
+
922
+ /**
923
+ * Helper type for converting a schema or object containing schemas to their
924
+ * output types.
925
+ */
926
+ type ToStandardSchemaOutputs<T> = T extends StandardSchemaV1
927
+ ? StandardSchemaV1.InferOutput<T>
928
+ : T extends { [key in keyof T]: any }
929
+ ? { [key in keyof T]: ToStandardSchemaOutputs<T[key]> }
930
+ : never;
931
+
932
+ /**
933
+ * Given a route definition, return the output type of the param schemas.
934
+ */
935
+ export type GetRequestParamsOutputFromDef<TRouteDef extends RouteDef> =
936
+ ToStandardSchemaOutputs<GetDefParams<TRouteDef>>;
937
+
938
+ /**
939
+ * Given a set of routes, a method, and a route, return the output type of the
940
+ * param schemas.
941
+ */
942
+ export type GetRequestParamsOutput<
943
+ TRoutes extends BaseRoutes,
944
+ TMethod extends keyof TRoutes,
945
+ TRoute extends keyof TRoutes[TMethod],
946
+ > = TRoute extends BasePath
947
+ ? GetRequestParamsOutputFromDef<TRoutes[TMethod][TRoute]>
948
+ : never;
949
+
950
+ type SuccessStatusCodes =
951
+ | 200
952
+ | HttpStatus.Ok
953
+ | 201
954
+ | HttpStatus.Created
955
+ | 202
956
+ | HttpStatus.Accepted
957
+ | 203
958
+ | HttpStatus.NonAuthoritativeInformation
959
+ | 204
960
+ | HttpStatus.NoContent
961
+ | 205
962
+ | HttpStatus.ResetContent
963
+ | 206
964
+ | HttpStatus.PartialContent
965
+ | 207
966
+ | HttpStatus.MultiStatus
967
+ | 208
968
+ | HttpStatus.AlreadyReported
969
+ | 226
970
+ | HttpStatus.ImUsed;
971
+
972
+ /**
973
+ * Given a `RouteDef`, return a union of all possible handler return values.
974
+ *
975
+ * If `responses` is defined, it will be a discriminated union of objects
976
+ * containing the status and body.
977
+ *
978
+ * If only `response` is defined, it will be the output of that schema.
979
+ *
980
+ * If neither is defined, it will be `void`.
981
+ */
982
+ export type GetResponseOutputFromDef<TRouteDef extends RouteDef> =
983
+ TRouteDef["responses"] extends undefined
984
+ ? undefined
985
+ : TRouteDef["responses"] extends StandardSchemaV1
986
+ ? StandardSchemaV1.InferOutput<TRouteDef["responses"]>
987
+ : {
988
+ [key in SuccessStatusCodes &
989
+ keyof TRouteDef["responses"]]: TRouteDef["responses"][key] extends StandardSchemaV1
990
+ ? StandardSchemaV1.InferOutput<TRouteDef["responses"][key]>
991
+ : unknown;
992
+ }[SuccessStatusCodes & keyof TRouteDef["responses"]];
993
+
994
+ /**
995
+ * Given a set of routes, a method, and a route, return the output type of the
996
+ * response schema.
997
+ */
998
+ export type GetResponseOutput<
999
+ TRoutes extends BaseRoutes,
1000
+ TMethod extends keyof TRoutes,
1001
+ TPath extends keyof TRoutes[TMethod],
1002
+ > = TPath extends BasePath
1003
+ ? GetResponseOutputFromDef<TRoutes[TMethod][TPath]>
1004
+ : 1;
1005
+
1006
+ type InputParams = "headers" | "params" | "query" | "body";
1007
+
1008
+ /**
1009
+ * Given a route definition, return an object with only the input parameeters.
1010
+ */
1011
+ type GetDefParams<TRouteDef extends RouteDef> = {
1012
+ [key in InputParams & keyof TRouteDef]: TRouteDef[key];
1013
+ };
1014
+
1015
+ //
1016
+ // SCHEMA ADAPTER
1017
+ //
1018
+
1019
+ /**
1020
+ * To generate open API docs, Zeta needs to know how process and extract
1021
+ * some information from your schema. This adapter is responsible for
1022
+ * providing additional functions for parsing your schema.
1023
+ */
1024
+ export interface SchemaAdapter {
1025
+ /**
1026
+ * Convert a standard schema definition to it's JSON schema.
1027
+ * @param schema The schema to convert.
1028
+ * @returns The JSON schema.
1029
+ */
1030
+ toJsonSchema: (schema: any) => any;
1031
+ /**
1032
+ * Used to pull out the openapi parameters from a schema.
1033
+ * @param schema The schema to parse.
1034
+ * @returns An array of objects used to generate the OpenAPI docs.
1035
+ */
1036
+ parseParamsRecord: (schema: StandardSchemaV1) => Array<{
1037
+ name: string;
1038
+ optional: boolean;
1039
+ schema: StandardSchemaV1;
1040
+ description?: string;
1041
+ }>;
1042
+ getMeta: (schema: StandardSchemaV1) => Record<string, any> | undefined;
1043
+ }
1044
+
1045
+ //
1046
+ // SETTER
1047
+ //
1048
+
1049
+ /**
1050
+ * Basic object type used to store custom status and headers set while handling the request.
1051
+ */
1052
+ export interface Setter {
1053
+ /**
1054
+ * Set this value to change the status code returned.
1055
+ */
1056
+ status: number;
1057
+ /**
1058
+ * Set a value on this header to change which headers are sent in the response.
1059
+ */
1060
+ headers: Record<string, string>;
1061
+ }
1062
+
1063
+ //
1064
+ // GENERAL UTILS
1065
+ //
1066
+
1067
+ /**
1068
+ * Given a union of objects, combine them into a single object that's easy to read.
1069
+ */
1070
+ export type Simplify<T> = T extends { [key: string]: any }
1071
+ ? { [K in keyof T]: T[K] }
1072
+ : T;
1073
+
1074
+ /**
1075
+ * Returns either a Promise of a type or just the type itself.
1076
+ */
1077
+ export type MaybePromise<T> = Promise<T> | T;
1078
+
1079
+ /**
1080
+ * A function that, given a request, returns a response. This type is compliant with WinterCG.
1081
+ */
1082
+ export type ServerSideFetch = (request: Request) => MaybePromise<Response>;
1083
+
1084
+ /**
1085
+ * Apply a string prefix to all the keys of an object.
1086
+ */
1087
+ export type PrefixObjectKeys<
1088
+ TPrefix extends string,
1089
+ TObject extends Record<string, unknown>,
1090
+ > = {
1091
+ [K in keyof TObject as `${TPrefix}${string & K extends "/" ? "" : string & K}`]: TObject[K];
1092
+ };
1093
+
1094
+ /**
1095
+ * A helper type that models a single-level object spread: { ...L, ...R }
1096
+ * It takes all properties from R, and all properties from L that are not in R.
1097
+ */
1098
+ type Spread<L, R> = Omit<L, keyof R> & R;
1099
+
1100
+ /**
1101
+ * Merges two objects, A and B, two levels deep.
1102
+ *
1103
+ * It combines the keys from both A and B.
1104
+ * - If a key exists only in A or only in B, it's carried over.
1105
+ * - If a key exists in *both* A and B, it recursively merges their
1106
+ * values using a single-level spread (`Spread<A[K], B[K]>`).
1107
+ * This ensures properties from B's inner objects overwrite those from A's.
1108
+ */
1109
+ export type Merge<A, B> = Omit<A, keyof B> & {
1110
+ [K in keyof B]: K extends keyof A ? Simplify<Spread<A[K], B[K]>> : B[K];
1111
+ };