@temporary-name/server 1.9.3-alpha.5dc8b200530586870ac736830d4584e0333cfd05 → 1.9.3-alpha.62d88f5cf3908d4411b5278f1824b69334da8072
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.
- package/dist/adapters/aws-lambda/index.d.mts +5 -6
- package/dist/adapters/aws-lambda/index.d.ts +5 -6
- package/dist/adapters/aws-lambda/index.mjs +5 -6
- package/dist/adapters/fetch/index.d.mts +8 -85
- package/dist/adapters/fetch/index.d.ts +8 -85
- package/dist/adapters/fetch/index.mjs +17 -157
- package/dist/adapters/node/index.d.mts +9 -63
- package/dist/adapters/node/index.d.ts +9 -63
- package/dist/adapters/node/index.mjs +15 -122
- package/dist/{adapters/standard → handler}/index.d.mts +5 -7
- package/dist/{adapters/standard → handler}/index.d.ts +5 -7
- package/dist/handler/index.mjs +8 -0
- package/dist/index.d.mts +355 -208
- package/dist/index.d.ts +355 -208
- package/dist/index.mjs +421 -207
- package/dist/openapi/index.d.mts +18 -53
- package/dist/openapi/index.d.ts +18 -53
- package/dist/openapi/index.mjs +391 -368
- package/dist/shared/server.Blt424vz.mjs +523 -0
- package/dist/shared/server.Bmxjwleq.d.ts +39 -0
- package/dist/shared/server.BnAF9pfn.mjs +339 -0
- package/dist/shared/server.CCWAen7P.mjs +156 -0
- package/dist/shared/server.CjPiuQYH.d.mts +51 -0
- package/dist/shared/server.CjPiuQYH.d.ts +51 -0
- package/dist/shared/server.DLyn62VH.d.mts +39 -0
- package/dist/shared/server.DpIhEnBO.d.mts +515 -0
- package/dist/shared/server.DpIhEnBO.d.ts +515 -0
- package/dist/shared/server.MJ43MXYj.mjs +432 -0
- package/package.json +13 -19
- package/dist/adapters/standard/index.mjs +0 -9
- package/dist/plugins/index.d.mts +0 -84
- package/dist/plugins/index.d.ts +0 -84
- package/dist/plugins/index.mjs +0 -116
- package/dist/shared/server.B-meye9-.d.ts +0 -55
- package/dist/shared/server.Ba0Z2fNc.mjs +0 -254
- package/dist/shared/server.DkYpsO6W.d.mts +0 -251
- package/dist/shared/server.DkYpsO6W.d.ts +0 -251
- package/dist/shared/server.DwNnHUZP.d.ts +0 -23
- package/dist/shared/server.I-tTl_ce.d.mts +0 -23
- package/dist/shared/server.JtIZ8YG7.mjs +0 -237
- package/dist/shared/server.miXh-9wo.mjs +0 -416
- package/dist/shared/server.vLcMd_kA.d.mts +0 -55
|
@@ -0,0 +1,339 @@
|
|
|
1
|
+
import { isObject, NullProtoObj, fallbackContractConfig, stringifyJSON, isAsyncIteratorObject, tryDecodeURIComponent, toHttpPath, runWithSpan, ORPC_NAME, asyncIteratorWithSpan, setSpanError } from '@temporary-name/shared';
|
|
2
|
+
import { e as encodeError, i as isAPIErrorStatus, s as standardizeHTTPPath, A as APIError, B as BadRequestError, t as toAPIError$1 } from './server.MJ43MXYj.mjs';
|
|
3
|
+
import { c as createProcedureClient } from './server.CCWAen7P.mjs';
|
|
4
|
+
import { toAPIError, traverseContractProcedures, getLazyMeta, unlazy } from '@temporary-name/server';
|
|
5
|
+
import { mapEventIterator, ErrorEvent } from '@temporary-name/standard-server';
|
|
6
|
+
import { createRouter, addRoute, findRoute } from 'rou3';
|
|
7
|
+
|
|
8
|
+
function bracketNotationDeserialize(serialized, { maxArrayIndex = 9999 } = {}) {
|
|
9
|
+
if (serialized.length === 0) {
|
|
10
|
+
return {};
|
|
11
|
+
}
|
|
12
|
+
const arrayPushStyles = /* @__PURE__ */ new WeakSet();
|
|
13
|
+
const ref = { value: [] };
|
|
14
|
+
for (const [path, value] of serialized) {
|
|
15
|
+
const segments = parsePath(path);
|
|
16
|
+
let currentRef = ref;
|
|
17
|
+
let nextSegment = "value";
|
|
18
|
+
segments.forEach((segment, i) => {
|
|
19
|
+
if (!Array.isArray(currentRef[nextSegment]) && !isObject(currentRef[nextSegment])) {
|
|
20
|
+
currentRef[nextSegment] = [];
|
|
21
|
+
}
|
|
22
|
+
if (i !== segments.length - 1) {
|
|
23
|
+
if (Array.isArray(currentRef[nextSegment]) && !isValidArrayIndex(segment, maxArrayIndex)) {
|
|
24
|
+
if (arrayPushStyles.has(currentRef[nextSegment])) {
|
|
25
|
+
arrayPushStyles.delete(currentRef[nextSegment]);
|
|
26
|
+
currentRef[nextSegment] = pushStyleArrayToObject(currentRef[nextSegment]);
|
|
27
|
+
} else {
|
|
28
|
+
currentRef[nextSegment] = arrayToObject(currentRef[nextSegment]);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
} else {
|
|
32
|
+
if (Array.isArray(currentRef[nextSegment])) {
|
|
33
|
+
if (segment === "") {
|
|
34
|
+
if (currentRef[nextSegment].length && !arrayPushStyles.has(currentRef[nextSegment])) {
|
|
35
|
+
currentRef[nextSegment] = arrayToObject(currentRef[nextSegment]);
|
|
36
|
+
}
|
|
37
|
+
} else {
|
|
38
|
+
if (arrayPushStyles.has(currentRef[nextSegment])) {
|
|
39
|
+
arrayPushStyles.delete(currentRef[nextSegment]);
|
|
40
|
+
currentRef[nextSegment] = pushStyleArrayToObject(currentRef[nextSegment]);
|
|
41
|
+
} else if (!isValidArrayIndex(segment, maxArrayIndex)) {
|
|
42
|
+
currentRef[nextSegment] = arrayToObject(currentRef[nextSegment]);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
currentRef = currentRef[nextSegment];
|
|
48
|
+
nextSegment = segment;
|
|
49
|
+
});
|
|
50
|
+
if (Array.isArray(currentRef) && nextSegment === "") {
|
|
51
|
+
arrayPushStyles.add(currentRef);
|
|
52
|
+
currentRef.push(value);
|
|
53
|
+
} else if (nextSegment in currentRef) {
|
|
54
|
+
if (Array.isArray(currentRef[nextSegment])) {
|
|
55
|
+
currentRef[nextSegment].push(value);
|
|
56
|
+
} else {
|
|
57
|
+
currentRef[nextSegment] = [currentRef[nextSegment], value];
|
|
58
|
+
}
|
|
59
|
+
} else {
|
|
60
|
+
currentRef[nextSegment] = value;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
return ref.value;
|
|
64
|
+
}
|
|
65
|
+
function parsePath(path) {
|
|
66
|
+
const segments = [];
|
|
67
|
+
let inBrackets = false;
|
|
68
|
+
let currentSegment = "";
|
|
69
|
+
let backslashCount = 0;
|
|
70
|
+
for (let i = 0; i < path.length; i++) {
|
|
71
|
+
const char = path[i];
|
|
72
|
+
const nextChar = path[i + 1];
|
|
73
|
+
if (inBrackets && char === "]" && (nextChar === void 0 || nextChar === "[") && backslashCount % 2 === 0) {
|
|
74
|
+
if (nextChar === void 0) {
|
|
75
|
+
inBrackets = false;
|
|
76
|
+
}
|
|
77
|
+
segments.push(currentSegment);
|
|
78
|
+
currentSegment = "";
|
|
79
|
+
i++;
|
|
80
|
+
} else if (segments.length === 0 && char === "[" && backslashCount % 2 === 0) {
|
|
81
|
+
inBrackets = true;
|
|
82
|
+
segments.push(currentSegment);
|
|
83
|
+
currentSegment = "";
|
|
84
|
+
} else if (char === "\\") {
|
|
85
|
+
backslashCount++;
|
|
86
|
+
} else {
|
|
87
|
+
currentSegment += "\\".repeat(backslashCount / 2) + char;
|
|
88
|
+
backslashCount = 0;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
return inBrackets || segments.length === 0 ? [path] : segments;
|
|
92
|
+
}
|
|
93
|
+
function isValidArrayIndex(value, maxIndex) {
|
|
94
|
+
return /^0$|^[1-9]\d*$/.test(value) && Number(value) <= maxIndex;
|
|
95
|
+
}
|
|
96
|
+
function arrayToObject(array) {
|
|
97
|
+
const obj = new NullProtoObj();
|
|
98
|
+
array.forEach((item, i) => {
|
|
99
|
+
obj[i] = item;
|
|
100
|
+
});
|
|
101
|
+
return obj;
|
|
102
|
+
}
|
|
103
|
+
function pushStyleArrayToObject(array) {
|
|
104
|
+
const obj = new NullProtoObj();
|
|
105
|
+
obj[""] = array.length === 1 ? array[0] : array;
|
|
106
|
+
return obj;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
async function decode(request, pathParams) {
|
|
110
|
+
return {
|
|
111
|
+
path: pathParams ?? {},
|
|
112
|
+
query: bracketNotationDeserialize(Array.from(request.url.searchParams.entries())),
|
|
113
|
+
headers: request.headers,
|
|
114
|
+
body: await request.body() ?? {}
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
function asyncSafeSerialize(data) {
|
|
118
|
+
if (isAsyncIteratorObject(data)) {
|
|
119
|
+
return mapEventIterator(data, {
|
|
120
|
+
value: async (value) => value,
|
|
121
|
+
error: async (e) => {
|
|
122
|
+
return new ErrorEvent({
|
|
123
|
+
data: encodeError(toAPIError(e))["body"],
|
|
124
|
+
cause: e
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
return data;
|
|
130
|
+
}
|
|
131
|
+
function encode(output, procedure) {
|
|
132
|
+
const successStatus = fallbackContractConfig(
|
|
133
|
+
"defaultSuccessStatus",
|
|
134
|
+
procedure["~orpc"].route.successStatus
|
|
135
|
+
);
|
|
136
|
+
const outputStructure = fallbackContractConfig(
|
|
137
|
+
"defaultOutputStructure",
|
|
138
|
+
procedure["~orpc"].route.outputStructure
|
|
139
|
+
);
|
|
140
|
+
if (outputStructure === "compact") {
|
|
141
|
+
return {
|
|
142
|
+
status: successStatus,
|
|
143
|
+
headers: new Headers(),
|
|
144
|
+
body: asyncSafeSerialize(output)
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
if (!isDetailedOutput(output)) {
|
|
148
|
+
throw new Error(`
|
|
149
|
+
Invalid "detailed" output structure:
|
|
150
|
+
\u2022 Expected an object with optional properties:
|
|
151
|
+
- status (number 200-399)
|
|
152
|
+
- headers (Record<string, string | string[]>)
|
|
153
|
+
- body (any)
|
|
154
|
+
\u2022 No extra keys allowed.
|
|
155
|
+
|
|
156
|
+
Actual value:
|
|
157
|
+
${stringifyJSON(output)}
|
|
158
|
+
`);
|
|
159
|
+
}
|
|
160
|
+
return {
|
|
161
|
+
status: output.status ?? successStatus,
|
|
162
|
+
headers: output.headers ?? new Headers(),
|
|
163
|
+
body: asyncSafeSerialize(output.body)
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
function isDetailedOutput(output) {
|
|
167
|
+
if (!isObject(output)) {
|
|
168
|
+
return false;
|
|
169
|
+
}
|
|
170
|
+
if (output.headers && !isObject(output.headers)) {
|
|
171
|
+
return false;
|
|
172
|
+
}
|
|
173
|
+
if (output.status !== void 0 && (typeof output.status !== "number" || !Number.isInteger(output.status) || isAPIErrorStatus(output.status))) {
|
|
174
|
+
return false;
|
|
175
|
+
}
|
|
176
|
+
return true;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
function resolveFriendlyStandardHandleOptions(options) {
|
|
180
|
+
return {
|
|
181
|
+
...options,
|
|
182
|
+
context: options.context ?? {}
|
|
183
|
+
// Context only optional if all fields are optional
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
function toRou3Pattern(path) {
|
|
187
|
+
return standardizeHTTPPath(path).replace(/\/\{\+([^}]+)\}/g, "/**:$1").replace(/\/\{([^}]+)\}/g, "/:$1");
|
|
188
|
+
}
|
|
189
|
+
function decodeParams(params) {
|
|
190
|
+
return Object.fromEntries(
|
|
191
|
+
Object.entries(params).map(([key, value]) => [key, tryDecodeURIComponent(value)])
|
|
192
|
+
);
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
class StandardOpenAPIMatcher {
|
|
196
|
+
tree = createRouter();
|
|
197
|
+
pendingRouters = [];
|
|
198
|
+
init(router, path = []) {
|
|
199
|
+
const laziedOptions = traverseContractProcedures({ router, path }, (traverseOptions) => {
|
|
200
|
+
const { path: path2, contract } = traverseOptions;
|
|
201
|
+
const method = fallbackContractConfig("defaultMethod", contract["~orpc"].route.method);
|
|
202
|
+
const httpPath = toRou3Pattern(contract["~orpc"].route.path ?? toHttpPath(path2));
|
|
203
|
+
addRoute(this.tree, method, httpPath, {
|
|
204
|
+
path: path2,
|
|
205
|
+
// cast is safe because router is typed as Router (not ContractRouter)
|
|
206
|
+
procedure: contract,
|
|
207
|
+
router
|
|
208
|
+
});
|
|
209
|
+
});
|
|
210
|
+
this.pendingRouters.push(
|
|
211
|
+
...laziedOptions.map((option) => ({
|
|
212
|
+
...option,
|
|
213
|
+
httpPathPrefix: toHttpPath(option.path),
|
|
214
|
+
laziedPrefix: getLazyMeta(option.router).prefix
|
|
215
|
+
}))
|
|
216
|
+
);
|
|
217
|
+
}
|
|
218
|
+
async match(method, pathname) {
|
|
219
|
+
if (this.pendingRouters.length) {
|
|
220
|
+
const newPendingRouters = [];
|
|
221
|
+
for (const pendingRouter of this.pendingRouters) {
|
|
222
|
+
if (!pendingRouter.laziedPrefix || pathname.startsWith(pendingRouter.laziedPrefix) || pathname.startsWith(pendingRouter.httpPathPrefix)) {
|
|
223
|
+
const { default: router } = await unlazy(pendingRouter.router);
|
|
224
|
+
this.init(router, pendingRouter.path);
|
|
225
|
+
} else {
|
|
226
|
+
newPendingRouters.push(pendingRouter);
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
this.pendingRouters = newPendingRouters;
|
|
230
|
+
}
|
|
231
|
+
const match = findRoute(this.tree, method, pathname);
|
|
232
|
+
if (!match) {
|
|
233
|
+
return void 0;
|
|
234
|
+
}
|
|
235
|
+
return {
|
|
236
|
+
path: match.data.path,
|
|
237
|
+
procedure: match.data.procedure,
|
|
238
|
+
params: match.params ? decodeParams(match.params) : void 0
|
|
239
|
+
};
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
function throwOrLog(error) {
|
|
244
|
+
if (process.env.NODE_ENV !== "production") {
|
|
245
|
+
throw error;
|
|
246
|
+
} else {
|
|
247
|
+
console.error(error);
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
class StandardHandler {
|
|
251
|
+
matcher;
|
|
252
|
+
constructor(router) {
|
|
253
|
+
this.matcher = new StandardOpenAPIMatcher();
|
|
254
|
+
this.matcher.init(router);
|
|
255
|
+
}
|
|
256
|
+
async handle(request, options) {
|
|
257
|
+
const prefix = options.prefix?.replace(/\/$/, "") || void 0;
|
|
258
|
+
if (prefix && !request.url.pathname.startsWith(`${prefix}/`) && request.url.pathname !== prefix) {
|
|
259
|
+
return { matched: false, response: void 0 };
|
|
260
|
+
}
|
|
261
|
+
return runWithSpan({ name: `${request.method} ${request.url.pathname}` }, async (span) => {
|
|
262
|
+
let step;
|
|
263
|
+
let errorMap;
|
|
264
|
+
try {
|
|
265
|
+
const context = options.context;
|
|
266
|
+
const method = request.method;
|
|
267
|
+
const url = request.url;
|
|
268
|
+
const pathname = prefix ? url.pathname.replace(prefix, "") : url.pathname;
|
|
269
|
+
const match = await runWithSpan(
|
|
270
|
+
{ name: "find_procedure" },
|
|
271
|
+
() => this.matcher.match(method, `/${pathname.replace(/^\/|\/$/g, "")}`)
|
|
272
|
+
);
|
|
273
|
+
if (!match) {
|
|
274
|
+
return { matched: false, response: void 0 };
|
|
275
|
+
}
|
|
276
|
+
errorMap = match.procedure["~orpc"].errorMap;
|
|
277
|
+
span?.updateName(`${ORPC_NAME}.${match.path.join("/")}`);
|
|
278
|
+
span?.setAttribute("rpc.system", ORPC_NAME);
|
|
279
|
+
span?.setAttribute("rpc.method", match.path.join("."));
|
|
280
|
+
step = "decode_input";
|
|
281
|
+
const input = await runWithSpan({ name: "decode_input" }, () => decode(request, match.params));
|
|
282
|
+
step = void 0;
|
|
283
|
+
if (isAsyncIteratorObject(input.body)) {
|
|
284
|
+
input.body = asyncIteratorWithSpan(
|
|
285
|
+
{ name: "consume_event_iterator_input", signal: request.signal },
|
|
286
|
+
input.body
|
|
287
|
+
);
|
|
288
|
+
}
|
|
289
|
+
const client = createProcedureClient(match.procedure, {
|
|
290
|
+
context,
|
|
291
|
+
path: match.path
|
|
292
|
+
});
|
|
293
|
+
step = "call_procedure";
|
|
294
|
+
const output = await client(input, {
|
|
295
|
+
request,
|
|
296
|
+
signal: request.signal,
|
|
297
|
+
lastEventId: request.headers.get("last-event-id") ?? void 0
|
|
298
|
+
});
|
|
299
|
+
step = void 0;
|
|
300
|
+
const response = encode(output, match.procedure);
|
|
301
|
+
return {
|
|
302
|
+
matched: true,
|
|
303
|
+
response
|
|
304
|
+
};
|
|
305
|
+
} catch (e) {
|
|
306
|
+
if (step !== "call_procedure") {
|
|
307
|
+
setSpanError(span, e);
|
|
308
|
+
}
|
|
309
|
+
const isAPIError = e instanceof APIError;
|
|
310
|
+
if (isAPIError) {
|
|
311
|
+
if (!errorMap) {
|
|
312
|
+
throwOrLog(
|
|
313
|
+
new Error(`Got APIError but errorMap is undefined. APIError="{${e.message}"`, { cause: e })
|
|
314
|
+
);
|
|
315
|
+
} else if (!errorMap[e.constructor.name]) {
|
|
316
|
+
throwOrLog(
|
|
317
|
+
new Error(
|
|
318
|
+
`APIError "${e.constructor.name}" (type "${e.constructor.type}") is not registered. Add it to your API with: baseApi.useErrors({ ${e.constructor.name} })`,
|
|
319
|
+
{ cause: e }
|
|
320
|
+
)
|
|
321
|
+
);
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
const error = step === "decode_input" && !(e instanceof APIError) ? new BadRequestError({
|
|
325
|
+
code: "malformed_request",
|
|
326
|
+
message: `Malformed request. Ensure the request body is properly formatted and the 'Content-Type' header is set correctly.`,
|
|
327
|
+
cause: e
|
|
328
|
+
}) : toAPIError$1(e);
|
|
329
|
+
const response = encodeError(error);
|
|
330
|
+
return {
|
|
331
|
+
matched: true,
|
|
332
|
+
response
|
|
333
|
+
};
|
|
334
|
+
}
|
|
335
|
+
});
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
export { StandardHandler as S, StandardOpenAPIMatcher as a, decodeParams as b, decode as d, encode as e, resolveFriendlyStandardHandleOptions as r, toRou3Pattern as t };
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
import { resolveMaybeOptionalOptions, toArray, value, runWithSpan, isAsyncIteratorObject, overlayProxy, asyncIteratorWithSpan } from '@temporary-name/shared';
|
|
2
|
+
import { HibernationEventIterator, mapEventIterator } from '@temporary-name/standard-server';
|
|
3
|
+
import { safeDecodeAsync, safeEncodeAsync } from '@temporary-name/zod';
|
|
4
|
+
import { u as unlazy, B as BadRequestError, V as ValidationError, I as InternalServerError } from './server.MJ43MXYj.mjs';
|
|
5
|
+
|
|
6
|
+
function mergeCurrentContext(context, other) {
|
|
7
|
+
return { ...context, ...other };
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
function middlewareOutputFn(output) {
|
|
11
|
+
return { output, context: {} };
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function createProcedureClient(lazyableProcedure, ...rest) {
|
|
15
|
+
const options = resolveMaybeOptionalOptions(rest);
|
|
16
|
+
return async (...[input, callerOptions]) => {
|
|
17
|
+
const path = toArray(options.path);
|
|
18
|
+
const { default: procedure } = await unlazy(lazyableProcedure);
|
|
19
|
+
const clientContext = callerOptions?.context ?? {};
|
|
20
|
+
const context = await value(options.context ?? {}, clientContext);
|
|
21
|
+
const output = await runWithSpan({ name: "call_procedure", signal: callerOptions?.signal }, (span) => {
|
|
22
|
+
span?.setAttribute("procedure.path", [...path]);
|
|
23
|
+
return executeProcedureInternal(procedure, input, {
|
|
24
|
+
context,
|
|
25
|
+
path,
|
|
26
|
+
procedure,
|
|
27
|
+
request: callerOptions?.request,
|
|
28
|
+
signal: callerOptions?.signal,
|
|
29
|
+
lastEventId: callerOptions?.lastEventId
|
|
30
|
+
});
|
|
31
|
+
});
|
|
32
|
+
if (isAsyncIteratorObject(output)) {
|
|
33
|
+
if (output instanceof HibernationEventIterator) {
|
|
34
|
+
return output;
|
|
35
|
+
}
|
|
36
|
+
return overlayProxy(
|
|
37
|
+
output,
|
|
38
|
+
mapEventIterator(
|
|
39
|
+
asyncIteratorWithSpan(
|
|
40
|
+
{ name: "consume_event_iterator_output", signal: callerOptions?.signal },
|
|
41
|
+
output
|
|
42
|
+
),
|
|
43
|
+
{
|
|
44
|
+
value: (v) => v,
|
|
45
|
+
error: async (e) => e
|
|
46
|
+
}
|
|
47
|
+
)
|
|
48
|
+
);
|
|
49
|
+
}
|
|
50
|
+
return output;
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
async function validateInput(procedure, input) {
|
|
54
|
+
const schemas = procedure["~orpc"].schemas;
|
|
55
|
+
return runWithSpan({ name: "validate_input" }, async () => {
|
|
56
|
+
const resultBody = await safeDecodeAsync(schemas.bodySchema, input.body, { parseType: "body" });
|
|
57
|
+
const resultPath = await safeDecodeAsync(schemas.pathSchema, input.path, { parseType: "path" });
|
|
58
|
+
const resultQuery = await safeDecodeAsync(schemas.querySchema, input.query, { parseType: "query" });
|
|
59
|
+
const issues = [];
|
|
60
|
+
if (!resultBody.success) {
|
|
61
|
+
issues.push(...resultBody.error.issues.map((i) => ({ ...i, path: ["body", ...i.path] })));
|
|
62
|
+
}
|
|
63
|
+
if (!resultPath.success) {
|
|
64
|
+
issues.push(...resultPath.error.issues.map((i) => ({ ...i, path: ["path", ...i.path] })));
|
|
65
|
+
}
|
|
66
|
+
if (!resultQuery.success) {
|
|
67
|
+
issues.push(...resultQuery.error.issues.map((i) => ({ ...i, path: ["query", ...i.path] })));
|
|
68
|
+
}
|
|
69
|
+
if (issues.length > 0) {
|
|
70
|
+
throw new BadRequestError({
|
|
71
|
+
code: "input_validation_failed",
|
|
72
|
+
message: "Input validation failed",
|
|
73
|
+
cause: new ValidationError({
|
|
74
|
+
issues,
|
|
75
|
+
data: input
|
|
76
|
+
})
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
const results = {
|
|
80
|
+
body: resultBody.data,
|
|
81
|
+
path: resultPath.data,
|
|
82
|
+
query: resultQuery.data
|
|
83
|
+
};
|
|
84
|
+
return results;
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
async function validateOutput(procedure, output) {
|
|
88
|
+
const schema = procedure["~orpc"].schemas.outputSchema;
|
|
89
|
+
if (!schema) {
|
|
90
|
+
return output;
|
|
91
|
+
}
|
|
92
|
+
return runWithSpan({ name: "validate_output" }, async () => {
|
|
93
|
+
const result = await safeEncodeAsync(schema, output, { parseType: "output" });
|
|
94
|
+
if (!result.success) {
|
|
95
|
+
throw new InternalServerError({
|
|
96
|
+
message: "Output validation failed",
|
|
97
|
+
cause: new ValidationError({
|
|
98
|
+
issues: result.error.issues,
|
|
99
|
+
data: output
|
|
100
|
+
})
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
return result.data;
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
async function executeProcedureInternal(procedure, input, options) {
|
|
107
|
+
const middlewares = procedure["~orpc"].middlewares;
|
|
108
|
+
const inputValidationIndex = Math.min(
|
|
109
|
+
Math.max(0, procedure["~orpc"].inputValidationIndex),
|
|
110
|
+
middlewares.length
|
|
111
|
+
);
|
|
112
|
+
const outputValidationIndex = Math.min(
|
|
113
|
+
Math.max(0, procedure["~orpc"].outputValidationIndex),
|
|
114
|
+
middlewares.length
|
|
115
|
+
);
|
|
116
|
+
const next = async (index, context, input2) => {
|
|
117
|
+
let currentInput = input2;
|
|
118
|
+
if (index === inputValidationIndex) {
|
|
119
|
+
currentInput = await validateInput(procedure, currentInput);
|
|
120
|
+
}
|
|
121
|
+
const mid = middlewares[index];
|
|
122
|
+
const output = mid ? await runWithSpan({ name: `middleware.${mid.name}`, signal: options.signal }, async (span) => {
|
|
123
|
+
span?.setAttribute("middleware.index", index);
|
|
124
|
+
span?.setAttribute("middleware.name", mid.name);
|
|
125
|
+
const result = await mid(
|
|
126
|
+
{
|
|
127
|
+
...options,
|
|
128
|
+
context,
|
|
129
|
+
next: async (nextOptions) => {
|
|
130
|
+
const nextContext = nextOptions?.context ?? {};
|
|
131
|
+
return {
|
|
132
|
+
output: await next(index + 1, mergeCurrentContext(context, nextContext), currentInput),
|
|
133
|
+
// NB: Pretty sure this isn't used (or meant to be used) at runtime, it's just there
|
|
134
|
+
// to get type inference in the builder (via the caller returning the output of next() in
|
|
135
|
+
// the middleware function)
|
|
136
|
+
context: nextContext
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
},
|
|
140
|
+
currentInput,
|
|
141
|
+
middlewareOutputFn
|
|
142
|
+
);
|
|
143
|
+
return result.output;
|
|
144
|
+
}) : await runWithSpan(
|
|
145
|
+
{ name: "handler", signal: options.signal },
|
|
146
|
+
() => procedure["~orpc"].handler(currentInput, { ...options, context })
|
|
147
|
+
);
|
|
148
|
+
if (index === outputValidationIndex) {
|
|
149
|
+
return await validateOutput(procedure, output);
|
|
150
|
+
}
|
|
151
|
+
return output;
|
|
152
|
+
};
|
|
153
|
+
return next(0, options.context, input);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
export { middlewareOutputFn as a, createProcedureClient as c, mergeCurrentContext as m };
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { JSONSchema, SchemaConverter } from '@temporary-name/server/openapi';
|
|
2
|
+
|
|
3
|
+
interface ZodToJsonSchemaConverterOptions {
|
|
4
|
+
/**
|
|
5
|
+
* Max depth of lazy type.
|
|
6
|
+
*
|
|
7
|
+
* Used anyJsonSchema (`{}`) when exceed max depth
|
|
8
|
+
*
|
|
9
|
+
* @default 2
|
|
10
|
+
*/
|
|
11
|
+
maxLazyDepth?: number;
|
|
12
|
+
/**
|
|
13
|
+
* Max depth of nested types.
|
|
14
|
+
*
|
|
15
|
+
* Used anyJsonSchema (`{}`) when exceed max depth
|
|
16
|
+
*
|
|
17
|
+
* @default 10
|
|
18
|
+
*/
|
|
19
|
+
maxStructureDepth?: number;
|
|
20
|
+
/**
|
|
21
|
+
* The schema to be used to represent the any | unknown type.
|
|
22
|
+
*
|
|
23
|
+
* @default { }
|
|
24
|
+
*/
|
|
25
|
+
anyJsonSchema?: Exclude<JSONSchema, boolean>;
|
|
26
|
+
/**
|
|
27
|
+
* The schema to be used when the Zod schema is unsupported.
|
|
28
|
+
*
|
|
29
|
+
* @default { not: {} }
|
|
30
|
+
*/
|
|
31
|
+
unsupportedJsonSchema?: Exclude<JSONSchema, boolean>;
|
|
32
|
+
/**
|
|
33
|
+
* The schema to be used to represent the undefined type.
|
|
34
|
+
*
|
|
35
|
+
* @default { not: {} }
|
|
36
|
+
*/
|
|
37
|
+
undefinedJsonSchema?: Exclude<JSONSchema, boolean>;
|
|
38
|
+
}
|
|
39
|
+
declare class ZodToJsonSchemaConverter {
|
|
40
|
+
#private;
|
|
41
|
+
private readonly maxLazyDepth;
|
|
42
|
+
private readonly maxStructureDepth;
|
|
43
|
+
private readonly anyJsonSchema;
|
|
44
|
+
private readonly unsupportedJsonSchema;
|
|
45
|
+
private readonly undefinedJsonSchema;
|
|
46
|
+
constructor(options?: ZodToJsonSchemaConverterOptions);
|
|
47
|
+
convert: SchemaConverter;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export { ZodToJsonSchemaConverter as a };
|
|
51
|
+
export type { ZodToJsonSchemaConverterOptions as Z };
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { JSONSchema, SchemaConverter } from '@temporary-name/server/openapi';
|
|
2
|
+
|
|
3
|
+
interface ZodToJsonSchemaConverterOptions {
|
|
4
|
+
/**
|
|
5
|
+
* Max depth of lazy type.
|
|
6
|
+
*
|
|
7
|
+
* Used anyJsonSchema (`{}`) when exceed max depth
|
|
8
|
+
*
|
|
9
|
+
* @default 2
|
|
10
|
+
*/
|
|
11
|
+
maxLazyDepth?: number;
|
|
12
|
+
/**
|
|
13
|
+
* Max depth of nested types.
|
|
14
|
+
*
|
|
15
|
+
* Used anyJsonSchema (`{}`) when exceed max depth
|
|
16
|
+
*
|
|
17
|
+
* @default 10
|
|
18
|
+
*/
|
|
19
|
+
maxStructureDepth?: number;
|
|
20
|
+
/**
|
|
21
|
+
* The schema to be used to represent the any | unknown type.
|
|
22
|
+
*
|
|
23
|
+
* @default { }
|
|
24
|
+
*/
|
|
25
|
+
anyJsonSchema?: Exclude<JSONSchema, boolean>;
|
|
26
|
+
/**
|
|
27
|
+
* The schema to be used when the Zod schema is unsupported.
|
|
28
|
+
*
|
|
29
|
+
* @default { not: {} }
|
|
30
|
+
*/
|
|
31
|
+
unsupportedJsonSchema?: Exclude<JSONSchema, boolean>;
|
|
32
|
+
/**
|
|
33
|
+
* The schema to be used to represent the undefined type.
|
|
34
|
+
*
|
|
35
|
+
* @default { not: {} }
|
|
36
|
+
*/
|
|
37
|
+
undefinedJsonSchema?: Exclude<JSONSchema, boolean>;
|
|
38
|
+
}
|
|
39
|
+
declare class ZodToJsonSchemaConverter {
|
|
40
|
+
#private;
|
|
41
|
+
private readonly maxLazyDepth;
|
|
42
|
+
private readonly maxStructureDepth;
|
|
43
|
+
private readonly anyJsonSchema;
|
|
44
|
+
private readonly unsupportedJsonSchema;
|
|
45
|
+
private readonly undefinedJsonSchema;
|
|
46
|
+
constructor(options?: ZodToJsonSchemaConverterOptions);
|
|
47
|
+
convert: SchemaConverter;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export { ZodToJsonSchemaConverter as a };
|
|
51
|
+
export type { ZodToJsonSchemaConverterOptions as Z };
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { HTTPPath, StandardResponse, StandardLazyRequest } from '@temporary-name/shared';
|
|
2
|
+
import { C as Context, m as Router } from './server.DpIhEnBO.mjs';
|
|
3
|
+
|
|
4
|
+
interface StandardHandleOptions<T extends Context> {
|
|
5
|
+
prefix?: HTTPPath;
|
|
6
|
+
context: T;
|
|
7
|
+
}
|
|
8
|
+
type StandardHandleResult = {
|
|
9
|
+
matched: true;
|
|
10
|
+
response: StandardResponse;
|
|
11
|
+
} | {
|
|
12
|
+
matched: false;
|
|
13
|
+
response: undefined;
|
|
14
|
+
};
|
|
15
|
+
declare class StandardHandler<T extends Context> {
|
|
16
|
+
private readonly matcher;
|
|
17
|
+
constructor(router: Router<T>);
|
|
18
|
+
handle(request: StandardLazyRequest, options: StandardHandleOptions<T>): Promise<StandardHandleResult>;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
type FriendlyStandardHandleOptions<T extends Context> = Omit<StandardHandleOptions<T>, 'context'> & (object extends T ? {
|
|
22
|
+
context?: T;
|
|
23
|
+
} : {
|
|
24
|
+
context: T;
|
|
25
|
+
});
|
|
26
|
+
declare function resolveFriendlyStandardHandleOptions<T extends Context>(options: FriendlyStandardHandleOptions<T>): StandardHandleOptions<T>;
|
|
27
|
+
/**
|
|
28
|
+
* {@link https://github.com/unjs/rou3}
|
|
29
|
+
*
|
|
30
|
+
* @internal
|
|
31
|
+
*/
|
|
32
|
+
declare function toRou3Pattern(path: HTTPPath): string;
|
|
33
|
+
/**
|
|
34
|
+
* @internal
|
|
35
|
+
*/
|
|
36
|
+
declare function decodeParams(params: Record<string, string>): Record<string, string>;
|
|
37
|
+
|
|
38
|
+
export { StandardHandler as b, decodeParams as d, resolveFriendlyStandardHandleOptions as r, toRou3Pattern as t };
|
|
39
|
+
export type { FriendlyStandardHandleOptions as F, StandardHandleOptions as S, StandardHandleResult as a };
|