@orpc/server 0.17.0 → 0.18.0
Sign up to get free protection for your applications and to get access to all the features.
- package/dist/fetch.js +252 -78
- package/dist/src/fetch/composite-handler.d.ts +8 -0
- package/dist/src/fetch/index.d.ts +3 -1
- package/dist/src/fetch/orpc-handler.d.ts +19 -2
- package/dist/src/fetch/orpc-payload-codec.d.ts +9 -0
- package/dist/src/fetch/orpc-procedure-matcher.d.ts +12 -0
- package/dist/src/fetch/super-json.d.ts +12 -0
- package/dist/src/fetch/types.d.ts +11 -23
- package/package.json +3 -7
- package/dist/src/fetch/handle-request.d.ts +0 -7
package/dist/fetch.js
CHANGED
@@ -5,108 +5,282 @@ import {
|
|
5
5
|
unlazy
|
6
6
|
} from "./chunk-FN62GL22.js";
|
7
7
|
|
8
|
-
// src/fetch/
|
8
|
+
// src/fetch/composite-handler.ts
|
9
|
+
var CompositeHandler = class {
|
10
|
+
constructor(handlers) {
|
11
|
+
this.handlers = handlers;
|
12
|
+
}
|
13
|
+
async fetch(request, ...opt) {
|
14
|
+
for (const handler of this.handlers) {
|
15
|
+
if (handler.condition(request)) {
|
16
|
+
return handler.fetch(request, ...opt);
|
17
|
+
}
|
18
|
+
}
|
19
|
+
return new Response("None of the handlers can handle the request.", {
|
20
|
+
status: 404
|
21
|
+
});
|
22
|
+
}
|
23
|
+
};
|
24
|
+
|
25
|
+
// src/fetch/orpc-handler.ts
|
26
|
+
import { executeWithHooks, ORPC_HANDLER_HEADER, ORPC_HANDLER_VALUE, trim as trim2 } from "@orpc/shared";
|
27
|
+
import { ORPCError as ORPCError2 } from "@orpc/shared/error";
|
28
|
+
|
29
|
+
// src/fetch/orpc-payload-codec.ts
|
30
|
+
import { findDeepMatches, set } from "@orpc/shared";
|
9
31
|
import { ORPCError } from "@orpc/shared/error";
|
10
|
-
|
11
|
-
|
12
|
-
|
13
|
-
|
14
|
-
|
32
|
+
|
33
|
+
// ../../node_modules/.pnpm/is-what@5.0.2/node_modules/is-what/dist/getType.js
|
34
|
+
function getType(payload) {
|
35
|
+
return Object.prototype.toString.call(payload).slice(8, -1);
|
36
|
+
}
|
37
|
+
|
38
|
+
// ../../node_modules/.pnpm/is-what@5.0.2/node_modules/is-what/dist/isPlainObject.js
|
39
|
+
function isPlainObject(payload) {
|
40
|
+
if (getType(payload) !== "Object")
|
41
|
+
return false;
|
42
|
+
const prototype = Object.getPrototypeOf(payload);
|
43
|
+
return !!prototype && prototype.constructor === Object && prototype === Object.prototype;
|
44
|
+
}
|
45
|
+
|
46
|
+
// src/fetch/super-json.ts
|
47
|
+
function serialize(value, segments = [], meta = []) {
|
48
|
+
if (typeof value === "bigint") {
|
49
|
+
meta.push(["bigint", segments]);
|
50
|
+
return { data: value.toString(), meta };
|
51
|
+
}
|
52
|
+
if (value instanceof Date) {
|
53
|
+
meta.push(["date", segments]);
|
54
|
+
const data = Number.isNaN(value.getTime()) ? "Invalid Date" : value.toISOString();
|
55
|
+
return { data, meta };
|
56
|
+
}
|
57
|
+
if (Number.isNaN(value)) {
|
58
|
+
meta.push(["nan", segments]);
|
59
|
+
return { data: "NaN", meta };
|
60
|
+
}
|
61
|
+
if (value instanceof RegExp) {
|
62
|
+
meta.push(["regexp", segments]);
|
63
|
+
return { data: value.toString(), meta };
|
64
|
+
}
|
65
|
+
if (value instanceof URL) {
|
66
|
+
meta.push(["url", segments]);
|
67
|
+
return { data: value.toString(), meta };
|
68
|
+
}
|
69
|
+
if (isPlainObject(value)) {
|
70
|
+
const data = {};
|
71
|
+
for (const k in value) {
|
72
|
+
data[k] = serialize(value[k], [...segments, k], meta).data;
|
15
73
|
}
|
74
|
+
return { data, meta };
|
75
|
+
}
|
76
|
+
if (Array.isArray(value)) {
|
77
|
+
const data = value.map((v, i) => {
|
78
|
+
if (v === void 0) {
|
79
|
+
meta.push(["undefined", [...segments, i]]);
|
80
|
+
return null;
|
81
|
+
}
|
82
|
+
return serialize(v, [...segments, i], meta).data;
|
83
|
+
});
|
84
|
+
return { data, meta };
|
85
|
+
}
|
86
|
+
if (value instanceof Set) {
|
87
|
+
const result = serialize(Array.from(value), segments, meta);
|
88
|
+
meta.push(["set", segments]);
|
89
|
+
return result;
|
90
|
+
}
|
91
|
+
if (value instanceof Map) {
|
92
|
+
const result = serialize(Array.from(value.entries()), segments, meta);
|
93
|
+
meta.push(["map", segments]);
|
94
|
+
return result;
|
16
95
|
}
|
17
|
-
|
18
|
-
|
19
|
-
|
20
|
-
|
21
|
-
|
96
|
+
return { data: value, meta };
|
97
|
+
}
|
98
|
+
function deserialize({
|
99
|
+
data,
|
100
|
+
meta
|
101
|
+
}) {
|
102
|
+
if (meta.length === 0) {
|
103
|
+
return data;
|
104
|
+
}
|
105
|
+
const ref = { data };
|
106
|
+
for (const [type, segments] of meta) {
|
107
|
+
let currentRef = ref;
|
108
|
+
let preSegment = "data";
|
109
|
+
for (let i = 0; i < segments.length; i++) {
|
110
|
+
currentRef = currentRef[preSegment];
|
111
|
+
preSegment = segments[i];
|
112
|
+
}
|
113
|
+
switch (type) {
|
114
|
+
case "nan":
|
115
|
+
currentRef[preSegment] = Number.NaN;
|
116
|
+
break;
|
117
|
+
case "bigint":
|
118
|
+
currentRef[preSegment] = BigInt(currentRef[preSegment]);
|
119
|
+
break;
|
120
|
+
case "date":
|
121
|
+
currentRef[preSegment] = new Date(currentRef[preSegment]);
|
122
|
+
break;
|
123
|
+
case "regexp": {
|
124
|
+
const [, pattern, flags] = currentRef[preSegment].match(/^\/(.*)\/([a-z]*)$/);
|
125
|
+
currentRef[preSegment] = new RegExp(pattern, flags);
|
126
|
+
break;
|
127
|
+
}
|
128
|
+
case "url":
|
129
|
+
currentRef[preSegment] = new URL(currentRef[preSegment]);
|
130
|
+
break;
|
131
|
+
case "undefined":
|
132
|
+
currentRef[preSegment] = void 0;
|
133
|
+
break;
|
134
|
+
case "map":
|
135
|
+
currentRef[preSegment] = new Map(currentRef[preSegment]);
|
136
|
+
break;
|
137
|
+
case "set":
|
138
|
+
currentRef[preSegment] = new Set(currentRef[preSegment]);
|
139
|
+
break;
|
140
|
+
/* v8 ignore next 3 */
|
141
|
+
default: {
|
142
|
+
const _expected = type;
|
143
|
+
}
|
22
144
|
}
|
23
|
-
}
|
145
|
+
}
|
146
|
+
return ref.data;
|
24
147
|
}
|
25
148
|
|
26
|
-
// src/fetch/orpc-
|
27
|
-
|
28
|
-
|
29
|
-
|
30
|
-
|
31
|
-
|
32
|
-
|
33
|
-
|
34
|
-
|
149
|
+
// src/fetch/orpc-payload-codec.ts
|
150
|
+
var ORPCPayloadCodec = class {
|
151
|
+
encode(payload) {
|
152
|
+
const { data, meta } = serialize(payload);
|
153
|
+
const { maps, values } = findDeepMatches((v) => v instanceof Blob, data);
|
154
|
+
if (values.length > 0) {
|
155
|
+
const form = new FormData();
|
156
|
+
if (data !== void 0) {
|
157
|
+
form.append("data", JSON.stringify(data));
|
158
|
+
}
|
159
|
+
form.append("meta", JSON.stringify(meta));
|
160
|
+
form.append("maps", JSON.stringify(maps));
|
161
|
+
for (const i in values) {
|
162
|
+
const value = values[i];
|
163
|
+
form.append(i, value);
|
164
|
+
}
|
165
|
+
return { body: form };
|
166
|
+
}
|
167
|
+
return {
|
168
|
+
body: JSON.stringify({ data, meta }),
|
169
|
+
headers: new Headers({
|
170
|
+
"content-type": "application/json"
|
171
|
+
})
|
172
|
+
};
|
173
|
+
}
|
174
|
+
async decode(re) {
|
175
|
+
try {
|
176
|
+
if (re.headers.get("content-type")?.startsWith("multipart/form-data")) {
|
177
|
+
const form = await re.formData();
|
178
|
+
const rawData = form.get("data");
|
179
|
+
const rawMeta = form.get("meta");
|
180
|
+
const rawMaps = form.get("maps");
|
181
|
+
let data = JSON.parse(rawData);
|
182
|
+
const meta = JSON.parse(rawMeta);
|
183
|
+
const maps = JSON.parse(rawMaps);
|
184
|
+
for (const i in maps) {
|
185
|
+
data = set(data, maps[i], form.get(i));
|
186
|
+
}
|
187
|
+
return deserialize({
|
188
|
+
data,
|
189
|
+
meta
|
190
|
+
});
|
191
|
+
}
|
192
|
+
const json = await re.json();
|
193
|
+
return deserialize(json);
|
194
|
+
} catch (e) {
|
195
|
+
throw new ORPCError({
|
196
|
+
code: "BAD_REQUEST",
|
197
|
+
message: "Cannot parse request/response. Please check the request/response body and Content-Type header.",
|
198
|
+
cause: e
|
199
|
+
});
|
200
|
+
}
|
201
|
+
}
|
202
|
+
};
|
203
|
+
|
204
|
+
// src/fetch/orpc-procedure-matcher.ts
|
205
|
+
import { trim } from "@orpc/shared";
|
206
|
+
var ORPCProcedureMatcher = class {
|
207
|
+
constructor(router) {
|
208
|
+
this.router = router;
|
209
|
+
}
|
210
|
+
async match(pathname) {
|
211
|
+
const path = trim(pathname, "/").split("/").map(decodeURIComponent);
|
212
|
+
const match = getRouterChild(this.router, ...path);
|
213
|
+
const { default: maybeProcedure } = await unlazy(match);
|
214
|
+
if (!isProcedure(maybeProcedure)) {
|
35
215
|
return void 0;
|
36
216
|
}
|
37
|
-
|
38
|
-
|
39
|
-
|
40
|
-
|
41
|
-
|
217
|
+
return {
|
218
|
+
procedure: maybeProcedure,
|
219
|
+
path
|
220
|
+
};
|
221
|
+
}
|
222
|
+
};
|
223
|
+
|
224
|
+
// src/fetch/orpc-handler.ts
|
225
|
+
var ORPCHandler = class {
|
226
|
+
constructor(router, options) {
|
227
|
+
this.router = router;
|
228
|
+
this.options = options;
|
229
|
+
this.procedureMatcher = options?.procedureMatcher ?? new ORPCProcedureMatcher(router);
|
230
|
+
this.payloadCodec = options?.payloadCodec ?? new ORPCPayloadCodec();
|
231
|
+
}
|
232
|
+
procedureMatcher;
|
233
|
+
payloadCodec;
|
234
|
+
condition(request) {
|
235
|
+
return Boolean(request.headers.get(ORPC_HANDLER_HEADER)?.includes(ORPC_HANDLER_VALUE));
|
236
|
+
}
|
237
|
+
async fetch(request, ...[options]) {
|
238
|
+
const context = options?.context;
|
239
|
+
const execute = async () => {
|
240
|
+
const url = new URL(request.url);
|
241
|
+
const pathname = `/${trim2(url.pathname.replace(options?.prefix ?? "", ""), "/")}`;
|
242
|
+
const match = await this.procedureMatcher.match(pathname);
|
42
243
|
if (!match) {
|
43
244
|
throw new ORPCError2({ code: "NOT_FOUND", message: "Not found" });
|
44
245
|
}
|
45
|
-
const input = await
|
46
|
-
const
|
246
|
+
const input = await this.payloadCodec.decode(request);
|
247
|
+
const client = createProcedureClient({
|
47
248
|
context,
|
48
249
|
procedure: match.procedure,
|
49
250
|
path: match.path
|
50
251
|
});
|
51
|
-
const output = await
|
52
|
-
const { body, headers } =
|
53
|
-
return new Response(body, {
|
54
|
-
status: 200,
|
55
|
-
headers
|
56
|
-
});
|
252
|
+
const output = await client(input, { signal: options?.signal });
|
253
|
+
const { body, headers } = this.payloadCodec.encode(output);
|
254
|
+
return new Response(body, { headers });
|
57
255
|
};
|
58
256
|
try {
|
59
257
|
return await executeWithHooks({
|
60
|
-
hooks: options,
|
61
258
|
context,
|
62
|
-
execute
|
63
|
-
input:
|
259
|
+
execute,
|
260
|
+
input: request,
|
261
|
+
hooks: this.options,
|
64
262
|
meta: {
|
65
|
-
signal: options
|
263
|
+
signal: options?.signal
|
66
264
|
}
|
67
265
|
});
|
68
|
-
} catch (
|
69
|
-
|
266
|
+
} catch (e) {
|
267
|
+
const error = e instanceof ORPCError2 ? e : new ORPCError2({
|
268
|
+
code: "INTERNAL_SERVER_ERROR",
|
269
|
+
message: "Internal server error",
|
270
|
+
cause: e
|
271
|
+
});
|
272
|
+
const { body, headers } = this.payloadCodec.encode(error.toJSON());
|
273
|
+
return new Response(body, {
|
274
|
+
headers,
|
275
|
+
status: error.status
|
276
|
+
});
|
70
277
|
}
|
71
|
-
};
|
72
|
-
}
|
73
|
-
async function resolveRouterMatch(router, pathname) {
|
74
|
-
const pathSegments = trim(pathname, "/").split("/").map(decodeURIComponent);
|
75
|
-
const match = getRouterChild(router, ...pathSegments);
|
76
|
-
const { default: maybeProcedure } = await unlazy(match);
|
77
|
-
if (!isProcedure(maybeProcedure)) {
|
78
|
-
return void 0;
|
79
|
-
}
|
80
|
-
return {
|
81
|
-
procedure: maybeProcedure,
|
82
|
-
path: pathSegments
|
83
|
-
};
|
84
|
-
}
|
85
|
-
async function parseRequestInput(request) {
|
86
|
-
try {
|
87
|
-
return await deserializer.deserialize(request);
|
88
|
-
} catch (error) {
|
89
|
-
throw new ORPCError2({
|
90
|
-
code: "BAD_REQUEST",
|
91
|
-
message: "Cannot parse request. Please check the request body and Content-Type header.",
|
92
|
-
cause: error
|
93
|
-
});
|
94
278
|
}
|
95
|
-
}
|
96
|
-
function handleErrorResponse(error) {
|
97
|
-
const orpcError = error instanceof ORPCError2 ? error : new ORPCError2({
|
98
|
-
code: "INTERNAL_SERVER_ERROR",
|
99
|
-
message: "Internal server error",
|
100
|
-
cause: error
|
101
|
-
});
|
102
|
-
const { body, headers } = serializer.serialize(orpcError.toJSON());
|
103
|
-
return new Response(body, {
|
104
|
-
status: orpcError.status,
|
105
|
-
headers
|
106
|
-
});
|
107
|
-
}
|
279
|
+
};
|
108
280
|
export {
|
109
|
-
|
110
|
-
|
281
|
+
CompositeHandler,
|
282
|
+
ORPCHandler,
|
283
|
+
ORPCPayloadCodec,
|
284
|
+
ORPCProcedureMatcher
|
111
285
|
};
|
112
286
|
//# sourceMappingURL=fetch.js.map
|
@@ -0,0 +1,8 @@
|
|
1
|
+
import type { Context } from '../types';
|
2
|
+
import type { ConditionalFetchHandler, FetchHandler, FetchOptions } from './types';
|
3
|
+
export declare class CompositeHandler<T extends Context> implements FetchHandler<T> {
|
4
|
+
private readonly handlers;
|
5
|
+
constructor(handlers: ConditionalFetchHandler<T>[]);
|
6
|
+
fetch(request: Request, ...opt: [options: FetchOptions<T>] | (undefined extends T ? [] : never)): Promise<Response>;
|
7
|
+
}
|
8
|
+
//# sourceMappingURL=composite-handler.d.ts.map
|
@@ -1,3 +1,20 @@
|
|
1
|
-
import type {
|
2
|
-
|
1
|
+
import type { Hooks } from '@orpc/shared';
|
2
|
+
import type { Router } from '../router';
|
3
|
+
import type { Context, WithSignal } from '../types';
|
4
|
+
import type { ConditionalFetchHandler, FetchOptions } from './types';
|
5
|
+
import { type PublicORPCPayloadCodec } from './orpc-payload-codec';
|
6
|
+
import { type PublicORPCProcedureMatcher } from './orpc-procedure-matcher';
|
7
|
+
export type ORPCHandlerOptions<T extends Context> = Hooks<Request, Response, T, WithSignal> & {
|
8
|
+
procedureMatcher?: PublicORPCProcedureMatcher;
|
9
|
+
payloadCodec?: PublicORPCPayloadCodec;
|
10
|
+
};
|
11
|
+
export declare class ORPCHandler<T extends Context> implements ConditionalFetchHandler<T> {
|
12
|
+
readonly router: Router<T, any>;
|
13
|
+
readonly options?: NoInfer<ORPCHandlerOptions<T>> | undefined;
|
14
|
+
private readonly procedureMatcher;
|
15
|
+
private readonly payloadCodec;
|
16
|
+
constructor(router: Router<T, any>, options?: NoInfer<ORPCHandlerOptions<T>> | undefined);
|
17
|
+
condition(request: Request): boolean;
|
18
|
+
fetch(request: Request, ...[options]: [options: FetchOptions<T>] | (undefined extends T ? [] : never)): Promise<Response>;
|
19
|
+
}
|
3
20
|
//# sourceMappingURL=orpc-handler.d.ts.map
|
@@ -0,0 +1,9 @@
|
|
1
|
+
export declare class ORPCPayloadCodec {
|
2
|
+
encode(payload: unknown): {
|
3
|
+
body: FormData | string;
|
4
|
+
headers?: Headers;
|
5
|
+
};
|
6
|
+
decode(re: Request | Response): Promise<unknown>;
|
7
|
+
}
|
8
|
+
export type PublicORPCPayloadCodec = Pick<ORPCPayloadCodec, keyof ORPCPayloadCodec>;
|
9
|
+
//# sourceMappingURL=orpc-payload-codec.d.ts.map
|
@@ -0,0 +1,12 @@
|
|
1
|
+
import type { ANY_PROCEDURE } from '../procedure';
|
2
|
+
import { type ANY_ROUTER } from '../router';
|
3
|
+
export declare class ORPCProcedureMatcher {
|
4
|
+
private readonly router;
|
5
|
+
constructor(router: ANY_ROUTER);
|
6
|
+
match(pathname: string): Promise<{
|
7
|
+
path: string[];
|
8
|
+
procedure: ANY_PROCEDURE;
|
9
|
+
} | undefined>;
|
10
|
+
}
|
11
|
+
export type PublicORPCProcedureMatcher = Pick<ORPCProcedureMatcher, keyof ORPCProcedureMatcher>;
|
12
|
+
//# sourceMappingURL=orpc-procedure-matcher.d.ts.map
|
@@ -0,0 +1,12 @@
|
|
1
|
+
import type { Segment } from '@orpc/shared';
|
2
|
+
export type JSONExtraType = 'bigint' | 'date' | 'nan' | 'undefined' | 'set' | 'map' | 'regexp' | 'url';
|
3
|
+
export type JSONMeta = [JSONExtraType, Segment[]][];
|
4
|
+
export declare function serialize(value: unknown, segments?: Segment[], meta?: JSONMeta): {
|
5
|
+
data: unknown;
|
6
|
+
meta: JSONMeta;
|
7
|
+
};
|
8
|
+
export declare function deserialize({ data, meta, }: {
|
9
|
+
data: unknown;
|
10
|
+
meta: JSONMeta;
|
11
|
+
}): unknown;
|
12
|
+
//# sourceMappingURL=super-json.d.ts.map
|
@@ -1,28 +1,16 @@
|
|
1
1
|
import type { HTTPPath } from '@orpc/contract';
|
2
|
-
import type { Hooks, Value } from '@orpc/shared';
|
3
|
-
import type { Router } from '../router';
|
4
2
|
import type { Context, WithSignal } from '../types';
|
5
|
-
export type
|
6
|
-
/**
|
7
|
-
* The `router` used for handling the request and routing,
|
8
|
-
*
|
9
|
-
*/
|
10
|
-
router: Router<T, any>;
|
11
|
-
/**
|
12
|
-
* The request need to be handled.
|
13
|
-
*/
|
14
|
-
request: Request;
|
15
|
-
/**
|
16
|
-
* Remove the prefix from the request path.
|
17
|
-
*
|
18
|
-
* @example /orpc
|
19
|
-
* @example /api
|
20
|
-
*/
|
3
|
+
export type FetchOptions<T extends Context> = WithSignal & {
|
21
4
|
prefix?: HTTPPath;
|
22
|
-
} &
|
23
|
-
context?:
|
5
|
+
} & (undefined extends T ? {
|
6
|
+
context?: T;
|
24
7
|
} : {
|
25
|
-
context:
|
26
|
-
})
|
27
|
-
export
|
8
|
+
context: T;
|
9
|
+
});
|
10
|
+
export interface FetchHandler<T extends Context> {
|
11
|
+
fetch: (request: Request, ...opt: [options: FetchOptions<T>] | (undefined extends T ? [] : never)) => Promise<Response>;
|
12
|
+
}
|
13
|
+
export interface ConditionalFetchHandler<T extends Context> extends FetchHandler<T> {
|
14
|
+
condition: (request: Request) => boolean;
|
15
|
+
}
|
28
16
|
//# sourceMappingURL=types.d.ts.map
|
package/package.json
CHANGED
@@ -1,7 +1,7 @@
|
|
1
1
|
{
|
2
2
|
"name": "@orpc/server",
|
3
3
|
"type": "module",
|
4
|
-
"version": "0.
|
4
|
+
"version": "0.18.0",
|
5
5
|
"license": "MIT",
|
6
6
|
"homepage": "https://orpc.unnoq.com",
|
7
7
|
"repository": {
|
@@ -33,13 +33,9 @@
|
|
33
33
|
"!**/*.tsbuildinfo",
|
34
34
|
"dist"
|
35
35
|
],
|
36
|
-
"peerDependencies": {
|
37
|
-
"@orpc/zod": "0.17.0"
|
38
|
-
},
|
39
36
|
"dependencies": {
|
40
|
-
"@orpc/contract": "0.
|
41
|
-
"@orpc/shared": "0.
|
42
|
-
"@orpc/transformer": "0.17.0"
|
37
|
+
"@orpc/contract": "0.18.0",
|
38
|
+
"@orpc/shared": "0.18.0"
|
43
39
|
},
|
44
40
|
"devDependencies": {
|
45
41
|
"zod": "^3.24.1"
|
@@ -1,7 +0,0 @@
|
|
1
|
-
import type { Context } from '../types';
|
2
|
-
import type { FetchHandler, FetchHandlerOptions } from './types';
|
3
|
-
export type HandleFetchRequestOptions<T extends Context> = FetchHandlerOptions<T> & {
|
4
|
-
handlers: readonly [FetchHandler, ...FetchHandler[]];
|
5
|
-
};
|
6
|
-
export declare function handleFetchRequest<T extends Context>(options: HandleFetchRequestOptions<T>): Promise<Response>;
|
7
|
-
//# sourceMappingURL=handle-request.d.ts.map
|