@orpc/server 0.0.0-next.3afb521 → 0.0.0-next.3b15fc2

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 (72) hide show
  1. package/README.md +31 -21
  2. package/dist/adapters/aws-lambda/index.d.mts +46 -0
  3. package/dist/adapters/aws-lambda/index.d.ts +46 -0
  4. package/dist/adapters/aws-lambda/index.mjs +42 -0
  5. package/dist/adapters/bun-ws/index.d.mts +36 -0
  6. package/dist/adapters/bun-ws/index.d.ts +36 -0
  7. package/dist/adapters/bun-ws/index.mjs +47 -0
  8. package/dist/adapters/crossws/index.d.mts +33 -0
  9. package/dist/adapters/crossws/index.d.ts +33 -0
  10. package/dist/adapters/crossws/index.mjs +45 -0
  11. package/dist/adapters/fetch/index.d.mts +108 -10
  12. package/dist/adapters/fetch/index.d.ts +108 -10
  13. package/dist/adapters/fetch/index.mjs +179 -8
  14. package/dist/adapters/message-port/index.d.mts +31 -0
  15. package/dist/adapters/message-port/index.d.ts +31 -0
  16. package/dist/adapters/message-port/index.mjs +39 -0
  17. package/dist/adapters/node/index.d.mts +86 -21
  18. package/dist/adapters/node/index.d.ts +86 -21
  19. package/dist/adapters/node/index.mjs +144 -23
  20. package/dist/adapters/standard/index.d.mts +11 -15
  21. package/dist/adapters/standard/index.d.ts +11 -15
  22. package/dist/adapters/standard/index.mjs +5 -3
  23. package/dist/adapters/standard-peer/index.d.mts +18 -0
  24. package/dist/adapters/standard-peer/index.d.ts +18 -0
  25. package/dist/adapters/standard-peer/index.mjs +7 -0
  26. package/dist/adapters/websocket/index.d.mts +54 -0
  27. package/dist/adapters/websocket/index.d.ts +54 -0
  28. package/dist/adapters/websocket/index.mjs +67 -0
  29. package/dist/adapters/ws/index.d.mts +31 -0
  30. package/dist/adapters/ws/index.d.ts +31 -0
  31. package/dist/adapters/ws/index.mjs +37 -0
  32. package/dist/helpers/index.d.mts +134 -0
  33. package/dist/helpers/index.d.ts +134 -0
  34. package/dist/helpers/index.mjs +188 -0
  35. package/dist/hibernation/index.d.mts +44 -0
  36. package/dist/hibernation/index.d.ts +44 -0
  37. package/dist/hibernation/index.mjs +65 -0
  38. package/dist/index.d.mts +664 -125
  39. package/dist/index.d.ts +664 -125
  40. package/dist/index.mjs +194 -40
  41. package/dist/plugins/index.d.mts +157 -19
  42. package/dist/plugins/index.d.ts +157 -19
  43. package/dist/plugins/index.mjs +201 -17
  44. package/dist/shared/server.B4BGqy3Y.d.mts +193 -0
  45. package/dist/shared/server.B4BGqy3Y.d.ts +193 -0
  46. package/dist/shared/server.BW-nUGgA.mjs +36 -0
  47. package/dist/shared/server.COL12UTb.d.ts +32 -0
  48. package/dist/shared/server.CVKCo60T.d.mts +12 -0
  49. package/dist/shared/{server.BFBhsdJr.mjs → server.CaqDCZX1.mjs} +157 -93
  50. package/dist/shared/server.Cb6yD7DZ.d.ts +42 -0
  51. package/dist/shared/server.Ck-gOLzq.d.mts +32 -0
  52. package/dist/shared/server.DBCUJijK.d.mts +74 -0
  53. package/dist/shared/server.DNtJ-p60.d.ts +12 -0
  54. package/dist/shared/server.DPIFWpxG.d.ts +74 -0
  55. package/dist/shared/server.DZ5BIITo.mjs +9 -0
  56. package/dist/shared/server.DzV1hr3z.d.mts +42 -0
  57. package/dist/shared/server.UVMTOWrk.mjs +26 -0
  58. package/dist/shared/server.vzZSq5UM.mjs +219 -0
  59. package/package.json +71 -20
  60. package/dist/adapters/hono/index.d.mts +0 -19
  61. package/dist/adapters/hono/index.d.ts +0 -19
  62. package/dist/adapters/hono/index.mjs +0 -32
  63. package/dist/adapters/next/index.d.mts +0 -26
  64. package/dist/adapters/next/index.d.ts +0 -26
  65. package/dist/adapters/next/index.mjs +0 -29
  66. package/dist/shared/server.3cSam35R.mjs +0 -158
  67. package/dist/shared/server.C99bm-AA.d.mts +0 -143
  68. package/dist/shared/server.C99bm-AA.d.ts +0 -143
  69. package/dist/shared/server.CjB_m7jG.mjs +0 -28
  70. package/dist/shared/server.Q6ZmnTgO.mjs +0 -12
  71. package/dist/shared/server.SegZfF38.d.ts +0 -77
  72. package/dist/shared/server.rcYTv2pz.d.mts +0 -77
@@ -0,0 +1,193 @@
1
+ import { ORPCErrorCode, ORPCErrorOptions, ORPCError, HTTPPath, ClientContext, Client } from '@orpc/client';
2
+ import { ErrorMap, ErrorMapItem, InferSchemaInput, AnySchema, Meta, ContractProcedureDef, InferSchemaOutput, ErrorFromErrorMap, AnyContractRouter, ContractProcedure } from '@orpc/contract';
3
+ import { MaybeOptionalOptions, Promisable, Interceptor, PromiseWithError, Value } from '@orpc/shared';
4
+
5
+ type Context = Record<PropertyKey, any>;
6
+ type MergedInitialContext<TInitial extends Context, TAdditional extends Context, TCurrent extends Context> = TInitial & Omit<TAdditional, keyof TCurrent>;
7
+ type MergedCurrentContext<T extends Context, U extends Context> = Omit<T, keyof U> & U;
8
+ declare function mergeCurrentContext<T extends Context, U extends Context>(context: T, other: U): MergedCurrentContext<T, U>;
9
+
10
+ type ORPCErrorConstructorMapItemOptions<TData> = Omit<ORPCErrorOptions<TData>, 'defined' | 'status'>;
11
+ type ORPCErrorConstructorMapItem<TCode extends ORPCErrorCode, TInData> = (...rest: MaybeOptionalOptions<ORPCErrorConstructorMapItemOptions<TInData>>) => ORPCError<TCode, TInData>;
12
+ type ORPCErrorConstructorMap<T extends ErrorMap> = {
13
+ [K in keyof T]: K extends ORPCErrorCode ? T[K] extends ErrorMapItem<infer UInputSchema> ? ORPCErrorConstructorMapItem<K, InferSchemaInput<UInputSchema>> : never : never;
14
+ };
15
+ declare function createORPCErrorConstructorMap<T extends ErrorMap>(errors: T): ORPCErrorConstructorMap<T>;
16
+
17
+ declare const LAZY_SYMBOL: unique symbol;
18
+ interface LazyMeta {
19
+ prefix?: HTTPPath;
20
+ }
21
+ interface Lazy<T> {
22
+ [LAZY_SYMBOL]: {
23
+ loader: () => Promise<{
24
+ default: T;
25
+ }>;
26
+ meta: LazyMeta;
27
+ };
28
+ }
29
+ type Lazyable<T> = T | Lazy<T>;
30
+ /**
31
+ * Creates a lazy-loaded item.
32
+ *
33
+ * @warning The `prefix` in `meta` only holds metadata and does not apply the prefix to the lazy router, use `os.prefix(...).lazy(...)` instead.
34
+ */
35
+ declare function lazy<T>(loader: () => Promise<{
36
+ default: T;
37
+ }>, meta?: LazyMeta): Lazy<T>;
38
+ declare function isLazy(item: unknown): item is Lazy<any>;
39
+ declare function getLazyMeta(lazied: Lazy<any>): LazyMeta;
40
+ declare function unlazy<T extends Lazyable<any>>(lazied: T): Promise<{
41
+ default: T extends Lazy<infer U> ? U : T;
42
+ }>;
43
+
44
+ interface ProcedureHandlerOptions<TCurrentContext extends Context, TInput, TErrorConstructorMap extends ORPCErrorConstructorMap<any>, TMeta extends Meta> {
45
+ context: TCurrentContext;
46
+ input: TInput;
47
+ path: readonly string[];
48
+ procedure: Procedure<Context, Context, AnySchema, AnySchema, ErrorMap, TMeta>;
49
+ signal?: AbortSignal;
50
+ lastEventId: string | undefined;
51
+ errors: TErrorConstructorMap;
52
+ }
53
+ interface ProcedureHandler<TCurrentContext extends Context, TInput, THandlerOutput, TErrorMap extends ErrorMap, TMeta extends Meta> {
54
+ (opt: ProcedureHandlerOptions<TCurrentContext, TInput, ORPCErrorConstructorMap<TErrorMap>, TMeta>): Promisable<THandlerOutput>;
55
+ }
56
+ interface ProcedureDef<TInitialContext extends Context, TCurrentContext extends Context, TInputSchema extends AnySchema, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap, TMeta extends Meta> extends ContractProcedureDef<TInputSchema, TOutputSchema, TErrorMap, TMeta> {
57
+ __initialContext?: (type: TInitialContext) => unknown;
58
+ middlewares: readonly AnyMiddleware[];
59
+ inputValidationIndex: number;
60
+ outputValidationIndex: number;
61
+ handler: ProcedureHandler<TCurrentContext, any, any, any, any>;
62
+ }
63
+ /**
64
+ * This class represents a procedure.
65
+ *
66
+ * @see {@link https://orpc.unnoq.com/docs/procedure Procedure Docs}
67
+ */
68
+ declare class Procedure<TInitialContext extends Context, TCurrentContext extends Context, TInputSchema extends AnySchema, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap, TMeta extends Meta> {
69
+ /**
70
+ * This property holds the defined options.
71
+ */
72
+ '~orpc': ProcedureDef<TInitialContext, TCurrentContext, TInputSchema, TOutputSchema, TErrorMap, TMeta>;
73
+ constructor(def: ProcedureDef<TInitialContext, TCurrentContext, TInputSchema, TOutputSchema, TErrorMap, TMeta>);
74
+ }
75
+ type AnyProcedure = Procedure<any, any, any, any, any, any>;
76
+ declare function isProcedure(item: unknown): item is AnyProcedure;
77
+
78
+ type MiddlewareResult<TOutContext extends Context, TOutput> = Promisable<{
79
+ output: TOutput;
80
+ context: TOutContext;
81
+ }>;
82
+ type MiddlewareNextFnOptions<TOutContext extends Context> = Record<never, never> extends TOutContext ? {
83
+ context?: TOutContext;
84
+ } : {
85
+ context: TOutContext;
86
+ };
87
+ interface MiddlewareNextFn<TOutput> {
88
+ <U extends Context = Record<never, never>>(...rest: MaybeOptionalOptions<MiddlewareNextFnOptions<U>>): MiddlewareResult<U, TOutput>;
89
+ }
90
+ interface MiddlewareOutputFn<TOutput> {
91
+ (output: TOutput): MiddlewareResult<Record<never, never>, TOutput>;
92
+ }
93
+ interface MiddlewareOptions<TInContext extends Context, TOutput, TErrorConstructorMap extends ORPCErrorConstructorMap<any>, TMeta extends Meta> {
94
+ context: TInContext;
95
+ path: readonly string[];
96
+ procedure: Procedure<Context, Context, AnySchema, AnySchema, ErrorMap, TMeta>;
97
+ signal?: AbortSignal;
98
+ lastEventId: string | undefined;
99
+ next: MiddlewareNextFn<TOutput>;
100
+ errors: TErrorConstructorMap;
101
+ }
102
+ /**
103
+ * A function that represents a middleware.
104
+ *
105
+ * @see {@link https://orpc.unnoq.com/docs/middleware Middleware Docs}
106
+ */
107
+ interface Middleware<TInContext extends Context, TOutContext extends Context, TInput, TOutput, TErrorConstructorMap extends ORPCErrorConstructorMap<any>, TMeta extends Meta> {
108
+ (options: MiddlewareOptions<TInContext, TOutput, TErrorConstructorMap, TMeta>, input: TInput, output: MiddlewareOutputFn<TOutput>): Promisable<MiddlewareResult<TOutContext, TOutput>>;
109
+ }
110
+ type AnyMiddleware = Middleware<any, any, any, any, any, any>;
111
+ interface MapInputMiddleware<TInput, TMappedInput> {
112
+ (input: TInput): TMappedInput;
113
+ }
114
+ declare function middlewareOutputFn<TOutput>(output: TOutput): MiddlewareResult<Record<never, never>, TOutput>;
115
+
116
+ type ProcedureClient<TClientContext extends ClientContext, TInputSchema extends AnySchema, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap> = Client<TClientContext, InferSchemaInput<TInputSchema>, InferSchemaOutput<TOutputSchema>, ErrorFromErrorMap<TErrorMap>>;
117
+ interface ProcedureClientInterceptorOptions<TInitialContext extends Context, TErrorMap extends ErrorMap, TMeta extends Meta> {
118
+ context: TInitialContext;
119
+ input: unknown;
120
+ errors: ORPCErrorConstructorMap<TErrorMap>;
121
+ path: readonly string[];
122
+ procedure: Procedure<Context, Context, AnySchema, AnySchema, ErrorMap, TMeta>;
123
+ signal?: AbortSignal;
124
+ lastEventId: string | undefined;
125
+ }
126
+ type CreateProcedureClientOptions<TInitialContext extends Context, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap, TMeta extends Meta, TClientContext extends ClientContext> = {
127
+ /**
128
+ * This is helpful for logging and analytics.
129
+ */
130
+ path?: readonly string[];
131
+ interceptors?: Interceptor<ProcedureClientInterceptorOptions<TInitialContext, TErrorMap, TMeta>, PromiseWithError<InferSchemaOutput<TOutputSchema>, ErrorFromErrorMap<TErrorMap>>>[];
132
+ } & (Record<never, never> extends TInitialContext ? {
133
+ context?: Value<Promisable<TInitialContext>, [clientContext: TClientContext]>;
134
+ } : {
135
+ context: Value<Promisable<TInitialContext>, [clientContext: TClientContext]>;
136
+ });
137
+ /**
138
+ * Create Server-side client from a procedure.
139
+ *
140
+ * @see {@link https://orpc.unnoq.com/docs/client/server-side Server-side Client Docs}
141
+ */
142
+ declare function createProcedureClient<TInitialContext extends Context, TInputSchema extends AnySchema, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap, TMeta extends Meta, TClientContext extends ClientContext>(lazyableProcedure: Lazyable<Procedure<TInitialContext, any, TInputSchema, TOutputSchema, TErrorMap, TMeta>>, ...rest: MaybeOptionalOptions<CreateProcedureClientOptions<TInitialContext, TOutputSchema, TErrorMap, TMeta, TClientContext>>): ProcedureClient<TClientContext, TInputSchema, TOutputSchema, TErrorMap>;
143
+
144
+ /**
145
+ * Represents a router, which defines a hierarchical structure of procedures.
146
+ *
147
+ * @info A procedure is a router too.
148
+ * @see {@link https://orpc.unnoq.com/docs/contract-first/define-contract#contract-router Contract Router Docs}
149
+ */
150
+ type Router<T extends AnyContractRouter, TInitialContext extends Context> = T extends ContractProcedure<infer UInputSchema, infer UOutputSchema, infer UErrorMap, infer UMeta> ? Procedure<TInitialContext, any, UInputSchema, UOutputSchema, UErrorMap, UMeta> : {
151
+ [K in keyof T]: T[K] extends AnyContractRouter ? Lazyable<Router<T[K], TInitialContext>> : never;
152
+ };
153
+ type AnyRouter = Router<any, any>;
154
+ type InferRouterInitialContext<T extends AnyRouter> = T extends Router<any, infer UInitialContext> ? UInitialContext : never;
155
+ /**
156
+ * Infer all initial context of the router.
157
+ *
158
+ * @info A procedure is a router too.
159
+ * @see {@link https://orpc.unnoq.com/docs/router#utilities Router Utilities Docs}
160
+ */
161
+ type InferRouterInitialContexts<T extends AnyRouter> = T extends Procedure<infer UInitialContext, any, any, any, any, any> ? UInitialContext : {
162
+ [K in keyof T]: T[K] extends Lazyable<infer U extends AnyRouter> ? InferRouterInitialContexts<U> : never;
163
+ };
164
+ /**
165
+ * Infer all current context of the router.
166
+ *
167
+ * @info A procedure is a router too.
168
+ * @see {@link https://orpc.unnoq.com/docs/router#utilities Router Utilities Docs}
169
+ */
170
+ type InferRouterCurrentContexts<T extends AnyRouter> = T extends Procedure<any, infer UCurrentContext, any, any, any, any> ? UCurrentContext : {
171
+ [K in keyof T]: T[K] extends Lazyable<infer U extends AnyRouter> ? InferRouterCurrentContexts<U> : never;
172
+ };
173
+ /**
174
+ * Infer all router inputs
175
+ *
176
+ * @info A procedure is a router too.
177
+ * @see {@link https://orpc.unnoq.com/docs/router#utilities Router Utilities Docs}
178
+ */
179
+ type InferRouterInputs<T extends AnyRouter> = T extends Procedure<any, any, infer UInputSchema, any, any, any> ? InferSchemaInput<UInputSchema> : {
180
+ [K in keyof T]: T[K] extends Lazyable<infer U extends AnyRouter> ? InferRouterInputs<U> : never;
181
+ };
182
+ /**
183
+ * Infer all router outputs
184
+ *
185
+ * @info A procedure is a router too.
186
+ * @see {@link https://orpc.unnoq.com/docs/router#utilities Router Utilities Docs}
187
+ */
188
+ type InferRouterOutputs<T extends AnyRouter> = T extends Procedure<any, any, any, infer UOutputSchema, any, any> ? InferSchemaOutput<UOutputSchema> : {
189
+ [K in keyof T]: T[K] extends Lazyable<infer U extends AnyRouter> ? InferRouterOutputs<U> : never;
190
+ };
191
+
192
+ export { isProcedure as E, createProcedureClient as F, Procedure as P, mergeCurrentContext as m, createORPCErrorConstructorMap as n, LAZY_SYMBOL as o, lazy as q, isLazy as r, getLazyMeta as s, unlazy as u, middlewareOutputFn as z };
193
+ export type { AnyProcedure as A, ProcedureHandlerOptions as B, Context as C, ProcedureDef as D, InferRouterInitialContexts as G, InferRouterCurrentContexts as H, InferRouterInitialContext as I, InferRouterInputs as J, InferRouterOutputs as K, Lazyable as L, MergedInitialContext as M, ORPCErrorConstructorMap as O, Router as R, AnyMiddleware as a, AnyRouter as b, Lazy as c, ProcedureClientInterceptorOptions as d, Middleware as e, MergedCurrentContext as f, MapInputMiddleware as g, CreateProcedureClientOptions as h, ProcedureClient as i, ProcedureHandler as j, ORPCErrorConstructorMapItemOptions as k, ORPCErrorConstructorMapItem as l, LazyMeta as p, MiddlewareResult as t, MiddlewareNextFnOptions as v, MiddlewareNextFn as w, MiddlewareOutputFn as x, MiddlewareOptions as y };
@@ -0,0 +1,36 @@
1
+ import { ORPCError, fallbackContractConfig } from '@orpc/contract';
2
+
3
+ const STRICT_GET_METHOD_PLUGIN_IS_GET_METHOD_CONTEXT_SYMBOL = Symbol("STRICT_GET_METHOD_PLUGIN_IS_GET_METHOD_CONTEXT");
4
+ class StrictGetMethodPlugin {
5
+ error;
6
+ order = 7e6;
7
+ constructor(options = {}) {
8
+ this.error = options.error ?? new ORPCError("METHOD_NOT_SUPPORTED");
9
+ }
10
+ init(options) {
11
+ options.rootInterceptors ??= [];
12
+ options.clientInterceptors ??= [];
13
+ options.rootInterceptors.unshift((options2) => {
14
+ const isGetMethod = options2.request.method === "GET";
15
+ return options2.next({
16
+ ...options2,
17
+ context: {
18
+ ...options2.context,
19
+ [STRICT_GET_METHOD_PLUGIN_IS_GET_METHOD_CONTEXT_SYMBOL]: isGetMethod
20
+ }
21
+ });
22
+ });
23
+ options.clientInterceptors.unshift((options2) => {
24
+ if (typeof options2.context[STRICT_GET_METHOD_PLUGIN_IS_GET_METHOD_CONTEXT_SYMBOL] !== "boolean") {
25
+ throw new TypeError("[StrictGetMethodPlugin] strict GET method context has been corrupted or modified by another plugin or interceptor");
26
+ }
27
+ const procedureMethod = fallbackContractConfig("defaultMethod", options2.procedure["~orpc"].route.method);
28
+ if (options2.context[STRICT_GET_METHOD_PLUGIN_IS_GET_METHOD_CONTEXT_SYMBOL] && procedureMethod !== "GET") {
29
+ throw this.error;
30
+ }
31
+ return options2.next();
32
+ });
33
+ }
34
+ }
35
+
36
+ export { StrictGetMethodPlugin as S };
@@ -0,0 +1,32 @@
1
+ import { StandardRPCJsonSerializerOptions } from '@orpc/client/standard';
2
+ import { b as AnyRouter, C as Context, R as Router } from './server.B4BGqy3Y.js';
3
+ import { i as StandardMatcher, h as StandardMatchResult, e as StandardHandlerOptions, f as StandardHandler } from './server.DPIFWpxG.js';
4
+ import { HTTPPath } from '@orpc/client';
5
+ import { Value } from '@orpc/shared';
6
+ import { T as TraverseContractProcedureCallbackOptions } from './server.Cb6yD7DZ.js';
7
+
8
+ interface StandardRPCMatcherOptions {
9
+ /**
10
+ * Filter procedures. Return `false` to exclude a procedure from matching.
11
+ *
12
+ * @default true
13
+ */
14
+ filter?: Value<boolean, [options: TraverseContractProcedureCallbackOptions]>;
15
+ }
16
+ declare class StandardRPCMatcher implements StandardMatcher {
17
+ private readonly filter;
18
+ private readonly tree;
19
+ private pendingRouters;
20
+ constructor(options?: StandardRPCMatcherOptions);
21
+ init(router: AnyRouter, path?: readonly string[]): void;
22
+ match(_method: string, pathname: HTTPPath): Promise<StandardMatchResult>;
23
+ }
24
+
25
+ interface StandardRPCHandlerOptions<T extends Context> extends StandardHandlerOptions<T>, StandardRPCJsonSerializerOptions, StandardRPCMatcherOptions {
26
+ }
27
+ declare class StandardRPCHandler<T extends Context> extends StandardHandler<T> {
28
+ constructor(router: Router<any, T>, options?: StandardRPCHandlerOptions<T>);
29
+ }
30
+
31
+ export { StandardRPCHandler as a, StandardRPCMatcher as c };
32
+ export type { StandardRPCHandlerOptions as S, StandardRPCMatcherOptions as b };
@@ -0,0 +1,12 @@
1
+ import { C as Context } from './server.B4BGqy3Y.mjs';
2
+ import { b as StandardHandleOptions } from './server.DBCUJijK.mjs';
3
+
4
+ type FriendlyStandardHandleOptions<T extends Context> = Omit<StandardHandleOptions<T>, 'context'> & (Record<never, never> extends T ? {
5
+ context?: T;
6
+ } : {
7
+ context: T;
8
+ });
9
+ declare function resolveFriendlyStandardHandleOptions<T extends Context>(options: FriendlyStandardHandleOptions<T>): StandardHandleOptions<T>;
10
+
11
+ export { resolveFriendlyStandardHandleOptions as r };
12
+ export type { FriendlyStandardHandleOptions as F };
@@ -1,6 +1,7 @@
1
- import { isContractProcedure, ValidationError, mergePrefix, mergeErrorMap, enhanceRoute } from '@orpc/contract';
2
- import { fallbackORPCErrorStatus, ORPCError } from '@orpc/client';
3
- import { value, intercept, toError } from '@orpc/shared';
1
+ import { isContractProcedure, validateORPCError, ValidationError, mergePrefix, mergeErrorMap, enhanceRoute } from '@orpc/contract';
2
+ import { resolveMaybeOptionalOptions, toArray, value, runWithSpan, intercept, isAsyncIteratorObject, asyncIteratorWithSpan } from '@orpc/shared';
3
+ import { ORPCError, mapEventIterator } from '@orpc/client';
4
+ import { HibernationEventIterator } from '@orpc/standard-server';
4
5
 
5
6
  const LAZY_SYMBOL = Symbol("ORPC_LAZY_SYMBOL");
6
7
  function lazy(loader, meta = {}) {
@@ -21,25 +22,34 @@ function unlazy(lazied) {
21
22
  return isLazy(lazied) ? lazied[LAZY_SYMBOL].loader() : Promise.resolve({ default: lazied });
22
23
  }
23
24
 
24
- function dedupeMiddlewares(compare, middlewares) {
25
- let min = 0;
25
+ function isStartWithMiddlewares(middlewares, compare) {
26
+ if (compare.length > middlewares.length) {
27
+ return false;
28
+ }
26
29
  for (let i = 0; i < middlewares.length; i++) {
27
- const index = compare.indexOf(middlewares[i], min);
28
- if (index === -1) {
29
- return middlewares.slice(i);
30
+ if (compare[i] === void 0) {
31
+ return true;
32
+ }
33
+ if (middlewares[i] !== compare[i]) {
34
+ return false;
30
35
  }
31
- min = index + 1;
32
36
  }
33
- return [];
37
+ return true;
34
38
  }
35
- function mergeMiddlewares(first, second) {
36
- return [...first, ...dedupeMiddlewares(first, second)];
39
+ function mergeMiddlewares(first, second, options) {
40
+ if (options.dedupeLeading && isStartWithMiddlewares(second, first)) {
41
+ return second;
42
+ }
43
+ return [...first, ...second];
37
44
  }
38
45
  function addMiddleware(middlewares, addition) {
39
46
  return [...middlewares, addition];
40
47
  }
41
48
 
42
49
  class Procedure {
50
+ /**
51
+ * This property holds the defined options.
52
+ */
43
53
  "~orpc";
44
54
  constructor(def) {
45
55
  this["~orpc"] = def;
@@ -52,20 +62,25 @@ function isProcedure(item) {
52
62
  return isContractProcedure(item) && "middlewares" in item["~orpc"] && "inputValidationIndex" in item["~orpc"] && "outputValidationIndex" in item["~orpc"] && "handler" in item["~orpc"];
53
63
  }
54
64
 
65
+ function mergeCurrentContext(context, other) {
66
+ return { ...context, ...other };
67
+ }
68
+
55
69
  function createORPCErrorConstructorMap(errors) {
56
70
  const proxy = new Proxy(errors, {
57
71
  get(target, code) {
58
72
  if (typeof code !== "string") {
59
73
  return Reflect.get(target, code);
60
74
  }
61
- const item = (...[options]) => {
75
+ const item = (...rest) => {
76
+ const options = resolveMaybeOptionalOptions(rest);
62
77
  const config = errors[code];
63
78
  return new ORPCError(code, {
64
79
  defined: Boolean(config),
65
80
  status: config?.status,
66
- message: options?.message ?? config?.message,
67
- data: options?.data,
68
- cause: options?.cause
81
+ message: options.message ?? config?.message,
82
+ data: options.data,
83
+ cause: options.cause
69
84
  });
70
85
  };
71
86
  return item;
@@ -73,54 +88,64 @@ function createORPCErrorConstructorMap(errors) {
73
88
  });
74
89
  return proxy;
75
90
  }
76
- async function validateORPCError(map, error) {
77
- const { code, status, message, data, cause, defined } = error;
78
- const config = map?.[error.code];
79
- if (!config || fallbackORPCErrorStatus(error.code, config.status) !== error.status) {
80
- return defined ? new ORPCError(code, { defined: false, status, message, data, cause }) : error;
81
- }
82
- if (!config.data) {
83
- return defined ? error : new ORPCError(code, { defined: true, status, message, data, cause });
84
- }
85
- const validated = await config.data["~standard"].validate(error.data);
86
- if (validated.issues) {
87
- return defined ? new ORPCError(code, { defined: false, status, message, data, cause }) : error;
88
- }
89
- return new ORPCError(code, { defined: true, status, message, data: validated.value, cause });
90
- }
91
91
 
92
92
  function middlewareOutputFn(output) {
93
93
  return { output, context: {} };
94
94
  }
95
95
 
96
- function createProcedureClient(lazyableProcedure, ...[options]) {
96
+ function createProcedureClient(lazyableProcedure, ...rest) {
97
+ const options = resolveMaybeOptionalOptions(rest);
97
98
  return async (...[input, callerOptions]) => {
98
- const path = options?.path ?? [];
99
+ const path = toArray(options.path);
99
100
  const { default: procedure } = await unlazy(lazyableProcedure);
100
101
  const clientContext = callerOptions?.context ?? {};
101
- const context = await value(options?.context ?? {}, clientContext);
102
+ const context = await value(options.context ?? {}, clientContext);
102
103
  const errors = createORPCErrorConstructorMap(procedure["~orpc"].errorMap);
104
+ const validateError = async (e) => {
105
+ if (e instanceof ORPCError) {
106
+ return await validateORPCError(procedure["~orpc"].errorMap, e);
107
+ }
108
+ return e;
109
+ };
103
110
  try {
104
- return await intercept(
105
- options?.interceptors ?? [],
106
- {
107
- context,
108
- input,
109
- // input only optional when it undefinable so we can safely cast it
110
- errors,
111
- path,
112
- procedure,
113
- signal: callerOptions?.signal,
114
- lastEventId: callerOptions?.lastEventId
115
- },
116
- (interceptorOptions) => executeProcedureInternal(interceptorOptions.procedure, interceptorOptions)
111
+ const output = await runWithSpan(
112
+ { name: "call_procedure", signal: callerOptions?.signal },
113
+ (span) => {
114
+ span?.setAttribute("procedure.path", [...path]);
115
+ return intercept(
116
+ toArray(options.interceptors),
117
+ {
118
+ context,
119
+ input,
120
+ // input only optional when it undefinable so we can safely cast it
121
+ errors,
122
+ path,
123
+ procedure,
124
+ signal: callerOptions?.signal,
125
+ lastEventId: callerOptions?.lastEventId
126
+ },
127
+ (interceptorOptions) => executeProcedureInternal(interceptorOptions.procedure, interceptorOptions)
128
+ );
129
+ }
117
130
  );
118
- } catch (e) {
119
- if (!(e instanceof ORPCError)) {
120
- throw toError(e);
131
+ if (isAsyncIteratorObject(output)) {
132
+ if (output instanceof HibernationEventIterator) {
133
+ return output;
134
+ }
135
+ return mapEventIterator(
136
+ asyncIteratorWithSpan(
137
+ { name: "consume_event_iterator_output", signal: callerOptions?.signal },
138
+ output
139
+ ),
140
+ {
141
+ value: (v) => v,
142
+ error: (e) => validateError(e)
143
+ }
144
+ );
121
145
  }
122
- const validated = await validateORPCError(procedure["~orpc"].errorMap, e);
123
- throw validated;
146
+ return output;
147
+ } catch (e) {
148
+ throw await validateError(e);
124
149
  }
125
150
  };
126
151
  }
@@ -129,58 +154,88 @@ async function validateInput(procedure, input) {
129
154
  if (!schema) {
130
155
  return input;
131
156
  }
132
- const result = await schema["~standard"].validate(input);
133
- if (result.issues) {
134
- throw new ORPCError("BAD_REQUEST", {
135
- message: "Input validation failed",
136
- data: {
137
- issues: result.issues
138
- },
139
- cause: new ValidationError({ message: "Input validation failed", issues: result.issues })
140
- });
141
- }
142
- return result.value;
157
+ return runWithSpan(
158
+ { name: "validate_input" },
159
+ async () => {
160
+ const result = await schema["~standard"].validate(input);
161
+ if (result.issues) {
162
+ throw new ORPCError("BAD_REQUEST", {
163
+ message: "Input validation failed",
164
+ data: {
165
+ issues: result.issues
166
+ },
167
+ cause: new ValidationError({
168
+ message: "Input validation failed",
169
+ issues: result.issues,
170
+ data: input
171
+ })
172
+ });
173
+ }
174
+ return result.value;
175
+ }
176
+ );
143
177
  }
144
178
  async function validateOutput(procedure, output) {
145
179
  const schema = procedure["~orpc"].outputSchema;
146
180
  if (!schema) {
147
181
  return output;
148
182
  }
149
- const result = await schema["~standard"].validate(output);
150
- if (result.issues) {
151
- throw new ORPCError("INTERNAL_SERVER_ERROR", {
152
- message: "Output validation failed",
153
- cause: new ValidationError({ message: "Output validation failed", issues: result.issues })
154
- });
155
- }
156
- return result.value;
183
+ return runWithSpan(
184
+ { name: "validate_output" },
185
+ async () => {
186
+ const result = await schema["~standard"].validate(output);
187
+ if (result.issues) {
188
+ throw new ORPCError("INTERNAL_SERVER_ERROR", {
189
+ message: "Output validation failed",
190
+ cause: new ValidationError({
191
+ message: "Output validation failed",
192
+ issues: result.issues,
193
+ data: output
194
+ })
195
+ });
196
+ }
197
+ return result.value;
198
+ }
199
+ );
157
200
  }
158
201
  async function executeProcedureInternal(procedure, options) {
159
202
  const middlewares = procedure["~orpc"].middlewares;
160
203
  const inputValidationIndex = Math.min(Math.max(0, procedure["~orpc"].inputValidationIndex), middlewares.length);
161
204
  const outputValidationIndex = Math.min(Math.max(0, procedure["~orpc"].outputValidationIndex), middlewares.length);
162
- let currentIndex = 0;
163
- let currentContext = options.context;
164
- let currentInput = options.input;
165
- const next = async (...[nextOptions]) => {
166
- const index = currentIndex;
167
- currentIndex += 1;
168
- currentContext = { ...currentContext, ...nextOptions?.context };
205
+ const next = async (index, context, input) => {
206
+ let currentInput = input;
169
207
  if (index === inputValidationIndex) {
170
208
  currentInput = await validateInput(procedure, currentInput);
171
209
  }
172
210
  const mid = middlewares[index];
173
- const result = mid ? await mid({ ...options, context: currentContext, next }, currentInput, middlewareOutputFn) : { output: await procedure["~orpc"].handler({ ...options, context: currentContext, input: currentInput }), context: currentContext };
211
+ const output = mid ? await runWithSpan(
212
+ { name: `middleware.${mid.name}`, signal: options.signal },
213
+ async (span) => {
214
+ span?.setAttribute("middleware.index", index);
215
+ span?.setAttribute("middleware.name", mid.name);
216
+ const result = await mid({
217
+ ...options,
218
+ context,
219
+ next: async (...[nextOptions]) => {
220
+ const nextContext = nextOptions?.context ?? {};
221
+ return {
222
+ output: await next(index + 1, mergeCurrentContext(context, nextContext), currentInput),
223
+ context: nextContext
224
+ };
225
+ }
226
+ }, currentInput, middlewareOutputFn);
227
+ return result.output;
228
+ }
229
+ ) : await runWithSpan(
230
+ { name: "handler", signal: options.signal },
231
+ () => procedure["~orpc"].handler({ ...options, context, input: currentInput })
232
+ );
174
233
  if (index === outputValidationIndex) {
175
- const validatedOutput = await validateOutput(procedure, result.output);
176
- return {
177
- ...result,
178
- output: validatedOutput
179
- };
234
+ return await validateOutput(procedure, output);
180
235
  }
181
- return result;
236
+ return output;
182
237
  };
183
- return (await next({})).output;
238
+ return next(0, options.context, options.input);
184
239
  }
185
240
 
186
241
  const HIDDEN_ROUTER_CONTRACT_SYMBOL = Symbol("ORPC_HIDDEN_ROUTER_CONTRACT");
@@ -250,7 +305,7 @@ function enhanceRouter(router, options) {
250
305
  return accessible;
251
306
  }
252
307
  if (isProcedure(router)) {
253
- const newMiddlewares = mergeMiddlewares(options.middlewares, router["~orpc"].middlewares);
308
+ const newMiddlewares = mergeMiddlewares(options.middlewares, router["~orpc"].middlewares, { dedupeLeading: options.dedupeLeadingMiddlewares });
254
309
  const newMiddlewareAdded = newMiddlewares.length - router["~orpc"].middlewares.length;
255
310
  const enhanced2 = new Procedure({
256
311
  ...router["~orpc"],
@@ -311,6 +366,18 @@ async function resolveContractProcedures(options, callback) {
311
366
  }
312
367
  }
313
368
  }
369
+ async function unlazyRouter(router) {
370
+ if (isProcedure(router)) {
371
+ return router;
372
+ }
373
+ const unlazied = {};
374
+ for (const key in router) {
375
+ const item = router[key];
376
+ const { default: unlaziedRouter } = await unlazy(item);
377
+ unlazied[key] = await unlazyRouter(unlaziedRouter);
378
+ }
379
+ return unlazied;
380
+ }
314
381
 
315
382
  function createAssertedLazyProcedure(lazied) {
316
383
  const lazyProcedure = lazy(async () => {
@@ -335,11 +402,8 @@ function createContractedProcedure(procedure, contract) {
335
402
  });
336
403
  }
337
404
  function call(procedure, input, ...rest) {
338
- return createProcedureClient(procedure, ...rest)(input);
339
- }
340
-
341
- function toHttpPath(path) {
342
- return `/${path.map(encodeURIComponent).join("/")}`;
405
+ const options = resolveMaybeOptionalOptions(rest);
406
+ return createProcedureClient(procedure, options)(input, options);
343
407
  }
344
408
 
345
- export { LAZY_SYMBOL as L, Procedure as P, toHttpPath as a, createContractedProcedure as b, createProcedureClient as c, addMiddleware as d, enhanceRouter as e, isLazy as f, getRouter as g, createAssertedLazyProcedure as h, isProcedure as i, getLazyMeta as j, call as k, lazy as l, middlewareOutputFn as m, getHiddenRouterContract as n, createAccessibleLazyRouter as o, resolveContractProcedures as r, setHiddenRouterContract as s, traverseContractProcedures as t, unlazy as u };
409
+ export { LAZY_SYMBOL as L, Procedure as P, createContractedProcedure as a, addMiddleware as b, createProcedureClient as c, isLazy as d, enhanceRouter as e, createAssertedLazyProcedure as f, getRouter as g, createORPCErrorConstructorMap as h, isProcedure as i, getLazyMeta as j, middlewareOutputFn as k, lazy as l, mergeCurrentContext as m, isStartWithMiddlewares as n, mergeMiddlewares as o, call as p, getHiddenRouterContract as q, createAccessibleLazyRouter as r, setHiddenRouterContract as s, traverseContractProcedures as t, unlazy as u, resolveContractProcedures as v, unlazyRouter as w };