@orpc/openapi 0.0.0-next.ea0903c → 0.0.0-next.ea1d4fd

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 (38) hide show
  1. package/README.md +23 -22
  2. package/dist/adapters/aws-lambda/index.d.mts +20 -0
  3. package/dist/adapters/aws-lambda/index.d.ts +20 -0
  4. package/dist/adapters/aws-lambda/index.mjs +18 -0
  5. package/dist/adapters/fastify/index.d.mts +23 -0
  6. package/dist/adapters/fastify/index.d.ts +23 -0
  7. package/dist/adapters/fastify/index.mjs +18 -0
  8. package/dist/adapters/fetch/index.d.mts +15 -3
  9. package/dist/adapters/fetch/index.d.ts +15 -3
  10. package/dist/adapters/fetch/index.mjs +13 -5
  11. package/dist/adapters/node/index.d.mts +15 -3
  12. package/dist/adapters/node/index.d.ts +15 -3
  13. package/dist/adapters/node/index.mjs +5 -9
  14. package/dist/adapters/standard/index.d.mts +8 -22
  15. package/dist/adapters/standard/index.d.ts +8 -22
  16. package/dist/adapters/standard/index.mjs +4 -2
  17. package/dist/index.d.mts +43 -40
  18. package/dist/index.d.ts +43 -40
  19. package/dist/index.mjs +31 -513
  20. package/dist/plugins/index.d.mts +84 -0
  21. package/dist/plugins/index.d.ts +84 -0
  22. package/dist/plugins/index.mjs +148 -0
  23. package/dist/shared/openapi.BfNjg7j9.d.mts +120 -0
  24. package/dist/shared/openapi.BfNjg7j9.d.ts +120 -0
  25. package/dist/shared/openapi.CzHcOMxv.mjs +853 -0
  26. package/dist/shared/{openapi.rzdlmBcy.mjs → openapi.DIt-Z9W1.mjs} +56 -12
  27. package/dist/shared/openapi.DwaweYRb.d.mts +54 -0
  28. package/dist/shared/openapi.DwaweYRb.d.ts +54 -0
  29. package/package.json +26 -21
  30. package/dist/adapters/hono/index.d.mts +0 -6
  31. package/dist/adapters/hono/index.d.ts +0 -6
  32. package/dist/adapters/hono/index.mjs +0 -10
  33. package/dist/adapters/next/index.d.mts +0 -6
  34. package/dist/adapters/next/index.d.ts +0 -6
  35. package/dist/adapters/next/index.mjs +0 -10
  36. package/dist/shared/openapi.By1hOIbk.mjs +0 -17
  37. package/dist/shared/openapi.IfmmOyba.d.mts +0 -8
  38. package/dist/shared/openapi.IfmmOyba.d.ts +0 -8
package/dist/index.d.ts CHANGED
@@ -1,16 +1,23 @@
1
- import { AnyContractProcedure, AnySchema, AnyContractRouter } from '@orpc/contract';
2
- import { OpenAPIV3_1 } from 'openapi-types';
3
- export { OpenAPIV3_1 as OpenAPI } from 'openapi-types';
4
- import { StandardOpenAPIJsonSerializerOptions } from '@orpc/openapi-client/standard';
5
- import { AnyRouter } from '@orpc/server';
6
- import { JSONSchema } from 'json-schema-typed/draft-2020-12';
7
- export { JSONSchema, Format as JSONSchemaFormat } from 'json-schema-typed/draft-2020-12';
1
+ import { OpenAPI, AnyContractProcedure } from '@orpc/contract';
2
+ export { OpenAPI } from '@orpc/contract';
3
+ export { e as CompositeSchemaConverter, C as ConditionalSchemaConverter, b as OpenAPIGenerator, a as OpenAPIGeneratorGenerateOptions, O as OpenAPIGeneratorOptions, c as SchemaConvertOptions, d as SchemaConverter, S as SchemaConverterComponent } from './shared/openapi.BfNjg7j9.js';
8
4
  import { HTTPPath, HTTPMethod } from '@orpc/client';
5
+ import { JSONSchema } from '@orpc/interop/json-schema-typed/draft-2020-12';
6
+ export { JSONSchema, ContentEncoding as JSONSchemaContentEncoding, Format as JSONSchemaFormat, TypeName as JSONSchemaTypeName } from '@orpc/interop/json-schema-typed/draft-2020-12';
7
+ import { JsonifiedClient } from '@orpc/openapi-client';
8
+ import { AnyRouter, ClientContext, Lazyable, CreateProcedureClientOptions, InferRouterInitialContext, Schema, ErrorMap, Meta, RouterClient } from '@orpc/server';
9
+ import { MaybeOptionalOptions } from '@orpc/shared';
10
+ import '@orpc/openapi-client/standard';
9
11
 
10
- type OverrideOperationValue = Partial<OpenAPIV3_1.OperationObject> | ((current: OpenAPIV3_1.OperationObject, procedure: AnyContractProcedure) => OpenAPIV3_1.OperationObject);
12
+ type OverrideOperationValue = Partial<OpenAPI.OperationObject> | ((current: OpenAPI.OperationObject, procedure: AnyContractProcedure) => OpenAPI.OperationObject);
13
+ /**
14
+ * Customize The Operation Object by proxy an error map item or a middleware.
15
+ *
16
+ * @see {@link https://orpc.unnoq.com/docs/openapi/openapi-specification#customizing-operation-objects Customizing Operation Objects Docs}
17
+ */
11
18
  declare function customOpenAPIOperation<T extends object>(o: T, extend: OverrideOperationValue): T;
12
19
  declare function getCustomOpenAPIOperation(o: object): OverrideOperationValue | undefined;
13
- declare function applyCustomOpenAPIOperation(operation: OpenAPIV3_1.OperationObject, contract: AnyContractProcedure): OpenAPIV3_1.OperationObject;
20
+ declare function applyCustomOpenAPIOperation(operation: OpenAPI.OperationObject, contract: AnyContractProcedure): OpenAPI.OperationObject;
14
21
 
15
22
  /**
16
23
  * @internal
@@ -30,32 +37,6 @@ type FileSchema = JSONSchema & {
30
37
  */
31
38
  declare const LOGIC_KEYWORDS: string[];
32
39
 
33
- interface SchemaConvertOptions {
34
- strategy: 'input' | 'output';
35
- }
36
- interface SchemaConverter {
37
- convert(schema: AnySchema | undefined, options: SchemaConvertOptions): [required: boolean, jsonSchema: JSONSchema];
38
- }
39
- interface ConditionalSchemaConverter extends SchemaConverter {
40
- condition(schema: AnySchema | undefined, options: SchemaConvertOptions): boolean;
41
- }
42
- declare class CompositeSchemaConverter implements SchemaConverter {
43
- private readonly converters;
44
- constructor(converters: ConditionalSchemaConverter[]);
45
- convert(schema: AnySchema | undefined, options: SchemaConvertOptions): [required: boolean, jsonSchema: JSONSchema];
46
- }
47
-
48
- interface OpenAPIGeneratorOptions extends StandardOpenAPIJsonSerializerOptions {
49
- schemaConverters?: ConditionalSchemaConverter[];
50
- }
51
- declare class OpenAPIGenerator {
52
- #private;
53
- private readonly serializer;
54
- private readonly converter;
55
- constructor(options?: OpenAPIGeneratorOptions);
56
- generate(router: AnyContractRouter | AnyRouter, base: Omit<OpenAPIV3_1.Document, 'openapi'>): Promise<OpenAPIV3_1.Document>;
57
- }
58
-
59
40
  /**
60
41
  * @internal
61
42
  */
@@ -67,15 +48,15 @@ declare function toOpenAPIMethod(method: HTTPMethod): Lowercase<HTTPMethod>;
67
48
  /**
68
49
  * @internal
69
50
  */
70
- declare function toOpenAPIContent(schema: JSONSchema): Record<string, OpenAPIV3_1.MediaTypeObject>;
51
+ declare function toOpenAPIContent(schema: JSONSchema): Record<string, OpenAPI.MediaTypeObject>;
71
52
  /**
72
53
  * @internal
73
54
  */
74
- declare function toOpenAPIEventIteratorContent([yieldsRequired, yieldsSchema]: [boolean, JSONSchema], [returnsRequired, returnsSchema]: [boolean, JSONSchema]): Record<string, OpenAPIV3_1.MediaTypeObject>;
55
+ declare function toOpenAPIEventIteratorContent([yieldsRequired, yieldsSchema]: [boolean, JSONSchema], [returnsRequired, returnsSchema]: [boolean, JSONSchema]): Record<string, OpenAPI.MediaTypeObject>;
75
56
  /**
76
57
  * @internal
77
58
  */
78
- declare function toOpenAPIParameters(schema: ObjectSchema, parameterIn: 'path' | 'query' | 'header' | 'cookie'): OpenAPIV3_1.ParameterObject[];
59
+ declare function toOpenAPIParameters(schema: ObjectSchema, parameterIn: 'path' | 'query' | 'header' | 'cookie'): OpenAPI.ParameterObject[];
79
60
  /**
80
61
  * @internal
81
62
  */
@@ -83,7 +64,16 @@ declare function checkParamsSchema(schema: ObjectSchema, params: string[]): bool
83
64
  /**
84
65
  * @internal
85
66
  */
86
- declare function toOpenAPISchema(schema: JSONSchema): OpenAPIV3_1.SchemaObject & object;
67
+ declare function toOpenAPISchema(schema: JSONSchema): OpenAPI.SchemaObject & object;
68
+ declare function resolveOpenAPIJsonSchemaRef(doc: OpenAPI.Document, schema: JSONSchema): JSONSchema;
69
+ /**
70
+ * Simplifies composed object JSON Schemas (using anyOf, oneOf, allOf) by flattening nested compositions
71
+ *
72
+ * @warning The result is looser than the original schema and may not fully validate the same data.
73
+ */
74
+ declare function simplifyComposedObjectJsonSchemasAndRefs(schema: JSONSchema, doc?: OpenAPI.Document): JSONSchema;
75
+
76
+ 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>>;
87
77
 
88
78
  /**
89
79
  *@internal
@@ -105,9 +95,22 @@ declare function separateObjectSchema(schema: ObjectSchema, separatedProperties:
105
95
  * @internal
106
96
  */
107
97
  declare function filterSchemaBranches(schema: JSONSchema, check: (schema: JSONSchema) => boolean, matches?: JSONSchema[]): [matches: JSONSchema[], rest: JSONSchema | undefined];
98
+ declare function applySchemaOptionality(required: boolean, schema: JSONSchema): JSONSchema;
99
+ /**
100
+ * Takes a JSON schema and, if it's primarily a union type (anyOf, oneOf),
101
+ * recursively expands it into an array of its constituent, non-union base schemas.
102
+ * If the schema is not a simple union or is a base type, it's returned as a single-element array.
103
+ */
104
+ declare function expandUnionSchema(schema: JSONSchema): JSONSchema[];
105
+ declare function expandArrayableSchema(schema: JSONSchema): undefined | [items: JSONSchema, array: JSONSchema & {
106
+ type: 'array';
107
+ items?: JSONSchema;
108
+ }];
109
+ declare function isPrimitiveSchema(schema: JSONSchema): boolean;
108
110
 
109
111
  declare const oo: {
110
112
  spec: typeof customOpenAPIOperation;
111
113
  };
112
114
 
113
- export { CompositeSchemaConverter, type ConditionalSchemaConverter, type FileSchema, LOGIC_KEYWORDS, type ObjectSchema, OpenAPIGenerator, type OpenAPIGeneratorOptions, type OverrideOperationValue, type SchemaConvertOptions, type SchemaConverter, applyCustomOpenAPIOperation, checkParamsSchema, customOpenAPIOperation, filterSchemaBranches, getCustomOpenAPIOperation, isAnySchema, isFileSchema, isObjectSchema, oo, separateObjectSchema, toOpenAPIContent, toOpenAPIEventIteratorContent, toOpenAPIMethod, toOpenAPIParameters, toOpenAPIPath, toOpenAPISchema };
115
+ export { LOGIC_KEYWORDS, applyCustomOpenAPIOperation, applySchemaOptionality, checkParamsSchema, createJsonifiedRouterClient, customOpenAPIOperation, expandArrayableSchema, expandUnionSchema, filterSchemaBranches, getCustomOpenAPIOperation, isAnySchema, isFileSchema, isObjectSchema, isPrimitiveSchema, oo, resolveOpenAPIJsonSchemaRef, separateObjectSchema, simplifyComposedObjectJsonSchemasAndRefs, toOpenAPIContent, toOpenAPIEventIteratorContent, toOpenAPIMethod, toOpenAPIParameters, toOpenAPIPath, toOpenAPISchema };
116
+ export type { FileSchema, ObjectSchema, OverrideOperationValue };
package/dist/index.mjs CHANGED
@@ -1,523 +1,41 @@
1
- import { isProcedure, resolveContractProcedures } from '@orpc/server';
2
- import { fallbackORPCErrorStatus, fallbackORPCErrorMessage } from '@orpc/client';
3
- import { toHttpPath } from '@orpc/client/standard';
4
- import { fallbackContractConfig, getEventIteratorSchemaDetails } from '@orpc/contract';
5
- import { standardizeHTTPPath, StandardOpenAPIJsonSerializer, getDynamicParams } from '@orpc/openapi-client/standard';
6
- import { isObject, findDeepMatches, clone } from '@orpc/shared';
7
- export { Format as JSONSchemaFormat } from 'json-schema-typed/draft-2020-12';
8
-
9
- const OPERATION_EXTENDER_SYMBOL = Symbol("ORPC_OPERATION_EXTENDER");
10
- function customOpenAPIOperation(o, extend) {
11
- return new Proxy(o, {
12
- get(target, prop, receiver) {
13
- if (prop === OPERATION_EXTENDER_SYMBOL) {
14
- return extend;
15
- }
16
- return Reflect.get(target, prop, receiver);
17
- }
18
- });
19
- }
20
- function getCustomOpenAPIOperation(o) {
21
- return o[OPERATION_EXTENDER_SYMBOL];
22
- }
23
- function applyCustomOpenAPIOperation(operation, contract) {
24
- const operationCustoms = [];
25
- for (const errorItem of Object.values(contract["~orpc"].errorMap)) {
26
- const maybeExtender = errorItem ? getCustomOpenAPIOperation(errorItem) : void 0;
27
- if (maybeExtender) {
28
- operationCustoms.push(maybeExtender);
29
- }
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
- let currentOperation = operation;
40
- for (const custom of operationCustoms) {
41
- if (typeof custom === "function") {
42
- currentOperation = custom(currentOperation, contract);
43
- } else {
44
- currentOperation = {
45
- ...currentOperation,
46
- ...custom
47
- };
48
- }
49
- }
50
- return currentOperation;
51
- }
52
-
53
- const LOGIC_KEYWORDS = [
54
- "$dynamicRef",
55
- "$ref",
56
- "additionalItems",
57
- "additionalProperties",
58
- "allOf",
59
- "anyOf",
60
- "const",
61
- "contains",
62
- "contentEncoding",
63
- "contentMediaType",
64
- "contentSchema",
65
- "dependencies",
66
- "dependentRequired",
67
- "dependentSchemas",
68
- "else",
69
- "enum",
70
- "exclusiveMaximum",
71
- "exclusiveMinimum",
72
- "format",
73
- "if",
74
- "items",
75
- "maxContains",
76
- "maximum",
77
- "maxItems",
78
- "maxLength",
79
- "maxProperties",
80
- "minContains",
81
- "minimum",
82
- "minItems",
83
- "minLength",
84
- "minProperties",
85
- "multipleOf",
86
- "not",
87
- "oneOf",
88
- "pattern",
89
- "patternProperties",
90
- "prefixItems",
91
- "properties",
92
- "propertyNames",
93
- "required",
94
- "then",
95
- "type",
96
- "unevaluatedItems",
97
- "unevaluatedProperties",
98
- "uniqueItems"
99
- ];
100
-
101
- function isFileSchema(schema) {
102
- return isObject(schema) && schema.type === "string" && typeof schema.contentMediaType === "string";
103
- }
104
- function isObjectSchema(schema) {
105
- return isObject(schema) && schema.type === "object";
106
- }
107
- function isAnySchema(schema) {
108
- if (schema === true) {
109
- return true;
110
- }
111
- if (Object.keys(schema).every((k) => !LOGIC_KEYWORDS.includes(k))) {
112
- return true;
113
- }
114
- return false;
115
- }
116
- function separateObjectSchema(schema, separatedProperties) {
117
- if (Object.keys(schema).some((k) => k !== "type" && k !== "properties" && k !== "required" && LOGIC_KEYWORDS.includes(k))) {
118
- return [{ type: "object" }, schema];
119
- }
120
- const matched = { ...schema };
121
- const rest = { ...schema };
122
- matched.properties = schema.properties && Object.entries(schema.properties).filter(([key]) => separatedProperties.includes(key)).reduce((acc, [key, value]) => {
123
- acc[key] = value;
124
- return acc;
125
- }, {});
126
- matched.required = schema.required?.filter((key) => separatedProperties.includes(key));
127
- matched.examples = schema.examples?.map((example) => {
128
- if (!isObject(example)) {
129
- return example;
130
- }
131
- return Object.entries(example).reduce((acc, [key, value]) => {
132
- if (separatedProperties.includes(key)) {
133
- acc[key] = value;
134
- }
135
- return acc;
136
- }, {});
137
- });
138
- rest.properties = schema.properties && Object.entries(schema.properties).filter(([key]) => !separatedProperties.includes(key)).reduce((acc, [key, value]) => {
139
- acc[key] = value;
140
- return acc;
141
- }, {});
142
- rest.required = schema.required?.filter((key) => !separatedProperties.includes(key));
143
- rest.examples = schema.examples?.map((example) => {
144
- if (!isObject(example)) {
145
- return example;
146
- }
147
- return Object.entries(example).reduce((acc, [key, value]) => {
148
- if (!separatedProperties.includes(key)) {
149
- acc[key] = value;
150
- }
151
- return acc;
152
- }, {});
153
- });
154
- return [matched, rest];
155
- }
156
- function filterSchemaBranches(schema, check, matches = []) {
157
- if (check(schema)) {
158
- matches.push(schema);
159
- return [matches, void 0];
160
- }
161
- if (isObject(schema)) {
162
- for (const keyword of ["anyOf", "oneOf"]) {
163
- if (schema[keyword] && Object.keys(schema).every(
164
- (k) => k === keyword || !LOGIC_KEYWORDS.includes(k)
165
- )) {
166
- const rest = schema[keyword].map((s) => filterSchemaBranches(s, check, matches)[1]).filter((v) => !!v);
167
- if (rest.length === 1 && typeof rest[0] === "object") {
168
- return [matches, { ...schema, [keyword]: void 0, ...rest[0] }];
169
- }
170
- return [matches, { ...schema, [keyword]: rest }];
171
- }
172
- }
173
- }
174
- return [matches, schema];
175
- }
176
-
177
- function toOpenAPIPath(path) {
178
- return standardizeHTTPPath(path).replace(/\/\{\+([^}]+)\}/g, "/{$1}");
179
- }
180
- function toOpenAPIMethod(method) {
181
- return method.toLocaleLowerCase();
182
- }
183
- function toOpenAPIContent(schema) {
184
- const content = {};
185
- const [matches, restSchema] = filterSchemaBranches(schema, isFileSchema);
186
- for (const file of matches) {
187
- content[file.contentMediaType] = {
188
- schema: toOpenAPISchema(file)
189
- };
190
- }
191
- if (restSchema !== void 0) {
192
- content["application/json"] = {
193
- schema: toOpenAPISchema(restSchema)
194
- };
195
- const isStillHasFileSchema = findDeepMatches((v) => isObject(v) && isFileSchema(v), restSchema).values.length > 0;
196
- if (isStillHasFileSchema) {
197
- content["multipart/form-data"] = {
198
- schema: toOpenAPISchema(restSchema)
199
- };
200
- }
201
- }
202
- return content;
203
- }
204
- function toOpenAPIEventIteratorContent([yieldsRequired, yieldsSchema], [returnsRequired, returnsSchema]) {
205
- return {
206
- "text/event-stream": {
207
- schema: toOpenAPISchema({
208
- oneOf: [
209
- {
210
- type: "object",
211
- properties: {
212
- event: { const: "message" },
213
- data: yieldsSchema,
214
- id: { type: "string" },
215
- retry: { type: "number" }
216
- },
217
- required: yieldsRequired ? ["event", "data"] : ["event"]
218
- },
219
- {
220
- type: "object",
221
- properties: {
222
- event: { const: "done" },
223
- data: returnsSchema,
224
- id: { type: "string" },
225
- retry: { type: "number" }
226
- },
227
- required: returnsRequired ? ["event", "data"] : ["event"]
228
- },
229
- {
230
- type: "object",
231
- properties: {
232
- event: { const: "error" },
233
- data: {},
234
- id: { type: "string" },
235
- retry: { type: "number" }
236
- },
237
- required: ["event"]
238
- }
239
- ]
240
- })
241
- }
242
- };
243
- }
244
- function toOpenAPIParameters(schema, parameterIn) {
245
- const parameters = [];
246
- for (const key in schema.properties) {
247
- const keySchema = schema.properties[key];
248
- parameters.push({
249
- name: key,
250
- in: parameterIn,
251
- required: schema.required?.includes(key),
252
- style: parameterIn === "query" ? "deepObject" : void 0,
253
- explode: parameterIn === "query" ? true : void 0,
254
- schema: toOpenAPISchema(keySchema)
255
- });
256
- }
257
- return parameters;
258
- }
259
- function checkParamsSchema(schema, params) {
260
- const properties = Object.keys(schema.properties ?? {});
261
- const required = schema.required ?? [];
262
- if (properties.length !== params.length || properties.some((v) => !params.includes(v))) {
263
- return false;
264
- }
265
- if (required.length !== params.length || required.some((v) => !params.includes(v))) {
266
- return false;
267
- }
268
- return true;
269
- }
270
- function toOpenAPISchema(schema) {
271
- return schema === true ? {} : schema === false ? { not: {} } : schema;
272
- }
273
-
274
- class CompositeSchemaConverter {
275
- converters;
276
- constructor(converters) {
277
- this.converters = converters;
278
- }
279
- convert(schema, options) {
280
- for (const converter of this.converters) {
281
- if (converter.condition(schema, options)) {
282
- return converter.convert(schema, options);
283
- }
284
- }
285
- return [false, {}];
286
- }
287
- }
288
-
289
- class OpenAPIGeneratorError extends Error {
290
- }
291
- class OpenAPIGenerator {
292
- serializer;
293
- converter;
294
- constructor(options = {}) {
295
- this.serializer = new StandardOpenAPIJsonSerializer(options);
296
- this.converter = new CompositeSchemaConverter(options.schemaConverters ?? []);
297
- }
298
- async generate(router, base) {
299
- const doc = clone(base);
300
- doc.openapi = "3.1.1";
301
- const errors = [];
302
- await resolveContractProcedures({ path: [], router }, ({ contract, path }) => {
303
- const operationId = path.join(".");
304
- try {
305
- const def = contract["~orpc"];
306
- const method = toOpenAPIMethod(fallbackContractConfig("defaultMethod", def.route.method));
307
- const httpPath = toOpenAPIPath(def.route.path ?? toHttpPath(path));
308
- const operationObjectRef = {
309
- operationId,
310
- summary: def.route.summary,
311
- description: def.route.description,
312
- deprecated: def.route.deprecated,
313
- tags: def.route.tags?.map((tag) => tag)
314
- };
315
- this.#request(operationObjectRef, def);
316
- this.#successResponse(operationObjectRef, def);
317
- this.#errorResponse(operationObjectRef, def);
318
- doc.paths ??= {};
319
- doc.paths[httpPath] ??= {};
320
- doc.paths[httpPath][method] = applyCustomOpenAPIOperation(operationObjectRef, contract);
321
- } catch (e) {
322
- if (!(e instanceof OpenAPIGeneratorError)) {
323
- throw e;
324
- }
325
- errors.push(
326
- `[OpenAPIGenerator] Error occurred while generating OpenAPI for procedure at path: ${operationId}
327
- ${e.message}`
328
- );
329
- }
330
- });
331
- if (errors.length) {
332
- throw new OpenAPIGeneratorError(
333
- `Some error occurred during OpenAPI generation:
334
-
335
- ${errors.join("\n\n")}`
336
- );
337
- }
338
- return this.serializer.serialize(doc)[0];
339
- }
340
- #request(ref, def) {
341
- const method = fallbackContractConfig("defaultMethod", def.route.method);
342
- const details = getEventIteratorSchemaDetails(def.inputSchema);
343
- if (details) {
344
- ref.requestBody = {
345
- required: true,
346
- content: toOpenAPIEventIteratorContent(
347
- this.converter.convert(details.yields, { strategy: "input" }),
348
- this.converter.convert(details.returns, { strategy: "input" })
1
+ import { c as customOpenAPIOperation } from './shared/openapi.CzHcOMxv.mjs';
2
+ export { C as CompositeSchemaConverter, L as LOGIC_KEYWORDS, O as OpenAPIGenerator, a as applyCustomOpenAPIOperation, o as applySchemaOptionality, h as checkParamsSchema, q as expandArrayableSchema, p as expandUnionSchema, n as filterSchemaBranches, g as getCustomOpenAPIOperation, l as isAnySchema, j as isFileSchema, k as isObjectSchema, u as isPrimitiveSchema, r as resolveOpenAPIJsonSchemaRef, m as separateObjectSchema, s as simplifyComposedObjectJsonSchemasAndRefs, d as toOpenAPIContent, e as toOpenAPIEventIteratorContent, b as toOpenAPIMethod, f as toOpenAPIParameters, t as toOpenAPIPath, i as toOpenAPISchema } from './shared/openapi.CzHcOMxv.mjs';
3
+ import { createORPCErrorFromJson } from '@orpc/client';
4
+ import { StandardOpenAPISerializer, StandardOpenAPIJsonSerializer, StandardBracketNotationSerializer } from '@orpc/openapi-client/standard';
5
+ import { ORPCError, createRouterClient } from '@orpc/server';
6
+ import { resolveMaybeOptionalOptions } from '@orpc/shared';
7
+ export { ContentEncoding as JSONSchemaContentEncoding, Format as JSONSchemaFormat, TypeName as JSONSchemaTypeName } from '@orpc/interop/json-schema-typed/draft-2020-12';
8
+ import '@orpc/client/standard';
9
+ import '@orpc/contract';
10
+
11
+ function createJsonifiedRouterClient(router, ...rest) {
12
+ const options = resolveMaybeOptionalOptions(rest);
13
+ const serializer = new StandardOpenAPISerializer(new StandardOpenAPIJsonSerializer(), new StandardBracketNotationSerializer());
14
+ options.interceptors ??= [];
15
+ options.interceptors.unshift(async (options2) => {
16
+ try {
17
+ return serializer.deserialize(
18
+ serializer.serialize(
19
+ await options2.next()
349
20
  )
350
- };
351
- return;
352
- }
353
- const dynamicParams = getDynamicParams(def.route.path)?.map((v) => v.name);
354
- const inputStructure = fallbackContractConfig("defaultInputStructure", def.route.inputStructure);
355
- let [required, schema] = this.converter.convert(def.inputSchema, { strategy: "input" });
356
- if (isAnySchema(schema) && !dynamicParams?.length) {
357
- return;
358
- }
359
- if (inputStructure === "compact") {
360
- if (dynamicParams?.length) {
361
- const error2 = new OpenAPIGeneratorError(
362
- 'When input structure is "compact", and path has dynamic params, input schema must be an object with all dynamic params as required.'
363
- );
364
- if (!isObjectSchema(schema)) {
365
- throw error2;
366
- }
367
- const [paramsSchema, rest] = separateObjectSchema(schema, dynamicParams);
368
- schema = rest;
369
- required = rest.required ? rest.required.length !== 0 : false;
370
- if (!checkParamsSchema(paramsSchema, dynamicParams)) {
371
- throw error2;
372
- }
373
- ref.parameters ??= [];
374
- ref.parameters.push(...toOpenAPIParameters(paramsSchema, "path"));
375
- }
376
- if (method === "GET") {
377
- if (!isObjectSchema(schema)) {
378
- throw new OpenAPIGeneratorError(
379
- 'When method is "GET", input schema must satisfy: object | any | unknown'
380
- );
381
- }
382
- ref.parameters ??= [];
383
- ref.parameters.push(...toOpenAPIParameters(schema, "query"));
384
- } else {
385
- ref.requestBody = {
386
- required,
387
- content: toOpenAPIContent(schema)
388
- };
389
- }
390
- return;
391
- }
392
- const error = new OpenAPIGeneratorError(
393
- 'When input structure is "detailed", input schema must satisfy: { params?: Record<string, unknown>, query?: Record<string, unknown>, headers?: Record<string, unknown>, body?: unknown }'
394
- );
395
- if (!isObjectSchema(schema)) {
396
- throw error;
397
- }
398
- if (dynamicParams?.length && (schema.properties?.params === void 0 || !isObjectSchema(schema.properties.params) || !checkParamsSchema(schema.properties.params, dynamicParams))) {
399
- throw new OpenAPIGeneratorError(
400
- 'When input structure is "detailed" and path has dynamic params, the "params" schema must be an object with all dynamic params as required.'
401
21
  );
402
- }
403
- for (const from of ["params", "query", "headers"]) {
404
- const fromSchema = schema.properties?.[from];
405
- if (fromSchema !== void 0) {
406
- if (!isObjectSchema(fromSchema)) {
407
- throw error;
408
- }
409
- const parameterIn = from === "params" ? "path" : from === "headers" ? "header" : "query";
410
- ref.parameters ??= [];
411
- ref.parameters.push(...toOpenAPIParameters(fromSchema, parameterIn));
412
- }
413
- }
414
- if (schema.properties?.body !== void 0) {
415
- ref.requestBody = {
416
- required: schema.required?.includes("body"),
417
- content: toOpenAPIContent(schema.properties.body)
418
- };
419
- }
420
- }
421
- #successResponse(ref, def) {
422
- const outputSchema = def.outputSchema;
423
- const status = fallbackContractConfig("defaultSuccessStatus", def.route.successStatus);
424
- const description = fallbackContractConfig("defaultSuccessDescription", def.route?.successDescription);
425
- const eventIteratorSchemaDetails = getEventIteratorSchemaDetails(outputSchema);
426
- const outputStructure = fallbackContractConfig("defaultOutputStructure", def.route.outputStructure);
427
- if (eventIteratorSchemaDetails) {
428
- ref.responses ??= {};
429
- ref.responses[status] = {
430
- description,
431
- content: toOpenAPIEventIteratorContent(
432
- this.converter.convert(eventIteratorSchemaDetails.yields, { strategy: "output" }),
433
- this.converter.convert(eventIteratorSchemaDetails.returns, { strategy: "output" })
434
- )
435
- };
436
- return;
437
- }
438
- const [_, json] = this.converter.convert(outputSchema, { strategy: "output" });
439
- ref.responses ??= {};
440
- ref.responses[status] = {
441
- description
442
- };
443
- if (outputStructure === "compact") {
444
- ref.responses[status].content = toOpenAPIContent(json);
445
- return;
446
- }
447
- const error = new OpenAPIGeneratorError(
448
- 'When output structure is "detailed", output schema must satisfy: { headers?: Record<string, unknown>, body?: unknown }'
449
- );
450
- if (!isObjectSchema(json)) {
451
- throw error;
452
- }
453
- if (json.properties?.headers !== void 0) {
454
- if (!isObjectSchema(json.properties.headers)) {
455
- throw error;
456
- }
457
- for (const key in json.properties.headers.properties) {
458
- ref.responses[status].headers ??= {};
459
- ref.responses[status].headers[key] = {
460
- schema: toOpenAPISchema(json.properties.headers.properties[key]),
461
- required: json.properties.headers.required?.includes(key)
462
- };
463
- }
464
- }
465
- if (json.properties?.body !== void 0) {
466
- ref.responses[status].content = toOpenAPIContent(json.properties.body);
467
- }
468
- }
469
- #errorResponse(ref, def) {
470
- const errorMap = def.errorMap;
471
- const errors = {};
472
- for (const code in errorMap) {
473
- const config = errorMap[code];
474
- if (!config) {
475
- continue;
22
+ } catch (e) {
23
+ if (e instanceof ORPCError) {
24
+ throw createORPCErrorFromJson(serializer.deserialize(
25
+ serializer.serialize(
26
+ e.toJSON(),
27
+ { outputFormat: "plain" }
28
+ )
29
+ ));
476
30
  }
477
- const status = fallbackORPCErrorStatus(code, config.status);
478
- const message = fallbackORPCErrorMessage(code, config.message);
479
- const [dataRequired, dataSchema] = this.converter.convert(config.data, { strategy: "output" });
480
- errors[status] ??= [];
481
- errors[status].push({
482
- type: "object",
483
- properties: {
484
- defined: { const: true },
485
- code: { const: code },
486
- status: { const: status },
487
- message: { type: "string", default: message },
488
- data: dataSchema
489
- },
490
- required: dataRequired ? ["defined", "code", "status", "message", "data"] : ["defined", "code", "status", "message"]
491
- });
31
+ throw e;
492
32
  }
493
- ref.responses ??= {};
494
- for (const status in errors) {
495
- const schemas = errors[status];
496
- ref.responses[status] = {
497
- description: status,
498
- content: toOpenAPIContent({
499
- oneOf: [
500
- ...schemas,
501
- {
502
- type: "object",
503
- properties: {
504
- defined: { const: false },
505
- code: { type: "string" },
506
- status: { type: "number" },
507
- message: { type: "string" },
508
- data: {}
509
- },
510
- required: ["defined", "code", "status", "message"]
511
- }
512
- ]
513
- })
514
- };
515
- }
516
- }
33
+ });
34
+ return createRouterClient(router, options);
517
35
  }
518
36
 
519
37
  const oo = {
520
38
  spec: customOpenAPIOperation
521
39
  };
522
40
 
523
- export { CompositeSchemaConverter, LOGIC_KEYWORDS, OpenAPIGenerator, applyCustomOpenAPIOperation, checkParamsSchema, customOpenAPIOperation, filterSchemaBranches, getCustomOpenAPIOperation, isAnySchema, isFileSchema, isObjectSchema, oo, separateObjectSchema, toOpenAPIContent, toOpenAPIEventIteratorContent, toOpenAPIMethod, toOpenAPIParameters, toOpenAPIPath, toOpenAPISchema };
41
+ export { createJsonifiedRouterClient, customOpenAPIOperation, oo };