@orpc/server 0.0.0-next.caefe3a → 0.0.0-next.cc4cb21

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 (47) hide show
  1. package/README.md +118 -0
  2. package/dist/chunk-EWOWWNDI.js +182 -0
  3. package/dist/{chunk-OEPDHGQ4.js → chunk-MHVECKBC.js} +60 -17
  4. package/dist/{chunk-OWMUECGT.js → chunk-TXHKQO7N.js} +20 -11
  5. package/dist/chunk-XT6IYOIS.js +32 -0
  6. package/dist/fetch.js +6 -14
  7. package/dist/hono.js +7 -15
  8. package/dist/index.js +16 -7
  9. package/dist/next.js +6 -14
  10. package/dist/node.js +7 -151
  11. package/dist/plugins.js +1 -1
  12. package/dist/src/adapters/fetch/index.d.ts +0 -1
  13. package/dist/src/adapters/fetch/rpc-handler.d.ts +3 -2
  14. package/dist/src/adapters/fetch/types.d.ts +3 -2
  15. package/dist/src/adapters/hono/middleware.d.ts +2 -3
  16. package/dist/src/adapters/next/serve.d.ts +2 -3
  17. package/dist/src/adapters/node/index.d.ts +0 -1
  18. package/dist/src/adapters/node/rpc-handler.d.ts +3 -2
  19. package/dist/src/adapters/node/types.d.ts +3 -2
  20. package/dist/src/adapters/standard/handler.d.ts +15 -9
  21. package/dist/src/adapters/standard/index.d.ts +0 -1
  22. package/dist/src/adapters/standard/rpc-codec.d.ts +4 -3
  23. package/dist/src/adapters/standard/types.d.ts +3 -26
  24. package/dist/src/builder-variants.d.ts +2 -1
  25. package/dist/src/builder.d.ts +2 -1
  26. package/dist/src/context.d.ts +0 -1
  27. package/dist/src/error.d.ts +12 -0
  28. package/dist/src/implementer-procedure.d.ts +7 -4
  29. package/dist/src/implementer-variants.d.ts +2 -1
  30. package/dist/src/implementer.d.ts +2 -1
  31. package/dist/src/index.d.ts +3 -1
  32. package/dist/src/middleware-decorated.d.ts +2 -1
  33. package/dist/src/middleware.d.ts +5 -4
  34. package/dist/src/plugins/cors.d.ts +2 -1
  35. package/dist/src/procedure-client.d.ts +8 -6
  36. package/dist/src/procedure-decorated.d.ts +7 -4
  37. package/dist/src/procedure-utils.d.ts +5 -3
  38. package/dist/src/procedure.d.ts +5 -3
  39. package/dist/src/router-client.d.ts +6 -4
  40. package/dist/src/router.d.ts +1 -0
  41. package/dist/standard.js +5 -9
  42. package/package.json +7 -4
  43. package/dist/chunk-M65OCXNG.js +0 -136
  44. package/dist/chunk-PZ44ZPVC.js +0 -308
  45. package/dist/src/adapters/fetch/utils.d.ts +0 -6
  46. package/dist/src/adapters/node/utils.d.ts +0 -5
  47. package/dist/src/adapters/standard/rpc-serializer.d.ts +0 -16
@@ -1,7 +1,10 @@
1
- import type { ClientRest, ErrorMap, MergedErrorMap, Meta, ORPCErrorConstructorMap, Route, Schema, SchemaInput, SchemaOutput } from '@orpc/contract';
1
+ import type { ClientContext, ClientRest } from '@orpc/client';
2
+ import type { ErrorMap, MergedErrorMap, Meta, Route, Schema, SchemaInput, SchemaOutput } from '@orpc/contract';
3
+ import type { MaybeOptionalOptions } from '@orpc/shared';
2
4
  import type { ConflictContextGuard, Context, MergedContext } from './context';
5
+ import type { ORPCErrorConstructorMap } from './error';
3
6
  import type { MapInputMiddleware, Middleware } from './middleware';
4
- import type { CreateProcedureClientRest, ProcedureClient } from './procedure-client';
7
+ import type { CreateProcedureClientOptions, ProcedureClient } from './procedure-client';
5
8
  import { Procedure } from './procedure';
6
9
  export declare class DecoratedProcedure<TInitialContext extends Context, TCurrentContext extends Context, TInputSchema extends Schema, TOutputSchema extends Schema, THandlerOutput extends SchemaInput<TOutputSchema>, TErrorMap extends ErrorMap, TMeta extends Meta> extends Procedure<TInitialContext, TCurrentContext, TInputSchema, TOutputSchema, THandlerOutput, TErrorMap, TMeta> {
7
10
  errors<U extends ErrorMap>(errors: U): DecoratedProcedure<TInitialContext, TCurrentContext, TInputSchema, TOutputSchema, THandlerOutput, MergedErrorMap<TErrorMap, U>, TMeta>;
@@ -12,10 +15,10 @@ export declare class DecoratedProcedure<TInitialContext extends Context, TCurren
12
15
  /**
13
16
  * Make this procedure callable (works like a function while still being a procedure).
14
17
  */
15
- callable<TClientContext>(...rest: CreateProcedureClientRest<TInitialContext, TInputSchema, TOutputSchema, THandlerOutput, TErrorMap, TMeta, TClientContext>): Procedure<TInitialContext, TCurrentContext, TInputSchema, TOutputSchema, THandlerOutput, TErrorMap, TMeta> & ProcedureClient<TClientContext, TInputSchema, TOutputSchema, THandlerOutput, TErrorMap>;
18
+ callable<TClientContext extends ClientContext>(...rest: MaybeOptionalOptions<CreateProcedureClientOptions<TInitialContext, TInputSchema, TOutputSchema, THandlerOutput, TErrorMap, TMeta, TClientContext>>): Procedure<TInitialContext, TCurrentContext, TInputSchema, TOutputSchema, THandlerOutput, TErrorMap, TMeta> & ProcedureClient<TClientContext, TInputSchema, TOutputSchema, THandlerOutput, TErrorMap>;
16
19
  /**
17
20
  * Make this procedure compatible with server action (the same as .callable, but the type is compatible with server action).
18
21
  */
19
- actionable<TClientContext>(...rest: CreateProcedureClientRest<TInitialContext, TInputSchema, TOutputSchema, THandlerOutput, TErrorMap, TMeta, TClientContext>): Procedure<TInitialContext, TCurrentContext, TInputSchema, TOutputSchema, THandlerOutput, TErrorMap, TMeta> & ((...rest: ClientRest<TClientContext, SchemaInput<TInputSchema>>) => Promise<SchemaOutput<TOutputSchema, THandlerOutput>>);
22
+ actionable<TClientContext extends ClientContext>(...rest: MaybeOptionalOptions<CreateProcedureClientOptions<TInitialContext, TInputSchema, TOutputSchema, THandlerOutput, TErrorMap, TMeta, TClientContext>>): Procedure<TInitialContext, TCurrentContext, TInputSchema, TOutputSchema, THandlerOutput, TErrorMap, TMeta> & ((...rest: ClientRest<TClientContext, SchemaInput<TInputSchema>>) => Promise<SchemaOutput<TOutputSchema, THandlerOutput>>);
20
23
  }
21
24
  //# sourceMappingURL=procedure-decorated.d.ts.map
@@ -1,8 +1,10 @@
1
- import type { ClientPromiseResult, ErrorFromErrorMap, ErrorMap, Meta, Schema, SchemaInput, SchemaOutput } from '@orpc/contract';
1
+ import type { ClientPromiseResult } from '@orpc/client';
2
+ import type { ErrorFromErrorMap, ErrorMap, Meta, Schema, SchemaInput, SchemaOutput } from '@orpc/contract';
3
+ import type { MaybeOptionalOptions } from '@orpc/shared';
2
4
  import type { Context } from './context';
3
5
  import type { Lazyable } from './lazy';
4
6
  import type { Procedure } from './procedure';
5
- import { type CreateProcedureClientRest } from './procedure-client';
7
+ import type { CreateProcedureClientOptions } from './procedure-client';
6
8
  /**
7
9
  * Directly call a procedure without creating a client.
8
10
  *
@@ -13,5 +15,5 @@ import { type CreateProcedureClientRest } from './procedure-client';
13
15
  * ```
14
16
  *
15
17
  */
16
- export declare function call<TInitialContext extends Context, TInputSchema extends Schema, TOutputSchema extends Schema, THandlerOutput extends SchemaInput<TOutputSchema>, TErrorMap extends ErrorMap, TMeta extends Meta>(procedure: Lazyable<Procedure<TInitialContext, any, TInputSchema, TOutputSchema, THandlerOutput, TErrorMap, TMeta>>, input: SchemaInput<TInputSchema>, ...rest: CreateProcedureClientRest<TInitialContext, TInputSchema, TOutputSchema, THandlerOutput, TErrorMap, TMeta, unknown>): ClientPromiseResult<SchemaOutput<TOutputSchema, THandlerOutput>, ErrorFromErrorMap<TErrorMap>>;
18
+ export declare function call<TInitialContext extends Context, TInputSchema extends Schema, TOutputSchema extends Schema, THandlerOutput extends SchemaInput<TOutputSchema>, TErrorMap extends ErrorMap, TMeta extends Meta>(procedure: Lazyable<Procedure<TInitialContext, any, TInputSchema, TOutputSchema, THandlerOutput, TErrorMap, TMeta>>, input: SchemaInput<TInputSchema>, ...rest: MaybeOptionalOptions<CreateProcedureClientOptions<TInitialContext, TInputSchema, TOutputSchema, THandlerOutput, TErrorMap, TMeta, Record<never, never>>>): ClientPromiseResult<SchemaOutput<TOutputSchema, THandlerOutput>, ErrorFromErrorMap<TErrorMap>>;
17
19
  //# sourceMappingURL=procedure-utils.d.ts.map
@@ -1,6 +1,7 @@
1
- import type { AbortSignal, ContractProcedureDef, ErrorMap, Meta, ORPCErrorConstructorMap, Schema, SchemaInput, SchemaOutput } from '@orpc/contract';
1
+ import type { ContractProcedureDef, ErrorMap, Meta, Schema, SchemaInput, SchemaOutput } from '@orpc/contract';
2
2
  import type { Promisable } from '@orpc/shared';
3
- import type { Context, TypeInitialContext } from './context';
3
+ import type { Context } from './context';
4
+ import type { ORPCErrorConstructorMap } from './error';
4
5
  import type { AnyMiddleware } from './middleware';
5
6
  export interface ProcedureHandlerOptions<TCurrentContext extends Context, TInput, TErrorConstructorMap extends ORPCErrorConstructorMap<any>, TMeta extends Meta> {
6
7
  context: TCurrentContext;
@@ -8,13 +9,14 @@ export interface ProcedureHandlerOptions<TCurrentContext extends Context, TInput
8
9
  path: string[];
9
10
  procedure: Procedure<Context, Context, Schema, Schema, unknown, ErrorMap, TMeta>;
10
11
  signal?: AbortSignal;
12
+ lastEventId: string | undefined;
11
13
  errors: TErrorConstructorMap;
12
14
  }
13
15
  export interface ProcedureHandler<TCurrentContext extends Context, TInputSchema extends Schema, TOutputSchema extends Schema, THandlerOutput extends SchemaInput<TOutputSchema>, TErrorMap extends ErrorMap, TMeta extends Meta> {
14
16
  (opt: ProcedureHandlerOptions<TCurrentContext, SchemaOutput<TInputSchema>, ORPCErrorConstructorMap<TErrorMap>, TMeta>): Promisable<SchemaInput<TOutputSchema, THandlerOutput>>;
15
17
  }
16
18
  export interface ProcedureDef<TInitialContext extends Context, TCurrentContext extends Context, TInputSchema extends Schema, TOutputSchema extends Schema, THandlerOutput extends SchemaInput<TOutputSchema>, TErrorMap extends ErrorMap, TMeta extends Meta> extends ContractProcedureDef<TInputSchema, TOutputSchema, TErrorMap, TMeta> {
17
- __initialContext?: TypeInitialContext<TInitialContext>;
19
+ __initialContext?: (type: TInitialContext) => unknown;
18
20
  middlewares: AnyMiddleware[];
19
21
  inputValidationIndex: number;
20
22
  outputValidationIndex: number;
@@ -1,10 +1,12 @@
1
+ import type { ClientContext } from '@orpc/client';
1
2
  import type { ErrorMap, Meta } from '@orpc/contract';
3
+ import type { MaybeOptionalOptions } from '@orpc/shared';
2
4
  import type { Lazy } from './lazy';
3
5
  import type { Procedure } from './procedure';
4
- import type { CreateProcedureClientRest, ProcedureClient } from './procedure-client';
5
- import type { AnyRouter, Router } from './router';
6
- export type RouterClient<TRouter extends AnyRouter, TClientContext> = TRouter extends Lazy<infer U extends AnyRouter> ? RouterClient<U, TClientContext> : TRouter extends Procedure<any, any, infer UInputSchema, infer UOutputSchema, infer UFuncOutput, infer UErrorMap, any> ? ProcedureClient<TClientContext, UInputSchema, UOutputSchema, UFuncOutput, UErrorMap> : {
6
+ import type { CreateProcedureClientOptions, ProcedureClient } from './procedure-client';
7
+ import type { AnyRouter, InferRouterInitialContext } from './router';
8
+ export type RouterClient<TRouter extends AnyRouter, TClientContext extends ClientContext = Record<never, never>> = TRouter extends Lazy<infer U extends AnyRouter> ? RouterClient<U, TClientContext> : TRouter extends Procedure<any, any, infer UInputSchema, infer UOutputSchema, infer UFuncOutput, infer UErrorMap, any> ? ProcedureClient<TClientContext, UInputSchema, UOutputSchema, UFuncOutput, UErrorMap> : {
7
9
  [K in keyof TRouter]: TRouter[K] extends AnyRouter ? RouterClient<TRouter[K], TClientContext> : never;
8
10
  };
9
- export declare function createRouterClient<TRouter extends AnyRouter, TClientContext>(router: TRouter | Lazy<undefined>, ...rest: CreateProcedureClientRest<TRouter extends Router<infer UContext, any> ? UContext : never, undefined, undefined, unknown, ErrorMap, Meta, TClientContext>): RouterClient<TRouter, TClientContext>;
11
+ export declare function createRouterClient<TRouter extends AnyRouter, TClientContext extends ClientContext>(router: TRouter | Lazy<undefined>, ...rest: MaybeOptionalOptions<CreateProcedureClientOptions<InferRouterInitialContext<TRouter>, undefined, undefined, unknown, ErrorMap, Meta, TClientContext>>): RouterClient<TRouter, TClientContext>;
10
12
  //# sourceMappingURL=router-client.d.ts.map
@@ -9,6 +9,7 @@ export type Router<TInitialContext extends Context, TContract extends AnyContrac
9
9
  [K in keyof TContract]: TContract[K] extends AnyContractRouter ? Router<TInitialContext, TContract[K]> : never;
10
10
  }>;
11
11
  export type AnyRouter = Router<any, any>;
12
+ export type InferRouterInitialContext<T extends AnyRouter> = T extends Router<infer UInitialContext, any> ? UInitialContext : never;
12
13
  export type InferRouterInputs<T extends AnyRouter> = T extends Lazy<infer U extends AnyRouter> ? InferRouterInputs<U> : T extends Procedure<any, any, infer UInputSchema, any, any, any, any> ? SchemaInput<UInputSchema> : {
13
14
  [K in keyof T]: T[K] extends AnyRouter ? InferRouterInputs<T[K]> : never;
14
15
  };
package/dist/standard.js CHANGED
@@ -1,17 +1,13 @@
1
1
  import {
2
2
  RPCCodec,
3
3
  RPCMatcher,
4
- RPCSerializer,
5
- StandardHandler,
6
- serializeRPCJson
7
- } from "./chunk-PZ44ZPVC.js";
8
- import "./chunk-OEPDHGQ4.js";
9
- import "./chunk-OWMUECGT.js";
4
+ StandardHandler
5
+ } from "./chunk-EWOWWNDI.js";
6
+ import "./chunk-MHVECKBC.js";
7
+ import "./chunk-TXHKQO7N.js";
10
8
  export {
11
9
  RPCCodec,
12
10
  RPCMatcher,
13
- RPCSerializer,
14
- StandardHandler,
15
- serializeRPCJson
11
+ StandardHandler
16
12
  };
17
13
  //# sourceMappingURL=standard.js.map
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.caefe3a",
4
+ "version": "0.0.0-next.cc4cb21",
5
5
  "license": "MIT",
6
6
  "homepage": "https://orpc.unnoq.com",
7
7
  "repository": {
@@ -63,9 +63,12 @@
63
63
  "next": ">=14.0.0"
64
64
  },
65
65
  "dependencies": {
66
- "content-disposition": "^0.5.4",
67
- "@orpc/shared": "0.0.0-next.caefe3a",
68
- "@orpc/contract": "0.0.0-next.caefe3a"
66
+ "@orpc/contract": "0.0.0-next.cc4cb21",
67
+ "@orpc/shared": "0.0.0-next.cc4cb21",
68
+ "@orpc/standard-server": "0.0.0-next.cc4cb21",
69
+ "@orpc/client": "0.0.0-next.cc4cb21",
70
+ "@orpc/standard-server-node": "0.0.0-next.cc4cb21",
71
+ "@orpc/standard-server-fetch": "0.0.0-next.cc4cb21"
69
72
  },
70
73
  "devDependencies": {
71
74
  "light-my-request": "^6.5.1"
@@ -1,136 +0,0 @@
1
- import {
2
- RPCCodec,
3
- RPCMatcher,
4
- StandardHandler
5
- } from "./chunk-PZ44ZPVC.js";
6
-
7
- // src/adapters/fetch/utils.ts
8
- import { once } from "@orpc/shared";
9
- import cd from "content-disposition";
10
- function fetchHeadersToStandardHeaders(headers) {
11
- const standardHeaders = {};
12
- for (const [key, value] of headers) {
13
- if (Array.isArray(standardHeaders[key])) {
14
- standardHeaders[key].push(value);
15
- } else if (standardHeaders[key] !== void 0) {
16
- standardHeaders[key] = [standardHeaders[key], value];
17
- } else {
18
- standardHeaders[key] = value;
19
- }
20
- }
21
- return standardHeaders;
22
- }
23
- async function fetchReToStandardBody(re) {
24
- if (!re.body) {
25
- return void 0;
26
- }
27
- const contentDisposition = re.headers.get("content-disposition");
28
- const fileName = contentDisposition ? cd.parse(contentDisposition).parameters.filename : void 0;
29
- if (fileName) {
30
- const blob2 = await re.blob();
31
- return new File([blob2], fileName, {
32
- type: blob2.type
33
- });
34
- }
35
- const contentType = re.headers.get("content-type");
36
- if (!contentType || contentType.startsWith("application/json")) {
37
- const text = await re.text();
38
- if (!text) {
39
- return void 0;
40
- }
41
- return JSON.parse(text);
42
- }
43
- if (contentType.startsWith("multipart/form-data")) {
44
- return await re.formData();
45
- }
46
- if (contentType.startsWith("application/x-www-form-urlencoded")) {
47
- return new URLSearchParams(await re.text());
48
- }
49
- if (contentType.startsWith("text/")) {
50
- return await re.text();
51
- }
52
- const blob = await re.blob();
53
- return new File([blob], "blob", {
54
- type: blob.type
55
- });
56
- }
57
- function fetchRequestToStandardRequest(request) {
58
- const url = new URL(request.url);
59
- return {
60
- raw: { request },
61
- url,
62
- signal: request.signal,
63
- method: request.method,
64
- body: once(() => {
65
- return fetchReToStandardBody(request);
66
- }),
67
- get headers() {
68
- const headers = fetchHeadersToStandardHeaders(request.headers);
69
- Object.defineProperty(this, "headers", { value: headers, writable: true });
70
- return headers;
71
- },
72
- set headers(value) {
73
- Object.defineProperty(this, "headers", { value, writable: true });
74
- }
75
- };
76
- }
77
- function standardResponseToFetchHeaders(response) {
78
- const fetchHeaders = new Headers();
79
- for (const [key, value] of Object.entries(response.headers)) {
80
- if (Array.isArray(value)) {
81
- for (const v of value) {
82
- fetchHeaders.append(key, v);
83
- }
84
- } else if (value !== void 0) {
85
- fetchHeaders.append(key, value);
86
- }
87
- }
88
- if (response.body instanceof Blob && !fetchHeaders.has("content-disposition")) {
89
- fetchHeaders.set("content-disposition", cd(response.body instanceof File ? response.body.name : "blob"));
90
- } else if (!(response.body instanceof Blob) && !(response.body instanceof URLSearchParams) && !(response.body instanceof FormData) && response.body !== void 0 && !fetchHeaders.has("content-type")) {
91
- fetchHeaders.set("content-type", "application/json");
92
- }
93
- return fetchHeaders;
94
- }
95
- function standardBodyToFetchBody(body) {
96
- if (body instanceof Blob || body instanceof FormData || body instanceof URLSearchParams) {
97
- return body;
98
- }
99
- return JSON.stringify(body);
100
- }
101
- function standardResponseToFetchResponse(response) {
102
- return new Response(standardBodyToFetchBody(response.body), {
103
- headers: standardResponseToFetchHeaders(response),
104
- status: response.status
105
- });
106
- }
107
-
108
- // src/adapters/fetch/rpc-handler.ts
109
- var RPCHandler = class {
110
- standardHandler;
111
- constructor(router, options) {
112
- const matcher = options?.matcher ?? new RPCMatcher();
113
- const codec = options?.codec ?? new RPCCodec();
114
- this.standardHandler = new StandardHandler(router, matcher, codec, options);
115
- }
116
- async handle(request, ...rest) {
117
- const standardRequest = fetchRequestToStandardRequest(request);
118
- const result = await this.standardHandler.handle(standardRequest, ...rest);
119
- if (!result.matched) {
120
- return result;
121
- }
122
- return {
123
- matched: true,
124
- response: standardResponseToFetchResponse(result.response)
125
- };
126
- }
127
- };
128
-
129
- export {
130
- fetchReToStandardBody,
131
- fetchRequestToStandardRequest,
132
- standardBodyToFetchBody,
133
- standardResponseToFetchResponse,
134
- RPCHandler
135
- };
136
- //# sourceMappingURL=chunk-M65OCXNG.js.map
@@ -1,308 +0,0 @@
1
- import {
2
- convertPathToHttpPath,
3
- createContractedProcedure,
4
- createProcedureClient,
5
- eachContractProcedure,
6
- getRouterChild,
7
- isProcedure,
8
- unlazy
9
- } from "./chunk-OEPDHGQ4.js";
10
- import {
11
- CompositePlugin
12
- } from "./chunk-OWMUECGT.js";
13
-
14
- // src/adapters/standard/handler.ts
15
- import { toORPCError } from "@orpc/contract";
16
- import { intercept, trim } from "@orpc/shared";
17
- var StandardHandler = class {
18
- constructor(router, matcher, codec, options = {}) {
19
- this.matcher = matcher;
20
- this.codec = codec;
21
- this.options = options;
22
- this.plugin = new CompositePlugin(options?.plugins);
23
- this.plugin.init(this.options);
24
- this.matcher.init(router);
25
- }
26
- plugin;
27
- handle(request, ...[options]) {
28
- const handleOptions = options ?? {};
29
- handleOptions.context ??= {};
30
- return intercept(
31
- this.options.interceptorsRoot ?? [],
32
- { request, ...handleOptions },
33
- async (interceptorRootOptions) => {
34
- try {
35
- return await intercept(
36
- this.options.interceptors ?? [],
37
- interceptorRootOptions,
38
- async ({ request: request2, context }) => {
39
- const method = request2.method;
40
- const url = request2.url;
41
- const pathname = `/${trim(url.pathname.replace(options?.prefix ?? "", ""), "/")}`;
42
- const match = await this.matcher.match(method, pathname);
43
- if (!match) {
44
- return { matched: false, response: void 0 };
45
- }
46
- const client = createProcedureClient(match.procedure, {
47
- context,
48
- path: match.path
49
- });
50
- const input = await this.codec.decode(request2, match.params, match.procedure);
51
- const output = await client(input, { signal: request2.signal });
52
- const response = this.codec.encode(output, match.procedure);
53
- return {
54
- matched: true,
55
- response
56
- };
57
- }
58
- );
59
- } catch (e) {
60
- const error = toORPCError(e);
61
- const response = this.codec.encodeError(error);
62
- return {
63
- matched: true,
64
- response
65
- };
66
- }
67
- }
68
- );
69
- }
70
- };
71
-
72
- // src/adapters/standard/rpc-serializer.ts
73
- import { findDeepMatches, isPlainObject, set } from "@orpc/shared";
74
- var RPCSerializer = class {
75
- serialize(data) {
76
- if (data instanceof Blob) {
77
- return data;
78
- }
79
- const serializedJSON = serializeRPCJson(data);
80
- const { maps, values: blobs } = findDeepMatches((v) => v instanceof Blob, serializedJSON.json);
81
- if (blobs.length === 0) {
82
- return serializedJSON;
83
- }
84
- const form = new FormData();
85
- form.set("data", JSON.stringify(serializedJSON));
86
- form.set("maps", JSON.stringify(maps));
87
- for (const i in blobs) {
88
- form.set(i, blobs[i]);
89
- }
90
- return form;
91
- }
92
- deserialize(serialized) {
93
- if (serialized instanceof Blob) {
94
- return serialized;
95
- }
96
- if (!(serialized instanceof FormData)) {
97
- return deserializeRPCJson(serialized);
98
- }
99
- const data = JSON.parse(serialized.get("data"));
100
- const maps = JSON.parse(serialized.get("maps"));
101
- for (const i in maps) {
102
- data.json = set(data.json, maps[i], serialized.get(i));
103
- }
104
- return deserializeRPCJson(data);
105
- }
106
- };
107
- function serializeRPCJson(value, segments = [], meta = []) {
108
- if (typeof value === "bigint") {
109
- meta.push(["bigint", segments]);
110
- return { json: value.toString(), meta };
111
- }
112
- if (value instanceof Date) {
113
- meta.push(["date", segments]);
114
- const data = Number.isNaN(value.getTime()) ? "Invalid Date" : value.toISOString();
115
- return { json: data, meta };
116
- }
117
- if (Number.isNaN(value)) {
118
- meta.push(["nan", segments]);
119
- return { json: "NaN", meta };
120
- }
121
- if (value instanceof RegExp) {
122
- meta.push(["regexp", segments]);
123
- return { json: value.toString(), meta };
124
- }
125
- if (value instanceof URL) {
126
- meta.push(["url", segments]);
127
- return { json: value.toString(), meta };
128
- }
129
- if (isPlainObject(value)) {
130
- const json = {};
131
- for (const k in value) {
132
- json[k] = serializeRPCJson(value[k], [...segments, k], meta).json;
133
- }
134
- return { json, meta };
135
- }
136
- if (Array.isArray(value)) {
137
- const json = value.map((v, i) => {
138
- if (v === void 0) {
139
- meta.push(["undefined", [...segments, i]]);
140
- return null;
141
- }
142
- return serializeRPCJson(v, [...segments, i], meta).json;
143
- });
144
- return { json, meta };
145
- }
146
- if (value instanceof Set) {
147
- const result = serializeRPCJson(Array.from(value), segments, meta);
148
- meta.push(["set", segments]);
149
- return result;
150
- }
151
- if (value instanceof Map) {
152
- const result = serializeRPCJson(Array.from(value.entries()), segments, meta);
153
- meta.push(["map", segments]);
154
- return result;
155
- }
156
- return { json: value, meta };
157
- }
158
- function deserializeRPCJson({
159
- json,
160
- meta
161
- }) {
162
- if (meta.length === 0) {
163
- return json;
164
- }
165
- const ref = { data: json };
166
- for (const [type, segments] of meta) {
167
- let currentRef = ref;
168
- let preSegment = "data";
169
- for (let i = 0; i < segments.length; i++) {
170
- currentRef = currentRef[preSegment];
171
- preSegment = segments[i];
172
- }
173
- switch (type) {
174
- case "nan":
175
- currentRef[preSegment] = Number.NaN;
176
- break;
177
- case "bigint":
178
- currentRef[preSegment] = BigInt(currentRef[preSegment]);
179
- break;
180
- case "date":
181
- currentRef[preSegment] = new Date(currentRef[preSegment]);
182
- break;
183
- case "regexp": {
184
- const [, pattern, flags] = currentRef[preSegment].match(/^\/(.*)\/([a-z]*)$/);
185
- currentRef[preSegment] = new RegExp(pattern, flags);
186
- break;
187
- }
188
- case "url":
189
- currentRef[preSegment] = new URL(currentRef[preSegment]);
190
- break;
191
- case "undefined":
192
- currentRef[preSegment] = void 0;
193
- break;
194
- case "map":
195
- currentRef[preSegment] = new Map(currentRef[preSegment]);
196
- break;
197
- case "set":
198
- currentRef[preSegment] = new Set(currentRef[preSegment]);
199
- break;
200
- /* v8 ignore next 3 */
201
- default: {
202
- const _expected = type;
203
- }
204
- }
205
- }
206
- return ref.data;
207
- }
208
-
209
- // src/adapters/standard/rpc-codec.ts
210
- var RPCCodec = class {
211
- serializer;
212
- constructor(options = {}) {
213
- this.serializer = options.serializer ?? new RPCSerializer();
214
- }
215
- async decode(request, _params, _procedure) {
216
- const serialized = request.method === "GET" ? JSON.parse(request.url.searchParams.getAll("data").at(-1)) : await request.body();
217
- return this.serializer.deserialize(serialized);
218
- }
219
- encode(output, _procedure) {
220
- return {
221
- status: 200,
222
- headers: {},
223
- body: this.serializer.serialize(output)
224
- };
225
- }
226
- encodeError(error) {
227
- return {
228
- status: error.status,
229
- headers: {},
230
- body: this.serializer.serialize(error.toJSON())
231
- };
232
- }
233
- };
234
-
235
- // src/adapters/standard/rpc-matcher.ts
236
- var RPCMatcher = class {
237
- tree = {};
238
- pendingRouters = [];
239
- init(router, path = []) {
240
- const laziedOptions = eachContractProcedure({
241
- router,
242
- path
243
- }, ({ path: path2, contract }) => {
244
- const httpPath = convertPathToHttpPath(path2);
245
- if (isProcedure(contract)) {
246
- this.tree[httpPath] = {
247
- path: path2,
248
- contract,
249
- procedure: contract,
250
- // this mean dev not used contract-first so we can used contract as procedure directly
251
- router
252
- };
253
- } else {
254
- this.tree[httpPath] = {
255
- path: path2,
256
- contract,
257
- procedure: void 0,
258
- router
259
- };
260
- }
261
- });
262
- this.pendingRouters.push(...laziedOptions.map((option) => ({
263
- ...option,
264
- httpPathPrefix: convertPathToHttpPath(option.path)
265
- })));
266
- }
267
- async match(_method, pathname) {
268
- if (this.pendingRouters.length) {
269
- const newPendingRouters = [];
270
- for (const pendingRouter of this.pendingRouters) {
271
- if (pathname.startsWith(pendingRouter.httpPathPrefix)) {
272
- const { default: router } = await unlazy(pendingRouter.lazied);
273
- this.init(router, pendingRouter.path);
274
- } else {
275
- newPendingRouters.push(pendingRouter);
276
- }
277
- }
278
- this.pendingRouters = newPendingRouters;
279
- }
280
- const match = this.tree[pathname];
281
- if (!match) {
282
- return void 0;
283
- }
284
- if (!match.procedure) {
285
- const { default: maybeProcedure } = await unlazy(getRouterChild(match.router, ...match.path));
286
- if (!isProcedure(maybeProcedure)) {
287
- throw new Error(`
288
- [Contract-First] Missing or invalid implementation for procedure at path: ${convertPathToHttpPath(match.path)}.
289
- Ensure that the procedure is correctly defined and matches the expected contract.
290
- `);
291
- }
292
- match.procedure = createContractedProcedure(match.contract, maybeProcedure);
293
- }
294
- return {
295
- path: match.path,
296
- procedure: match.procedure
297
- };
298
- }
299
- };
300
-
301
- export {
302
- StandardHandler,
303
- RPCSerializer,
304
- serializeRPCJson,
305
- RPCCodec,
306
- RPCMatcher
307
- };
308
- //# sourceMappingURL=chunk-PZ44ZPVC.js.map
@@ -1,6 +0,0 @@
1
- import type { StandardBody, StandardRequest, StandardResponse } from '../standard';
2
- export declare function fetchReToStandardBody(re: Request | Response): Promise<StandardBody>;
3
- export declare function fetchRequestToStandardRequest(request: Request): StandardRequest;
4
- export declare function standardBodyToFetchBody(body: StandardBody): Blob | FormData | URLSearchParams | string | undefined;
5
- export declare function standardResponseToFetchResponse(response: StandardResponse): Response;
6
- //# sourceMappingURL=utils.d.ts.map
@@ -1,5 +0,0 @@
1
- import type { StandardRequest, StandardResponse } from '../standard';
2
- import type { NodeHttpRequest, NodeHttpResponse } from './types';
3
- export declare function nodeHttpToStandardRequest(req: NodeHttpRequest, res: NodeHttpResponse): StandardRequest;
4
- export declare function nodeHttpResponseSendStandardResponse(res: NodeHttpResponse, standardResponse: StandardResponse): Promise<void>;
5
- //# sourceMappingURL=utils.d.ts.map
@@ -1,16 +0,0 @@
1
- import type { Segment } from '@orpc/shared';
2
- export type RPCSerializedJsonMeta = ['bigint' | 'date' | 'nan' | 'undefined' | 'set' | 'map' | 'regexp' | 'url', Segment[]][];
3
- export type RPCSerialized = {
4
- json: unknown;
5
- meta: RPCSerializedJsonMeta;
6
- } | FormData | Blob;
7
- export type RPCSerializedFormDataMaps = Segment[][];
8
- export declare class RPCSerializer {
9
- serialize(data: unknown): RPCSerialized;
10
- deserialize(serialized: RPCSerialized): unknown;
11
- }
12
- export declare function serializeRPCJson(value: unknown, segments?: Segment[], meta?: RPCSerializedJsonMeta): {
13
- json: unknown;
14
- meta: RPCSerializedJsonMeta;
15
- };
16
- //# sourceMappingURL=rpc-serializer.d.ts.map