@temporary-name/server 1.9.3-alpha.8dcf0da5d97e7b89ab5ce50c8d1733c158e629a8 → 1.9.3-alpha.907c7c78d0193d34752279de92d699e50d6bc3a1

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.
Files changed (42) hide show
  1. package/dist/adapters/aws-lambda/index.d.mts +4 -6
  2. package/dist/adapters/aws-lambda/index.d.ts +4 -6
  3. package/dist/adapters/aws-lambda/index.mjs +4 -4
  4. package/dist/adapters/fetch/index.d.mts +8 -86
  5. package/dist/adapters/fetch/index.d.ts +8 -86
  6. package/dist/adapters/fetch/index.mjs +16 -155
  7. package/dist/adapters/node/index.d.mts +8 -63
  8. package/dist/adapters/node/index.d.ts +8 -63
  9. package/dist/adapters/node/index.mjs +14 -120
  10. package/dist/adapters/standard/index.d.mts +5 -7
  11. package/dist/adapters/standard/index.d.ts +5 -7
  12. package/dist/adapters/standard/index.mjs +4 -4
  13. package/dist/helpers/index.mjs +3 -29
  14. package/dist/index.d.mts +104 -182
  15. package/dist/index.d.ts +104 -182
  16. package/dist/index.mjs +126 -104
  17. package/dist/openapi/index.d.mts +11 -27
  18. package/dist/openapi/index.d.ts +11 -27
  19. package/dist/openapi/index.mjs +8 -75
  20. package/dist/shared/server.Bj_UpI5O.d.mts +372 -0
  21. package/dist/shared/server.Bj_UpI5O.d.ts +372 -0
  22. package/dist/shared/server.C1RJffw4.mjs +30 -0
  23. package/dist/shared/server.C6VnFy4S.d.mts +41 -0
  24. package/dist/shared/server.CQIFwyhc.mjs +40 -0
  25. package/dist/shared/server.ChOv1yG3.mjs +319 -0
  26. package/dist/shared/server.CnzXkSjj.d.ts +41 -0
  27. package/dist/shared/server.DXzEGRE2.mjs +403 -0
  28. package/dist/shared/server.DgzAlPjF.mjs +160 -0
  29. package/dist/shared/server.YUvuxHty.mjs +48 -0
  30. package/package.json +10 -27
  31. package/dist/plugins/index.d.mts +0 -160
  32. package/dist/plugins/index.d.ts +0 -160
  33. package/dist/plugins/index.mjs +0 -288
  34. package/dist/shared/server.BSJugGGA.d.mts +0 -56
  35. package/dist/shared/server.Bs8EZATl.d.ts +0 -23
  36. package/dist/shared/server.CHV9AQHl.mjs +0 -412
  37. package/dist/shared/server.CWWP8ypC.d.mts +0 -239
  38. package/dist/shared/server.CWWP8ypC.d.ts +0 -239
  39. package/dist/shared/server.Cn7WsRHl.mjs +0 -254
  40. package/dist/shared/server.DrMgIiBr.d.mts +0 -23
  41. package/dist/shared/server.EKwDe0d2.d.ts +0 -56
  42. package/dist/shared/server.JtIZ8YG7.mjs +0 -237
@@ -1,239 +0,0 @@
1
- import { ErrorMap, ErrorMapItem, InferSchemaInput, Schemas, Meta, ContractProcedureDef, AnyContractRouter, ContractProcedure, InferProcedureClientInputs, InferSchemaOutput, EnhanceRouteOptions, MergedErrorMap, AnyContractProcedure, ContractRouter, AnySchema, ErrorFromErrorMap } from '@temporary-name/contract';
2
- import { ORPCErrorCode, MaybeOptionalOptions, ORPCErrorOptions, ORPCError, Promisable, HTTPPath, ClientContext, Interceptor, PromiseWithError, Value, Client } from '@temporary-name/shared';
3
-
4
- type Context = Record<PropertyKey, any>;
5
- type MergedInitialContext<TInitial extends Context, TAdditional extends Context, TCurrent extends Context> = TInitial & Omit<TAdditional, keyof TCurrent>;
6
- type MergedCurrentContext<T extends Context, U extends Context> = Omit<T, keyof U> & U;
7
- declare function mergeCurrentContext<T extends Context, U extends Context>(context: T, other: U): MergedCurrentContext<T, U>;
8
-
9
- type ORPCErrorConstructorMapItemOptions<TData> = Omit<ORPCErrorOptions<TData>, 'defined' | 'status'>;
10
- type ORPCErrorConstructorMapItem<TCode extends ORPCErrorCode, TInData> = (...rest: MaybeOptionalOptions<ORPCErrorConstructorMapItemOptions<TInData>>) => ORPCError<TCode, TInData>;
11
- type ORPCErrorConstructorMap<T extends ErrorMap> = {
12
- [K in keyof T]: K extends ORPCErrorCode ? T[K] extends ErrorMapItem<infer UInputSchema> ? ORPCErrorConstructorMapItem<K, InferSchemaInput<UInputSchema>> : never : never;
13
- };
14
- declare function createORPCErrorConstructorMap<T extends ErrorMap>(errors: T): ORPCErrorConstructorMap<T>;
15
-
16
- interface ProcedureHandlerOptions<TCurrentContext extends Context, TErrorConstructorMap extends ORPCErrorConstructorMap<any>, TMeta extends Meta> {
17
- context: TCurrentContext;
18
- path: readonly string[];
19
- procedure: Procedure<Context, Context, Schemas, ErrorMap, TMeta>;
20
- signal?: AbortSignal;
21
- lastEventId: string | undefined;
22
- errors: TErrorConstructorMap;
23
- }
24
- interface ProcedureHandler<TCurrentContext extends Context, TInput extends {
25
- path: any;
26
- query: any;
27
- body: any;
28
- }, THandlerOutput, TErrorMap extends ErrorMap, TMeta extends Meta> {
29
- (input: TInput, opt: ProcedureHandlerOptions<TCurrentContext, ORPCErrorConstructorMap<TErrorMap>, TMeta>): Promisable<THandlerOutput>;
30
- }
31
- interface ProcedureDef<TInitialContext extends Context, TCurrentContext extends Context, TSchemas extends Schemas, TErrorMap extends ErrorMap, TMeta extends Meta> extends ContractProcedureDef<TSchemas, TErrorMap, TMeta> {
32
- __initialContext?: (type: TInitialContext) => unknown;
33
- middlewares: readonly AnyMiddleware[];
34
- inputValidationIndex: number;
35
- outputValidationIndex: number;
36
- handler: ProcedureHandler<TCurrentContext, any, any, any, any>;
37
- }
38
- /**
39
- * This class represents a procedure.
40
- *
41
- * @see {@link https://orpc.unnoq.com/docs/procedure Procedure Docs}
42
- */
43
- declare class Procedure<TInitialContext extends Context, TCurrentContext extends Context, TSchemas extends Schemas, TErrorMap extends ErrorMap, TMeta extends Meta> {
44
- /**
45
- * This property holds the defined options.
46
- */
47
- '~orpc': ProcedureDef<TInitialContext, TCurrentContext, TSchemas, TErrorMap, TMeta>;
48
- constructor(def: ProcedureDef<TInitialContext, TCurrentContext, TSchemas, TErrorMap, TMeta>);
49
- }
50
- type AnyProcedure = Procedure<any, any, Schemas, any, any>;
51
- declare function isProcedure(item: unknown): item is AnyProcedure;
52
-
53
- type MiddlewareResult<TOutContext extends Context, TOutput> = Promisable<{
54
- output: TOutput;
55
- context: TOutContext;
56
- }>;
57
- interface MiddlewareNextFn<TOutput> {
58
- <U extends Context = {}>(options?: {
59
- context?: U;
60
- }): MiddlewareResult<U, TOutput>;
61
- }
62
- interface MiddlewareOutputFn<TOutput> {
63
- (output: TOutput): MiddlewareResult<Record<never, never>, TOutput>;
64
- }
65
- interface MiddlewareOptions<TInContext extends Context, TOutput, TErrorConstructorMap extends ORPCErrorConstructorMap<any>, TMeta extends Meta> {
66
- context: TInContext;
67
- path: readonly string[];
68
- procedure: Procedure<Context, Context, Schemas, ErrorMap, TMeta>;
69
- signal?: AbortSignal;
70
- lastEventId: string | undefined;
71
- next: MiddlewareNextFn<TOutput>;
72
- errors: TErrorConstructorMap;
73
- }
74
- /**
75
- * A function that represents a middleware.
76
- *
77
- * @see {@link https://orpc.unnoq.com/docs/middleware Middleware Docs}
78
- */
79
- interface Middleware<TInContext extends Context, TOutContext extends Context, TInput, TOutput, TErrorConstructorMap extends ORPCErrorConstructorMap<any>, TMeta extends Meta> {
80
- (options: MiddlewareOptions<TInContext, TOutput, TErrorConstructorMap, TMeta>, input: TInput, output: MiddlewareOutputFn<TOutput>): Promisable<MiddlewareResult<TOutContext, TOutput>>;
81
- }
82
- type AnyMiddleware = Middleware<any, any, any, any, any, any>;
83
- interface MapInputMiddleware<TInput, TMappedInput> {
84
- (input: TInput): TMappedInput;
85
- }
86
- declare function middlewareOutputFn<TOutput>(output: TOutput): MiddlewareResult<Record<never, never>, TOutput>;
87
-
88
- /**
89
- * Represents a router, which defines a hierarchical structure of procedures.
90
- *
91
- * @info A procedure is a router too.
92
- * @see {@link https://orpc.unnoq.com/docs/contract-first/define-contract#contract-router Contract Router Docs}
93
- */
94
- type Router<T extends AnyContractRouter, TInitialContext extends Context> = T extends ContractProcedure<infer USchemas, infer UErrorMap, infer UMeta> ? Procedure<TInitialContext, any, USchemas, UErrorMap, UMeta> : {
95
- [K in keyof T]: T[K] extends AnyContractRouter ? Lazyable<Router<T[K], TInitialContext>> : never;
96
- };
97
- type AnyRouter = Router<any, any>;
98
- type InferRouterInitialContext<T extends AnyRouter> = T extends Router<any, infer UInitialContext> ? UInitialContext : never;
99
- /**
100
- * Infer all initial context of the router.
101
- *
102
- * @info A procedure is a router too.
103
- * @see {@link https://orpc.unnoq.com/docs/router#utilities Router Utilities Docs}
104
- */
105
- type InferRouterInitialContexts<T extends AnyRouter> = T extends Procedure<infer UInitialContext, any, any, any, any> ? UInitialContext : {
106
- [K in keyof T]: T[K] extends Lazyable<infer U extends AnyRouter> ? InferRouterInitialContexts<U> : never;
107
- };
108
- /**
109
- * Infer all current context of the router.
110
- *
111
- * @info A procedure is a router too.
112
- * @see {@link https://orpc.unnoq.com/docs/router#utilities Router Utilities Docs}
113
- */
114
- type InferRouterCurrentContexts<T extends AnyRouter> = T extends Procedure<any, infer UCurrentContext, any, any, any> ? UCurrentContext : {
115
- [K in keyof T]: T[K] extends Lazyable<infer U extends AnyRouter> ? InferRouterCurrentContexts<U> : never;
116
- };
117
- /**
118
- * Infer all router inputs
119
- *
120
- * @info A procedure is a router too.
121
- * @see {@link https://orpc.unnoq.com/docs/router#utilities Router Utilities Docs}
122
- */
123
- type InferRouterInputs<T extends AnyRouter> = T extends Procedure<any, any, infer USchemas, any, any> ? InferProcedureClientInputs<USchemas> : {
124
- [K in keyof T]: T[K] extends Lazyable<infer U extends AnyRouter> ? InferRouterInputs<U> : never;
125
- };
126
- /**
127
- * Infer all router outputs
128
- *
129
- * @info A procedure is a router too.
130
- * @see {@link https://orpc.unnoq.com/docs/router#utilities Router Utilities Docs}
131
- */
132
- type InferRouterOutputs<T extends AnyRouter> = T extends Procedure<any, any, infer USchemas, any, any> ? InferSchemaOutput<USchemas['outputSchema']> : {
133
- [K in keyof T]: T[K] extends Lazyable<infer U extends AnyRouter> ? InferRouterOutputs<U> : never;
134
- };
135
-
136
- declare function getRouter<T extends Lazyable<AnyRouter | undefined>>(router: T, path: readonly string[]): T extends Lazy<any> ? Lazy<AnyRouter | undefined> : Lazyable<AnyRouter | undefined>;
137
- type AccessibleLazyRouter<T extends Lazyable<AnyRouter | undefined>> = T extends Lazy<infer U extends AnyRouter | undefined | Lazy<AnyRouter | undefined>> ? AccessibleLazyRouter<U> : T extends AnyProcedure | undefined ? Lazy<T> : Lazy<T> & {
138
- [K in keyof T]: T[K] extends Lazyable<AnyRouter> ? AccessibleLazyRouter<T[K]> : never;
139
- };
140
- declare function createAccessibleLazyRouter<T extends Lazy<AnyRouter | undefined>>(lazied: T): AccessibleLazyRouter<T>;
141
- type EnhancedRouter<T extends Lazyable<AnyRouter>, TInitialContext extends Context, TCurrentContext extends Context, TErrorMap extends ErrorMap> = T extends Lazy<infer U extends AnyRouter> ? AccessibleLazyRouter<EnhancedRouter<U, TInitialContext, TCurrentContext, TErrorMap>> : T extends (Procedure<infer UInitialContext, infer UCurrentContext, infer USchemas, infer UErrorMap, infer UMeta>) ? Procedure<MergedInitialContext<TInitialContext, UInitialContext, TCurrentContext>, UCurrentContext, USchemas, MergedErrorMap<TErrorMap, UErrorMap>, UMeta> : {
142
- [K in keyof T]: T[K] extends Lazyable<AnyRouter> ? EnhancedRouter<T[K], TInitialContext, TCurrentContext, TErrorMap> : never;
143
- };
144
- interface EnhanceRouterOptions<TErrorMap extends ErrorMap> extends EnhanceRouteOptions {
145
- middlewares: readonly AnyMiddleware[];
146
- errorMap: TErrorMap;
147
- dedupeLeadingMiddlewares: boolean;
148
- }
149
- declare function enhanceRouter<T extends Lazyable<AnyRouter>, TInitialContext extends Context, TCurrentContext extends Context, TErrorMap extends ErrorMap>(router: T, options: EnhanceRouterOptions<TErrorMap>): EnhancedRouter<T, TInitialContext, TCurrentContext, TErrorMap>;
150
- interface TraverseContractProceduresOptions {
151
- router: AnyContractRouter | AnyRouter;
152
- path: readonly string[];
153
- }
154
- interface TraverseContractProcedureCallbackOptions {
155
- contract: AnyContractProcedure | AnyProcedure;
156
- path: readonly string[];
157
- }
158
- /**
159
- * @deprecated Use `TraverseContractProcedureCallbackOptions` instead.
160
- */
161
- type ContractProcedureCallbackOptions = TraverseContractProcedureCallbackOptions;
162
- interface LazyTraverseContractProceduresOptions {
163
- router: Lazy<AnyRouter>;
164
- path: readonly string[];
165
- }
166
- declare function traverseContractProcedures(options: TraverseContractProceduresOptions, callback: (options: TraverseContractProcedureCallbackOptions) => void, lazyOptions?: LazyTraverseContractProceduresOptions[]): LazyTraverseContractProceduresOptions[];
167
- declare function resolveContractProcedures(options: TraverseContractProceduresOptions, callback: (options: TraverseContractProcedureCallbackOptions) => void): Promise<void>;
168
- type UnlaziedRouter<T extends AnyRouter> = T extends AnyProcedure ? T : {
169
- [K in keyof T]: T[K] extends Lazyable<infer U extends AnyRouter> ? UnlaziedRouter<U> : never;
170
- };
171
- declare function unlazyRouter<T extends AnyRouter>(router: T): Promise<UnlaziedRouter<T>>;
172
-
173
- declare const LAZY_SYMBOL: unique symbol;
174
- interface LazyMeta {
175
- prefix?: HTTPPath;
176
- }
177
- interface Lazy<T> {
178
- [LAZY_SYMBOL]: {
179
- loader: () => Promise<{
180
- default: T;
181
- }>;
182
- meta: LazyMeta;
183
- };
184
- }
185
- type Lazyable<T> = T | Lazy<T>;
186
- /**
187
- * @internal
188
- */
189
- declare function lazyInternal<T>(loader: () => Promise<{
190
- default: T;
191
- }>, meta?: LazyMeta): Lazy<T>;
192
- /**
193
- * Creates a lazy-loaded item.
194
- *
195
- * @warning The `prefix` in `meta` only holds metadata and does not apply the prefix to the lazy router, use `os.prefix(...).lazyRoute(...)` instead.
196
- */
197
- declare function lazy<T extends Router<ContractRouter<{}>, any>>(prefix: HTTPPath, loader: () => Promise<{
198
- default: T;
199
- }>): EnhancedRouter<Lazy<T>, {}, {}, {}>;
200
- declare function isLazy(item: unknown): item is Lazy<any>;
201
- declare function getLazyMeta(lazied: Lazy<any>): LazyMeta;
202
- declare function unlazy<T extends Lazyable<any>>(lazied: T): Promise<{
203
- default: T extends Lazy<infer U> ? U : T;
204
- }>;
205
-
206
- type ProcedureClient<TClientContext extends ClientContext, TSchemas extends Schemas, TErrorMap extends ErrorMap> = Client<TClientContext, InferProcedureClientInputs<TSchemas>, InferSchemaOutput<TSchemas['outputSchema']>, ErrorFromErrorMap<TErrorMap>>;
207
- interface ProcedureClientInterceptorOptions<TInitialContext extends Context, TErrorMap extends ErrorMap, TMeta extends Meta> {
208
- context: TInitialContext;
209
- input: {
210
- path: unknown;
211
- query: unknown;
212
- body: unknown;
213
- };
214
- errors: ORPCErrorConstructorMap<TErrorMap>;
215
- path: readonly string[];
216
- procedure: Procedure<Context, Context, Schemas, ErrorMap, TMeta>;
217
- signal?: AbortSignal;
218
- lastEventId: string | undefined;
219
- }
220
- type CreateProcedureClientOptions<TInitialContext extends Context, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap, TMeta extends Meta, TClientContext extends ClientContext> = {
221
- /**
222
- * This is helpful for logging and analytics.
223
- */
224
- path?: readonly string[];
225
- interceptors?: Interceptor<ProcedureClientInterceptorOptions<TInitialContext, TErrorMap, TMeta>, PromiseWithError<InferSchemaOutput<TOutputSchema>, ErrorFromErrorMap<TErrorMap>>>[];
226
- } & (Record<never, never> extends TInitialContext ? {
227
- context?: Value<Promisable<TInitialContext>, [clientContext: TClientContext]>;
228
- } : {
229
- context: Value<Promisable<TInitialContext>, [clientContext: TClientContext]>;
230
- });
231
- /**
232
- * Create Server-side client from a procedure.
233
- *
234
- * @see {@link https://orpc.unnoq.com/docs/client/server-side Server-side Client Docs}
235
- */
236
- declare function createProcedureClient<TInitialContext extends Context, TSchemas extends Schemas, TErrorMap extends ErrorMap, TMeta extends Meta, TClientContext extends ClientContext>(lazyableProcedure: Lazyable<Procedure<TInitialContext, any, TSchemas, TErrorMap, TMeta>>, ...rest: MaybeOptionalOptions<CreateProcedureClientOptions<TInitialContext, TSchemas['outputSchema'], TErrorMap, TMeta, TClientContext>>): ProcedureClient<TClientContext, TSchemas, TErrorMap>;
237
-
238
- export { resolveContractProcedures as $, isProcedure as F, createProcedureClient as H, Procedure as P, getRouter as S, createAccessibleLazyRouter as U, enhanceRouter as V, traverseContractProcedures as _, unlazyRouter as a1, mergeCurrentContext as m, createORPCErrorConstructorMap as n, LAZY_SYMBOL as o, lazyInternal as q, lazy as r, isLazy as s, getLazyMeta as t, unlazy as u, middlewareOutputFn as z };
239
- export type { AnyMiddleware as A, ProcedureHandlerOptions as B, Context as C, ProcedureDef as D, EnhanceRouterOptions as E, ProcedureClientInterceptorOptions as G, InferRouterInitialContext as I, InferRouterInitialContexts as J, InferRouterCurrentContexts as K, Lazy as L, Middleware as M, InferRouterInputs as N, ORPCErrorConstructorMap as O, InferRouterOutputs as Q, Router as R, AccessibleLazyRouter as T, TraverseContractProceduresOptions as W, TraverseContractProcedureCallbackOptions as X, ContractProcedureCallbackOptions as Y, LazyTraverseContractProceduresOptions as Z, CreateProcedureClientOptions as a, UnlaziedRouter as a0, ProcedureClient as b, MergedInitialContext as c, MergedCurrentContext as d, ProcedureHandler as e, EnhancedRouter as f, MapInputMiddleware as g, AnyProcedure as h, Lazyable as i, AnyRouter as j, ORPCErrorConstructorMapItemOptions as k, ORPCErrorConstructorMapItem as l, LazyMeta as p, MiddlewareResult as v, MiddlewareNextFn as w, MiddlewareOutputFn as x, MiddlewareOptions as y };
@@ -1,254 +0,0 @@
1
- import { stringifyJSON, isObject, isORPCErrorStatus, tryDecodeURIComponent, toHttpPath, toArray, intercept, runWithSpan, ORPC_NAME, isAsyncIteratorObject, asyncIteratorWithSpan, setSpanError, ORPCError, toORPCError } from '@temporary-name/shared';
2
- import { flattenHeader } from '@temporary-name/standard-server';
3
- import { c as createProcedureClient } from './server.CHV9AQHl.mjs';
4
- import { fallbackContractConfig, standardizeHTTPPath } from '@temporary-name/contract';
5
- import { d as deserialize, b as bracketNotationDeserialize, s as serialize } from './server.JtIZ8YG7.mjs';
6
- import { traverseContractProcedures, isProcedure, getLazyMeta, unlazy, getRouter, createContractedProcedure } from '@temporary-name/server';
7
- import { createRouter, addRoute, findRoute } from 'rou3';
8
-
9
- async function decode(request, pathParams) {
10
- return {
11
- path: pathParams ?? {},
12
- query: bracketNotationDeserialize(Array.from(request.url.searchParams.entries())),
13
- headers: request.headers,
14
- body: deserialize(await request.body()) ?? {}
15
- };
16
- }
17
- function encode(output, procedure) {
18
- const successStatus = fallbackContractConfig(
19
- "defaultSuccessStatus",
20
- procedure["~orpc"].route.successStatus
21
- );
22
- const outputStructure = fallbackContractConfig(
23
- "defaultOutputStructure",
24
- procedure["~orpc"].route.outputStructure
25
- );
26
- if (outputStructure === "compact") {
27
- return {
28
- status: successStatus,
29
- headers: {},
30
- body: serialize(output)
31
- };
32
- }
33
- if (!isDetailedOutput(output)) {
34
- throw new Error(`
35
- Invalid "detailed" output structure:
36
- \u2022 Expected an object with optional properties:
37
- - status (number 200-399)
38
- - headers (Record<string, string | string[]>)
39
- - body (any)
40
- \u2022 No extra keys allowed.
41
-
42
- Actual value:
43
- ${stringifyJSON(output)}
44
- `);
45
- }
46
- return {
47
- status: output.status ?? successStatus,
48
- headers: output.headers ?? {},
49
- body: serialize(output.body)
50
- };
51
- }
52
- function encodeError(error) {
53
- return {
54
- status: error.status,
55
- headers: {},
56
- body: serialize(error.toJSON(), { outputFormat: "plain" })
57
- };
58
- }
59
- function isDetailedOutput(output) {
60
- if (!isObject(output)) {
61
- return false;
62
- }
63
- if (output.headers && !isObject(output.headers)) {
64
- return false;
65
- }
66
- if (output.status !== void 0 && (typeof output.status !== "number" || !Number.isInteger(output.status) || isORPCErrorStatus(output.status))) {
67
- return false;
68
- }
69
- return true;
70
- }
71
-
72
- function resolveFriendlyStandardHandleOptions(options) {
73
- return {
74
- ...options,
75
- context: options.context ?? {}
76
- // Context only optional if all fields are optional
77
- };
78
- }
79
- function toRou3Pattern(path) {
80
- return standardizeHTTPPath(path).replace(/\/\{\+([^}]+)\}/g, "/**:$1").replace(/\/\{([^}]+)\}/g, "/:$1");
81
- }
82
- function decodeParams(params) {
83
- return Object.fromEntries(
84
- Object.entries(params).map(([key, value]) => [key, tryDecodeURIComponent(value)])
85
- );
86
- }
87
-
88
- class StandardOpenAPIMatcher {
89
- tree = createRouter();
90
- pendingRouters = [];
91
- init(router, path = []) {
92
- const laziedOptions = traverseContractProcedures({ router, path }, (traverseOptions) => {
93
- const { path: path2, contract } = traverseOptions;
94
- const method = fallbackContractConfig("defaultMethod", contract["~orpc"].route.method);
95
- const httpPath = toRou3Pattern(contract["~orpc"].route.path ?? toHttpPath(path2));
96
- if (isProcedure(contract)) {
97
- addRoute(this.tree, method, httpPath, {
98
- path: path2,
99
- contract,
100
- procedure: contract,
101
- // this mean dev not used contract-first so we can used contract as procedure directly
102
- router
103
- });
104
- } else {
105
- addRoute(this.tree, method, httpPath, {
106
- path: path2,
107
- contract,
108
- procedure: void 0,
109
- router
110
- });
111
- }
112
- });
113
- this.pendingRouters.push(
114
- ...laziedOptions.map((option) => ({
115
- ...option,
116
- httpPathPrefix: toHttpPath(option.path),
117
- laziedPrefix: getLazyMeta(option.router).prefix
118
- }))
119
- );
120
- }
121
- async match(method, pathname) {
122
- if (this.pendingRouters.length) {
123
- const newPendingRouters = [];
124
- for (const pendingRouter of this.pendingRouters) {
125
- if (!pendingRouter.laziedPrefix || pathname.startsWith(pendingRouter.laziedPrefix) || pathname.startsWith(pendingRouter.httpPathPrefix)) {
126
- const { default: router } = await unlazy(pendingRouter.router);
127
- this.init(router, pendingRouter.path);
128
- } else {
129
- newPendingRouters.push(pendingRouter);
130
- }
131
- }
132
- this.pendingRouters = newPendingRouters;
133
- }
134
- const match = findRoute(this.tree, method, pathname);
135
- if (!match) {
136
- return void 0;
137
- }
138
- if (!match.data.procedure) {
139
- const { default: maybeProcedure } = await unlazy(getRouter(match.data.router, match.data.path));
140
- if (!isProcedure(maybeProcedure)) {
141
- throw new Error(`
142
- [Contract-First] Missing or invalid implementation for procedure at path: ${toHttpPath(match.data.path)}.
143
- Ensure that the procedure is correctly defined and matches the expected contract.
144
- `);
145
- }
146
- match.data.procedure = createContractedProcedure(maybeProcedure, match.data.contract);
147
- }
148
- return {
149
- path: match.data.path,
150
- procedure: match.data.procedure,
151
- params: match.params ? decodeParams(match.params) : void 0
152
- };
153
- }
154
- }
155
-
156
- class CompositeStandardHandlerPlugin {
157
- plugins;
158
- constructor(plugins = []) {
159
- this.plugins = [...plugins].sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
160
- }
161
- init(options, router) {
162
- for (const plugin of this.plugins) {
163
- plugin.init?.(options, router);
164
- }
165
- }
166
- }
167
-
168
- class StandardHandler {
169
- interceptors;
170
- clientInterceptors;
171
- rootInterceptors;
172
- matcher;
173
- constructor(router, options) {
174
- this.matcher = new StandardOpenAPIMatcher();
175
- const plugins = new CompositeStandardHandlerPlugin(options.plugins);
176
- plugins.init(options, router);
177
- this.interceptors = toArray(options.interceptors);
178
- this.clientInterceptors = toArray(options.clientInterceptors);
179
- this.rootInterceptors = toArray(options.rootInterceptors);
180
- this.matcher.init(router);
181
- }
182
- async handle(request, options) {
183
- const prefix = options.prefix?.replace(/\/$/, "") || void 0;
184
- if (prefix && !request.url.pathname.startsWith(`${prefix}/`) && request.url.pathname !== prefix) {
185
- return { matched: false, response: void 0 };
186
- }
187
- return intercept(this.rootInterceptors, { ...options, request, prefix }, async (interceptorOptions) => {
188
- return runWithSpan({ name: `${request.method} ${request.url.pathname}` }, async (span) => {
189
- let step;
190
- try {
191
- return await intercept(
192
- this.interceptors,
193
- interceptorOptions,
194
- async ({ request: request2, context, prefix: prefix2 }) => {
195
- const method = request2.method;
196
- const url = request2.url;
197
- const pathname = prefix2 ? url.pathname.replace(prefix2, "") : url.pathname;
198
- const match = await runWithSpan(
199
- { name: "find_procedure" },
200
- () => this.matcher.match(method, `/${pathname.replace(/^\/|\/$/g, "")}`)
201
- );
202
- if (!match) {
203
- return { matched: false, response: void 0 };
204
- }
205
- span?.updateName(`${ORPC_NAME}.${match.path.join("/")}`);
206
- span?.setAttribute("rpc.system", ORPC_NAME);
207
- span?.setAttribute("rpc.method", match.path.join("."));
208
- step = "decode_input";
209
- const input = await runWithSpan({ name: "decode_input" }, () => decode(request2, match.params));
210
- step = void 0;
211
- if (isAsyncIteratorObject(input.body)) {
212
- input.body = asyncIteratorWithSpan(
213
- { name: "consume_event_iterator_input", signal: request2.signal },
214
- input.body
215
- );
216
- }
217
- const client = createProcedureClient(match.procedure, {
218
- context,
219
- path: match.path,
220
- interceptors: this.clientInterceptors
221
- });
222
- step = "call_procedure";
223
- const output = await client(input, {
224
- signal: request2.signal,
225
- lastEventId: flattenHeader(request2.headers["last-event-id"])
226
- });
227
- step = void 0;
228
- const response = encode(output, match.procedure);
229
- return {
230
- matched: true,
231
- response
232
- };
233
- }
234
- );
235
- } catch (e) {
236
- if (step !== "call_procedure") {
237
- setSpanError(span, e);
238
- }
239
- const error = step === "decode_input" && !(e instanceof ORPCError) ? new ORPCError("BAD_REQUEST", {
240
- message: `Malformed request. Ensure the request body is properly formatted and the 'Content-Type' header is set correctly.`,
241
- cause: e
242
- }) : toORPCError(e);
243
- const response = encodeError(error);
244
- return {
245
- matched: true,
246
- response
247
- };
248
- }
249
- });
250
- });
251
- }
252
- }
253
-
254
- export { CompositeStandardHandlerPlugin as C, StandardHandler as S, encodeError as a, StandardOpenAPIMatcher as b, decodeParams as c, decode as d, encode as e, resolveFriendlyStandardHandleOptions as r, toRou3Pattern as t };
@@ -1,23 +0,0 @@
1
- import { HTTPPath } from '@temporary-name/shared';
2
- import { C as Context } from './server.CWWP8ypC.mjs';
3
- import { c as StandardHandleOptions } from './server.BSJugGGA.mjs';
4
-
5
- type FriendlyStandardHandleOptions<T extends Context> = Omit<StandardHandleOptions<T>, 'context'> & (Record<never, never> extends T ? {
6
- context?: T;
7
- } : {
8
- context: T;
9
- });
10
- declare function resolveFriendlyStandardHandleOptions<T extends Context>(options: FriendlyStandardHandleOptions<T>): StandardHandleOptions<T>;
11
- /**
12
- * {@link https://github.com/unjs/rou3}
13
- *
14
- * @internal
15
- */
16
- declare function toRou3Pattern(path: HTTPPath): string;
17
- /**
18
- * @internal
19
- */
20
- declare function decodeParams(params: Record<string, string>): Record<string, string>;
21
-
22
- export { decodeParams as d, resolveFriendlyStandardHandleOptions as r, toRou3Pattern as t };
23
- export type { FriendlyStandardHandleOptions as F };
@@ -1,56 +0,0 @@
1
- import { Meta } from '@temporary-name/contract';
2
- import { HTTPPath, Interceptor } from '@temporary-name/shared';
3
- import { StandardLazyRequest, StandardResponse } from '@temporary-name/standard-server';
4
- import { C as Context, R as Router, G as ProcedureClientInterceptorOptions } from './server.CWWP8ypC.js';
5
-
6
- interface StandardHandlerPlugin<T extends Context> {
7
- order?: number;
8
- init?(options: StandardHandlerOptions<T>, router: Router<any, T>): void;
9
- }
10
- declare class CompositeStandardHandlerPlugin<T extends Context, TPlugin extends StandardHandlerPlugin<T>> implements StandardHandlerPlugin<T> {
11
- protected readonly plugins: TPlugin[];
12
- constructor(plugins?: readonly TPlugin[]);
13
- init(options: StandardHandlerOptions<T>, router: Router<any, T>): void;
14
- }
15
-
16
- interface StandardHandleOptions<T extends Context> {
17
- prefix?: HTTPPath;
18
- context: T;
19
- }
20
- type StandardHandleResult = {
21
- matched: true;
22
- response: StandardResponse;
23
- } | {
24
- matched: false;
25
- response: undefined;
26
- };
27
- interface StandardHandlerInterceptorOptions<T extends Context> extends StandardHandleOptions<T> {
28
- request: StandardLazyRequest;
29
- }
30
- interface StandardHandlerOptions<TContext extends Context> {
31
- plugins?: StandardHandlerPlugin<TContext>[];
32
- /**
33
- * Interceptors at the request level, helpful when you want catch errors
34
- */
35
- interceptors?: Interceptor<StandardHandlerInterceptorOptions<TContext>, Promise<StandardHandleResult>>[];
36
- /**
37
- * Interceptors at the root level, helpful when you want override the request/response
38
- */
39
- rootInterceptors?: Interceptor<StandardHandlerInterceptorOptions<TContext>, Promise<StandardHandleResult>>[];
40
- /**
41
- *
42
- * Interceptors for procedure client.
43
- */
44
- clientInterceptors?: Interceptor<ProcedureClientInterceptorOptions<TContext, Record<never, never>, Meta>, Promise<unknown>>[];
45
- }
46
- declare class StandardHandler<T extends Context> {
47
- private readonly interceptors;
48
- private readonly clientInterceptors;
49
- private readonly rootInterceptors;
50
- private readonly matcher;
51
- constructor(router: Router<any, T>, options: NoInfer<StandardHandlerOptions<T>>);
52
- handle(request: StandardLazyRequest, options: StandardHandleOptions<T>): Promise<StandardHandleResult>;
53
- }
54
-
55
- export { CompositeStandardHandlerPlugin as C, StandardHandler as e };
56
- export type { StandardHandlerInterceptorOptions as S, StandardHandlerPlugin as a, StandardHandlerOptions as b, StandardHandleOptions as c, StandardHandleResult as d };