@orpc/server 0.0.0-next.93e6063 → 0.0.0-next.9486ab5

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 (43) hide show
  1. package/README.md +14 -1
  2. package/dist/adapters/fetch/index.d.mts +38 -11
  3. package/dist/adapters/fetch/index.d.ts +38 -11
  4. package/dist/adapters/fetch/index.mjs +6 -6
  5. package/dist/adapters/hono/index.d.mts +6 -4
  6. package/dist/adapters/hono/index.d.ts +6 -4
  7. package/dist/adapters/hono/index.mjs +6 -6
  8. package/dist/adapters/next/index.d.mts +6 -4
  9. package/dist/adapters/next/index.d.ts +6 -4
  10. package/dist/adapters/next/index.mjs +6 -6
  11. package/dist/adapters/node/index.d.mts +40 -22
  12. package/dist/adapters/node/index.d.ts +40 -22
  13. package/dist/adapters/node/index.mjs +77 -22
  14. package/dist/adapters/standard/index.d.mts +12 -15
  15. package/dist/adapters/standard/index.d.ts +12 -15
  16. package/dist/adapters/standard/index.mjs +2 -3
  17. package/dist/index.d.mts +156 -120
  18. package/dist/index.d.ts +156 -120
  19. package/dist/index.mjs +78 -48
  20. package/dist/plugins/index.d.mts +15 -16
  21. package/dist/plugins/index.d.ts +15 -16
  22. package/dist/plugins/index.mjs +10 -6
  23. package/dist/shared/server.89QkKw3a.d.mts +10 -0
  24. package/dist/shared/server.B1S3zwuw.d.mts +8 -0
  25. package/dist/shared/server.BMkFIQUb.d.mts +66 -0
  26. package/dist/shared/server.BT0gne12.d.ts +8 -0
  27. package/dist/shared/server.BVwwTHyO.mjs +9 -0
  28. package/dist/shared/{server.V6zT5iYQ.mjs → server.CjWkNG6l.mjs} +151 -160
  29. package/dist/shared/server.D0YVcfZk.d.mts +143 -0
  30. package/dist/shared/server.D0YVcfZk.d.ts +143 -0
  31. package/dist/shared/{server.BBGuTxHE.mjs → server.D9QduY95.mjs} +43 -45
  32. package/dist/shared/server.Et1O6Bm7.mjs +98 -0
  33. package/dist/shared/server.taqJyaMn.d.ts +10 -0
  34. package/dist/shared/server.ywWqDZgA.d.ts +66 -0
  35. package/package.json +8 -8
  36. package/dist/shared/server.B-ewprcf.d.ts +0 -77
  37. package/dist/shared/server.CA-o8cUY.d.mts +0 -9
  38. package/dist/shared/server.Cn9ybJtE.d.mts +0 -152
  39. package/dist/shared/server.Cn9ybJtE.d.ts +0 -152
  40. package/dist/shared/server.DJrh0Ceu.d.mts +0 -77
  41. package/dist/shared/server.DPQt9YYq.d.ts +0 -9
  42. package/dist/shared/server.KwueCzFr.mjs +0 -26
  43. package/dist/shared/server.Q6ZmnTgO.mjs +0 -12
@@ -0,0 +1,143 @@
1
+ import { ORPCErrorCode, ORPCErrorOptions, ORPCError, HTTPPath, ClientContext, Client } from '@orpc/client';
2
+ import { MaybeOptionalOptions, Promisable, Interceptor, Value } from '@orpc/shared';
3
+ import { ErrorMap, ErrorMapItem, InferSchemaInput, AnySchema, Meta, ContractProcedureDef, InferSchemaOutput, ErrorFromErrorMap, AnyContractRouter, ContractProcedure } from '@orpc/contract';
4
+
5
+ type Context = Record<string, 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, TInputSchema extends AnySchema, TErrorMap extends ErrorMap, TMeta extends Meta> {
101
+ context: TInitialContext;
102
+ input: InferSchemaInput<TInputSchema>;
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, TInputSchema extends AnySchema, 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, TInputSchema, 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, TInputSchema, 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 { type AnyProcedure as A, middlewareOutputFn as B, type Context as C, type ProcedureHandlerOptions as D, type ProcedureDef as E, isProcedure as F, createProcedureClient as G, type InferRouterInitialContexts as H, type InferRouterInitialContext as I, type InferRouterCurrentContexts as J, type InferRouterInputs as K, type Lazyable as L, type Middleware as M, type InferRouterOutputs as N, type ORPCErrorConstructorMap as O, type ProcedureClientInterceptorOptions as P, type Router as R, type AnyRouter as a, Procedure as b, type MergedInitialContext as c, type MergedCurrentContext as d, type MapInputMiddleware as e, type CreateProcedureClientOptions as f, type ProcedureClient as g, type AnyMiddleware as h, type Lazy as i, type ProcedureHandler as j, type ORPCErrorConstructorMapItemOptions as k, type ORPCErrorConstructorMapItem as l, mergeCurrentContext as m, createORPCErrorConstructorMap as n, LAZY_SYMBOL as o, type LazyMeta as p, lazy as q, isLazy as r, getLazyMeta as s, type MiddlewareResult as t, unlazy as u, validateORPCError as v, type MiddlewareNextFnOptions as w, type MiddlewareNextFn as x, type MiddlewareOutputFn as y, type MiddlewareOptions as z };
@@ -1,52 +1,54 @@
1
1
  import { ORPCError, toORPCError } from '@orpc/client';
2
- import { intercept, trim, parseEmptyableJSON } from '@orpc/shared';
3
- import { C as CompositePlugin } from './server.Q6ZmnTgO.mjs';
4
- import { c as createProcedureClient, e as eachContractProcedure, a as convertPathToHttpPath, i as isProcedure, u as unlazy, g as getRouterChild, b as createContractedProcedure } from './server.V6zT5iYQ.mjs';
5
- import { RPCSerializer } from '@orpc/client/standard';
2
+ import { toArray, intercept, parseEmptyableJSON } from '@orpc/shared';
3
+ import { c as createProcedureClient, t as traverseContractProcedures, i as isProcedure, u as unlazy, g as getRouter, a as createContractedProcedure } from './server.CjWkNG6l.mjs';
4
+ import { toHttpPath } from '@orpc/client/standard';
6
5
 
7
6
  class StandardHandler {
8
- constructor(router, matcher, codec, options = {}) {
7
+ constructor(router, matcher, codec, options) {
9
8
  this.matcher = matcher;
10
9
  this.codec = codec;
11
- this.options = options;
12
- this.plugin = new CompositePlugin(options.plugins);
13
- this.plugin.init(this.options);
10
+ for (const plugin of toArray(options.plugins)) {
11
+ plugin.init?.(options);
12
+ }
13
+ this.interceptors = toArray(options.interceptors);
14
+ this.clientInterceptors = toArray(options.clientInterceptors);
15
+ this.rootInterceptors = toArray(options.rootInterceptors);
14
16
  this.matcher.init(router);
15
17
  }
16
- plugin;
17
- handle(request, ...[options]) {
18
+ interceptors;
19
+ clientInterceptors;
20
+ rootInterceptors;
21
+ handle(request, options) {
18
22
  return intercept(
19
- this.options.rootInterceptors ?? [],
20
- {
21
- request,
22
- ...options,
23
- context: options?.context ?? {}
24
- // context is optional only when all fields are optional so we can safely force it to have a context
25
- },
23
+ this.rootInterceptors,
24
+ { ...options, request },
26
25
  async (interceptorOptions) => {
27
26
  let isDecoding = false;
28
27
  try {
29
28
  return await intercept(
30
- this.options.interceptors ?? [],
29
+ this.interceptors,
31
30
  interceptorOptions,
32
- async (interceptorOptions2) => {
33
- const method = interceptorOptions2.request.method;
34
- const url = interceptorOptions2.request.url;
35
- const pathname = `/${trim(url.pathname.replace(interceptorOptions2.prefix ?? "", ""), "/")}`;
36
- const match = await this.matcher.match(method, pathname);
31
+ async ({ request: request2, context, prefix }) => {
32
+ const method = request2.method;
33
+ const url = request2.url;
34
+ if (prefix && !url.pathname.startsWith(prefix)) {
35
+ return { matched: false, response: void 0 };
36
+ }
37
+ const pathname = prefix ? url.pathname.replace(prefix, "") : url.pathname;
38
+ const match = await this.matcher.match(method, `/${pathname.replace(/^\/|\/$/g, "")}`);
37
39
  if (!match) {
38
40
  return { matched: false, response: void 0 };
39
41
  }
40
42
  const client = createProcedureClient(match.procedure, {
41
- context: interceptorOptions2.context,
43
+ context,
42
44
  path: match.path,
43
- interceptors: this.options.clientInterceptors
45
+ interceptors: this.clientInterceptors
44
46
  });
45
47
  isDecoding = true;
46
- const input = await this.codec.decode(request, match.params, match.procedure);
48
+ const input = await this.codec.decode(request2, match.params, match.procedure);
47
49
  isDecoding = false;
48
- const lastEventId = Array.isArray(request.headers["last-event-id"]) ? request.headers["last-event-id"].at(-1) : request.headers["last-event-id"];
49
- const output = await client(input, { signal: request.signal, lastEventId });
50
+ const lastEventId = Array.isArray(request2.headers["last-event-id"]) ? request2.headers["last-event-id"].at(-1) : request2.headers["last-event-id"];
51
+ const output = await client(input, { signal: request2.signal, lastEventId });
50
52
  const response = this.codec.encode(output, match.procedure);
51
53
  return {
52
54
  matched: true,
@@ -55,7 +57,7 @@ class StandardHandler {
55
57
  }
56
58
  );
57
59
  } catch (e) {
58
- const error = isDecoding ? new ORPCError("BAD_REQUEST", {
60
+ const error = isDecoding && !(e instanceof ORPCError) ? new ORPCError("BAD_REQUEST", {
59
61
  message: `Malformed request. Ensure the request body is properly formatted and the 'Content-Type' header is set correctly.`,
60
62
  cause: e
61
63
  }) : toORPCError(e);
@@ -70,10 +72,9 @@ class StandardHandler {
70
72
  }
71
73
  }
72
74
 
73
- class RPCCodec {
74
- serializer;
75
- constructor(options = {}) {
76
- this.serializer = options.serializer ?? new RPCSerializer();
75
+ class StandardRPCCodec {
76
+ constructor(serializer) {
77
+ this.serializer = serializer;
77
78
  }
78
79
  async decode(request, _params, _procedure) {
79
80
  const serialized = request.method === "GET" ? parseEmptyableJSON(request.url.searchParams.getAll("data").at(-1)) : await request.body();
@@ -95,15 +96,12 @@ class RPCCodec {
95
96
  }
96
97
  }
97
98
 
98
- class RPCMatcher {
99
+ class StandardRPCMatcher {
99
100
  tree = {};
100
101
  pendingRouters = [];
101
102
  init(router, path = []) {
102
- const laziedOptions = eachContractProcedure({
103
- router,
104
- path
105
- }, ({ path: path2, contract }) => {
106
- const httpPath = convertPathToHttpPath(path2);
103
+ const laziedOptions = traverseContractProcedures({ router, path }, ({ path: path2, contract }) => {
104
+ const httpPath = toHttpPath(path2);
107
105
  if (isProcedure(contract)) {
108
106
  this.tree[httpPath] = {
109
107
  path: path2,
@@ -123,7 +121,7 @@ class RPCMatcher {
123
121
  });
124
122
  this.pendingRouters.push(...laziedOptions.map((option) => ({
125
123
  ...option,
126
- httpPathPrefix: convertPathToHttpPath(option.path)
124
+ httpPathPrefix: toHttpPath(option.path)
127
125
  })));
128
126
  }
129
127
  async match(_method, pathname) {
@@ -131,7 +129,7 @@ class RPCMatcher {
131
129
  const newPendingRouters = [];
132
130
  for (const pendingRouter of this.pendingRouters) {
133
131
  if (pathname.startsWith(pendingRouter.httpPathPrefix)) {
134
- const { default: router } = await unlazy(pendingRouter.lazied);
132
+ const { default: router } = await unlazy(pendingRouter.router);
135
133
  this.init(router, pendingRouter.path);
136
134
  } else {
137
135
  newPendingRouters.push(pendingRouter);
@@ -144,14 +142,14 @@ class RPCMatcher {
144
142
  return void 0;
145
143
  }
146
144
  if (!match.procedure) {
147
- const { default: maybeProcedure } = await unlazy(getRouterChild(match.router, ...match.path));
145
+ const { default: maybeProcedure } = await unlazy(getRouter(match.router, match.path));
148
146
  if (!isProcedure(maybeProcedure)) {
149
147
  throw new Error(`
150
- [Contract-First] Missing or invalid implementation for procedure at path: ${convertPathToHttpPath(match.path)}.
148
+ [Contract-First] Missing or invalid implementation for procedure at path: ${toHttpPath(match.path)}.
151
149
  Ensure that the procedure is correctly defined and matches the expected contract.
152
150
  `);
153
151
  }
154
- match.procedure = createContractedProcedure(match.contract, maybeProcedure);
152
+ match.procedure = createContractedProcedure(maybeProcedure, match.contract);
155
153
  }
156
154
  return {
157
155
  path: match.path,
@@ -160,4 +158,4 @@ class RPCMatcher {
160
158
  }
161
159
  }
162
160
 
163
- export { RPCCodec as R, StandardHandler as S, RPCMatcher as a };
161
+ export { StandardHandler as S, StandardRPCCodec as a, StandardRPCMatcher as b };
@@ -0,0 +1,98 @@
1
+ import { ORPCError } from '@orpc/client';
2
+ import { StandardRPCJsonSerializer, StandardRPCSerializer } from '@orpc/client/standard';
3
+ import { S as StandardHandler, b as StandardRPCMatcher, a as StandardRPCCodec } from './server.D9QduY95.mjs';
4
+ import { toArray, intercept, resolveMaybeOptionalOptions } from '@orpc/shared';
5
+ import { toStandardLazyRequest, toFetchResponse } from '@orpc/standard-server-fetch';
6
+ import { r as resolveFriendlyStandardHandleOptions } from './server.BVwwTHyO.mjs';
7
+
8
+ class BodyLimitPlugin {
9
+ maxBodySize;
10
+ constructor(options) {
11
+ this.maxBodySize = options.maxBodySize;
12
+ }
13
+ initRuntimeAdapter(options) {
14
+ options.adapterInterceptors ??= [];
15
+ options.adapterInterceptors.push(async (options2) => {
16
+ if (!options2.request.body) {
17
+ return options2.next();
18
+ }
19
+ let currentBodySize = 0;
20
+ const rawReader = options2.request.body.getReader();
21
+ const reader = new ReadableStream({
22
+ start: async (controller) => {
23
+ try {
24
+ if (Number(options2.request.headers.get("content-length")) > this.maxBodySize) {
25
+ controller.error(new ORPCError("PAYLOAD_TOO_LARGE"));
26
+ return;
27
+ }
28
+ while (true) {
29
+ const { done, value } = await rawReader.read();
30
+ if (done) {
31
+ break;
32
+ }
33
+ currentBodySize += value.length;
34
+ if (currentBodySize > this.maxBodySize) {
35
+ controller.error(new ORPCError("PAYLOAD_TOO_LARGE"));
36
+ break;
37
+ }
38
+ controller.enqueue(value);
39
+ }
40
+ } finally {
41
+ controller.close();
42
+ }
43
+ }
44
+ });
45
+ const requestInit = { body: reader, duplex: "half" };
46
+ return options2.next({
47
+ ...options2,
48
+ request: new Request(options2.request, requestInit)
49
+ });
50
+ });
51
+ }
52
+ }
53
+
54
+ class FetchHandler {
55
+ constructor(standardHandler, options = {}) {
56
+ this.standardHandler = standardHandler;
57
+ for (const plugin of toArray(options.plugins)) {
58
+ plugin.initRuntimeAdapter?.(options);
59
+ }
60
+ this.adapterInterceptors = toArray(options.adapterInterceptors);
61
+ this.toFetchResponseOptions = options;
62
+ }
63
+ toFetchResponseOptions;
64
+ adapterInterceptors;
65
+ async handle(request, ...rest) {
66
+ return intercept(
67
+ this.adapterInterceptors,
68
+ {
69
+ ...resolveFriendlyStandardHandleOptions(resolveMaybeOptionalOptions(rest)),
70
+ request,
71
+ toFetchResponseOptions: this.toFetchResponseOptions
72
+ },
73
+ async ({ request: request2, toFetchResponseOptions, ...options }) => {
74
+ const standardRequest = toStandardLazyRequest(request2);
75
+ const result = await this.standardHandler.handle(standardRequest, options);
76
+ if (!result.matched) {
77
+ return result;
78
+ }
79
+ return {
80
+ matched: true,
81
+ response: toFetchResponse(result.response, toFetchResponseOptions)
82
+ };
83
+ }
84
+ );
85
+ }
86
+ }
87
+
88
+ class RPCHandler extends FetchHandler {
89
+ constructor(router, options = {}) {
90
+ const jsonSerializer = new StandardRPCJsonSerializer(options);
91
+ const serializer = new StandardRPCSerializer(jsonSerializer);
92
+ const matcher = new StandardRPCMatcher();
93
+ const codec = new StandardRPCCodec(serializer);
94
+ super(new StandardHandler(router, matcher, codec, options), options);
95
+ }
96
+ }
97
+
98
+ export { BodyLimitPlugin as B, FetchHandler as F, RPCHandler as R };
@@ -0,0 +1,10 @@
1
+ import { C as Context } from './server.D0YVcfZk.js';
2
+ import { S as StandardHandleOptions } from './server.ywWqDZgA.js';
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
+
10
+ export type { FriendlyStandardHandleOptions as F };
@@ -0,0 +1,66 @@
1
+ import { HTTPPath, ORPCError } from '@orpc/client';
2
+ import { AnySchema, Meta, InferSchemaOutput, ErrorFromErrorMap } from '@orpc/contract';
3
+ import { Interceptor } from '@orpc/shared';
4
+ import { StandardResponse, StandardLazyRequest } from '@orpc/standard-server';
5
+ import { a as AnyRouter, A as AnyProcedure, C as Context, P as ProcedureClientInterceptorOptions, R as Router } from './server.D0YVcfZk.js';
6
+
7
+ type StandardParams = Record<string, string>;
8
+ type StandardMatchResult = {
9
+ path: readonly string[];
10
+ procedure: AnyProcedure;
11
+ params?: StandardParams;
12
+ } | undefined;
13
+ interface StandardMatcher {
14
+ init(router: AnyRouter): void;
15
+ match(method: string, pathname: HTTPPath): Promise<StandardMatchResult>;
16
+ }
17
+ interface StandardCodec {
18
+ encode(output: unknown, procedure: AnyProcedure): StandardResponse;
19
+ encodeError(error: ORPCError<any, any>): StandardResponse;
20
+ decode(request: StandardLazyRequest, params: StandardParams | undefined, procedure: AnyProcedure): Promise<unknown>;
21
+ }
22
+
23
+ interface StandardHandleOptions<T extends Context> {
24
+ prefix?: HTTPPath;
25
+ context: T;
26
+ }
27
+ type StandardHandleResult = {
28
+ matched: true;
29
+ response: StandardResponse;
30
+ } | {
31
+ matched: false;
32
+ response: undefined;
33
+ };
34
+ interface StandardHandlerPlugin<TContext extends Context> {
35
+ init?(options: StandardHandlerOptions<TContext>): void;
36
+ }
37
+ interface StandardHandlerInterceptorOptions<T extends Context> extends StandardHandleOptions<T> {
38
+ request: StandardLazyRequest;
39
+ }
40
+ interface StandardHandlerOptions<TContext extends Context> {
41
+ plugins?: StandardHandlerPlugin<TContext>[];
42
+ /**
43
+ * Interceptors at the request level, helpful when you want catch errors
44
+ */
45
+ interceptors?: Interceptor<StandardHandlerInterceptorOptions<TContext>, StandardHandleResult, unknown>[];
46
+ /**
47
+ * Interceptors at the root level, helpful when you want override the request/response
48
+ */
49
+ rootInterceptors?: Interceptor<StandardHandlerInterceptorOptions<TContext>, StandardHandleResult, unknown>[];
50
+ /**
51
+ *
52
+ * Interceptors for procedure client.
53
+ */
54
+ clientInterceptors?: Interceptor<ProcedureClientInterceptorOptions<TContext, AnySchema, Record<never, never>, Meta>, InferSchemaOutput<AnySchema>, ErrorFromErrorMap<Record<never, never>>>[];
55
+ }
56
+ declare class StandardHandler<T extends Context> {
57
+ private readonly matcher;
58
+ private readonly codec;
59
+ private readonly interceptors;
60
+ private readonly clientInterceptors;
61
+ private readonly rootInterceptors;
62
+ constructor(router: Router<any, T>, matcher: StandardMatcher, codec: StandardCodec, options: NoInfer<StandardHandlerOptions<T>>);
63
+ handle(request: StandardLazyRequest, options: StandardHandleOptions<T>): Promise<StandardHandleResult>;
64
+ }
65
+
66
+ export { type StandardHandleOptions as S, type StandardHandlerOptions as a, type StandardHandlerInterceptorOptions as b, type StandardHandlerPlugin as c, type StandardCodec as d, type StandardParams as e, type StandardMatcher as f, type StandardMatchResult as g, type StandardHandleResult as h, StandardHandler as i };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@orpc/server",
3
3
  "type": "module",
4
- "version": "0.0.0-next.93e6063",
4
+ "version": "0.0.0-next.9486ab5",
5
5
  "license": "MIT",
6
6
  "homepage": "https://orpc.unnoq.com",
7
7
  "repository": {
@@ -58,15 +58,15 @@
58
58
  "next": ">=14.0.0"
59
59
  },
60
60
  "dependencies": {
61
- "@orpc/client": "0.0.0-next.93e6063",
62
- "@orpc/contract": "0.0.0-next.93e6063",
63
- "@orpc/shared": "0.0.0-next.93e6063",
64
- "@orpc/standard-server": "0.0.0-next.93e6063",
65
- "@orpc/standard-server-fetch": "0.0.0-next.93e6063",
66
- "@orpc/standard-server-node": "0.0.0-next.93e6063"
61
+ "@orpc/client": "0.0.0-next.9486ab5",
62
+ "@orpc/contract": "0.0.0-next.9486ab5",
63
+ "@orpc/shared": "0.0.0-next.9486ab5",
64
+ "@orpc/standard-server": "0.0.0-next.9486ab5",
65
+ "@orpc/standard-server-node": "0.0.0-next.9486ab5",
66
+ "@orpc/standard-server-fetch": "0.0.0-next.9486ab5"
67
67
  },
68
68
  "devDependencies": {
69
- "light-my-request": "^6.5.1"
69
+ "supertest": "^7.0.0"
70
70
  },
71
71
  "scripts": {
72
72
  "build": "unbuild",
@@ -1,77 +0,0 @@
1
- import { HTTPPath, Schema, Meta, SchemaOutput, ErrorFromErrorMap } from '@orpc/contract';
2
- import { Interceptor, MaybeOptionalOptions } from '@orpc/shared';
3
- import { StandardResponse, StandardLazyRequest } from '@orpc/standard-server';
4
- import { a as AnyRouter, A as AnyProcedure, C as Context, P as ProcedureClientInterceptorOptions, R as Router } from './server.Cn9ybJtE.js';
5
- import { ORPCError } from '@orpc/client';
6
-
7
- type StandardParams = Record<string, string>;
8
- type StandardMatchResult = {
9
- path: string[];
10
- procedure: AnyProcedure;
11
- params?: StandardParams;
12
- } | undefined;
13
- interface StandardMatcher {
14
- init(router: AnyRouter): void;
15
- match(method: string, pathname: HTTPPath): Promise<StandardMatchResult>;
16
- }
17
- interface StandardCodec {
18
- encode(output: unknown, procedure: AnyProcedure): StandardResponse;
19
- encodeError(error: ORPCError<any, any>): StandardResponse;
20
- decode(request: StandardLazyRequest, params: StandardParams | undefined, procedure: AnyProcedure): Promise<unknown>;
21
- }
22
-
23
- type StandardHandleOptions<T extends Context> = {
24
- prefix?: HTTPPath;
25
- } & (Record<never, never> extends T ? {
26
- context?: T;
27
- } : {
28
- context: T;
29
- });
30
- type WellStandardHandleOptions<T extends Context> = StandardHandleOptions<T> & {
31
- context: T;
32
- };
33
- type StandardHandleResult = {
34
- matched: true;
35
- response: StandardResponse;
36
- } | {
37
- matched: false;
38
- response: undefined;
39
- };
40
- type StandardHandlerInterceptorOptions<TContext extends Context> = WellStandardHandleOptions<TContext> & {
41
- request: StandardLazyRequest;
42
- };
43
- interface StandardHandlerOptions<TContext extends Context> {
44
- plugins?: Plugin<TContext>[];
45
- /**
46
- * Interceptors at the request level, helpful when you want catch errors
47
- */
48
- interceptors?: Interceptor<StandardHandlerInterceptorOptions<TContext>, StandardHandleResult, unknown>[];
49
- /**
50
- * Interceptors at the root level, helpful when you want override the request/response
51
- */
52
- rootInterceptors?: Interceptor<StandardHandlerInterceptorOptions<TContext>, StandardHandleResult, unknown>[];
53
- /**
54
- *
55
- * Interceptors for procedure client.
56
- */
57
- clientInterceptors?: Interceptor<ProcedureClientInterceptorOptions<TContext, Schema, Record<never, never>, Meta>, SchemaOutput<Schema, unknown>, ErrorFromErrorMap<Record<never, never>>>[];
58
- }
59
- declare class StandardHandler<T extends Context> {
60
- private readonly matcher;
61
- private readonly codec;
62
- private readonly options;
63
- private readonly plugin;
64
- constructor(router: Router<T, any>, matcher: StandardMatcher, codec: StandardCodec, options?: NoInfer<StandardHandlerOptions<T>>);
65
- handle(request: StandardLazyRequest, ...[options]: MaybeOptionalOptions<StandardHandleOptions<T>>): Promise<StandardHandleResult>;
66
- }
67
-
68
- interface Plugin<TContext extends Context> {
69
- init?(options: StandardHandlerOptions<TContext>): void;
70
- }
71
- declare class CompositePlugin<TContext extends Context> implements Plugin<TContext> {
72
- private readonly plugins;
73
- constructor(plugins?: Plugin<TContext>[]);
74
- init(options: StandardHandlerOptions<TContext>): void;
75
- }
76
-
77
- export { CompositePlugin as C, type Plugin as P, type StandardHandleOptions as S, type WellStandardHandleOptions as W, type StandardHandlerOptions as a, type StandardMatcher as b, type StandardCodec as c, type StandardHandlerInterceptorOptions as d, type StandardParams as e, type StandardMatchResult as f, type StandardHandleResult as g, StandardHandler as h };
@@ -1,9 +0,0 @@
1
- import { C as Context } from './server.Cn9ybJtE.mjs';
2
- import { a as StandardHandlerOptions, b as StandardMatcher, c as StandardCodec } from './server.DJrh0Ceu.mjs';
3
-
4
- interface RPCHandlerOptions<T extends Context> extends StandardHandlerOptions<T> {
5
- matcher?: StandardMatcher;
6
- codec?: StandardCodec;
7
- }
8
-
9
- export type { RPCHandlerOptions as R };