@temporary-name/server 1.9.3-alpha.65222302f1b71807a849530b3fe0fa0326d3c1a2 → 1.9.3-alpha.6d3c10e7b535aec2de4b812161c8001a916134b9

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 (42) hide show
  1. package/dist/adapters/aws-lambda/index.d.mts +4 -6
  2. package/dist/adapters/aws-lambda/index.d.ts +4 -6
  3. package/dist/adapters/aws-lambda/index.mjs +5 -7
  4. package/dist/adapters/fetch/index.d.mts +8 -86
  5. package/dist/adapters/fetch/index.d.ts +8 -86
  6. package/dist/adapters/fetch/index.mjs +17 -158
  7. package/dist/adapters/node/index.d.mts +8 -63
  8. package/dist/adapters/node/index.d.ts +8 -63
  9. package/dist/adapters/node/index.mjs +15 -123
  10. package/dist/adapters/standard/index.d.mts +20 -33
  11. package/dist/adapters/standard/index.d.ts +20 -33
  12. package/dist/adapters/standard/index.mjs +5 -7
  13. package/dist/helpers/index.mjs +3 -29
  14. package/dist/index.d.mts +122 -267
  15. package/dist/index.d.ts +122 -267
  16. package/dist/index.mjs +214 -380
  17. package/dist/openapi/index.d.mts +12 -28
  18. package/dist/openapi/index.d.ts +12 -28
  19. package/dist/openapi/index.mjs +66 -150
  20. package/dist/shared/server.BYV-qTJt.d.ts +41 -0
  21. package/dist/shared/server.C1RJffw4.mjs +30 -0
  22. package/dist/shared/server.CQIFwyhc.mjs +40 -0
  23. package/dist/shared/server.CWb33y9B.d.mts +41 -0
  24. package/dist/shared/server.ChOv1yG3.mjs +319 -0
  25. package/dist/shared/server.DXzEGRE2.mjs +403 -0
  26. package/dist/shared/server.DgzAlPjF.mjs +160 -0
  27. package/dist/shared/server.DimTvmOQ.d.mts +373 -0
  28. package/dist/shared/server.DimTvmOQ.d.ts +373 -0
  29. package/dist/shared/server.YUvuxHty.mjs +48 -0
  30. package/package.json +10 -26
  31. package/dist/plugins/index.d.mts +0 -160
  32. package/dist/plugins/index.d.ts +0 -160
  33. package/dist/plugins/index.mjs +0 -288
  34. package/dist/shared/server.BEHw7Eyx.mjs +0 -247
  35. package/dist/shared/server.BKSOrA6h.d.mts +0 -192
  36. package/dist/shared/server.BKSOrA6h.d.ts +0 -192
  37. package/dist/shared/server.BKh8I1Ny.mjs +0 -239
  38. package/dist/shared/server.BeuTpcmO.d.mts +0 -23
  39. package/dist/shared/server.C1fnTLq0.d.mts +0 -57
  40. package/dist/shared/server.CQyYNJ1H.d.ts +0 -57
  41. package/dist/shared/server.DLsti1Pv.mjs +0 -293
  42. package/dist/shared/server.SLLuK6_v.d.ts +0 -23
package/dist/index.mjs CHANGED
@@ -1,136 +1,72 @@
1
- import { onError, resolveMaybeOptionalOptions } from '@temporary-name/shared';
2
- export { AsyncIteratorClass, EventPublisher, ORPCError, asyncIteratorToStream as eventIteratorToStream, isDefinedError, onError, onFinish, onStart, onSuccess, safe, streamToAsyncIteratorClass as streamToEventIterator } from '@temporary-name/shared';
3
- import { isContractProcedure, mergeErrorMap, mergeMeta, mergeRoute, mergePrefix, enhanceRoute, mergeTags, ContractProcedureBuilder, getContractRouter } from '@temporary-name/contract';
4
- export { ValidationError, eventIterator, type, validateORPCError } from '@temporary-name/contract';
5
- import { c as createProcedureClient, i as isLazy, g as getLazyMeta, l as lazy, u as unlazy, a as gatingContext } from './shared/server.BKh8I1Ny.mjs';
6
- export { L as LAZY_SYMBOL, b as createORPCErrorConstructorMap, m as mergeCurrentContext, d as middlewareOutputFn } from './shared/server.BKh8I1Ny.mjs';
1
+ import { assertNever, splitFirst, ORPCError, onError, resolveMaybeOptionalOptions, isTypescriptObject, isPropertyKey } from '@temporary-name/shared';
2
+ export { AsyncIteratorClass, EventPublisher, ORPCError, asyncIteratorToStream as eventIteratorToStream, isDefinedError, onError, onFinish, onStart, onSuccess, streamToAsyncIteratorClass as streamToEventIterator } from '@temporary-name/shared';
3
+ import * as z from '@temporary-name/zod';
4
+ import { SchemaClass, object, core, gatingContext } from '@temporary-name/zod';
5
+ import { g as getCookie } from './shared/server.C1RJffw4.mjs';
6
+ import { P as Procedure, m as mergePrefix, a as mergeTags, e as enhanceRouter, C as Contract, p as parseEndpointDefinition, b as mergeRoute, c as prefixRoute, d as addMiddleware, l as lazyInternal, f as getLazyMeta, u as unlazy, i as isProcedure, h as isLazy, j as getRouter } from './shared/server.ChOv1yG3.mjs';
7
+ export { L as LAZY_SYMBOL, V as ValidationError, q as createAccessibleLazyRouter, w as endpointRegex, g as getDynamicParams, n as isStartWithMiddlewares, k as lazy, o as mergeMiddlewares, r as resolveContractProcedures, s as standardizeHTTPPath, t as traverseContractProcedures, v as unlazyRouter } from './shared/server.ChOv1yG3.mjs';
8
+ import { c as createProcedureClient } from './shared/server.DgzAlPjF.mjs';
9
+ export { m as mergeCurrentContext, a as middlewareOutputFn } from './shared/server.DgzAlPjF.mjs';
10
+ export { e as eventIterator, g as getEventIteratorSchemaDetails } from './shared/server.YUvuxHty.mjs';
7
11
  export { getEventMeta, withEventMeta } from '@temporary-name/standard-server';
8
- import 'node:async_hooks';
9
- import 'zod';
10
- import 'zod/v4/core';
12
+ import 'cookie';
11
13
 
12
- function isStartWithMiddlewares(middlewares, compare) {
13
- if (compare.length > middlewares.length) {
14
- return false;
15
- }
16
- for (let i = 0; i < middlewares.length; i++) {
17
- if (compare[i] === void 0) {
18
- return true;
19
- }
20
- if (middlewares[i] !== compare[i]) {
21
- return false;
22
- }
14
+ function validateTokenPrefix(prefix, token) {
15
+ if (prefix && !token.startsWith(prefix)) {
16
+ throw new ORPCError("UNAUTHORIZED", { message: `Invalid auth token. It must start with "${prefix}"` });
23
17
  }
24
- return true;
25
18
  }
26
- function mergeMiddlewares(first, second, options) {
27
- if (options.dedupeLeading && isStartWithMiddlewares(second, first)) {
28
- return second;
29
- }
30
- return [...first, ...second];
19
+ function validateTokenAuth(config, token, options) {
20
+ const { tokenPrefix, validate } = config;
21
+ validateTokenPrefix(tokenPrefix, token);
22
+ return validate(token, options);
31
23
  }
32
- function addMiddleware(middlewares, addition) {
33
- return [...middlewares, addition];
24
+ function authByQuery(config, options) {
25
+ const { name, tokenPrefix, validate } = config;
26
+ const query = options.request.url.searchParams;
27
+ const token = query.get(name);
28
+ if (!token) return void 0;
29
+ validateTokenPrefix(tokenPrefix, token);
30
+ return validate(token, options);
34
31
  }
35
-
36
- function decorateMiddleware(middleware) {
37
- const decorated = ((...args) => middleware(...args));
38
- decorated.mapInput = (mapInput) => {
39
- const mapped = decorateMiddleware(
40
- (options, input, ...rest) => middleware(options, mapInput(input), ...rest)
41
- );
42
- return mapped;
43
- };
44
- decorated.concat = (concatMiddleware, mapInput) => {
45
- const mapped = mapInput ? decorateMiddleware(concatMiddleware).mapInput(mapInput) : concatMiddleware;
46
- const concatted = decorateMiddleware((options, input, output, ...rest) => {
47
- const merged = middleware(
48
- {
49
- ...options,
50
- next: (...[nextOptions1]) => mapped(
51
- {
52
- ...options,
53
- context: { ...options.context, ...nextOptions1?.context },
54
- next: (...[nextOptions2]) => options.next({ context: { ...nextOptions1?.context, ...nextOptions2?.context } })
55
- },
56
- input,
57
- output,
58
- ...rest
59
- )
60
- },
61
- input,
62
- output,
63
- ...rest
64
- );
65
- return merged;
66
- });
67
- return concatted;
68
- };
69
- return decorated;
32
+ function authByHeader(config, options) {
33
+ const authHeader = options.request.headers.get(config.name);
34
+ return authHeader ? validateTokenAuth(config, authHeader, options) : void 0;
70
35
  }
71
-
72
- class Procedure {
73
- /**
74
- * This property holds the defined options.
75
- */
76
- "~orpc";
77
- constructor(def) {
78
- this["~orpc"] = def;
79
- }
36
+ function authByCookie(config, options) {
37
+ const cookie = getCookie(options.request.headers, config.name);
38
+ return cookie ? validateTokenAuth(config, cookie, options) : void 0;
80
39
  }
81
- function isProcedure(item) {
82
- if (item instanceof Procedure) {
83
- return true;
84
- }
85
- return isContractProcedure(item) && "middlewares" in item["~orpc"] && "inputValidationIndex" in item["~orpc"] && "outputValidationIndex" in item["~orpc"] && "handler" in item["~orpc"];
40
+ function authByBearer(config, options) {
41
+ const authHeader = options.request.headers.get("Authorization");
42
+ if (!authHeader) return void 0;
43
+ const [authType, bearer] = splitFirst(authHeader, " ");
44
+ return authType === "Bearer" ? validateTokenAuth(config, bearer, options) : void 0;
45
+ }
46
+ function authByBasic(config, options) {
47
+ const authHeader = options.request.headers.get("Authorization");
48
+ if (!authHeader) return void 0;
49
+ const [authType, encoded] = splitFirst(authHeader, " ");
50
+ if (authType !== "Basic") return void 0;
51
+ const decoded = Buffer.from(encoded, "base64").toString("utf-8");
52
+ const [username, password] = splitFirst(decoded, ":");
53
+ validateTokenPrefix(config.tokenPrefix, password);
54
+ return config.validate(username, password, options);
55
+ }
56
+ function authByType(config, options) {
57
+ const { type } = config;
58
+ return type === "header" ? authByHeader(config, options) : type === "query" ? authByQuery(config, options) : type === "cookie" ? authByCookie(config, options) : type === "bearer" ? authByBearer(config, options) : type === "basic" ? authByBasic(config, options) : type === "none" ? false : assertNever(type);
59
+ }
60
+ function authDescription(config) {
61
+ const { type } = config;
62
+ return type === "basic" ? "a Basic Authentication header" : type === "bearer" ? "a Bearer Authentication header" : type === "header" ? `a header named "${config.name}"` : type === "query" ? `a query parameter named "${config.name}"` : type === "cookie" ? `a cookie named "${config.name}"` : type === "none" ? "no authentication" : assertNever(type);
63
+ }
64
+
65
+ function mergeMeta(meta1, meta2) {
66
+ return { ...meta1, ...meta2 };
86
67
  }
87
68
 
88
69
  class DecoratedProcedure extends Procedure {
89
- /**
90
- * Adds type-safe custom errors.
91
- * The provided errors are spared-merged with any existing errors.
92
- *
93
- * @see {@link https://orpc.unnoq.com/docs/error-handling#type%E2%80%90safe-error-handling Type-Safe Error Handling Docs}
94
- */
95
- errors(errors) {
96
- return new DecoratedProcedure({
97
- ...this["~orpc"],
98
- errorMap: mergeErrorMap(this["~orpc"].errorMap, errors)
99
- });
100
- }
101
- /**
102
- * Sets or updates the metadata.
103
- * The provided metadata is spared-merged with any existing metadata.
104
- *
105
- * @see {@link https://orpc.unnoq.com/docs/metadata Metadata Docs}
106
- */
107
- meta(meta) {
108
- return new DecoratedProcedure({
109
- ...this["~orpc"],
110
- meta: mergeMeta(this["~orpc"].meta, meta)
111
- });
112
- }
113
- /**
114
- * Sets or updates the route definition.
115
- * The provided route is spared-merged with any existing route.
116
- * This option is typically relevant when integrating with OpenAPI.
117
- *
118
- * @see {@link https://orpc.unnoq.com/docs/openapi/routing OpenAPI Routing Docs}
119
- * @see {@link https://orpc.unnoq.com/docs/openapi/input-output-structure OpenAPI Input/Output Structure Docs}
120
- */
121
- route(route) {
122
- return new DecoratedProcedure({
123
- ...this["~orpc"],
124
- route: mergeRoute(this["~orpc"].route, route)
125
- });
126
- }
127
- use(middleware, mapInput) {
128
- const mapped = mapInput ? decorateMiddleware(middleware).mapInput(mapInput) : middleware;
129
- return new DecoratedProcedure({
130
- ...this["~orpc"],
131
- middlewares: addMiddleware(this["~orpc"].middlewares, mapped)
132
- });
133
- }
134
70
  /**
135
71
  * Make this procedure callable (works like a function while still being a procedure).
136
72
  *
@@ -149,165 +85,76 @@ class DecoratedProcedure extends Procedure {
149
85
  }
150
86
  }
151
87
 
152
- const HIDDEN_ROUTER_CONTRACT_SYMBOL = Symbol("ORPC_HIDDEN_ROUTER_CONTRACT");
153
- function setHiddenRouterContract(router, contract) {
154
- return new Proxy(router, {
155
- get(target, key) {
156
- if (key === HIDDEN_ROUTER_CONTRACT_SYMBOL) {
157
- return contract;
158
- }
159
- return Reflect.get(target, key);
160
- }
161
- });
162
- }
163
- function getHiddenRouterContract(router) {
164
- return router[HIDDEN_ROUTER_CONTRACT_SYMBOL];
165
- }
88
+ const initialSchemas = {
89
+ pathSchema: z.strictObject({}),
90
+ querySchema: z.strictObject({}),
91
+ bodySchema: z.strictObject({}),
92
+ outputSchema: z.unknown()
93
+ };
166
94
 
167
- function getRouter(router, path) {
168
- let current = router;
169
- for (let i = 0; i < path.length; i++) {
170
- const segment = path[i];
171
- if (!current) {
172
- return void 0;
173
- }
174
- if (isProcedure(current)) {
175
- return void 0;
176
- }
177
- if (!isLazy(current)) {
178
- current = current[segment];
179
- continue;
180
- }
181
- const lazied = current;
182
- const rest = path.slice(i);
183
- return lazy(async () => {
184
- const unwrapped = await unlazy(lazied);
185
- const next = getRouter(unwrapped.default, rest);
186
- return unlazy(next);
187
- }, getLazyMeta(lazied));
188
- }
189
- return current;
190
- }
191
- function createAccessibleLazyRouter(lazied) {
192
- const recursive = new Proxy(lazied, {
193
- get(target, key) {
194
- if (typeof key !== "string") {
195
- return Reflect.get(target, key);
196
- }
197
- const next = getRouter(lazied, [key]);
198
- return createAccessibleLazyRouter(next);
199
- }
200
- });
201
- return recursive;
202
- }
203
- function enhanceRouter(router, options) {
204
- if (isLazy(router)) {
205
- const laziedMeta = getLazyMeta(router);
206
- const enhancedPrefix = laziedMeta?.prefix ? mergePrefix(options.prefix, laziedMeta?.prefix) : options.prefix;
207
- const enhanced2 = lazy(
208
- async () => {
209
- const { default: unlaziedRouter } = await unlazy(router);
210
- const enhanced3 = enhanceRouter(unlaziedRouter, options);
211
- return unlazy(enhanced3);
212
- },
213
- {
214
- ...laziedMeta,
215
- prefix: enhancedPrefix
216
- }
217
- );
218
- const accessible = createAccessibleLazyRouter(enhanced2);
219
- return accessible;
95
+ class ProcedureBuilder extends Contract {
96
+ z;
97
+ constructor(def) {
98
+ super(def);
99
+ this.z = new SchemaClass();
220
100
  }
221
- if (isProcedure(router)) {
222
- const newMiddlewares = mergeMiddlewares(options.middlewares, router["~orpc"].middlewares, {
223
- dedupeLeading: options.dedupeLeadingMiddlewares
224
- });
225
- const newMiddlewareAdded = newMiddlewares.length - router["~orpc"].middlewares.length;
226
- const enhanced2 = new Procedure({
227
- ...router["~orpc"],
228
- route: enhanceRoute(router["~orpc"].route, options),
229
- errorMap: mergeErrorMap(options.errorMap, router["~orpc"].errorMap),
230
- middlewares: newMiddlewares,
231
- inputValidationIndex: router["~orpc"].inputValidationIndex + newMiddlewareAdded,
232
- outputValidationIndex: router["~orpc"].outputValidationIndex + newMiddlewareAdded
101
+ /**
102
+ * Sets or updates the metadata for the contract.
103
+ * The provided metadata is spared-merged with any existing metadata in the contract.
104
+ *
105
+ * @see {@link https://orpc.unnoq.com/docs/metadata Metadata Docs}
106
+ */
107
+ meta(meta) {
108
+ return new ProcedureBuilder({
109
+ ...this["~orpc"],
110
+ meta: mergeMeta(this["~orpc"].meta, meta)
233
111
  });
234
- return enhanced2;
235
- }
236
- const enhanced = {};
237
- for (const key in router) {
238
- enhanced[key] = enhanceRouter(router[key], options);
239
112
  }
240
- return enhanced;
241
- }
242
- function traverseContractProcedures(options, callback, lazyOptions = []) {
243
- let currentRouter = options.router;
244
- const hiddenContract = getHiddenRouterContract(options.router);
245
- if (hiddenContract !== void 0) {
246
- currentRouter = hiddenContract;
247
- }
248
- if (isLazy(currentRouter)) {
249
- lazyOptions.push({
250
- router: currentRouter,
251
- path: options.path
252
- });
253
- } else if (isContractProcedure(currentRouter)) {
254
- callback({
255
- contract: currentRouter,
256
- path: options.path
113
+ endpoint(stringsOrEndpoint, ...values) {
114
+ const { method, path, pathSchema } = parseEndpointDefinition(stringsOrEndpoint, values);
115
+ const { prefix } = this["~orpc"];
116
+ const route = { method, path };
117
+ return new ProcedureBuilder({
118
+ ...this["~orpc"],
119
+ route: mergeRoute(this["~orpc"].route, prefix ? prefixRoute(route, prefix) : route),
120
+ schemas: {
121
+ ...this["~orpc"].schemas,
122
+ pathSchema
123
+ }
257
124
  });
258
- } else {
259
- for (const key in currentRouter) {
260
- traverseContractProcedures(
261
- {
262
- router: currentRouter[key],
263
- path: [...options.path, key]
264
- },
265
- callback,
266
- lazyOptions
267
- );
268
- }
269
- }
270
- return lazyOptions;
271
- }
272
- async function resolveContractProcedures(options, callback) {
273
- const pending = [options];
274
- for (const options2 of pending) {
275
- const lazyOptions = traverseContractProcedures(options2, callback);
276
- for (const options3 of lazyOptions) {
277
- const { default: router } = await unlazy(options3.router);
278
- pending.push({
279
- router,
280
- path: options3.path
281
- });
282
- }
283
- }
284
- }
285
- async function unlazyRouter(router) {
286
- if (isProcedure(router)) {
287
- return router;
288
- }
289
- const unlazied = {};
290
- for (const key in router) {
291
- const item = router[key];
292
- const { default: unlaziedRouter } = await unlazy(item);
293
- unlazied[key] = await unlazyRouter(unlaziedRouter);
294
- }
295
- return unlazied;
296
- }
297
-
298
- class ProcedureBuilder extends ContractProcedureBuilder {
299
- constructor(def) {
300
- super(def);
301
125
  }
302
126
  /**
303
- * Defines the input validation schema.
127
+ * Sets or updates the route definition for the contract.
128
+ * The provided route is spared-merged with any existing route in the contract.
129
+ * This option is typically relevant when integrating with OpenAPI.
304
130
  *
305
- * @see {@link https://orpc.unnoq.com/docs/procedure#input-output-validation Input Validation Docs}
131
+ * @see {@link https://orpc.unnoq.com/docs/openapi/routing OpenAPI Routing Docs}
132
+ * @see {@link https://orpc.unnoq.com/docs/openapi/input-output-structure OpenAPI Input/Output Structure Docs}
306
133
  */
307
- input(schema) {
134
+ endpointOpts(route) {
135
+ const { prefix } = this["~orpc"];
308
136
  return new ProcedureBuilder({
309
137
  ...this["~orpc"],
310
- inputSchema: schema,
138
+ route: mergeRoute(this["~orpc"].route, prefix ? prefixRoute(route, prefix) : route)
139
+ });
140
+ }
141
+ query(schema) {
142
+ return new ProcedureBuilder({
143
+ ...this["~orpc"],
144
+ schemas: {
145
+ ...this["~orpc"].schemas,
146
+ querySchema: schema instanceof core.$ZodType ? schema : object(schema)
147
+ },
148
+ inputValidationIndex: this["~orpc"].middlewares.length
149
+ });
150
+ }
151
+ body(schema) {
152
+ return new ProcedureBuilder({
153
+ ...this["~orpc"],
154
+ schemas: {
155
+ ...this["~orpc"].schemas,
156
+ bodySchema: schema instanceof core.$ZodType ? schema : object(schema)
157
+ },
311
158
  inputValidationIndex: this["~orpc"].middlewares.length
312
159
  });
313
160
  }
@@ -319,7 +166,10 @@ class ProcedureBuilder extends ContractProcedureBuilder {
319
166
  output(schema) {
320
167
  return new ProcedureBuilder({
321
168
  ...this["~orpc"],
322
- outputSchema: schema,
169
+ schemas: {
170
+ ...this["~orpc"].schemas,
171
+ outputSchema: schema instanceof core.$ZodType ? schema : object(schema)
172
+ },
323
173
  outputValidationIndex: this["~orpc"].middlewares.length
324
174
  });
325
175
  }
@@ -336,6 +186,36 @@ class ProcedureBuilder extends ContractProcedureBuilder {
336
186
  middlewares: addMiddleware(this["~orpc"].middlewares, middleware)
337
187
  });
338
188
  }
189
+ // `& {}` is so AuthType will be expanded in parameter info tooltips.
190
+ // The default of false for ValidatedAuthContext is used when you pass in the type 'none'. We use false
191
+ // because we can't use null or undefined (see ValidatedAuthContext) but we still want it to be falsy.
192
+ useAuth(type, ...rest) {
193
+ const config = { type, ...rest[0] };
194
+ const middleware = os.$context().middleware(async (options) => {
195
+ const { next, context } = options;
196
+ if (context.auth) return next();
197
+ const auth = await authByType(config, options);
198
+ if (auth === void 0) {
199
+ const { authConfigs } = options.procedure["~orpc"];
200
+ if (context.auth !== false && config === authConfigs.at(-1)) {
201
+ let authDescriptions = authConfigs.map(authDescription).join(", ");
202
+ if (authConfigs.length > 1) {
203
+ authDescriptions = `one of: ${authDescriptions}`;
204
+ }
205
+ throw new ORPCError("UNAUTHORIZED", {
206
+ message: `Authentication required. You must provide ${authDescriptions}`
207
+ });
208
+ }
209
+ return next();
210
+ }
211
+ return next({ context: { auth } });
212
+ });
213
+ return new this.constructor({
214
+ ...this["~orpc"],
215
+ authConfigs: [...this["~orpc"].authConfigs, config],
216
+ middlewares: addMiddleware(this["~orpc"].middlewares, middleware)
217
+ });
218
+ }
339
219
  useGating(gates, isGateEnabled) {
340
220
  return this.use(({ next, context }) => {
341
221
  return gatingContext.run(
@@ -350,6 +230,9 @@ class ProcedureBuilder extends ContractProcedureBuilder {
350
230
  * @see {@link https://orpc.unnoq.com/docs/procedure Procedure Docs}
351
231
  */
352
232
  handler(handler) {
233
+ if (this["~orpc"].schemas.outputSchema === initialSchemas.outputSchema) {
234
+ throw new Error("You must call .output() before calling .handler()");
235
+ }
353
236
  return new DecoratedProcedure({
354
237
  ...this["~orpc"],
355
238
  handler
@@ -391,15 +274,42 @@ class BuilderWithMiddlewares extends ProcedureBuilder {
391
274
  router(router) {
392
275
  return enhanceRouter(router, this["~orpc"]);
393
276
  }
394
- /**
395
- * Create a lazy router
396
- * And applies all of the previously defined options to the specified router.
397
- *
398
- * @see {@link https://orpc.unnoq.com/docs/router#extending-router Extending Router Docs}
399
- */
400
- lazyRoute(loader) {
401
- return enhanceRouter(lazy(loader), this["~orpc"]);
402
- }
277
+ }
278
+
279
+ function decorateMiddleware(middleware) {
280
+ const decorated = ((...args) => middleware(...args));
281
+ decorated.mapInput = (mapInput) => {
282
+ const mapped = decorateMiddleware(
283
+ (options, input, ...rest) => middleware(options, mapInput(input), ...rest)
284
+ );
285
+ return mapped;
286
+ };
287
+ decorated.concat = (concatMiddleware, mapInput) => {
288
+ const mapped = mapInput ? decorateMiddleware(concatMiddleware).mapInput(mapInput) : concatMiddleware;
289
+ const concatted = decorateMiddleware((options, input, output, ...rest) => {
290
+ const merged = middleware(
291
+ {
292
+ ...options,
293
+ next: (...[nextOptions1]) => mapped(
294
+ {
295
+ ...options,
296
+ context: { ...options.context, ...nextOptions1?.context },
297
+ next: (...[nextOptions2]) => options.next({ context: { ...nextOptions1?.context, ...nextOptions2?.context } })
298
+ },
299
+ input,
300
+ output,
301
+ ...rest
302
+ )
303
+ },
304
+ input,
305
+ output,
306
+ ...rest
307
+ );
308
+ return merged;
309
+ });
310
+ return concatted;
311
+ };
312
+ return decorated;
403
313
  }
404
314
 
405
315
  class Builder extends BuilderWithMiddlewares {
@@ -421,112 +331,27 @@ class Builder extends BuilderWithMiddlewares {
421
331
  }
422
332
  }
423
333
  function createApiBuilder(opts = {}) {
424
- const base = new Builder({
334
+ return new Builder({
425
335
  route: {},
426
336
  meta: opts.meta ?? {},
427
- errorMap: {},
428
337
  inputValidationIndex: 0,
429
338
  outputValidationIndex: 0,
430
339
  middlewares: [
431
- onError((error, options) => {
340
+ onError((error, _options) => {
432
341
  console.dir(error, { depth: null });
433
342
  })
434
343
  ],
344
+ schemas: initialSchemas,
435
345
  // NB: this is a relic from orpc -- I'm not convinced there's a need for this (or if there is, that it's
436
346
  // the best solution). For now I've removed the interface to configure it externally.
437
- dedupeLeadingMiddlewares: true
347
+ dedupeLeadingMiddlewares: true,
348
+ authConfigs: []
438
349
  });
439
- return base;
440
350
  }
441
351
  const os = createApiBuilder();
442
352
 
443
- function implementerInternal(contract, middlewares) {
444
- if (isContractProcedure(contract)) {
445
- const impl2 = new Builder({
446
- ...contract["~orpc"],
447
- middlewares,
448
- inputValidationIndex: middlewares.length,
449
- outputValidationIndex: middlewares.length,
450
- dedupeLeadingMiddlewares: true
451
- });
452
- return impl2;
453
- }
454
- const impl = new Proxy(contract, {
455
- get: (target, key) => {
456
- if (typeof key !== "string") {
457
- return Reflect.get(target, key);
458
- }
459
- let method;
460
- if (key === "middleware") {
461
- method = (mid) => decorateMiddleware(mid);
462
- } else if (key === "use") {
463
- method = (mid) => {
464
- return implementerInternal(contract, addMiddleware(middlewares, mid));
465
- };
466
- } else if (key === "router") {
467
- method = (router) => {
468
- const adapted = enhanceRouter(router, {
469
- middlewares,
470
- errorMap: {},
471
- prefix: void 0,
472
- tags: void 0,
473
- dedupeLeadingMiddlewares: true
474
- });
475
- return setHiddenRouterContract(adapted, contract);
476
- };
477
- } else if (key === "lazyRoute") {
478
- method = (loader) => {
479
- const adapted = enhanceRouter(lazy(loader), {
480
- middlewares,
481
- errorMap: {},
482
- prefix: void 0,
483
- tags: void 0,
484
- dedupeLeadingMiddlewares: true
485
- });
486
- return setHiddenRouterContract(adapted, contract);
487
- };
488
- }
489
- const next = getContractRouter(target, [key]);
490
- if (!next) {
491
- return method ?? next;
492
- }
493
- const nextImpl = implementerInternal(next, middlewares);
494
- if (method) {
495
- return new Proxy(method, {
496
- get(_, key2) {
497
- return Reflect.get(nextImpl, key2);
498
- }
499
- });
500
- }
501
- return nextImpl;
502
- }
503
- });
504
- return impl;
505
- }
506
- function implement(contract) {
507
- const implInternal = implementerInternal(contract, []);
508
- const impl = new Proxy(implInternal, {
509
- get: (target, key) => {
510
- let method;
511
- if (key === "$context") {
512
- method = () => impl;
513
- }
514
- const next = Reflect.get(target, key);
515
- if (!method || !next || typeof next !== "function" && typeof next !== "object") {
516
- return method || next;
517
- }
518
- return new Proxy(method, {
519
- get(_, key2) {
520
- return Reflect.get(next, key2);
521
- }
522
- });
523
- }
524
- });
525
- return impl;
526
- }
527
-
528
353
  function createAssertedLazyProcedure(lazied) {
529
- const lazyProcedure = lazy(async () => {
354
+ const lazyProcedure = lazyInternal(async () => {
530
355
  const { default: maybeProcedure } = await unlazy(lazied);
531
356
  if (!isProcedure(maybeProcedure)) {
532
357
  throw new Error(`
@@ -539,14 +364,6 @@ function createAssertedLazyProcedure(lazied) {
539
364
  }, getLazyMeta(lazied));
540
365
  return lazyProcedure;
541
366
  }
542
- function createContractedProcedure(procedure, contract) {
543
- return new Procedure({
544
- ...procedure["~orpc"],
545
- errorMap: contract["~orpc"].errorMap,
546
- route: contract["~orpc"].route,
547
- meta: contract["~orpc"].meta
548
- });
549
- }
550
367
  function call(procedure, input, ...rest) {
551
368
  const options = resolveMaybeOptionalOptions(rest);
552
369
  return createProcedureClient(procedure, options)(input, options);
@@ -577,4 +394,21 @@ function createRouterClient(router, ...rest) {
577
394
  return recursive;
578
395
  }
579
396
 
580
- export { Builder, BuilderWithMiddlewares, DecoratedProcedure, Procedure, ProcedureBuilder, addMiddleware, call, createAccessibleLazyRouter, createApiBuilder, createAssertedLazyProcedure, createContractedProcedure, createProcedureClient, createRouterClient, decorateMiddleware, enhanceRouter, getHiddenRouterContract, getLazyMeta, getRouter, implement, implementerInternal, isLazy, isProcedure, isStartWithMiddlewares, lazy, mergeMiddlewares, os, resolveContractProcedures, setHiddenRouterContract, traverseContractProcedures, unlazy, unlazyRouter };
397
+ function isSchemaIssue(issue) {
398
+ if (!isTypescriptObject(issue) || typeof issue.message !== "string") {
399
+ return false;
400
+ }
401
+ if (issue.path !== void 0) {
402
+ if (!Array.isArray(issue.path)) {
403
+ return false;
404
+ }
405
+ if (!issue.path.every(
406
+ (segment) => isPropertyKey(segment) || isTypescriptObject(segment) && isPropertyKey(segment.key)
407
+ )) {
408
+ return false;
409
+ }
410
+ }
411
+ return true;
412
+ }
413
+
414
+ export { Builder, BuilderWithMiddlewares, Contract, DecoratedProcedure, Procedure, ProcedureBuilder, addMiddleware, call, createApiBuilder, createAssertedLazyProcedure, createProcedureClient, createRouterClient, decorateMiddleware, enhanceRouter, getLazyMeta, getRouter, initialSchemas, isLazy, isProcedure, isSchemaIssue, lazyInternal, mergeMeta, os, parseEndpointDefinition, unlazy };