@temporary-name/server 1.9.3-alpha.2957dbc009ec31fa21575f028b83c96651cba827 → 1.9.3-alpha.305aebe633f301e28426c6b15cdfd58ddf45641c

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 (30) hide show
  1. package/dist/adapters/aws-lambda/index.d.mts +3 -3
  2. package/dist/adapters/aws-lambda/index.d.ts +3 -3
  3. package/dist/adapters/aws-lambda/index.mjs +3 -3
  4. package/dist/adapters/fetch/index.d.mts +3 -3
  5. package/dist/adapters/fetch/index.d.ts +3 -3
  6. package/dist/adapters/fetch/index.mjs +3 -3
  7. package/dist/adapters/node/index.d.mts +3 -3
  8. package/dist/adapters/node/index.d.ts +3 -3
  9. package/dist/adapters/node/index.mjs +3 -3
  10. package/dist/adapters/standard/index.d.mts +3 -3
  11. package/dist/adapters/standard/index.d.ts +3 -3
  12. package/dist/adapters/standard/index.mjs +3 -3
  13. package/dist/index.d.mts +338 -34
  14. package/dist/index.d.ts +338 -34
  15. package/dist/index.mjs +424 -96
  16. package/dist/openapi/index.d.mts +16 -34
  17. package/dist/openapi/index.d.ts +16 -34
  18. package/dist/openapi/index.mjs +339 -298
  19. package/dist/shared/{server.DfUs5c4R.d.ts → server.B0LJ_wu-.d.ts} +3 -3
  20. package/dist/shared/{server.L8lRAYBR.d.mts → server.BQZMQrPe.d.mts} +3 -3
  21. package/dist/shared/{server.CpS0m3at.mjs → server.CYa9puL2.mjs} +3 -3
  22. package/dist/shared/server.ChOv1yG3.mjs +319 -0
  23. package/dist/shared/server.CjPiuQYH.d.mts +51 -0
  24. package/dist/shared/server.CjPiuQYH.d.ts +51 -0
  25. package/dist/shared/server.Cza0RB3u.mjs +160 -0
  26. package/dist/shared/{server.DPD7R7h_.d.mts → server.DXPMDozZ.d.mts} +182 -20
  27. package/dist/shared/{server.DPD7R7h_.d.ts → server.DXPMDozZ.d.ts} +182 -20
  28. package/dist/shared/server.Ny4yD6yY.mjs +525 -0
  29. package/package.json +10 -11
  30. package/dist/shared/server.B7tjiDal.mjs +0 -354
@@ -1,354 +0,0 @@
1
- import { mergePrefix, enhanceRoute, ValidationError } from '@temporary-name/contract';
2
- import { resolveMaybeOptionalOptions, toArray, value, runWithSpan, isAsyncIteratorObject, overlayProxy, asyncIteratorWithSpan, ORPCError } from '@temporary-name/shared';
3
- import { HibernationEventIterator, mapEventIterator } from '@temporary-name/standard-server';
4
- import { safeDecodeAsync, safeEncodeAsync } from '@temporary-name/zod';
5
-
6
- function isStartWithMiddlewares(middlewares, compare) {
7
- if (compare.length > middlewares.length) {
8
- return false;
9
- }
10
- for (let i = 0; i < middlewares.length; i++) {
11
- if (compare[i] === void 0) {
12
- return true;
13
- }
14
- if (middlewares[i] !== compare[i]) {
15
- return false;
16
- }
17
- }
18
- return true;
19
- }
20
- function mergeMiddlewares(first, second, options) {
21
- if (options.dedupeLeading && isStartWithMiddlewares(second, first)) {
22
- return second;
23
- }
24
- return [...first, ...second];
25
- }
26
- function addMiddleware(middlewares, addition) {
27
- return [...middlewares, addition];
28
- }
29
-
30
- class Contract {
31
- /**
32
- * This property holds the defined options.
33
- */
34
- "~orpc";
35
- constructor(def) {
36
- this["~orpc"] = def;
37
- }
38
- }
39
- class Procedure extends Contract {
40
- }
41
- function isProcedure(item) {
42
- return item instanceof Procedure || // This is so we'll return true for Proxy-wrapped Procedures e.g. as returned by `callable`
43
- (typeof item === "object" || typeof item === "function") && item !== null && "~orpc" in item && typeof item["~orpc"] === "object" && item["~orpc"] !== null && "route" in item["~orpc"] && "meta" in item["~orpc"] && "middlewares" in item["~orpc"] && "inputValidationIndex" in item["~orpc"] && "outputValidationIndex" in item["~orpc"] && "handler" in item["~orpc"];
44
- }
45
-
46
- function mergeCurrentContext(context, other) {
47
- return { ...context, ...other };
48
- }
49
-
50
- function getRouter(router, path) {
51
- let current = router;
52
- for (let i = 0; i < path.length; i++) {
53
- const segment = path[i];
54
- if (!current) {
55
- return void 0;
56
- }
57
- if (isProcedure(current)) {
58
- return void 0;
59
- }
60
- if (!isLazy(current)) {
61
- current = current[segment];
62
- continue;
63
- }
64
- const lazied = current;
65
- const rest = path.slice(i);
66
- return lazyInternal(async () => {
67
- const unwrapped = await unlazy(lazied);
68
- const next = getRouter(unwrapped.default, rest);
69
- return unlazy(next);
70
- }, getLazyMeta(lazied));
71
- }
72
- return current;
73
- }
74
- function createAccessibleLazyRouter(lazied) {
75
- const recursive = new Proxy(lazied, {
76
- get(target, key) {
77
- if (typeof key !== "string") {
78
- return Reflect.get(target, key);
79
- }
80
- const next = getRouter(lazied, [key]);
81
- return createAccessibleLazyRouter(next);
82
- }
83
- });
84
- return recursive;
85
- }
86
- function enhanceRouter(router, options) {
87
- if (isLazy(router)) {
88
- const laziedMeta = getLazyMeta(router);
89
- const enhancedPrefix = laziedMeta?.prefix ? mergePrefix(options.prefix, laziedMeta?.prefix) : options.prefix;
90
- const enhanced2 = lazyInternal(
91
- async () => {
92
- const { default: unlaziedRouter } = await unlazy(router);
93
- const enhanced3 = enhanceRouter(unlaziedRouter, options);
94
- return unlazy(enhanced3);
95
- },
96
- {
97
- ...laziedMeta,
98
- prefix: enhancedPrefix
99
- }
100
- );
101
- const accessible = createAccessibleLazyRouter(enhanced2);
102
- return accessible;
103
- }
104
- if (isProcedure(router)) {
105
- const newMiddlewares = mergeMiddlewares(options.middlewares, router["~orpc"].middlewares, {
106
- dedupeLeading: options.dedupeLeadingMiddlewares
107
- });
108
- const newMiddlewareAdded = newMiddlewares.length - router["~orpc"].middlewares.length;
109
- const enhanced2 = new Procedure({
110
- ...router["~orpc"],
111
- route: enhanceRoute(router["~orpc"].route, options),
112
- middlewares: newMiddlewares,
113
- inputValidationIndex: router["~orpc"].inputValidationIndex + newMiddlewareAdded,
114
- outputValidationIndex: router["~orpc"].outputValidationIndex + newMiddlewareAdded
115
- });
116
- return enhanced2;
117
- }
118
- const enhanced = {};
119
- for (const key in router) {
120
- enhanced[key] = enhanceRouter(router[key], options);
121
- }
122
- return enhanced;
123
- }
124
- function traverseContractProcedures(options, callback, lazyOptions = []) {
125
- const currentRouter = options.router;
126
- if (isLazy(currentRouter)) {
127
- lazyOptions.push({
128
- router: currentRouter,
129
- path: options.path
130
- });
131
- } else if (currentRouter instanceof Contract) {
132
- callback({
133
- contract: currentRouter,
134
- path: options.path
135
- });
136
- } else if (typeof currentRouter === "string") {
137
- throw new Error("Unexpected: got string instead of router");
138
- } else {
139
- for (const key in currentRouter) {
140
- traverseContractProcedures(
141
- {
142
- router: currentRouter[key],
143
- path: [...options.path, key]
144
- },
145
- callback,
146
- lazyOptions
147
- );
148
- }
149
- }
150
- return lazyOptions;
151
- }
152
- async function resolveContractProcedures(options, callback) {
153
- const pending = [options];
154
- for (const options2 of pending) {
155
- const lazyOptions = traverseContractProcedures(options2, callback);
156
- for (const options3 of lazyOptions) {
157
- const { default: router } = await unlazy(options3.router);
158
- pending.push({
159
- router,
160
- path: options3.path
161
- });
162
- }
163
- }
164
- }
165
- async function unlazyRouter(router) {
166
- if (isProcedure(router)) {
167
- return router;
168
- }
169
- const unlazied = {};
170
- for (const key in router) {
171
- const item = router[key];
172
- const { default: unlaziedRouter } = await unlazy(item);
173
- unlazied[key] = await unlazyRouter(unlaziedRouter);
174
- }
175
- return unlazied;
176
- }
177
-
178
- const LAZY_SYMBOL = Symbol("ORPC_LAZY_SYMBOL");
179
- function lazyInternal(loader, meta = {}) {
180
- return {
181
- [LAZY_SYMBOL]: {
182
- loader,
183
- meta
184
- }
185
- };
186
- }
187
- function lazy(prefix, loader) {
188
- return enhanceRouter(lazyInternal(loader), {
189
- middlewares: [],
190
- dedupeLeadingMiddlewares: true,
191
- prefix
192
- });
193
- }
194
- function isLazy(item) {
195
- return (typeof item === "object" || typeof item === "function") && item !== null && LAZY_SYMBOL in item;
196
- }
197
- function getLazyMeta(lazied) {
198
- return lazied[LAZY_SYMBOL].meta;
199
- }
200
- function unlazy(lazied) {
201
- return isLazy(lazied) ? lazied[LAZY_SYMBOL].loader() : Promise.resolve({ default: lazied });
202
- }
203
-
204
- function middlewareOutputFn(output) {
205
- return { output, context: {} };
206
- }
207
-
208
- function createProcedureClient(lazyableProcedure, ...rest) {
209
- const options = resolveMaybeOptionalOptions(rest);
210
- return async (...[input, callerOptions]) => {
211
- const path = toArray(options.path);
212
- const { default: procedure } = await unlazy(lazyableProcedure);
213
- const clientContext = callerOptions?.context ?? {};
214
- const context = await value(options.context ?? {}, clientContext);
215
- const output = await runWithSpan({ name: "call_procedure", signal: callerOptions?.signal }, (span) => {
216
- span?.setAttribute("procedure.path", [...path]);
217
- return executeProcedureInternal(procedure, input, {
218
- context,
219
- path,
220
- procedure,
221
- request: callerOptions?.request,
222
- signal: callerOptions?.signal,
223
- lastEventId: callerOptions?.lastEventId
224
- });
225
- });
226
- if (isAsyncIteratorObject(output)) {
227
- if (output instanceof HibernationEventIterator) {
228
- return output;
229
- }
230
- return overlayProxy(
231
- output,
232
- mapEventIterator(
233
- asyncIteratorWithSpan(
234
- { name: "consume_event_iterator_output", signal: callerOptions?.signal },
235
- output
236
- ),
237
- {
238
- value: (v) => v,
239
- error: async (e) => e
240
- }
241
- )
242
- );
243
- }
244
- return output;
245
- };
246
- }
247
- async function validateInput(procedure, input) {
248
- const schemas = procedure["~orpc"].schemas;
249
- return runWithSpan({ name: "validate_input" }, async () => {
250
- const resultBody = await safeDecodeAsync(schemas.bodySchema, input.body, { parseType: "body" });
251
- const resultPath = await safeDecodeAsync(schemas.pathSchema, input.path, { parseType: "path" });
252
- const resultQuery = await safeDecodeAsync(schemas.querySchema, input.query, { parseType: "query" });
253
- const issues = [];
254
- if (!resultBody.success) {
255
- issues.push(...resultBody.error.issues.map((i) => ({ ...i, path: ["body", ...i.path] })));
256
- }
257
- if (!resultPath.success) {
258
- issues.push(...resultPath.error.issues.map((i) => ({ ...i, path: ["path", ...i.path] })));
259
- }
260
- if (!resultQuery.success) {
261
- issues.push(...resultQuery.error.issues.map((i) => ({ ...i, path: ["query", ...i.path] })));
262
- }
263
- if (issues.length > 0) {
264
- throw new ORPCError("BAD_REQUEST", {
265
- message: "Input validation failed",
266
- data: {
267
- issues
268
- },
269
- cause: new ValidationError({
270
- message: "Input validation failed",
271
- issues,
272
- data: input
273
- })
274
- });
275
- }
276
- const results = {
277
- body: resultBody.data,
278
- path: resultPath.data,
279
- query: resultQuery.data
280
- };
281
- return results;
282
- });
283
- }
284
- async function validateOutput(procedure, output) {
285
- const schema = procedure["~orpc"].schemas.outputSchema;
286
- if (!schema) {
287
- return output;
288
- }
289
- return runWithSpan({ name: "validate_output" }, async () => {
290
- const result = await safeEncodeAsync(schema, output, { parseType: "output" });
291
- if (!result.success) {
292
- throw new ORPCError("INTERNAL_SERVER_ERROR", {
293
- message: "Output validation failed",
294
- cause: new ValidationError({
295
- message: "Output validation failed",
296
- issues: result.error.issues,
297
- data: output
298
- })
299
- });
300
- }
301
- return result.data;
302
- });
303
- }
304
- async function executeProcedureInternal(procedure, input, options) {
305
- const middlewares = procedure["~orpc"].middlewares;
306
- const inputValidationIndex = Math.min(
307
- Math.max(0, procedure["~orpc"].inputValidationIndex),
308
- middlewares.length
309
- );
310
- const outputValidationIndex = Math.min(
311
- Math.max(0, procedure["~orpc"].outputValidationIndex),
312
- middlewares.length
313
- );
314
- const next = async (index, context, input2) => {
315
- let currentInput = input2;
316
- if (index === inputValidationIndex) {
317
- currentInput = await validateInput(procedure, currentInput);
318
- }
319
- const mid = middlewares[index];
320
- const output = mid ? await runWithSpan({ name: `middleware.${mid.name}`, signal: options.signal }, async (span) => {
321
- span?.setAttribute("middleware.index", index);
322
- span?.setAttribute("middleware.name", mid.name);
323
- const result = await mid(
324
- {
325
- ...options,
326
- context,
327
- next: async (...[nextOptions]) => {
328
- const nextContext = nextOptions?.context ?? {};
329
- return {
330
- output: await next(index + 1, mergeCurrentContext(context, nextContext), currentInput),
331
- // NB: Pretty sure this isn't used (or meant to be used) at runtime, it's just there
332
- // to get type inference in the builder (via the caller returning the output of next() in
333
- // the middleware function)
334
- context: nextContext
335
- };
336
- }
337
- },
338
- currentInput,
339
- middlewareOutputFn
340
- );
341
- return result.output;
342
- }) : await runWithSpan(
343
- { name: "handler", signal: options.signal },
344
- () => procedure["~orpc"].handler(currentInput, { ...options, context })
345
- );
346
- if (index === outputValidationIndex) {
347
- return await validateOutput(procedure, output);
348
- }
349
- return output;
350
- };
351
- return next(0, options.context, input);
352
- }
353
-
354
- export { Contract as C, LAZY_SYMBOL as L, Procedure as P, addMiddleware as a, isLazy as b, createProcedureClient as c, getRouter as d, enhanceRouter as e, lazy as f, getLazyMeta as g, middlewareOutputFn as h, isProcedure as i, isStartWithMiddlewares as j, mergeMiddlewares as k, lazyInternal as l, mergeCurrentContext as m, createAccessibleLazyRouter as n, unlazyRouter as o, resolveContractProcedures as r, traverseContractProcedures as t, unlazy as u };