@temporary-name/server 1.9.3-alpha.8026644f8b8b29ec5943323a4b1a32713d47dfd2 → 1.9.3-alpha.843e52d0b7b6ee25c0e3e090fefb2f73878bc139

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 +128 -487
  15. package/dist/index.d.ts +128 -487
  16. package/dist/index.mjs +224 -458
  17. package/dist/openapi/index.d.mts +12 -28
  18. package/dist/openapi/index.d.ts +12 -28
  19. package/dist/openapi/index.mjs +67 -154
  20. package/dist/shared/server.1ES3rTdy.d.ts +41 -0
  21. package/dist/shared/server.7SKDzhNs.d.mts +381 -0
  22. package/dist/shared/server.7SKDzhNs.d.ts +381 -0
  23. package/dist/shared/server.BbWZx2r6.d.mts +41 -0
  24. package/dist/shared/server.C1RJffw4.mjs +30 -0
  25. package/dist/shared/server.CQIFwyhc.mjs +40 -0
  26. package/dist/shared/server.CYa9puL2.mjs +403 -0
  27. package/dist/shared/server.ChOv1yG3.mjs +319 -0
  28. package/dist/shared/server.Cza0RB3u.mjs +160 -0
  29. package/dist/shared/server.YUvuxHty.mjs +48 -0
  30. package/package.json +10 -27
  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,78 @@
1
- import { isContractProcedure, mergeErrorMap, mergeMeta, mergeRoute, mergePrefix, enhanceRoute, mergeTags, getContractRouter } from '@temporary-name/contract';
2
- export { ValidationError, eventIterator, type, validateORPCError } from '@temporary-name/contract';
3
- import { onError, resolveMaybeOptionalOptions } from '@temporary-name/shared';
4
- export { AsyncIteratorClass, EventPublisher, ORPCError, asyncIteratorToStream as eventIteratorToStream, isDefinedError, onError, onFinish, onStart, onSuccess, safe, streamToAsyncIteratorClass as streamToEventIterator } from '@temporary-name/shared';
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.Cza0RB3u.mjs';
9
+ export { m as mergeCurrentContext, a as middlewareOutputFn } from './shared/server.Cza0RB3u.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 decorateMiddleware(middleware) {
13
- const decorated = ((...args) => middleware(...args));
14
- decorated.mapInput = (mapInput) => {
15
- const mapped = decorateMiddleware(
16
- (options, input, ...rest) => middleware(options, mapInput(input), ...rest)
17
- );
18
- return mapped;
19
- };
20
- decorated.concat = (concatMiddleware, mapInput) => {
21
- const mapped = mapInput ? decorateMiddleware(concatMiddleware).mapInput(mapInput) : concatMiddleware;
22
- const concatted = decorateMiddleware((options, input, output, ...rest) => {
23
- const merged = middleware(
24
- {
25
- ...options,
26
- next: (...[nextOptions1]) => mapped(
27
- {
28
- ...options,
29
- context: { ...options.context, ...nextOptions1?.context },
30
- next: (...[nextOptions2]) => options.next({ context: { ...nextOptions1?.context, ...nextOptions2?.context } })
31
- },
32
- input,
33
- output,
34
- ...rest
35
- )
36
- },
37
- input,
38
- output,
39
- ...rest
40
- );
41
- return merged;
42
- });
43
- return concatted;
44
- };
45
- return decorated;
46
- }
47
-
48
- function isStartWithMiddlewares(middlewares, compare) {
49
- if (compare.length > middlewares.length) {
50
- return false;
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}"` });
51
17
  }
52
- for (let i = 0; i < middlewares.length; i++) {
53
- if (compare[i] === void 0) {
54
- return true;
18
+ }
19
+ function validateTokenAuth(config, token, options) {
20
+ const { tokenPrefix, validate } = config;
21
+ validateTokenPrefix(tokenPrefix, token);
22
+ return validate(token, options);
23
+ }
24
+ function runAuth(config, options) {
25
+ switch (config.type) {
26
+ case "header": {
27
+ const authHeader = options.request.headers.get(config.name);
28
+ return authHeader ? validateTokenAuth(config, authHeader, options) : void 0;
29
+ }
30
+ case "query": {
31
+ const { name, tokenPrefix, validate } = config;
32
+ const query = options.request.url.searchParams;
33
+ const token = query.get(name);
34
+ if (!token) return void 0;
35
+ validateTokenPrefix(tokenPrefix, token);
36
+ return validate(token, options);
37
+ }
38
+ case "cookie": {
39
+ const cookie = getCookie(options.request.headers, config.name);
40
+ return cookie ? validateTokenAuth(config, cookie, options) : void 0;
41
+ }
42
+ case "bearer": {
43
+ const authHeader = options.request.headers.get("Authorization");
44
+ if (!authHeader) return void 0;
45
+ const [authType, bearer] = splitFirst(authHeader, " ");
46
+ return authType === "Bearer" ? validateTokenAuth(config, bearer, options) : void 0;
55
47
  }
56
- if (middlewares[i] !== compare[i]) {
48
+ case "basic": {
49
+ const authHeader = options.request.headers.get("Authorization");
50
+ if (!authHeader) return void 0;
51
+ const [authType, encoded] = splitFirst(authHeader, " ");
52
+ if (authType !== "Basic") return void 0;
53
+ const decoded = Buffer.from(encoded, "base64").toString("utf-8");
54
+ const [username, password] = splitFirst(decoded, ":");
55
+ validateTokenPrefix(config.tokenPrefix, password);
56
+ return config.validate(username, password, options);
57
+ }
58
+ case "none": {
57
59
  return false;
58
60
  }
61
+ default: {
62
+ assertNever(config);
63
+ }
59
64
  }
60
- return true;
61
- }
62
- function mergeMiddlewares(first, second, options) {
63
- if (options.dedupeLeading && isStartWithMiddlewares(second, first)) {
64
- return second;
65
- }
66
- return [...first, ...second];
67
65
  }
68
- function addMiddleware(middlewares, addition) {
69
- return [...middlewares, addition];
66
+ function authDescription(config) {
67
+ const { type } = config;
68
+ 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);
70
69
  }
71
70
 
72
- class Procedure {
73
- /**
74
- * This property holds the defined options.
75
- */
76
- "~orpc";
77
- constructor(def) {
78
- this["~orpc"] = def;
79
- }
80
- }
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"];
71
+ function mergeMeta(meta1, meta2) {
72
+ return { ...meta1, ...meta2 };
86
73
  }
87
74
 
88
75
  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
76
  /**
135
77
  * Make this procedure callable (works like a function while still being a procedure).
136
78
  *
@@ -149,244 +91,76 @@ class DecoratedProcedure extends Procedure {
149
91
  }
150
92
  }
151
93
 
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
- }
166
-
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;
220
- }
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
233
- });
234
- return enhanced2;
235
- }
236
- const enhanced = {};
237
- for (const key in router) {
238
- enhanced[key] = enhanceRouter(router[key], options);
239
- }
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
257
- });
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
- }
94
+ const initialSchemas = {
95
+ pathSchema: z.strictObject({}),
96
+ querySchema: z.strictObject({}),
97
+ bodySchema: z.strictObject({}),
98
+ outputSchema: z.unknown()
99
+ };
297
100
 
298
- class Builder {
299
- /**
300
- * This property holds the defined options.
301
- */
302
- "~orpc";
101
+ class ProcedureBuilder extends Contract {
102
+ z;
303
103
  constructor(def) {
304
- this["~orpc"] = def;
104
+ super(def);
105
+ this.z = new SchemaClass();
305
106
  }
306
107
  /**
307
- * Set or override the initial context.
308
- *
309
- * @see {@link https://orpc.unnoq.com/docs/context Context Docs}
310
- */
311
- $context() {
312
- return this;
313
- }
314
- /**
315
- * Creates a middleware.
316
- *
317
- * @see {@link https://orpc.unnoq.com/docs/middleware Middleware Docs}
318
- */
319
- middleware(middleware) {
320
- return decorateMiddleware(middleware);
321
- }
322
- /**
323
- * Adds type-safe custom errors.
324
- * The provided errors are spared-merged with any existing errors.
325
- *
326
- * @see {@link https://orpc.unnoq.com/docs/error-handling#type%E2%80%90safe-error-handling Type-Safe Error Handling Docs}
327
- */
328
- errors(errors) {
329
- return new Builder({
330
- ...this["~orpc"],
331
- errorMap: mergeErrorMap(this["~orpc"].errorMap, errors)
332
- });
333
- }
334
- /**
335
- * Uses a middleware to modify the context or improve the pipeline.
336
- *
337
- * @info Supports both normal middleware and inline middleware implementations.
338
- * @note The current context must be satisfy middleware dependent-context
339
- * @see {@link https://orpc.unnoq.com/docs/middleware Middleware Docs}
340
- */
341
- use(middleware) {
342
- return new Builder({
343
- ...this["~orpc"],
344
- middlewares: addMiddleware(this["~orpc"].middlewares, middleware)
345
- });
346
- }
347
- useGating(gates, isGateEnabled) {
348
- return this.use(({ next, context }) => {
349
- return gatingContext.run(
350
- (gate) => isGateEnabled(gate, context),
351
- () => next({ context: { isGateEnabled } })
352
- );
353
- });
354
- }
355
- /**
356
- * Sets or updates the metadata.
357
- * The provided metadata is spared-merged with any existing metadata.
108
+ * Sets or updates the metadata for the contract.
109
+ * The provided metadata is spared-merged with any existing metadata in the contract.
358
110
  *
359
111
  * @see {@link https://orpc.unnoq.com/docs/metadata Metadata Docs}
360
112
  */
361
113
  meta(meta) {
362
- return new Builder({
114
+ return new ProcedureBuilder({
363
115
  ...this["~orpc"],
364
116
  meta: mergeMeta(this["~orpc"].meta, meta)
365
117
  });
366
118
  }
119
+ endpoint(stringsOrEndpoint, ...values) {
120
+ const { method, path, pathSchema } = parseEndpointDefinition(stringsOrEndpoint, values);
121
+ const { prefix } = this["~orpc"];
122
+ const route = { method, path };
123
+ return new ProcedureBuilder({
124
+ ...this["~orpc"],
125
+ route: mergeRoute(this["~orpc"].route, prefix ? prefixRoute(route, prefix) : route),
126
+ schemas: {
127
+ ...this["~orpc"].schemas,
128
+ pathSchema
129
+ }
130
+ });
131
+ }
367
132
  /**
368
- * Sets or updates the route definition.
369
- * The provided route is spared-merged with any existing route.
133
+ * Sets or updates the route definition for the contract.
134
+ * The provided route is spared-merged with any existing route in the contract.
370
135
  * This option is typically relevant when integrating with OpenAPI.
371
136
  *
372
137
  * @see {@link https://orpc.unnoq.com/docs/openapi/routing OpenAPI Routing Docs}
373
138
  * @see {@link https://orpc.unnoq.com/docs/openapi/input-output-structure OpenAPI Input/Output Structure Docs}
374
139
  */
375
- route(route) {
376
- return new Builder({
140
+ endpointOpts(route) {
141
+ const { prefix } = this["~orpc"];
142
+ return new ProcedureBuilder({
377
143
  ...this["~orpc"],
378
- route: mergeRoute(this["~orpc"].route, route)
144
+ route: mergeRoute(this["~orpc"].route, prefix ? prefixRoute(route, prefix) : route)
379
145
  });
380
146
  }
381
- /**
382
- * Defines the input validation schema.
383
- *
384
- * @see {@link https://orpc.unnoq.com/docs/procedure#input-output-validation Input Validation Docs}
385
- */
386
- input(schema) {
387
- return new Builder({
147
+ query(schema) {
148
+ return new ProcedureBuilder({
388
149
  ...this["~orpc"],
389
- inputSchema: schema,
150
+ schemas: {
151
+ ...this["~orpc"].schemas,
152
+ querySchema: schema instanceof core.$ZodType ? schema : object(schema)
153
+ },
154
+ inputValidationIndex: this["~orpc"].middlewares.length
155
+ });
156
+ }
157
+ body(schema) {
158
+ return new ProcedureBuilder({
159
+ ...this["~orpc"],
160
+ schemas: {
161
+ ...this["~orpc"].schemas,
162
+ bodySchema: schema instanceof core.$ZodType ? schema : object(schema)
163
+ },
390
164
  inputValidationIndex: this["~orpc"].middlewares.length
391
165
  });
392
166
  }
@@ -396,23 +170,73 @@ class Builder {
396
170
  * @see {@link https://orpc.unnoq.com/docs/procedure#input-output-validation Output Validation Docs}
397
171
  */
398
172
  output(schema) {
399
- return new Builder({
173
+ return new ProcedureBuilder({
400
174
  ...this["~orpc"],
401
- outputSchema: schema,
175
+ schemas: {
176
+ ...this["~orpc"].schemas,
177
+ outputSchema: schema instanceof core.$ZodType ? schema : object(schema)
178
+ },
402
179
  outputValidationIndex: this["~orpc"].middlewares.length
403
180
  });
404
181
  }
182
+ use(middleware) {
183
+ return new this.constructor({
184
+ ...this["~orpc"],
185
+ middlewares: addMiddleware(this["~orpc"].middlewares, middleware)
186
+ });
187
+ }
188
+ // The default of false for ValidatedAuthContext is used when you pass in the type 'none'. We use false
189
+ // because we can't use null or undefined (see ValidatedAuthContext) but we still want it to be falsy.
190
+ useAuth(config) {
191
+ const middleware = baseApi.$context().middleware(async (options) => {
192
+ const { next, context } = options;
193
+ if (context.auth) return next();
194
+ const auth = await runAuth(config, options);
195
+ if (auth === void 0) {
196
+ const { authConfigs } = options.procedure["~orpc"];
197
+ if (context.auth !== false && config === authConfigs.at(-1)) {
198
+ let authDescriptions = authConfigs.map(authDescription).join(", ");
199
+ if (authConfigs.length > 1) {
200
+ authDescriptions = `one of: ${authDescriptions}`;
201
+ }
202
+ throw new ORPCError("UNAUTHORIZED", {
203
+ message: `Authentication required. You must provide ${authDescriptions}`
204
+ });
205
+ }
206
+ return next();
207
+ }
208
+ return next({ context: { auth } });
209
+ });
210
+ return new this.constructor({
211
+ ...this["~orpc"],
212
+ authConfigs: [...this["~orpc"].authConfigs, config],
213
+ middlewares: addMiddleware(this["~orpc"].middlewares, middleware)
214
+ });
215
+ }
216
+ useGating(gates, isGateEnabled) {
217
+ return this.use(({ next, context }) => {
218
+ return gatingContext.run(
219
+ (gate) => isGateEnabled(gate, context),
220
+ () => next({ context: { isGateEnabled } })
221
+ );
222
+ });
223
+ }
405
224
  /**
406
225
  * Defines the handler of the procedure.
407
226
  *
408
227
  * @see {@link https://orpc.unnoq.com/docs/procedure Procedure Docs}
409
228
  */
410
229
  handler(handler) {
230
+ if (this["~orpc"].schemas.outputSchema === initialSchemas.outputSchema) {
231
+ throw new Error("You must call .output() before calling .handler()");
232
+ }
411
233
  return new DecoratedProcedure({
412
234
  ...this["~orpc"],
413
235
  handler
414
236
  });
415
237
  }
238
+ }
239
+ class BuilderWithMiddlewares extends ProcedureBuilder {
416
240
  /**
417
241
  * Prefixes all procedures in the router.
418
242
  * The provided prefix is post-appended to any existing router prefix.
@@ -422,7 +246,7 @@ class Builder {
422
246
  * @see {@link https://orpc.unnoq.com/docs/openapi/routing#route-prefixes OpenAPI Route Prefixes Docs}
423
247
  */
424
248
  prefix(prefix) {
425
- return new Builder({
249
+ return new this.constructor({
426
250
  ...this["~orpc"],
427
251
  prefix: mergePrefix(this["~orpc"].prefix, prefix)
428
252
  });
@@ -434,7 +258,7 @@ class Builder {
434
258
  * @see {@link https://orpc.unnoq.com/docs/openapi/openapi-specification#operation-metadata OpenAPI Operation Metadata Docs}
435
259
  */
436
260
  tag(...tags) {
437
- return new Builder({
261
+ return new this.constructor({
438
262
  ...this["~orpc"],
439
263
  tags: mergeTags(this["~orpc"].tags, tags)
440
264
  });
@@ -447,123 +271,56 @@ class Builder {
447
271
  router(router) {
448
272
  return enhanceRouter(router, this["~orpc"]);
449
273
  }
274
+ }
275
+
276
+ function decorateMiddleware(middleware) {
277
+ const decorated = ((...args) => middleware(...args));
278
+ decorated.mapInput = (mapInput) => {
279
+ const mapped = decorateMiddleware(
280
+ (options, input, ...rest) => middleware(options, mapInput(input), ...rest)
281
+ );
282
+ return mapped;
283
+ };
284
+ return decorated;
285
+ }
286
+
287
+ class Builder extends BuilderWithMiddlewares {
450
288
  /**
451
- * Create a lazy router
452
- * And applies all of the previously defined options to the specified router.
289
+ * Set or override the initial context.
453
290
  *
454
- * @see {@link https://orpc.unnoq.com/docs/router#extending-router Extending Router Docs}
291
+ * @see {@link https://orpc.unnoq.com/docs/context Context Docs}
455
292
  */
456
- lazyRoute(loader) {
457
- return enhanceRouter(lazy(loader), this["~orpc"]);
293
+ $context() {
294
+ return this;
458
295
  }
459
- }
460
- function createApiBuilder(opts = {}) {
461
- const base = new Builder({
462
- route: {},
463
- meta: opts.meta ?? {},
464
- errorMap: {},
465
- inputValidationIndex: 0,
466
- outputValidationIndex: 0,
467
- middlewares: [
468
- onError((error, options) => {
469
- console.dir(error, { depth: null });
470
- })
471
- ],
472
- // NB: this is a relic from orpc -- I'm not convinced there's a need for this (or if there is, that it's
473
- // the best solution). For now I've removed the interface to configure it externally.
474
- dedupeLeadingMiddlewares: true
475
- });
476
- return base;
477
- }
478
- const os = createApiBuilder();
479
-
480
- function implementerInternal(contract, middlewares) {
481
- if (isContractProcedure(contract)) {
482
- const impl2 = new Builder({
483
- ...contract["~orpc"],
484
- middlewares,
485
- inputValidationIndex: middlewares.length,
486
- outputValidationIndex: middlewares.length,
487
- dedupeLeadingMiddlewares: true
488
- });
489
- return impl2;
296
+ /**
297
+ * Creates a middleware.
298
+ *
299
+ * @see {@link https://orpc.unnoq.com/docs/middleware Middleware Docs}
300
+ */
301
+ middleware(middleware) {
302
+ return decorateMiddleware(middleware);
490
303
  }
491
- const impl = new Proxy(contract, {
492
- get: (target, key) => {
493
- if (typeof key !== "string") {
494
- return Reflect.get(target, key);
495
- }
496
- let method;
497
- if (key === "middleware") {
498
- method = (mid) => decorateMiddleware(mid);
499
- } else if (key === "use") {
500
- method = (mid) => {
501
- return implementerInternal(contract, addMiddleware(middlewares, mid));
502
- };
503
- } else if (key === "router") {
504
- method = (router) => {
505
- const adapted = enhanceRouter(router, {
506
- middlewares,
507
- errorMap: {},
508
- prefix: void 0,
509
- tags: void 0,
510
- dedupeLeadingMiddlewares: true
511
- });
512
- return setHiddenRouterContract(adapted, contract);
513
- };
514
- } else if (key === "lazyRoute") {
515
- method = (loader) => {
516
- const adapted = enhanceRouter(lazy(loader), {
517
- middlewares,
518
- errorMap: {},
519
- prefix: void 0,
520
- tags: void 0,
521
- dedupeLeadingMiddlewares: true
522
- });
523
- return setHiddenRouterContract(adapted, contract);
524
- };
525
- }
526
- const next = getContractRouter(target, [key]);
527
- if (!next) {
528
- return method ?? next;
529
- }
530
- const nextImpl = implementerInternal(next, middlewares);
531
- if (method) {
532
- return new Proxy(method, {
533
- get(_, key2) {
534
- return Reflect.get(nextImpl, key2);
535
- }
536
- });
537
- }
538
- return nextImpl;
539
- }
540
- });
541
- return impl;
542
- }
543
- function implement(contract) {
544
- const implInternal = implementerInternal(contract, []);
545
- const impl = new Proxy(implInternal, {
546
- get: (target, key) => {
547
- let method;
548
- if (key === "$context") {
549
- method = () => impl;
550
- }
551
- const next = Reflect.get(target, key);
552
- if (!method || !next || typeof next !== "function" && typeof next !== "object") {
553
- return method || next;
554
- }
555
- return new Proxy(method, {
556
- get(_, key2) {
557
- return Reflect.get(next, key2);
558
- }
559
- });
560
- }
561
- });
562
- return impl;
563
304
  }
305
+ const baseApi = new Builder({
306
+ route: {},
307
+ meta: {},
308
+ inputValidationIndex: 0,
309
+ outputValidationIndex: 0,
310
+ middlewares: [
311
+ onError((error, _options) => {
312
+ console.dir(error, { depth: null });
313
+ })
314
+ ],
315
+ schemas: initialSchemas,
316
+ // NB: this is a relic from orpc -- I'm not convinced there's a need for this (or if there is, that it's
317
+ // the best solution). For now I've removed the interface to configure it externally.
318
+ dedupeLeadingMiddlewares: true,
319
+ authConfigs: []
320
+ });
564
321
 
565
322
  function createAssertedLazyProcedure(lazied) {
566
- const lazyProcedure = lazy(async () => {
323
+ const lazyProcedure = lazyInternal(async () => {
567
324
  const { default: maybeProcedure } = await unlazy(lazied);
568
325
  if (!isProcedure(maybeProcedure)) {
569
326
  throw new Error(`
@@ -576,14 +333,6 @@ function createAssertedLazyProcedure(lazied) {
576
333
  }, getLazyMeta(lazied));
577
334
  return lazyProcedure;
578
335
  }
579
- function createContractedProcedure(procedure, contract) {
580
- return new Procedure({
581
- ...procedure["~orpc"],
582
- errorMap: contract["~orpc"].errorMap,
583
- route: contract["~orpc"].route,
584
- meta: contract["~orpc"].meta
585
- });
586
- }
587
336
  function call(procedure, input, ...rest) {
588
337
  const options = resolveMaybeOptionalOptions(rest);
589
338
  return createProcedureClient(procedure, options)(input, options);
@@ -614,4 +363,21 @@ function createRouterClient(router, ...rest) {
614
363
  return recursive;
615
364
  }
616
365
 
617
- export { Builder, DecoratedProcedure, Procedure, 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 };
366
+ function isSchemaIssue(issue) {
367
+ if (!isTypescriptObject(issue) || typeof issue.message !== "string") {
368
+ return false;
369
+ }
370
+ if (issue.path !== void 0) {
371
+ if (!Array.isArray(issue.path)) {
372
+ return false;
373
+ }
374
+ if (!issue.path.every(
375
+ (segment) => isPropertyKey(segment) || isTypescriptObject(segment) && isPropertyKey(segment.key)
376
+ )) {
377
+ return false;
378
+ }
379
+ }
380
+ return true;
381
+ }
382
+
383
+ export { Builder, BuilderWithMiddlewares, Contract, DecoratedProcedure, Procedure, ProcedureBuilder, addMiddleware, baseApi, call, createAssertedLazyProcedure, createProcedureClient, createRouterClient, decorateMiddleware, enhanceRouter, getLazyMeta, getRouter, initialSchemas, isLazy, isProcedure, isSchemaIssue, lazyInternal, mergeMeta, parseEndpointDefinition, unlazy };