@temporary-name/server 1.9.3-alpha.21b0289906d115f2f3db137ea407a6d8d50b5ad6 → 1.9.3-alpha.2957dbc009ec31fa21575f028b83c96651cba827

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 (39) hide show
  1. package/dist/adapters/aws-lambda/index.d.mts +3 -4
  2. package/dist/adapters/aws-lambda/index.d.ts +3 -4
  3. package/dist/adapters/aws-lambda/index.mjs +3 -3
  4. package/dist/adapters/fetch/index.d.mts +7 -84
  5. package/dist/adapters/fetch/index.d.ts +7 -84
  6. package/dist/adapters/fetch/index.mjs +15 -154
  7. package/dist/adapters/node/index.d.mts +7 -61
  8. package/dist/adapters/node/index.d.ts +7 -61
  9. package/dist/adapters/node/index.mjs +13 -119
  10. package/dist/adapters/standard/index.d.mts +4 -5
  11. package/dist/adapters/standard/index.d.ts +4 -5
  12. package/dist/adapters/standard/index.mjs +4 -4
  13. package/dist/helpers/index.mjs +3 -29
  14. package/dist/index.d.mts +60 -191
  15. package/dist/index.d.ts +60 -191
  16. package/dist/index.mjs +96 -104
  17. package/dist/openapi/index.d.mts +9 -26
  18. package/dist/openapi/index.d.ts +9 -26
  19. package/dist/openapi/index.mjs +6 -74
  20. package/dist/shared/{server.DmGicgbG.mjs → server.B7tjiDal.mjs} +46 -105
  21. package/dist/shared/server.C1RJffw4.mjs +30 -0
  22. package/dist/shared/server.CQIFwyhc.mjs +40 -0
  23. package/dist/shared/server.CpS0m3at.mjs +403 -0
  24. package/dist/shared/server.DPD7R7h_.d.mts +226 -0
  25. package/dist/shared/server.DPD7R7h_.d.ts +226 -0
  26. package/dist/shared/server.DfUs5c4R.d.ts +41 -0
  27. package/dist/shared/server.L8lRAYBR.d.mts +41 -0
  28. package/package.json +10 -27
  29. package/dist/plugins/index.d.mts +0 -159
  30. package/dist/plugins/index.d.ts +0 -159
  31. package/dist/plugins/index.mjs +0 -288
  32. package/dist/shared/server.7aL9gcoU.d.mts +0 -23
  33. package/dist/shared/server.BL2R5jcp.d.mts +0 -228
  34. package/dist/shared/server.BL2R5jcp.d.ts +0 -228
  35. package/dist/shared/server.CttFCjkj.mjs +0 -255
  36. package/dist/shared/server.D6Qs_UcF.d.mts +0 -55
  37. package/dist/shared/server.DFptr1Nz.d.ts +0 -23
  38. package/dist/shared/server.DpoO_ER_.d.ts +0 -55
  39. package/dist/shared/server.JtIZ8YG7.mjs +0 -237
package/dist/index.mjs CHANGED
@@ -1,11 +1,64 @@
1
- import { mergePrefix, mergeTags, ContractProcedure, mergeErrorMap, mergeMeta, parseEndpointDefinition, mergeRoute, prefixRoute, initialSchemas, isContractProcedure, getContractRouter } from '@temporary-name/contract';
2
- export { ValidationError, eventIterator, 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';
1
+ import { mergePrefix, mergeTags, mergeMeta, parseEndpointDefinition, mergeRoute, prefixRoute, initialSchemas } from '@temporary-name/contract';
2
+ export { ValidationError, eventIterator } from '@temporary-name/contract';
3
+ import { assertNever, splitFirst, ORPCError, onError, resolveMaybeOptionalOptions } from '@temporary-name/shared';
4
+ export { AsyncIteratorClass, EventPublisher, ORPCError, asyncIteratorToStream as eventIteratorToStream, isDefinedError, onError, onFinish, onStart, onSuccess, streamToAsyncIteratorClass as streamToEventIterator } from '@temporary-name/shared';
5
5
  import { SchemaClass, object, core, gatingContext } from '@temporary-name/zod';
6
- import { P as Procedure, c as createProcedureClient, e as enhanceRouter, a as addMiddleware, s as setHiddenRouterContract, l as lazyInternal, g as getLazyMeta, u as unlazy, i as isProcedure, b as isLazy, d as getRouter } from './shared/server.DmGicgbG.mjs';
7
- export { L as LAZY_SYMBOL, p as createAccessibleLazyRouter, f as createORPCErrorConstructorMap, o as getHiddenRouterContract, k as isStartWithMiddlewares, h as lazy, m as mergeCurrentContext, n as mergeMiddlewares, j as middlewareOutputFn, r as resolveContractProcedures, t as traverseContractProcedures, q as unlazyRouter } from './shared/server.DmGicgbG.mjs';
6
+ import { g as getCookie } from './shared/server.C1RJffw4.mjs';
7
+ import { P as Procedure, c as createProcedureClient, e as enhanceRouter, C as Contract, a as addMiddleware, l as lazyInternal, g as getLazyMeta, u as unlazy, i as isProcedure, b as isLazy, d as getRouter } from './shared/server.B7tjiDal.mjs';
8
+ export { L as LAZY_SYMBOL, n as createAccessibleLazyRouter, j as isStartWithMiddlewares, f as lazy, m as mergeCurrentContext, k as mergeMiddlewares, h as middlewareOutputFn, r as resolveContractProcedures, t as traverseContractProcedures, o as unlazyRouter } from './shared/server.B7tjiDal.mjs';
8
9
  export { getEventMeta, withEventMeta } from '@temporary-name/standard-server';
10
+ import 'cookie';
11
+
12
+ function validateTokenPrefix(prefix, token) {
13
+ if (prefix && !token.startsWith(prefix)) {
14
+ throw new ORPCError("UNAUTHORIZED", { message: `Invalid auth token. It must start with "${prefix}"` });
15
+ }
16
+ }
17
+ function validateTokenAuth(config, token, options) {
18
+ const { tokenPrefix, validate } = config;
19
+ validateTokenPrefix(tokenPrefix, token);
20
+ return validate(token, options);
21
+ }
22
+ function authByQuery(config, options) {
23
+ const { name, tokenPrefix, validate } = config;
24
+ const query = options.request.url.searchParams;
25
+ const token = query.get(name);
26
+ if (!token) return void 0;
27
+ validateTokenPrefix(tokenPrefix, token);
28
+ return validate(token, options);
29
+ }
30
+ function authByHeader(config, options) {
31
+ const authHeader = options.request.headers.get(config.name);
32
+ return authHeader ? validateTokenAuth(config, authHeader, options) : void 0;
33
+ }
34
+ function authByCookie(config, options) {
35
+ const cookie = getCookie(options.request.headers, config.name);
36
+ return cookie ? validateTokenAuth(config, cookie, options) : void 0;
37
+ }
38
+ function authByBearer(config, options) {
39
+ const authHeader = options.request.headers.get("Authorization");
40
+ if (!authHeader) return void 0;
41
+ const [authType, bearer] = splitFirst(authHeader, " ");
42
+ return authType === "Bearer" ? validateTokenAuth(config, bearer, options) : void 0;
43
+ }
44
+ function authByBasic(config, options) {
45
+ const authHeader = options.request.headers.get("Authorization");
46
+ if (!authHeader) return void 0;
47
+ const [authType, encoded] = splitFirst(authHeader, " ");
48
+ if (authType !== "Basic") return void 0;
49
+ const decoded = Buffer.from(encoded, "base64").toString("utf-8");
50
+ const [username, password] = splitFirst(decoded, ":");
51
+ validateTokenPrefix(config.tokenPrefix, password);
52
+ return config.validate(username, password, options);
53
+ }
54
+ function authByType(config, options) {
55
+ const { type } = config;
56
+ 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);
57
+ }
58
+ function authDescription(config) {
59
+ const { type } = config;
60
+ 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);
61
+ }
9
62
 
10
63
  class DecoratedProcedure extends Procedure {
11
64
  /**
@@ -26,24 +79,12 @@ class DecoratedProcedure extends Procedure {
26
79
  }
27
80
  }
28
81
 
29
- class ProcedureBuilder extends ContractProcedure {
82
+ class ProcedureBuilder extends Contract {
30
83
  z;
31
84
  constructor(def) {
32
85
  super(def);
33
86
  this.z = new SchemaClass();
34
87
  }
35
- /**
36
- * Adds type-safe custom errors to the contract.
37
- * The provided errors are spared-merged with any existing errors in the contract.
38
- *
39
- * @see {@link https://orpc.unnoq.com/docs/error-handling#type%E2%80%90safe-error-handling Type-Safe Error Handling Docs}
40
- */
41
- errors(errors) {
42
- return new ProcedureBuilder({
43
- ...this["~orpc"],
44
- errorMap: mergeErrorMap(this["~orpc"].errorMap, errors)
45
- });
46
- }
47
88
  /**
48
89
  * Sets or updates the metadata for the contract.
49
90
  * The provided metadata is spared-merged with any existing metadata in the contract.
@@ -132,6 +173,36 @@ class ProcedureBuilder extends ContractProcedure {
132
173
  middlewares: addMiddleware(this["~orpc"].middlewares, middleware)
133
174
  });
134
175
  }
176
+ // `& {}` is so AuthType will be expanded in parameter info tooltips.
177
+ // The default of false for ValidatedAuthContext is used when you pass in the type 'none'. We use false
178
+ // because we can't use null or undefined (see ValidatedAuthContext) but we still want it to be falsy.
179
+ useAuth(type, ...rest) {
180
+ const config = { type, ...rest[0] };
181
+ const middleware = os.$context().middleware(async (options) => {
182
+ const { next, context } = options;
183
+ if (context.auth) return next();
184
+ const auth = await authByType(config, options);
185
+ if (auth === void 0) {
186
+ const { authConfigs } = options.procedure["~orpc"];
187
+ if (context.auth !== false && config === authConfigs.at(-1)) {
188
+ let authDescriptions = authConfigs.map(authDescription).join(", ");
189
+ if (authConfigs.length > 1) {
190
+ authDescriptions = `one of: ${authDescriptions}`;
191
+ }
192
+ throw new ORPCError("UNAUTHORIZED", {
193
+ message: `Authentication required. You must provide ${authDescriptions}`
194
+ });
195
+ }
196
+ return next();
197
+ }
198
+ return next({ context: { auth } });
199
+ });
200
+ return new this.constructor({
201
+ ...this["~orpc"],
202
+ authConfigs: [...this["~orpc"].authConfigs, config],
203
+ middlewares: addMiddleware(this["~orpc"].middlewares, middleware)
204
+ });
205
+ }
135
206
  useGating(gates, isGateEnabled) {
136
207
  return this.use(({ next, context }) => {
137
208
  return gatingContext.run(
@@ -146,6 +217,9 @@ class ProcedureBuilder extends ContractProcedure {
146
217
  * @see {@link https://orpc.unnoq.com/docs/procedure Procedure Docs}
147
218
  */
148
219
  handler(handler) {
220
+ if (this["~orpc"].schemas.outputSchema === initialSchemas.outputSchema) {
221
+ throw new Error("You must call .output() before calling .handler()");
222
+ }
149
223
  return new DecoratedProcedure({
150
224
  ...this["~orpc"],
151
225
  handler
@@ -247,7 +321,6 @@ function createApiBuilder(opts = {}) {
247
321
  return new Builder({
248
322
  route: {},
249
323
  meta: opts.meta ?? {},
250
- errorMap: {},
251
324
  inputValidationIndex: 0,
252
325
  outputValidationIndex: 0,
253
326
  middlewares: [
@@ -258,85 +331,12 @@ function createApiBuilder(opts = {}) {
258
331
  schemas: initialSchemas,
259
332
  // NB: this is a relic from orpc -- I'm not convinced there's a need for this (or if there is, that it's
260
333
  // the best solution). For now I've removed the interface to configure it externally.
261
- dedupeLeadingMiddlewares: true
334
+ dedupeLeadingMiddlewares: true,
335
+ authConfigs: []
262
336
  });
263
337
  }
264
338
  const os = createApiBuilder();
265
339
 
266
- function implementerInternal(contract, middlewares) {
267
- if (isContractProcedure(contract)) {
268
- const impl2 = new Builder({
269
- ...contract["~orpc"],
270
- middlewares,
271
- inputValidationIndex: middlewares.length,
272
- outputValidationIndex: middlewares.length,
273
- dedupeLeadingMiddlewares: true
274
- });
275
- return impl2;
276
- }
277
- const impl = new Proxy(contract, {
278
- get: (target, key) => {
279
- if (typeof key !== "string") {
280
- return Reflect.get(target, key);
281
- }
282
- let method;
283
- if (key === "middleware") {
284
- method = (mid) => decorateMiddleware(mid);
285
- } else if (key === "use") {
286
- method = (mid) => {
287
- return implementerInternal(contract, addMiddleware(middlewares, mid));
288
- };
289
- } else if (key === "router") {
290
- method = (router) => {
291
- const adapted = enhanceRouter(router, {
292
- middlewares,
293
- errorMap: {},
294
- prefix: void 0,
295
- tags: void 0,
296
- dedupeLeadingMiddlewares: true
297
- });
298
- return setHiddenRouterContract(adapted, contract);
299
- };
300
- }
301
- const next = getContractRouter(target, [key]);
302
- if (!next) {
303
- return method ?? next;
304
- }
305
- const nextImpl = implementerInternal(next, middlewares);
306
- if (method) {
307
- return new Proxy(method, {
308
- get(_, key2) {
309
- return Reflect.get(nextImpl, key2);
310
- }
311
- });
312
- }
313
- return nextImpl;
314
- }
315
- });
316
- return impl;
317
- }
318
- function implement(contract) {
319
- const implInternal = implementerInternal(contract, []);
320
- const impl = new Proxy(implInternal, {
321
- get: (target, key) => {
322
- let method;
323
- if (key === "$context") {
324
- method = () => impl;
325
- }
326
- const next = Reflect.get(target, key);
327
- if (!method || !next || typeof next !== "function" && typeof next !== "object") {
328
- return method || next;
329
- }
330
- return new Proxy(method, {
331
- get(_, key2) {
332
- return Reflect.get(next, key2);
333
- }
334
- });
335
- }
336
- });
337
- return impl;
338
- }
339
-
340
340
  function createAssertedLazyProcedure(lazied) {
341
341
  const lazyProcedure = lazyInternal(async () => {
342
342
  const { default: maybeProcedure } = await unlazy(lazied);
@@ -351,14 +351,6 @@ function createAssertedLazyProcedure(lazied) {
351
351
  }, getLazyMeta(lazied));
352
352
  return lazyProcedure;
353
353
  }
354
- function createContractedProcedure(procedure, contract) {
355
- return new Procedure({
356
- ...procedure["~orpc"],
357
- errorMap: contract["~orpc"].errorMap,
358
- route: contract["~orpc"].route,
359
- meta: contract["~orpc"].meta
360
- });
361
- }
362
354
  function call(procedure, input, ...rest) {
363
355
  const options = resolveMaybeOptionalOptions(rest);
364
356
  return createProcedureClient(procedure, options)(input, options);
@@ -389,4 +381,4 @@ function createRouterClient(router, ...rest) {
389
381
  return recursive;
390
382
  }
391
383
 
392
- export { Builder, BuilderWithMiddlewares, DecoratedProcedure, Procedure, ProcedureBuilder, addMiddleware, call, createApiBuilder, createAssertedLazyProcedure, createContractedProcedure, createProcedureClient, createRouterClient, decorateMiddleware, enhanceRouter, getLazyMeta, getRouter, implement, implementerInternal, isLazy, isProcedure, lazyInternal, os, setHiddenRouterContract, unlazy };
384
+ export { Builder, BuilderWithMiddlewares, Contract, DecoratedProcedure, Procedure, ProcedureBuilder, addMiddleware, call, createApiBuilder, createAssertedLazyProcedure, createProcedureClient, createRouterClient, decorateMiddleware, enhanceRouter, getLazyMeta, getRouter, isLazy, isProcedure, lazyInternal, os, unlazy };
@@ -1,11 +1,11 @@
1
- import { OpenAPI, AnyContractProcedure, AnySchema, AnyContractRouter } from '@temporary-name/contract';
1
+ import { OpenAPI, AnySchema } from '@temporary-name/contract';
2
2
  export { OpenAPI } from '@temporary-name/contract';
3
- import { AnyProcedure, TraverseContractProcedureCallbackOptions, AnyRouter, ORPCError, ClientContext, Lazyable, CreateProcedureClientOptions, InferRouterInitialContext, Schema, ErrorMap, Meta, RouterClient } from '@temporary-name/server';
4
- import { Promisable, Value, HTTPPath, HTTPMethod, NestedClient, Client, MaybeOptionalOptions } from '@temporary-name/shared';
3
+ import { Contract, TraverseContractProcedureCallbackOptions, ContractRouter, AnyRouter } from '@temporary-name/server';
4
+ import { Promisable, Value, HTTPPath, HTTPMethod } from '@temporary-name/shared';
5
5
  import { JSONSchema } from '@temporary-name/interop/json-schema-typed/draft-2020-12';
6
6
  export { JSONSchema, ContentEncoding as JSONSchemaContentEncoding, Format as JSONSchemaFormat, TypeName as JSONSchemaTypeName } from '@temporary-name/interop/json-schema-typed/draft-2020-12';
7
7
 
8
- type OverrideOperationValue = Partial<OpenAPI.OperationObject> | ((current: OpenAPI.OperationObject, procedure: AnyContractProcedure) => OpenAPI.OperationObject);
8
+ type OverrideOperationValue = Partial<OpenAPI.OperationObject> | ((current: OpenAPI.OperationObject, procedure: Contract) => OpenAPI.OperationObject);
9
9
  /**
10
10
  * Customize The Operation Object by proxy an error map item or a middleware.
11
11
  *
@@ -13,7 +13,7 @@ type OverrideOperationValue = Partial<OpenAPI.OperationObject> | ((current: Open
13
13
  */
14
14
  declare function customOpenAPIOperation<T extends object>(o: T, extend: OverrideOperationValue): T;
15
15
  declare function getCustomOpenAPIOperation(o: object): OverrideOperationValue | undefined;
16
- declare function applyCustomOpenAPIOperation(operation: OpenAPI.OperationObject, contract: AnyContractProcedure): OpenAPI.OperationObject;
16
+ declare function applyCustomOpenAPIOperation(operation: OpenAPI.OperationObject, contract: Contract): OpenAPI.OperationObject;
17
17
 
18
18
  /**
19
19
  * @internal
@@ -76,7 +76,7 @@ interface OpenAPIGeneratorGenerateOptions extends Partial<Omit<OpenAPI.Document,
76
76
  * @deprecated Use `filter` option instead.
77
77
  * @default () => false
78
78
  */
79
- exclude?: (procedure: AnyProcedure | AnyContractProcedure, path: readonly string[]) => boolean;
79
+ exclude?: (procedure: Contract, path: readonly string[]) => boolean;
80
80
  /**
81
81
  * Filter procedures. Return `false` to exclude a procedure from the OpenAPI specification.
82
82
  *
@@ -129,7 +129,7 @@ declare class OpenAPIGenerator {
129
129
  *
130
130
  * @see {@link https://orpc.unnoq.com/docs/openapi/openapi-specification OpenAPI Specification Docs}
131
131
  */
132
- generate(router: AnyContractRouter | AnyRouter, options?: OpenAPIGeneratorGenerateOptions): Promise<OpenAPI.Document>;
132
+ generate(router: ContractRouter | AnyRouter, options?: OpenAPIGeneratorGenerateOptions): Promise<OpenAPI.Document>;
133
133
  }
134
134
 
135
135
  /**
@@ -162,23 +162,6 @@ declare function checkParamsSchema(schema: ObjectSchema, params: string[]): bool
162
162
  declare function toOpenAPISchema(schema: JSONSchema): OpenAPI.SchemaObject & object;
163
163
  declare function resolveOpenAPIJsonSchemaRef(doc: OpenAPI.Document, schema: JSONSchema): JSONSchema;
164
164
 
165
- type JsonifiedValue<T> = T extends string ? T : T extends number ? T : T extends boolean ? T : T extends null ? T : T extends undefined ? T : T extends Array<unknown> ? JsonifiedArray<T> : T extends Record<string, unknown> ? {
166
- [K in keyof T]: JsonifiedValue<T[K]>;
167
- } : T extends Date ? string : T extends bigint ? string : T extends File ? File : T extends Blob ? Blob : T extends RegExp ? string : T extends URL ? string : T extends Map<infer K, infer V> ? JsonifiedArray<[K, V][]> : T extends Set<infer U> ? JsonifiedArray<U[]> : T extends AsyncIteratorObject<infer U, infer V> ? AsyncIteratorObject<JsonifiedValue<U>, JsonifiedValue<V>> : unknown;
168
- type JsonifiedArray<T extends Array<unknown>> = T extends readonly [] ? [] : T extends readonly [infer U, ...infer V] ? [
169
- U extends undefined ? null : JsonifiedValue<U>,
170
- ...JsonifiedArray<V>
171
- ] : T extends Array<infer U> ? Array<JsonifiedValue<U>> : unknown;
172
- /**
173
- * Convert types that JSON not support to corresponding json types
174
- *
175
- * @see {@link https://orpc.unnoq.com/docs/openapi/client/openapi-link OpenAPI Link Docs}
176
- */
177
- type JsonifiedClient<T extends NestedClient<any>> = T extends Client<infer UClientContext, infer UInput, infer UOutput, infer UError> ? Client<UClientContext, UInput, JsonifiedValue<UOutput>, UError extends ORPCError<infer UCode, infer UData> ? ORPCError<UCode, JsonifiedValue<UData>> : UError> : {
178
- [K in keyof T]: T[K] extends NestedClient<any> ? JsonifiedClient<T[K]> : T[K];
179
- };
180
- declare function createJsonifiedRouterClient<T extends AnyRouter, TClientContext extends ClientContext>(router: Lazyable<T | undefined>, ...rest: MaybeOptionalOptions<CreateProcedureClientOptions<InferRouterInitialContext<T>, Schema<unknown, unknown>, ErrorMap, Meta, TClientContext>>): JsonifiedClient<RouterClient<T, TClientContext>>;
181
-
182
165
  /**
183
166
  *@internal
184
167
  */
@@ -216,5 +199,5 @@ declare const oo: {
216
199
  spec: typeof customOpenAPIOperation;
217
200
  };
218
201
 
219
- export { CompositeSchemaConverter, LOGIC_KEYWORDS, OpenAPIGenerator, applyCustomOpenAPIOperation, applySchemaOptionality, checkParamsSchema, createJsonifiedRouterClient, customOpenAPIOperation, expandArrayableSchema, expandUnionSchema, filterSchemaBranches, getCustomOpenAPIOperation, isAnySchema, isFileSchema, isObjectSchema, isPrimitiveSchema, oo, resolveOpenAPIJsonSchemaRef, separateObjectSchema, toOpenAPIContent, toOpenAPIEventIteratorContent, toOpenAPIMethod, toOpenAPIParameters, toOpenAPIPath, toOpenAPISchema };
220
- export type { ConditionalSchemaConverter, FileSchema, JsonifiedArray, JsonifiedClient, JsonifiedValue, ObjectSchema, OpenAPIGeneratorGenerateOptions, OpenAPIGeneratorOptions, OverrideOperationValue, SchemaConvertOptions, SchemaConverter, SchemaConverterComponent };
202
+ export { CompositeSchemaConverter, LOGIC_KEYWORDS, OpenAPIGenerator, applyCustomOpenAPIOperation, applySchemaOptionality, checkParamsSchema, customOpenAPIOperation, expandArrayableSchema, expandUnionSchema, filterSchemaBranches, getCustomOpenAPIOperation, isAnySchema, isFileSchema, isObjectSchema, isPrimitiveSchema, oo, resolveOpenAPIJsonSchemaRef, separateObjectSchema, toOpenAPIContent, toOpenAPIEventIteratorContent, toOpenAPIMethod, toOpenAPIParameters, toOpenAPIPath, toOpenAPISchema };
203
+ export type { ConditionalSchemaConverter, FileSchema, ObjectSchema, OpenAPIGeneratorGenerateOptions, OpenAPIGeneratorOptions, OverrideOperationValue, SchemaConvertOptions, SchemaConverter, SchemaConverterComponent };
@@ -1,11 +1,11 @@
1
- import { OpenAPI, AnyContractProcedure, AnySchema, AnyContractRouter } from '@temporary-name/contract';
1
+ import { OpenAPI, AnySchema } from '@temporary-name/contract';
2
2
  export { OpenAPI } from '@temporary-name/contract';
3
- import { AnyProcedure, TraverseContractProcedureCallbackOptions, AnyRouter, ORPCError, ClientContext, Lazyable, CreateProcedureClientOptions, InferRouterInitialContext, Schema, ErrorMap, Meta, RouterClient } from '@temporary-name/server';
4
- import { Promisable, Value, HTTPPath, HTTPMethod, NestedClient, Client, MaybeOptionalOptions } from '@temporary-name/shared';
3
+ import { Contract, TraverseContractProcedureCallbackOptions, ContractRouter, AnyRouter } from '@temporary-name/server';
4
+ import { Promisable, Value, HTTPPath, HTTPMethod } from '@temporary-name/shared';
5
5
  import { JSONSchema } from '@temporary-name/interop/json-schema-typed/draft-2020-12';
6
6
  export { JSONSchema, ContentEncoding as JSONSchemaContentEncoding, Format as JSONSchemaFormat, TypeName as JSONSchemaTypeName } from '@temporary-name/interop/json-schema-typed/draft-2020-12';
7
7
 
8
- type OverrideOperationValue = Partial<OpenAPI.OperationObject> | ((current: OpenAPI.OperationObject, procedure: AnyContractProcedure) => OpenAPI.OperationObject);
8
+ type OverrideOperationValue = Partial<OpenAPI.OperationObject> | ((current: OpenAPI.OperationObject, procedure: Contract) => OpenAPI.OperationObject);
9
9
  /**
10
10
  * Customize The Operation Object by proxy an error map item or a middleware.
11
11
  *
@@ -13,7 +13,7 @@ type OverrideOperationValue = Partial<OpenAPI.OperationObject> | ((current: Open
13
13
  */
14
14
  declare function customOpenAPIOperation<T extends object>(o: T, extend: OverrideOperationValue): T;
15
15
  declare function getCustomOpenAPIOperation(o: object): OverrideOperationValue | undefined;
16
- declare function applyCustomOpenAPIOperation(operation: OpenAPI.OperationObject, contract: AnyContractProcedure): OpenAPI.OperationObject;
16
+ declare function applyCustomOpenAPIOperation(operation: OpenAPI.OperationObject, contract: Contract): OpenAPI.OperationObject;
17
17
 
18
18
  /**
19
19
  * @internal
@@ -76,7 +76,7 @@ interface OpenAPIGeneratorGenerateOptions extends Partial<Omit<OpenAPI.Document,
76
76
  * @deprecated Use `filter` option instead.
77
77
  * @default () => false
78
78
  */
79
- exclude?: (procedure: AnyProcedure | AnyContractProcedure, path: readonly string[]) => boolean;
79
+ exclude?: (procedure: Contract, path: readonly string[]) => boolean;
80
80
  /**
81
81
  * Filter procedures. Return `false` to exclude a procedure from the OpenAPI specification.
82
82
  *
@@ -129,7 +129,7 @@ declare class OpenAPIGenerator {
129
129
  *
130
130
  * @see {@link https://orpc.unnoq.com/docs/openapi/openapi-specification OpenAPI Specification Docs}
131
131
  */
132
- generate(router: AnyContractRouter | AnyRouter, options?: OpenAPIGeneratorGenerateOptions): Promise<OpenAPI.Document>;
132
+ generate(router: ContractRouter | AnyRouter, options?: OpenAPIGeneratorGenerateOptions): Promise<OpenAPI.Document>;
133
133
  }
134
134
 
135
135
  /**
@@ -162,23 +162,6 @@ declare function checkParamsSchema(schema: ObjectSchema, params: string[]): bool
162
162
  declare function toOpenAPISchema(schema: JSONSchema): OpenAPI.SchemaObject & object;
163
163
  declare function resolveOpenAPIJsonSchemaRef(doc: OpenAPI.Document, schema: JSONSchema): JSONSchema;
164
164
 
165
- type JsonifiedValue<T> = T extends string ? T : T extends number ? T : T extends boolean ? T : T extends null ? T : T extends undefined ? T : T extends Array<unknown> ? JsonifiedArray<T> : T extends Record<string, unknown> ? {
166
- [K in keyof T]: JsonifiedValue<T[K]>;
167
- } : T extends Date ? string : T extends bigint ? string : T extends File ? File : T extends Blob ? Blob : T extends RegExp ? string : T extends URL ? string : T extends Map<infer K, infer V> ? JsonifiedArray<[K, V][]> : T extends Set<infer U> ? JsonifiedArray<U[]> : T extends AsyncIteratorObject<infer U, infer V> ? AsyncIteratorObject<JsonifiedValue<U>, JsonifiedValue<V>> : unknown;
168
- type JsonifiedArray<T extends Array<unknown>> = T extends readonly [] ? [] : T extends readonly [infer U, ...infer V] ? [
169
- U extends undefined ? null : JsonifiedValue<U>,
170
- ...JsonifiedArray<V>
171
- ] : T extends Array<infer U> ? Array<JsonifiedValue<U>> : unknown;
172
- /**
173
- * Convert types that JSON not support to corresponding json types
174
- *
175
- * @see {@link https://orpc.unnoq.com/docs/openapi/client/openapi-link OpenAPI Link Docs}
176
- */
177
- type JsonifiedClient<T extends NestedClient<any>> = T extends Client<infer UClientContext, infer UInput, infer UOutput, infer UError> ? Client<UClientContext, UInput, JsonifiedValue<UOutput>, UError extends ORPCError<infer UCode, infer UData> ? ORPCError<UCode, JsonifiedValue<UData>> : UError> : {
178
- [K in keyof T]: T[K] extends NestedClient<any> ? JsonifiedClient<T[K]> : T[K];
179
- };
180
- declare function createJsonifiedRouterClient<T extends AnyRouter, TClientContext extends ClientContext>(router: Lazyable<T | undefined>, ...rest: MaybeOptionalOptions<CreateProcedureClientOptions<InferRouterInitialContext<T>, Schema<unknown, unknown>, ErrorMap, Meta, TClientContext>>): JsonifiedClient<RouterClient<T, TClientContext>>;
181
-
182
165
  /**
183
166
  *@internal
184
167
  */
@@ -216,5 +199,5 @@ declare const oo: {
216
199
  spec: typeof customOpenAPIOperation;
217
200
  };
218
201
 
219
- export { CompositeSchemaConverter, LOGIC_KEYWORDS, OpenAPIGenerator, applyCustomOpenAPIOperation, applySchemaOptionality, checkParamsSchema, createJsonifiedRouterClient, customOpenAPIOperation, expandArrayableSchema, expandUnionSchema, filterSchemaBranches, getCustomOpenAPIOperation, isAnySchema, isFileSchema, isObjectSchema, isPrimitiveSchema, oo, resolveOpenAPIJsonSchemaRef, separateObjectSchema, toOpenAPIContent, toOpenAPIEventIteratorContent, toOpenAPIMethod, toOpenAPIParameters, toOpenAPIPath, toOpenAPISchema };
220
- export type { ConditionalSchemaConverter, FileSchema, JsonifiedArray, JsonifiedClient, JsonifiedValue, ObjectSchema, OpenAPIGeneratorGenerateOptions, OpenAPIGeneratorOptions, OverrideOperationValue, SchemaConvertOptions, SchemaConverter, SchemaConverterComponent };
202
+ export { CompositeSchemaConverter, LOGIC_KEYWORDS, OpenAPIGenerator, applyCustomOpenAPIOperation, applySchemaOptionality, checkParamsSchema, customOpenAPIOperation, expandArrayableSchema, expandUnionSchema, filterSchemaBranches, getCustomOpenAPIOperation, isAnySchema, isFileSchema, isObjectSchema, isPrimitiveSchema, oo, resolveOpenAPIJsonSchemaRef, separateObjectSchema, toOpenAPIContent, toOpenAPIEventIteratorContent, toOpenAPIMethod, toOpenAPIParameters, toOpenAPIPath, toOpenAPISchema };
203
+ export type { ConditionalSchemaConverter, FileSchema, ObjectSchema, OpenAPIGeneratorGenerateOptions, OpenAPIGeneratorOptions, OverrideOperationValue, SchemaConvertOptions, SchemaConverter, SchemaConverterComponent };
@@ -1,7 +1,7 @@
1
- import { isProcedure, resolveContractProcedures, ORPCError, createRouterClient } from '@temporary-name/server';
2
1
  import { standardizeHTTPPath, fallbackContractConfig, getDynamicParams, getEventIteratorSchemaDetails } from '@temporary-name/contract';
3
- import { isObject, stringifyJSON, findDeepMatches, toArray, clone, value, toHttpPath, isORPCErrorStatus, fallbackORPCErrorStatus, fallbackORPCErrorMessage, resolveMaybeOptionalOptions, createORPCErrorFromJson } from '@temporary-name/shared';
4
- import { j as jsonSerialize, d as deserialize, s as serialize } from '../shared/server.JtIZ8YG7.mjs';
2
+ import { resolveContractProcedures } from '@temporary-name/server';
3
+ import { isObject, stringifyJSON, findDeepMatches, toArray, clone, value, toHttpPath, isORPCErrorStatus } from '@temporary-name/shared';
4
+ import { j as jsonSerialize } from '../shared/server.CQIFwyhc.mjs';
5
5
  import '@temporary-name/standard-server';
6
6
  import { TypeName } from '@temporary-name/interop/json-schema-typed/draft-2020-12';
7
7
  export { ContentEncoding as JSONSchemaContentEncoding, Format as JSONSchemaFormat, TypeName as JSONSchemaTypeName } from '@temporary-name/interop/json-schema-typed/draft-2020-12';
@@ -22,20 +22,12 @@ function getCustomOpenAPIOperation(o) {
22
22
  }
23
23
  function applyCustomOpenAPIOperation(operation, contract) {
24
24
  const operationCustoms = [];
25
- for (const errorItem of Object.values(contract["~orpc"].errorMap)) {
26
- const maybeExtender = errorItem ? getCustomOpenAPIOperation(errorItem) : void 0;
25
+ for (const middleware of contract["~orpc"].middlewares) {
26
+ const maybeExtender = getCustomOpenAPIOperation(middleware);
27
27
  if (maybeExtender) {
28
28
  operationCustoms.push(maybeExtender);
29
29
  }
30
30
  }
31
- if (isProcedure(contract)) {
32
- for (const middleware of contract["~orpc"].middlewares) {
33
- const maybeExtender = getCustomOpenAPIOperation(middleware);
34
- if (maybeExtender) {
35
- operationCustoms.push(maybeExtender);
36
- }
37
- }
38
- }
39
31
  let currentOperation = operation;
40
32
  for (const custom of operationCustoms) {
41
33
  if (typeof custom === "function") {
@@ -432,12 +424,6 @@ class OpenAPIGenerator {
432
424
  };
433
425
  await this.#request(doc, operationObjectRef, def, baseSchemaConvertOptions);
434
426
  await this.#successResponse(doc, operationObjectRef, def, baseSchemaConvertOptions);
435
- await this.#errorResponse(
436
- operationObjectRef,
437
- def,
438
- baseSchemaConvertOptions,
439
- undefinedErrorJsonSchema
440
- );
441
427
  }
442
428
  if (typeof def.route.spec === "function") {
443
429
  operationObjectRef = def.route.spec(operationObjectRef);
@@ -696,64 +682,10 @@ ${errors.join("\n\n")}`
696
682
  }
697
683
  }
698
684
  }
699
- async #errorResponse(ref, def, baseSchemaConvertOptions, undefinedErrorSchema) {
700
- const errorMap = def.errorMap;
701
- const errors = {};
702
- for (const code in errorMap) {
703
- const config = errorMap[code];
704
- if (!config) {
705
- continue;
706
- }
707
- const status = fallbackORPCErrorStatus(code, config.status);
708
- const message = fallbackORPCErrorMessage(code, config.message);
709
- const [dataRequired, dataSchema] = await this.converter.convert(config.data, {
710
- ...baseSchemaConvertOptions,
711
- strategy: "output"
712
- });
713
- errors[status] ??= [];
714
- errors[status].push({
715
- type: "object",
716
- properties: {
717
- defined: { const: true },
718
- code: { const: code },
719
- status: { const: status },
720
- message: { type: "string", default: message },
721
- data: dataSchema
722
- },
723
- required: dataRequired ? ["defined", "code", "status", "message", "data"] : ["defined", "code", "status", "message"]
724
- });
725
- }
726
- ref.responses ??= {};
727
- for (const status in errors) {
728
- const schemas = errors[status];
729
- ref.responses[status] = {
730
- description: status,
731
- content: toOpenAPIContent({
732
- oneOf: [...schemas, undefinedErrorSchema]
733
- })
734
- };
735
- }
736
- }
737
- }
738
-
739
- function createJsonifiedRouterClient(router, ...rest) {
740
- const options = resolveMaybeOptionalOptions(rest);
741
- options.interceptors ??= [];
742
- options.interceptors.unshift(async (options2) => {
743
- try {
744
- return deserialize(serialize(await options2.next()));
745
- } catch (e) {
746
- if (e instanceof ORPCError) {
747
- throw createORPCErrorFromJson(deserialize(serialize(e.toJSON(), { outputFormat: "plain" })));
748
- }
749
- throw e;
750
- }
751
- });
752
- return createRouterClient(router, options);
753
685
  }
754
686
 
755
687
  const oo = {
756
688
  spec: customOpenAPIOperation
757
689
  };
758
690
 
759
- export { CompositeSchemaConverter, LOGIC_KEYWORDS, OpenAPIGenerator, applyCustomOpenAPIOperation, applySchemaOptionality, checkParamsSchema, createJsonifiedRouterClient, customOpenAPIOperation, expandArrayableSchema, expandUnionSchema, filterSchemaBranches, getCustomOpenAPIOperation, isAnySchema, isFileSchema, isObjectSchema, isPrimitiveSchema, oo, resolveOpenAPIJsonSchemaRef, separateObjectSchema, toOpenAPIContent, toOpenAPIEventIteratorContent, toOpenAPIMethod, toOpenAPIParameters, toOpenAPIPath, toOpenAPISchema };
691
+ export { CompositeSchemaConverter, LOGIC_KEYWORDS, OpenAPIGenerator, applyCustomOpenAPIOperation, applySchemaOptionality, checkParamsSchema, customOpenAPIOperation, expandArrayableSchema, expandUnionSchema, filterSchemaBranches, getCustomOpenAPIOperation, isAnySchema, isFileSchema, isObjectSchema, isPrimitiveSchema, oo, resolveOpenAPIJsonSchemaRef, separateObjectSchema, toOpenAPIContent, toOpenAPIEventIteratorContent, toOpenAPIMethod, toOpenAPIParameters, toOpenAPIPath, toOpenAPISchema };