@orpc/server 0.0.0-next.0787cc6 → 0.0.0-next.08f0a9e

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 (84) hide show
  1. package/README.md +131 -0
  2. package/dist/adapters/fetch/index.d.mts +59 -0
  3. package/dist/adapters/fetch/index.d.ts +59 -0
  4. package/dist/adapters/fetch/index.mjs +105 -0
  5. package/dist/adapters/node/index.d.mts +58 -0
  6. package/dist/adapters/node/index.d.ts +58 -0
  7. package/dist/adapters/node/index.mjs +90 -0
  8. package/dist/adapters/standard/index.d.mts +26 -0
  9. package/dist/adapters/standard/index.d.ts +26 -0
  10. package/dist/adapters/standard/index.mjs +8 -0
  11. package/dist/index.d.mts +292 -0
  12. package/dist/index.d.ts +292 -0
  13. package/dist/{index.js → index.mjs} +115 -156
  14. package/dist/plugins/index.d.mts +125 -0
  15. package/dist/plugins/index.d.ts +125 -0
  16. package/dist/plugins/index.mjs +252 -0
  17. package/dist/shared/server.B1oIHH_j.d.mts +74 -0
  18. package/dist/shared/server.BVHsfJ99.d.mts +144 -0
  19. package/dist/shared/server.BVHsfJ99.d.ts +144 -0
  20. package/dist/shared/server.BVwwTHyO.mjs +9 -0
  21. package/dist/shared/server.BW-nUGgA.mjs +36 -0
  22. package/dist/shared/server.BuLPHTX1.d.mts +18 -0
  23. package/dist/shared/server.C37gDhSZ.mjs +364 -0
  24. package/dist/shared/server.CaWivVk3.d.ts +74 -0
  25. package/dist/shared/server.DFuJLDuo.mjs +190 -0
  26. package/dist/shared/server.DMhSfHk1.d.ts +10 -0
  27. package/dist/shared/server.D_vpYits.d.ts +18 -0
  28. package/dist/shared/server.Dwnm6cSk.d.mts +10 -0
  29. package/package.json +24 -40
  30. package/dist/chunk-2OH4QMZ4.js +0 -145
  31. package/dist/chunk-BFGSRNYZ.js +0 -319
  32. package/dist/chunk-EDQKEHUX.js +0 -377
  33. package/dist/chunk-XFBAK67J.js +0 -128
  34. package/dist/fetch.js +0 -16
  35. package/dist/hono.js +0 -40
  36. package/dist/next.js +0 -37
  37. package/dist/node.js +0 -170
  38. package/dist/plugins.js +0 -11
  39. package/dist/src/adapters/fetch/index.d.ts +0 -4
  40. package/dist/src/adapters/fetch/rpc-handler.d.ts +0 -10
  41. package/dist/src/adapters/fetch/types.d.ts +0 -13
  42. package/dist/src/adapters/fetch/utils.d.ts +0 -5
  43. package/dist/src/adapters/hono/index.d.ts +0 -3
  44. package/dist/src/adapters/hono/middleware.d.ts +0 -13
  45. package/dist/src/adapters/next/index.d.ts +0 -3
  46. package/dist/src/adapters/next/serve.d.ts +0 -20
  47. package/dist/src/adapters/node/index.d.ts +0 -4
  48. package/dist/src/adapters/node/rpc-handler.d.ts +0 -10
  49. package/dist/src/adapters/node/types.d.ts +0 -21
  50. package/dist/src/adapters/node/utils.d.ts +0 -5
  51. package/dist/src/adapters/standard/handler.d.ts +0 -51
  52. package/dist/src/adapters/standard/index.d.ts +0 -7
  53. package/dist/src/adapters/standard/rpc-codec.d.ts +0 -15
  54. package/dist/src/adapters/standard/rpc-handler.d.ts +0 -8
  55. package/dist/src/adapters/standard/rpc-matcher.d.ts +0 -10
  56. package/dist/src/adapters/standard/rpc-serializer.d.ts +0 -16
  57. package/dist/src/adapters/standard/types.d.ts +0 -44
  58. package/dist/src/builder-variants.d.ts +0 -74
  59. package/dist/src/builder.d.ts +0 -57
  60. package/dist/src/config.d.ts +0 -6
  61. package/dist/src/context.d.ts +0 -9
  62. package/dist/src/hidden.d.ts +0 -8
  63. package/dist/src/implementer-procedure.d.ts +0 -30
  64. package/dist/src/implementer-variants.d.ts +0 -17
  65. package/dist/src/implementer.d.ts +0 -28
  66. package/dist/src/index.d.ts +0 -23
  67. package/dist/src/lazy-utils.d.ts +0 -6
  68. package/dist/src/lazy.d.ts +0 -22
  69. package/dist/src/middleware-decorated.d.ts +0 -10
  70. package/dist/src/middleware-utils.d.ts +0 -5
  71. package/dist/src/middleware.d.ts +0 -37
  72. package/dist/src/plugins/base.d.ts +0 -13
  73. package/dist/src/plugins/cors.d.ts +0 -19
  74. package/dist/src/plugins/index.d.ts +0 -4
  75. package/dist/src/plugins/response-headers.d.ts +0 -10
  76. package/dist/src/procedure-client.d.ts +0 -31
  77. package/dist/src/procedure-decorated.d.ts +0 -21
  78. package/dist/src/procedure-utils.d.ts +0 -17
  79. package/dist/src/procedure.d.ts +0 -29
  80. package/dist/src/router-accessible-lazy.d.ts +0 -8
  81. package/dist/src/router-client.d.ts +0 -11
  82. package/dist/src/router.d.ts +0 -29
  83. package/dist/src/utils.d.ts +0 -24
  84. package/dist/standard.js +0 -17
@@ -0,0 +1,144 @@
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, 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
+ declare function validateORPCError(map: ErrorMap, error: ORPCError<any, any>): Promise<ORPCError<string, unknown>>;
17
+
18
+ declare const LAZY_SYMBOL: unique symbol;
19
+ interface LazyMeta {
20
+ prefix?: HTTPPath;
21
+ }
22
+ interface Lazy<T> {
23
+ [LAZY_SYMBOL]: {
24
+ loader: () => Promise<{
25
+ default: T;
26
+ }>;
27
+ meta: LazyMeta;
28
+ };
29
+ }
30
+ type Lazyable<T> = T | Lazy<T>;
31
+ declare function lazy<T>(loader: () => Promise<{
32
+ default: T;
33
+ }>, meta?: LazyMeta): Lazy<T>;
34
+ declare function isLazy(item: unknown): item is Lazy<any>;
35
+ declare function getLazyMeta(lazied: Lazy<any>): LazyMeta;
36
+ declare function unlazy<T extends Lazyable<any>>(lazied: T): Promise<{
37
+ default: T extends Lazy<infer U> ? U : T;
38
+ }>;
39
+
40
+ interface ProcedureHandlerOptions<TCurrentContext extends Context, TInput, TErrorConstructorMap extends ORPCErrorConstructorMap<any>, TMeta extends Meta> {
41
+ context: TCurrentContext;
42
+ input: TInput;
43
+ path: readonly string[];
44
+ procedure: Procedure<Context, Context, AnySchema, AnySchema, ErrorMap, TMeta>;
45
+ signal?: AbortSignal;
46
+ lastEventId: string | undefined;
47
+ errors: TErrorConstructorMap;
48
+ }
49
+ interface ProcedureHandler<TCurrentContext extends Context, TInput, THandlerOutput, TErrorMap extends ErrorMap, TMeta extends Meta> {
50
+ (opt: ProcedureHandlerOptions<TCurrentContext, TInput, ORPCErrorConstructorMap<TErrorMap>, TMeta>): Promisable<THandlerOutput>;
51
+ }
52
+ 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> {
53
+ __initialContext?: (type: TInitialContext) => unknown;
54
+ middlewares: readonly AnyMiddleware[];
55
+ inputValidationIndex: number;
56
+ outputValidationIndex: number;
57
+ handler: ProcedureHandler<TCurrentContext, any, any, any, any>;
58
+ }
59
+ declare class Procedure<TInitialContext extends Context, TCurrentContext extends Context, TInputSchema extends AnySchema, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap, TMeta extends Meta> {
60
+ '~orpc': ProcedureDef<TInitialContext, TCurrentContext, TInputSchema, TOutputSchema, TErrorMap, TMeta>;
61
+ constructor(def: ProcedureDef<TInitialContext, TCurrentContext, TInputSchema, TOutputSchema, TErrorMap, TMeta>);
62
+ }
63
+ type AnyProcedure = Procedure<any, any, any, any, any, any>;
64
+ declare function isProcedure(item: unknown): item is AnyProcedure;
65
+
66
+ type MiddlewareResult<TOutContext extends Context, TOutput> = Promisable<{
67
+ output: TOutput;
68
+ context: TOutContext;
69
+ }>;
70
+ type MiddlewareNextFnOptions<TOutContext extends Context> = Record<never, never> extends TOutContext ? {
71
+ context?: TOutContext;
72
+ } : {
73
+ context: TOutContext;
74
+ };
75
+ interface MiddlewareNextFn<TOutput> {
76
+ <U extends Context = Record<never, never>>(...rest: MaybeOptionalOptions<MiddlewareNextFnOptions<U>>): MiddlewareResult<U, TOutput>;
77
+ }
78
+ interface MiddlewareOutputFn<TOutput> {
79
+ (output: TOutput): MiddlewareResult<Record<never, never>, TOutput>;
80
+ }
81
+ interface MiddlewareOptions<TInContext extends Context, TOutput, TErrorConstructorMap extends ORPCErrorConstructorMap<any>, TMeta extends Meta> {
82
+ context: TInContext;
83
+ path: readonly string[];
84
+ procedure: Procedure<Context, Context, AnySchema, AnySchema, ErrorMap, TMeta>;
85
+ signal?: AbortSignal;
86
+ lastEventId: string | undefined;
87
+ next: MiddlewareNextFn<TOutput>;
88
+ errors: TErrorConstructorMap;
89
+ }
90
+ interface Middleware<TInContext extends Context, TOutContext extends Context, TInput, TOutput, TErrorConstructorMap extends ORPCErrorConstructorMap<any>, TMeta extends Meta> {
91
+ (options: MiddlewareOptions<TInContext, TOutput, TErrorConstructorMap, TMeta>, input: TInput, output: MiddlewareOutputFn<TOutput>): Promisable<MiddlewareResult<TOutContext, TOutput>>;
92
+ }
93
+ type AnyMiddleware = Middleware<any, any, any, any, any, any>;
94
+ interface MapInputMiddleware<TInput, TMappedInput> {
95
+ (input: TInput): TMappedInput;
96
+ }
97
+ declare function middlewareOutputFn<TOutput>(output: TOutput): MiddlewareResult<Record<never, never>, TOutput>;
98
+
99
+ type ProcedureClient<TClientContext extends ClientContext, TInputSchema extends AnySchema, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap> = Client<TClientContext, InferSchemaInput<TInputSchema>, InferSchemaOutput<TOutputSchema>, ErrorFromErrorMap<TErrorMap>>;
100
+ interface ProcedureClientInterceptorOptions<TInitialContext extends Context, TErrorMap extends ErrorMap, TMeta extends Meta> {
101
+ context: TInitialContext;
102
+ input: unknown;
103
+ errors: ORPCErrorConstructorMap<TErrorMap>;
104
+ path: readonly string[];
105
+ procedure: Procedure<Context, Context, AnySchema, AnySchema, ErrorMap, TMeta>;
106
+ signal?: AbortSignal;
107
+ lastEventId: string | undefined;
108
+ }
109
+ /**
110
+ * Options for creating a procedure caller with comprehensive type safety
111
+ */
112
+ type CreateProcedureClientOptions<TInitialContext extends Context, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap, TMeta extends Meta, TClientContext extends ClientContext> = {
113
+ /**
114
+ * This is helpful for logging and analytics.
115
+ */
116
+ path?: readonly string[];
117
+ interceptors?: Interceptor<ProcedureClientInterceptorOptions<TInitialContext, TErrorMap, TMeta>, InferSchemaOutput<TOutputSchema>, ErrorFromErrorMap<TErrorMap>>[];
118
+ } & (Record<never, never> extends TInitialContext ? {
119
+ context?: Value<TInitialContext, [clientContext: TClientContext]>;
120
+ } : {
121
+ context: Value<TInitialContext, [clientContext: TClientContext]>;
122
+ });
123
+ 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>>, ...[options]: MaybeOptionalOptions<CreateProcedureClientOptions<TInitialContext, TOutputSchema, TErrorMap, TMeta, TClientContext>>): ProcedureClient<TClientContext, TInputSchema, TOutputSchema, TErrorMap>;
124
+
125
+ 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> : {
126
+ [K in keyof T]: T[K] extends AnyContractRouter ? Lazyable<Router<T[K], TInitialContext>> : never;
127
+ };
128
+ type AnyRouter = Router<any, any>;
129
+ type InferRouterInitialContext<T extends AnyRouter> = T extends Router<any, infer UInitialContext> ? UInitialContext : never;
130
+ type InferRouterInitialContexts<T extends AnyRouter> = T extends Procedure<infer UInitialContext, any, any, any, any, any> ? UInitialContext : {
131
+ [K in keyof T]: T[K] extends Lazyable<infer U extends AnyRouter> ? InferRouterInitialContexts<U> : never;
132
+ };
133
+ type InferRouterCurrentContexts<T extends AnyRouter> = T extends Procedure<any, infer UCurrentContext, any, any, any, any> ? UCurrentContext : {
134
+ [K in keyof T]: T[K] extends Lazyable<infer U extends AnyRouter> ? InferRouterCurrentContexts<U> : never;
135
+ };
136
+ type InferRouterInputs<T extends AnyRouter> = T extends Procedure<any, any, infer UInputSchema, any, any, any> ? InferSchemaInput<UInputSchema> : {
137
+ [K in keyof T]: T[K] extends Lazyable<infer U extends AnyRouter> ? InferRouterInputs<U> : never;
138
+ };
139
+ type InferRouterOutputs<T extends AnyRouter> = T extends Procedure<any, any, any, infer UOutputSchema, any, any> ? InferSchemaOutput<UOutputSchema> : {
140
+ [K in keyof T]: T[K] extends Lazyable<infer U extends AnyRouter> ? InferRouterOutputs<U> : never;
141
+ };
142
+
143
+ export { isProcedure as E, createProcedureClient as G, Procedure as P, createORPCErrorConstructorMap as l, mergeCurrentContext as m, LAZY_SYMBOL as n, lazy as p, isLazy as q, getLazyMeta as r, unlazy as u, validateORPCError as v, middlewareOutputFn as z };
144
+ export type { AnyMiddleware as A, ProcedureHandlerOptions as B, Context as C, ProcedureDef as D, ProcedureClientInterceptorOptions as F, InferRouterInitialContexts as H, InferRouterInitialContext as I, InferRouterCurrentContexts as J, InferRouterInputs as K, Lazyable as L, Middleware as M, InferRouterOutputs as N, ORPCErrorConstructorMap as O, Router as R, MergedInitialContext as a, MergedCurrentContext as b, MapInputMiddleware as c, CreateProcedureClientOptions as d, ProcedureClient as e, AnyRouter as f, Lazy as g, AnyProcedure as h, ProcedureHandler as i, ORPCErrorConstructorMapItemOptions as j, ORPCErrorConstructorMapItem as k, LazyMeta as o, MiddlewareResult as s, MiddlewareNextFnOptions as t, MiddlewareNextFn as w, MiddlewareOutputFn as x, MiddlewareOptions as y };
@@ -0,0 +1,9 @@
1
+ function resolveFriendlyStandardHandleOptions(options) {
2
+ return {
3
+ ...options,
4
+ context: options?.context ?? {}
5
+ // Context only optional if all fields are optional
6
+ };
7
+ }
8
+
9
+ export { resolveFriendlyStandardHandleOptions as r };
@@ -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,18 @@
1
+ import { StandardRPCJsonSerializerOptions } from '@orpc/client/standard';
2
+ import { C as Context, R as Router } from './server.BVHsfJ99.mjs';
3
+ import { b as StandardHandlerOptions, i as StandardHandler } from './server.B1oIHH_j.mjs';
4
+
5
+ interface StandardRPCHandlerOptions<T extends Context> extends StandardHandlerOptions<T>, StandardRPCJsonSerializerOptions {
6
+ /**
7
+ * Enables or disables the StrictGetMethodPlugin.
8
+ *
9
+ * @default true
10
+ */
11
+ strictGetMethodPluginEnabled?: boolean;
12
+ }
13
+ declare class StandardRPCHandler<T extends Context> extends StandardHandler<T> {
14
+ constructor(router: Router<any, T>, options: StandardRPCHandlerOptions<T>);
15
+ }
16
+
17
+ export { StandardRPCHandler as a };
18
+ export type { StandardRPCHandlerOptions as S };
@@ -0,0 +1,364 @@
1
+ import { isContractProcedure, ValidationError, mergePrefix, mergeErrorMap, enhanceRoute } from '@orpc/contract';
2
+ import { fallbackORPCErrorStatus, ORPCError } from '@orpc/client';
3
+ import { value, intercept } from '@orpc/shared';
4
+
5
+ const LAZY_SYMBOL = Symbol("ORPC_LAZY_SYMBOL");
6
+ function lazy(loader, meta = {}) {
7
+ return {
8
+ [LAZY_SYMBOL]: {
9
+ loader,
10
+ meta
11
+ }
12
+ };
13
+ }
14
+ function isLazy(item) {
15
+ return (typeof item === "object" || typeof item === "function") && item !== null && LAZY_SYMBOL in item;
16
+ }
17
+ function getLazyMeta(lazied) {
18
+ return lazied[LAZY_SYMBOL].meta;
19
+ }
20
+ function unlazy(lazied) {
21
+ return isLazy(lazied) ? lazied[LAZY_SYMBOL].loader() : Promise.resolve({ default: lazied });
22
+ }
23
+
24
+ function isStartWithMiddlewares(middlewares, compare) {
25
+ if (compare.length > middlewares.length) {
26
+ return false;
27
+ }
28
+ for (let i = 0; i < middlewares.length; i++) {
29
+ if (compare[i] === void 0) {
30
+ return true;
31
+ }
32
+ if (middlewares[i] !== compare[i]) {
33
+ return false;
34
+ }
35
+ }
36
+ return true;
37
+ }
38
+ function mergeMiddlewares(first, second, options) {
39
+ if (options.dedupeLeading && isStartWithMiddlewares(second, first)) {
40
+ return second;
41
+ }
42
+ return [...first, ...second];
43
+ }
44
+ function addMiddleware(middlewares, addition) {
45
+ return [...middlewares, addition];
46
+ }
47
+
48
+ class Procedure {
49
+ "~orpc";
50
+ constructor(def) {
51
+ this["~orpc"] = def;
52
+ }
53
+ }
54
+ function isProcedure(item) {
55
+ if (item instanceof Procedure) {
56
+ return true;
57
+ }
58
+ return isContractProcedure(item) && "middlewares" in item["~orpc"] && "inputValidationIndex" in item["~orpc"] && "outputValidationIndex" in item["~orpc"] && "handler" in item["~orpc"];
59
+ }
60
+
61
+ function mergeCurrentContext(context, other) {
62
+ return { ...context, ...other };
63
+ }
64
+
65
+ function createORPCErrorConstructorMap(errors) {
66
+ const proxy = new Proxy(errors, {
67
+ get(target, code) {
68
+ if (typeof code !== "string") {
69
+ return Reflect.get(target, code);
70
+ }
71
+ const item = (...[options]) => {
72
+ const config = errors[code];
73
+ return new ORPCError(code, {
74
+ defined: Boolean(config),
75
+ status: config?.status,
76
+ message: options?.message ?? config?.message,
77
+ data: options?.data,
78
+ cause: options?.cause
79
+ });
80
+ };
81
+ return item;
82
+ }
83
+ });
84
+ return proxy;
85
+ }
86
+ async function validateORPCError(map, error) {
87
+ const { code, status, message, data, cause, defined } = error;
88
+ const config = map?.[error.code];
89
+ if (!config || fallbackORPCErrorStatus(error.code, config.status) !== error.status) {
90
+ return defined ? new ORPCError(code, { defined: false, status, message, data, cause }) : error;
91
+ }
92
+ if (!config.data) {
93
+ return defined ? error : new ORPCError(code, { defined: true, status, message, data, cause });
94
+ }
95
+ const validated = await config.data["~standard"].validate(error.data);
96
+ if (validated.issues) {
97
+ return defined ? new ORPCError(code, { defined: false, status, message, data, cause }) : error;
98
+ }
99
+ return new ORPCError(code, { defined: true, status, message, data: validated.value, cause });
100
+ }
101
+
102
+ function middlewareOutputFn(output) {
103
+ return { output, context: {} };
104
+ }
105
+
106
+ function createProcedureClient(lazyableProcedure, ...[options]) {
107
+ return async (...[input, callerOptions]) => {
108
+ const path = options?.path ?? [];
109
+ const { default: procedure } = await unlazy(lazyableProcedure);
110
+ const clientContext = callerOptions?.context ?? {};
111
+ const context = await value(options?.context ?? {}, clientContext);
112
+ const errors = createORPCErrorConstructorMap(procedure["~orpc"].errorMap);
113
+ try {
114
+ return await intercept(
115
+ options?.interceptors ?? [],
116
+ {
117
+ context,
118
+ input,
119
+ // input only optional when it undefinable so we can safely cast it
120
+ errors,
121
+ path,
122
+ procedure,
123
+ signal: callerOptions?.signal,
124
+ lastEventId: callerOptions?.lastEventId
125
+ },
126
+ (interceptorOptions) => executeProcedureInternal(interceptorOptions.procedure, interceptorOptions)
127
+ );
128
+ } catch (e) {
129
+ if (!(e instanceof ORPCError)) {
130
+ throw e;
131
+ }
132
+ const validated = await validateORPCError(procedure["~orpc"].errorMap, e);
133
+ throw validated;
134
+ }
135
+ };
136
+ }
137
+ async function validateInput(procedure, input) {
138
+ const schema = procedure["~orpc"].inputSchema;
139
+ if (!schema) {
140
+ return input;
141
+ }
142
+ const result = await schema["~standard"].validate(input);
143
+ if (result.issues) {
144
+ throw new ORPCError("BAD_REQUEST", {
145
+ message: "Input validation failed",
146
+ data: {
147
+ issues: result.issues
148
+ },
149
+ cause: new ValidationError({ message: "Input validation failed", issues: result.issues })
150
+ });
151
+ }
152
+ return result.value;
153
+ }
154
+ async function validateOutput(procedure, output) {
155
+ const schema = procedure["~orpc"].outputSchema;
156
+ if (!schema) {
157
+ return output;
158
+ }
159
+ const result = await schema["~standard"].validate(output);
160
+ if (result.issues) {
161
+ throw new ORPCError("INTERNAL_SERVER_ERROR", {
162
+ message: "Output validation failed",
163
+ cause: new ValidationError({ message: "Output validation failed", issues: result.issues })
164
+ });
165
+ }
166
+ return result.value;
167
+ }
168
+ async function executeProcedureInternal(procedure, options) {
169
+ const middlewares = procedure["~orpc"].middlewares;
170
+ const inputValidationIndex = Math.min(Math.max(0, procedure["~orpc"].inputValidationIndex), middlewares.length);
171
+ const outputValidationIndex = Math.min(Math.max(0, procedure["~orpc"].outputValidationIndex), middlewares.length);
172
+ const next = async (index, context, input) => {
173
+ let currentInput = input;
174
+ if (index === inputValidationIndex) {
175
+ currentInput = await validateInput(procedure, currentInput);
176
+ }
177
+ const mid = middlewares[index];
178
+ const output = mid ? (await mid({
179
+ ...options,
180
+ context,
181
+ next: async (...[nextOptions]) => {
182
+ const nextContext = nextOptions?.context ?? {};
183
+ return {
184
+ output: await next(index + 1, mergeCurrentContext(context, nextContext), currentInput),
185
+ context: nextContext
186
+ };
187
+ }
188
+ }, currentInput, middlewareOutputFn)).output : await procedure["~orpc"].handler({ ...options, context, input: currentInput });
189
+ if (index === outputValidationIndex) {
190
+ return await validateOutput(procedure, output);
191
+ }
192
+ return output;
193
+ };
194
+ return next(0, options.context, options.input);
195
+ }
196
+
197
+ const HIDDEN_ROUTER_CONTRACT_SYMBOL = Symbol("ORPC_HIDDEN_ROUTER_CONTRACT");
198
+ function setHiddenRouterContract(router, contract) {
199
+ return new Proxy(router, {
200
+ get(target, key) {
201
+ if (key === HIDDEN_ROUTER_CONTRACT_SYMBOL) {
202
+ return contract;
203
+ }
204
+ return Reflect.get(target, key);
205
+ }
206
+ });
207
+ }
208
+ function getHiddenRouterContract(router) {
209
+ return router[HIDDEN_ROUTER_CONTRACT_SYMBOL];
210
+ }
211
+
212
+ function getRouter(router, path) {
213
+ let current = router;
214
+ for (let i = 0; i < path.length; i++) {
215
+ const segment = path[i];
216
+ if (!current) {
217
+ return void 0;
218
+ }
219
+ if (isProcedure(current)) {
220
+ return void 0;
221
+ }
222
+ if (!isLazy(current)) {
223
+ current = current[segment];
224
+ continue;
225
+ }
226
+ const lazied = current;
227
+ const rest = path.slice(i);
228
+ return lazy(async () => {
229
+ const unwrapped = await unlazy(lazied);
230
+ const next = getRouter(unwrapped.default, rest);
231
+ return unlazy(next);
232
+ }, getLazyMeta(lazied));
233
+ }
234
+ return current;
235
+ }
236
+ function createAccessibleLazyRouter(lazied) {
237
+ const recursive = new Proxy(lazied, {
238
+ get(target, key) {
239
+ if (typeof key !== "string") {
240
+ return Reflect.get(target, key);
241
+ }
242
+ const next = getRouter(lazied, [key]);
243
+ return createAccessibleLazyRouter(next);
244
+ }
245
+ });
246
+ return recursive;
247
+ }
248
+ function enhanceRouter(router, options) {
249
+ if (isLazy(router)) {
250
+ const laziedMeta = getLazyMeta(router);
251
+ const enhancedPrefix = laziedMeta?.prefix ? mergePrefix(options.prefix, laziedMeta?.prefix) : options.prefix;
252
+ const enhanced2 = lazy(async () => {
253
+ const { default: unlaziedRouter } = await unlazy(router);
254
+ const enhanced3 = enhanceRouter(unlaziedRouter, options);
255
+ return unlazy(enhanced3);
256
+ }, {
257
+ ...laziedMeta,
258
+ prefix: enhancedPrefix
259
+ });
260
+ const accessible = createAccessibleLazyRouter(enhanced2);
261
+ return accessible;
262
+ }
263
+ if (isProcedure(router)) {
264
+ const newMiddlewares = mergeMiddlewares(options.middlewares, router["~orpc"].middlewares, { dedupeLeading: options.dedupeLeadingMiddlewares });
265
+ const newMiddlewareAdded = newMiddlewares.length - router["~orpc"].middlewares.length;
266
+ const enhanced2 = new Procedure({
267
+ ...router["~orpc"],
268
+ route: enhanceRoute(router["~orpc"].route, options),
269
+ errorMap: mergeErrorMap(options.errorMap, router["~orpc"].errorMap),
270
+ middlewares: newMiddlewares,
271
+ inputValidationIndex: router["~orpc"].inputValidationIndex + newMiddlewareAdded,
272
+ outputValidationIndex: router["~orpc"].outputValidationIndex + newMiddlewareAdded
273
+ });
274
+ return enhanced2;
275
+ }
276
+ const enhanced = {};
277
+ for (const key in router) {
278
+ enhanced[key] = enhanceRouter(router[key], options);
279
+ }
280
+ return enhanced;
281
+ }
282
+ function traverseContractProcedures(options, callback, lazyOptions = []) {
283
+ let currentRouter = options.router;
284
+ const hiddenContract = getHiddenRouterContract(options.router);
285
+ if (hiddenContract !== void 0) {
286
+ currentRouter = hiddenContract;
287
+ }
288
+ if (isLazy(currentRouter)) {
289
+ lazyOptions.push({
290
+ router: currentRouter,
291
+ path: options.path
292
+ });
293
+ } else if (isContractProcedure(currentRouter)) {
294
+ callback({
295
+ contract: currentRouter,
296
+ path: options.path
297
+ });
298
+ } else {
299
+ for (const key in currentRouter) {
300
+ traverseContractProcedures(
301
+ {
302
+ router: currentRouter[key],
303
+ path: [...options.path, key]
304
+ },
305
+ callback,
306
+ lazyOptions
307
+ );
308
+ }
309
+ }
310
+ return lazyOptions;
311
+ }
312
+ async function resolveContractProcedures(options, callback) {
313
+ const pending = [options];
314
+ for (const options2 of pending) {
315
+ const lazyOptions = traverseContractProcedures(options2, callback);
316
+ for (const options3 of lazyOptions) {
317
+ const { default: router } = await unlazy(options3.router);
318
+ pending.push({
319
+ router,
320
+ path: options3.path
321
+ });
322
+ }
323
+ }
324
+ }
325
+ async function unlazyRouter(router) {
326
+ if (isProcedure(router)) {
327
+ return router;
328
+ }
329
+ const unlazied = {};
330
+ for (const key in router) {
331
+ const item = router[key];
332
+ const { default: unlaziedRouter } = await unlazy(item);
333
+ unlazied[key] = await unlazyRouter(unlaziedRouter);
334
+ }
335
+ return unlazied;
336
+ }
337
+
338
+ function createAssertedLazyProcedure(lazied) {
339
+ const lazyProcedure = lazy(async () => {
340
+ const { default: maybeProcedure } = await unlazy(lazied);
341
+ if (!isProcedure(maybeProcedure)) {
342
+ throw new Error(`
343
+ Expected a lazy<procedure> but got lazy<unknown>.
344
+ This should be caught by TypeScript compilation.
345
+ Please report this issue if this makes you feel uncomfortable.
346
+ `);
347
+ }
348
+ return { default: maybeProcedure };
349
+ }, getLazyMeta(lazied));
350
+ return lazyProcedure;
351
+ }
352
+ function createContractedProcedure(procedure, contract) {
353
+ return new Procedure({
354
+ ...procedure["~orpc"],
355
+ errorMap: contract["~orpc"].errorMap,
356
+ route: contract["~orpc"].route,
357
+ meta: contract["~orpc"].meta
358
+ });
359
+ }
360
+ function call(procedure, input, ...rest) {
361
+ return createProcedureClient(procedure, ...rest)(input);
362
+ }
363
+
364
+ 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, validateORPCError as v, resolveContractProcedures as w, unlazyRouter as x };
@@ -0,0 +1,74 @@
1
+ import { HTTPPath, ORPCError } from '@orpc/client';
2
+ import { Meta, InferSchemaOutput, AnySchema, ErrorFromErrorMap } from '@orpc/contract';
3
+ import { Interceptor, ThrowableError } from '@orpc/shared';
4
+ import { StandardResponse, StandardLazyRequest } from '@orpc/standard-server';
5
+ import { C as Context, f as AnyRouter, h as AnyProcedure, F as ProcedureClientInterceptorOptions, R as Router } from './server.BVHsfJ99.js';
6
+
7
+ interface StandardHandlerPlugin<TContext extends Context> {
8
+ order?: number;
9
+ init?(options: StandardHandlerOptions<TContext>): void;
10
+ }
11
+ declare class CompositeStandardHandlerPlugin<T extends Context, TPlugin extends StandardHandlerPlugin<T>> implements StandardHandlerPlugin<T> {
12
+ protected readonly plugins: TPlugin[];
13
+ constructor(plugins?: readonly TPlugin[]);
14
+ init(options: StandardHandlerOptions<T>): void;
15
+ }
16
+
17
+ type StandardParams = Record<string, string>;
18
+ type StandardMatchResult = {
19
+ path: readonly string[];
20
+ procedure: AnyProcedure;
21
+ params?: StandardParams;
22
+ } | undefined;
23
+ interface StandardMatcher {
24
+ init(router: AnyRouter): void;
25
+ match(method: string, pathname: HTTPPath): Promise<StandardMatchResult>;
26
+ }
27
+ interface StandardCodec {
28
+ encode(output: unknown, procedure: AnyProcedure): StandardResponse;
29
+ encodeError(error: ORPCError<any, any>): StandardResponse;
30
+ decode(request: StandardLazyRequest, params: StandardParams | undefined, procedure: AnyProcedure): Promise<unknown>;
31
+ }
32
+
33
+ interface StandardHandleOptions<T extends Context> {
34
+ prefix?: HTTPPath;
35
+ context: T;
36
+ }
37
+ type StandardHandleResult = {
38
+ matched: true;
39
+ response: StandardResponse;
40
+ } | {
41
+ matched: false;
42
+ response: undefined;
43
+ };
44
+ interface StandardHandlerInterceptorOptions<T extends Context> extends StandardHandleOptions<T> {
45
+ request: StandardLazyRequest;
46
+ }
47
+ interface StandardHandlerOptions<TContext extends Context> {
48
+ plugins?: StandardHandlerPlugin<TContext>[];
49
+ /**
50
+ * Interceptors at the request level, helpful when you want catch errors
51
+ */
52
+ interceptors?: Interceptor<StandardHandlerInterceptorOptions<TContext>, StandardHandleResult, ThrowableError>[];
53
+ /**
54
+ * Interceptors at the root level, helpful when you want override the request/response
55
+ */
56
+ rootInterceptors?: Interceptor<StandardHandlerInterceptorOptions<TContext>, StandardHandleResult, ThrowableError>[];
57
+ /**
58
+ *
59
+ * Interceptors for procedure client.
60
+ */
61
+ clientInterceptors?: Interceptor<ProcedureClientInterceptorOptions<TContext, Record<never, never>, Meta>, InferSchemaOutput<AnySchema>, ErrorFromErrorMap<Record<never, never>>>[];
62
+ }
63
+ declare class StandardHandler<T extends Context> {
64
+ private readonly matcher;
65
+ private readonly codec;
66
+ private readonly interceptors;
67
+ private readonly clientInterceptors;
68
+ private readonly rootInterceptors;
69
+ constructor(router: Router<any, T>, matcher: StandardMatcher, codec: StandardCodec, options: NoInfer<StandardHandlerOptions<T>>);
70
+ handle(request: StandardLazyRequest, options: StandardHandleOptions<T>): Promise<StandardHandleResult>;
71
+ }
72
+
73
+ export { CompositeStandardHandlerPlugin as C, StandardHandler as i };
74
+ export type { StandardHandlerInterceptorOptions as S, StandardHandlerPlugin as a, StandardHandlerOptions as b, StandardCodec as c, StandardParams as d, StandardMatcher as e, StandardMatchResult as f, StandardHandleOptions as g, StandardHandleResult as h };