@orpc/openapi 0.0.0-next.e361acd → 0.0.0-next.e563486

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 (36) hide show
  1. package/README.md +95 -0
  2. package/dist/adapters/fetch/index.d.mts +15 -0
  3. package/dist/adapters/fetch/index.d.ts +15 -0
  4. package/dist/adapters/fetch/index.mjs +11 -0
  5. package/dist/adapters/hono/index.d.mts +8 -0
  6. package/dist/adapters/hono/index.d.ts +8 -0
  7. package/dist/adapters/hono/index.mjs +11 -0
  8. package/dist/adapters/next/index.d.mts +8 -0
  9. package/dist/adapters/next/index.d.ts +8 -0
  10. package/dist/adapters/next/index.mjs +11 -0
  11. package/dist/adapters/node/index.d.mts +15 -0
  12. package/dist/adapters/node/index.d.ts +15 -0
  13. package/dist/adapters/node/index.mjs +35 -0
  14. package/dist/adapters/standard/index.d.mts +35 -0
  15. package/dist/adapters/standard/index.d.ts +35 -0
  16. package/dist/adapters/standard/index.mjs +7 -0
  17. package/dist/index.d.mts +120 -0
  18. package/dist/index.d.ts +120 -0
  19. package/dist/index.mjs +303 -0
  20. package/dist/shared/openapi.BNHmrMe2.mjs +145 -0
  21. package/dist/shared/openapi.DZzpQAb-.mjs +231 -0
  22. package/dist/shared/openapi.Dv-KT_Bx.mjs +33 -0
  23. package/dist/shared/openapi.IfmmOyba.d.mts +8 -0
  24. package/dist/shared/openapi.IfmmOyba.d.ts +8 -0
  25. package/package.json +38 -23
  26. package/dist/chunk-CMRY2Z4J.js +0 -54
  27. package/dist/fetch.js +0 -697
  28. package/dist/index.js +0 -4585
  29. package/dist/src/fetch/base-handler.d.ts +0 -13
  30. package/dist/src/fetch/index.d.ts +0 -4
  31. package/dist/src/fetch/server-handler.d.ts +0 -3
  32. package/dist/src/fetch/serverless-handler.d.ts +0 -3
  33. package/dist/src/generator.d.ts +0 -24
  34. package/dist/src/index.d.ts +0 -3
  35. package/dist/src/utils.d.ts +0 -17
  36. package/dist/src/zod-to-json-schema.d.ts +0 -43
package/dist/index.mjs ADDED
@@ -0,0 +1,303 @@
1
+ import { isProcedure, resolveContractProcedures, toHttpPath } from '@orpc/server';
2
+ import { fallbackORPCErrorStatus, fallbackORPCErrorMessage } from '@orpc/client';
3
+ import { fallbackContractConfig, getEventIteratorSchemaDetails } from '@orpc/contract';
4
+ import { StandardOpenAPIJsonSerializer } from '@orpc/openapi-client/standard';
5
+ import { clone } from '@orpc/shared';
6
+ import { t as toOpenAPIMethod, a as toOpenAPIPath, b as toOpenAPIEventIteratorContent, g as getDynamicParams, i as isAnySchema, c as isObjectSchema, d as separateObjectSchema, e as checkParamsSchema, f as toOpenAPIParameters, h as toOpenAPIContent, j as toOpenAPISchema } from './shared/openapi.DZzpQAb-.mjs';
7
+ export { L as LOGIC_KEYWORDS, l as filterSchemaBranches, k as isFileSchema, s as standardizeHTTPPath } from './shared/openapi.DZzpQAb-.mjs';
8
+ export { Format as JSONSchemaFormat } from 'json-schema-typed/draft-2020-12';
9
+
10
+ const OPERATION_EXTENDER_SYMBOL = Symbol("ORPC_OPERATION_EXTENDER");
11
+ function customOpenAPIOperation(o, extend) {
12
+ return new Proxy(o, {
13
+ get(target, prop, receiver) {
14
+ if (prop === OPERATION_EXTENDER_SYMBOL) {
15
+ return extend;
16
+ }
17
+ return Reflect.get(target, prop, receiver);
18
+ }
19
+ });
20
+ }
21
+ function getCustomOpenAPIOperation(o) {
22
+ return o[OPERATION_EXTENDER_SYMBOL];
23
+ }
24
+ function applyCustomOpenAPIOperation(operation, contract) {
25
+ const operationCustoms = [];
26
+ for (const errorItem of Object.values(contract["~orpc"].errorMap)) {
27
+ const maybeExtender = errorItem ? getCustomOpenAPIOperation(errorItem) : void 0;
28
+ if (maybeExtender) {
29
+ operationCustoms.push(maybeExtender);
30
+ }
31
+ }
32
+ if (isProcedure(contract)) {
33
+ for (const middleware of contract["~orpc"].middlewares) {
34
+ const maybeExtender = getCustomOpenAPIOperation(middleware);
35
+ if (maybeExtender) {
36
+ operationCustoms.push(maybeExtender);
37
+ }
38
+ }
39
+ }
40
+ let currentOperation = operation;
41
+ for (const custom of operationCustoms) {
42
+ if (typeof custom === "function") {
43
+ currentOperation = custom(currentOperation, contract);
44
+ } else {
45
+ currentOperation = {
46
+ ...currentOperation,
47
+ ...custom
48
+ };
49
+ }
50
+ }
51
+ return currentOperation;
52
+ }
53
+
54
+ class CompositeSchemaConverter {
55
+ converters;
56
+ constructor(converters) {
57
+ this.converters = converters;
58
+ }
59
+ convert(schema, options) {
60
+ for (const converter of this.converters) {
61
+ if (converter.condition(schema, options)) {
62
+ return converter.convert(schema, options);
63
+ }
64
+ }
65
+ return [false, {}];
66
+ }
67
+ }
68
+
69
+ class OpenAPIGeneratorError extends Error {
70
+ }
71
+ class OpenAPIGenerator {
72
+ serializer;
73
+ converter;
74
+ constructor(options = {}) {
75
+ this.serializer = new StandardOpenAPIJsonSerializer(options);
76
+ this.converter = new CompositeSchemaConverter(options.schemaConverters ?? []);
77
+ }
78
+ async generate(router, base) {
79
+ const doc = clone(base);
80
+ doc.openapi = "3.1.1";
81
+ const errors = [];
82
+ await resolveContractProcedures({ path: [], router }, ({ contract, path }) => {
83
+ const operationId = path.join(".");
84
+ try {
85
+ const def = contract["~orpc"];
86
+ const method = toOpenAPIMethod(fallbackContractConfig("defaultMethod", def.route.method));
87
+ const httpPath = toOpenAPIPath(def.route.path ?? toHttpPath(path));
88
+ const operationObjectRef = {
89
+ operationId,
90
+ summary: def.route.summary,
91
+ description: def.route.description,
92
+ deprecated: def.route.deprecated,
93
+ tags: def.route.tags?.map((tag) => tag)
94
+ };
95
+ this.#request(operationObjectRef, def);
96
+ this.#successResponse(operationObjectRef, def);
97
+ this.#errorResponse(operationObjectRef, def);
98
+ doc.paths ??= {};
99
+ doc.paths[httpPath] ??= {};
100
+ doc.paths[httpPath][method] = applyCustomOpenAPIOperation(operationObjectRef, contract);
101
+ } catch (e) {
102
+ if (!(e instanceof OpenAPIGeneratorError)) {
103
+ throw e;
104
+ }
105
+ errors.push(
106
+ `[OpenAPIGenerator] Error occurred while generating OpenAPI for procedure at path: ${operationId}
107
+ ${e.message}`
108
+ );
109
+ }
110
+ });
111
+ if (errors.length) {
112
+ throw new OpenAPIGeneratorError(
113
+ `Some error occurred during OpenAPI generation:
114
+
115
+ ${errors.join("\n\n")}`
116
+ );
117
+ }
118
+ return this.serializer.serialize(doc)[0];
119
+ }
120
+ #request(ref, def) {
121
+ const method = fallbackContractConfig("defaultMethod", def.route.method);
122
+ const details = getEventIteratorSchemaDetails(def.inputSchema);
123
+ if (details) {
124
+ ref.requestBody = {
125
+ required: true,
126
+ content: toOpenAPIEventIteratorContent(
127
+ this.converter.convert(details.yields, { strategy: "input" }),
128
+ this.converter.convert(details.returns, { strategy: "input" })
129
+ )
130
+ };
131
+ return;
132
+ }
133
+ const dynamicParams = getDynamicParams(def.route.path);
134
+ const inputStructure = fallbackContractConfig("defaultInputStructure", def.route.inputStructure);
135
+ let [required, schema] = this.converter.convert(def.inputSchema, { strategy: "input" });
136
+ if (isAnySchema(schema) && !dynamicParams?.length) {
137
+ return;
138
+ }
139
+ if (inputStructure === "compact") {
140
+ if (dynamicParams?.length) {
141
+ const error2 = new OpenAPIGeneratorError(
142
+ 'When input structure is "compact", and path has dynamic params, input schema must be an object with all dynamic params as required.'
143
+ );
144
+ if (!isObjectSchema(schema)) {
145
+ throw error2;
146
+ }
147
+ const [paramsSchema, rest] = separateObjectSchema(schema, dynamicParams);
148
+ schema = rest;
149
+ required = rest.required ? rest.required.length !== 0 : false;
150
+ if (!checkParamsSchema(paramsSchema, dynamicParams)) {
151
+ throw error2;
152
+ }
153
+ ref.parameters ??= [];
154
+ ref.parameters.push(...toOpenAPIParameters(paramsSchema, "path"));
155
+ }
156
+ if (method === "GET") {
157
+ if (!isObjectSchema(schema)) {
158
+ throw new OpenAPIGeneratorError(
159
+ 'When method is "GET", input schema must satisfy: object | any | unknown'
160
+ );
161
+ }
162
+ ref.parameters ??= [];
163
+ ref.parameters.push(...toOpenAPIParameters(schema, "query"));
164
+ } else {
165
+ ref.requestBody = {
166
+ required,
167
+ content: toOpenAPIContent(schema)
168
+ };
169
+ }
170
+ return;
171
+ }
172
+ const error = new OpenAPIGeneratorError(
173
+ 'When input structure is "detailed", input schema must satisfy: { params?: Record<string, unknown>, query?: Record<string, unknown>, headers?: Record<string, unknown>, body?: unknown }'
174
+ );
175
+ if (!isObjectSchema(schema)) {
176
+ throw error;
177
+ }
178
+ if (dynamicParams?.length && (schema.properties?.params === void 0 || !isObjectSchema(schema.properties.params) || !checkParamsSchema(schema.properties.params, dynamicParams))) {
179
+ throw new OpenAPIGeneratorError(
180
+ 'When input structure is "detailed" and path has dynamic params, the "params" schema must be an object with all dynamic params as required.'
181
+ );
182
+ }
183
+ for (const from of ["params", "query", "headers"]) {
184
+ const fromSchema = schema.properties?.[from];
185
+ if (fromSchema !== void 0) {
186
+ if (!isObjectSchema(fromSchema)) {
187
+ throw error;
188
+ }
189
+ const parameterIn = from === "params" ? "path" : from === "headers" ? "header" : "query";
190
+ ref.parameters ??= [];
191
+ ref.parameters.push(...toOpenAPIParameters(fromSchema, parameterIn));
192
+ }
193
+ }
194
+ if (schema.properties?.body !== void 0) {
195
+ ref.requestBody = {
196
+ required: schema.required?.includes("body"),
197
+ content: toOpenAPIContent(schema.properties.body)
198
+ };
199
+ }
200
+ }
201
+ #successResponse(ref, def) {
202
+ const outputSchema = def.outputSchema;
203
+ const status = fallbackContractConfig("defaultSuccessStatus", def.route.successStatus);
204
+ const description = fallbackContractConfig("defaultSuccessDescription", def.route?.successDescription);
205
+ const eventIteratorSchemaDetails = getEventIteratorSchemaDetails(outputSchema);
206
+ const outputStructure = fallbackContractConfig("defaultOutputStructure", def.route.outputStructure);
207
+ if (eventIteratorSchemaDetails) {
208
+ ref.responses ??= {};
209
+ ref.responses[status] = {
210
+ description,
211
+ content: toOpenAPIEventIteratorContent(
212
+ this.converter.convert(eventIteratorSchemaDetails.yields, { strategy: "output" }),
213
+ this.converter.convert(eventIteratorSchemaDetails.returns, { strategy: "output" })
214
+ )
215
+ };
216
+ return;
217
+ }
218
+ const [_, json] = this.converter.convert(outputSchema, { strategy: "output" });
219
+ ref.responses ??= {};
220
+ ref.responses[status] = {
221
+ description
222
+ };
223
+ if (outputStructure === "compact") {
224
+ ref.responses[status].content = toOpenAPIContent(json);
225
+ return;
226
+ }
227
+ const error = new OpenAPIGeneratorError(
228
+ 'When output structure is "detailed", output schema must satisfy: { headers?: Record<string, unknown>, body?: unknown }'
229
+ );
230
+ if (!isObjectSchema(json)) {
231
+ throw error;
232
+ }
233
+ if (json.properties?.headers !== void 0) {
234
+ if (!isObjectSchema(json.properties.headers)) {
235
+ throw error;
236
+ }
237
+ for (const key in json.properties.headers.properties) {
238
+ ref.responses[status].headers ??= {};
239
+ ref.responses[status].headers[key] = {
240
+ schema: toOpenAPISchema(json.properties.headers.properties[key]),
241
+ required: json.properties.headers.required?.includes(key)
242
+ };
243
+ }
244
+ }
245
+ if (json.properties?.body !== void 0) {
246
+ ref.responses[status].content = toOpenAPIContent(json.properties.body);
247
+ }
248
+ }
249
+ #errorResponse(ref, def) {
250
+ const errorMap = def.errorMap;
251
+ const errors = {};
252
+ for (const code in errorMap) {
253
+ const config = errorMap[code];
254
+ if (!config) {
255
+ continue;
256
+ }
257
+ const status = fallbackORPCErrorStatus(code, config.status);
258
+ const message = fallbackORPCErrorMessage(code, config.message);
259
+ const [dataRequired, dataSchema] = this.converter.convert(config.data, { strategy: "output" });
260
+ errors[status] ??= [];
261
+ errors[status].push({
262
+ type: "object",
263
+ properties: {
264
+ defined: { const: true },
265
+ code: { const: code },
266
+ status: { const: status },
267
+ message: { type: "string", default: message },
268
+ data: dataSchema
269
+ },
270
+ required: dataRequired ? ["defined", "code", "status", "message", "data"] : ["defined", "code", "status", "message"]
271
+ });
272
+ }
273
+ ref.responses ??= {};
274
+ for (const status in errors) {
275
+ const schemas = errors[status];
276
+ ref.responses[status] = {
277
+ description: status,
278
+ content: toOpenAPIContent({
279
+ oneOf: [
280
+ ...schemas,
281
+ {
282
+ type: "object",
283
+ properties: {
284
+ defined: { const: false },
285
+ code: { type: "string" },
286
+ status: { type: "number" },
287
+ message: { type: "string" },
288
+ data: {}
289
+ },
290
+ required: ["defined", "code", "status", "message"]
291
+ }
292
+ ]
293
+ })
294
+ };
295
+ }
296
+ }
297
+ }
298
+
299
+ const oo = {
300
+ spec: customOpenAPIOperation
301
+ };
302
+
303
+ export { CompositeSchemaConverter, OpenAPIGenerator, applyCustomOpenAPIOperation, checkParamsSchema, customOpenAPIOperation, getCustomOpenAPIOperation, getDynamicParams, isAnySchema, isObjectSchema, oo, separateObjectSchema, toOpenAPIContent, toOpenAPIEventIteratorContent, toOpenAPIMethod, toOpenAPIParameters, toOpenAPIPath, toOpenAPISchema };
@@ -0,0 +1,145 @@
1
+ import { fallbackContractConfig } from '@orpc/contract';
2
+ import { isObject } from '@orpc/shared';
3
+ import { traverseContractProcedures, toHttpPath, isProcedure, getLazyMeta, unlazy, getRouter, createContractedProcedure } from '@orpc/server';
4
+ import { createRouter, addRoute, findRoute } from 'rou3';
5
+ import { s as standardizeHTTPPath } from './openapi.DZzpQAb-.mjs';
6
+
7
+ class StandardOpenAPICodec {
8
+ constructor(serializer) {
9
+ this.serializer = serializer;
10
+ }
11
+ async decode(request, params, procedure) {
12
+ const inputStructure = fallbackContractConfig("defaultInputStructure", procedure["~orpc"].route.inputStructure);
13
+ if (inputStructure === "compact") {
14
+ const data = request.method === "GET" ? this.serializer.deserialize(request.url.searchParams) : this.serializer.deserialize(await request.body());
15
+ if (data === void 0) {
16
+ return params;
17
+ }
18
+ if (isObject(data)) {
19
+ return {
20
+ ...params,
21
+ ...data
22
+ };
23
+ }
24
+ return data;
25
+ }
26
+ const deserializeSearchParams = () => {
27
+ return this.serializer.deserialize(request.url.searchParams);
28
+ };
29
+ return {
30
+ params,
31
+ get query() {
32
+ const value = deserializeSearchParams();
33
+ Object.defineProperty(this, "query", { value, writable: true });
34
+ return value;
35
+ },
36
+ set query(value) {
37
+ Object.defineProperty(this, "query", { value, writable: true });
38
+ },
39
+ headers: request.headers,
40
+ body: this.serializer.deserialize(await request.body())
41
+ };
42
+ }
43
+ encode(output, procedure) {
44
+ const successStatus = fallbackContractConfig("defaultSuccessStatus", procedure["~orpc"].route.successStatus);
45
+ const outputStructure = fallbackContractConfig("defaultOutputStructure", procedure["~orpc"].route.outputStructure);
46
+ if (outputStructure === "compact") {
47
+ return {
48
+ status: successStatus,
49
+ headers: {},
50
+ body: this.serializer.serialize(output)
51
+ };
52
+ }
53
+ if (!isObject(output)) {
54
+ throw new Error(
55
+ 'Invalid output structure for "detailed" output. Expected format: { body: any, headers?: Record<string, string | string[] | undefined> }'
56
+ );
57
+ }
58
+ return {
59
+ status: successStatus,
60
+ headers: output.headers ?? {},
61
+ body: this.serializer.serialize(output.body)
62
+ };
63
+ }
64
+ encodeError(error) {
65
+ return {
66
+ status: error.status,
67
+ headers: {},
68
+ body: this.serializer.serialize(error.toJSON())
69
+ };
70
+ }
71
+ }
72
+
73
+ function toRou3Pattern(path) {
74
+ return standardizeHTTPPath(path).replace(/\/\{\+([^}]+)\}/g, "/**:$1").replace(/\/\{([^}]+)\}/g, "/:$1");
75
+ }
76
+ function decodeParams(params) {
77
+ return Object.fromEntries(Object.entries(params).map(([key, value]) => [key, decodeURIComponent(value)]));
78
+ }
79
+
80
+ class StandardOpenAPIMatcher {
81
+ tree = createRouter();
82
+ pendingRouters = [];
83
+ init(router, path = []) {
84
+ const laziedOptions = traverseContractProcedures({ router, path }, ({ path: path2, contract }) => {
85
+ const method = fallbackContractConfig("defaultMethod", contract["~orpc"].route.method);
86
+ const httpPath = toRou3Pattern(contract["~orpc"].route.path ?? toHttpPath(path2));
87
+ if (isProcedure(contract)) {
88
+ addRoute(this.tree, method, httpPath, {
89
+ path: path2,
90
+ contract,
91
+ procedure: contract,
92
+ // this mean dev not used contract-first so we can used contract as procedure directly
93
+ router
94
+ });
95
+ } else {
96
+ addRoute(this.tree, method, httpPath, {
97
+ path: path2,
98
+ contract,
99
+ procedure: void 0,
100
+ router
101
+ });
102
+ }
103
+ });
104
+ this.pendingRouters.push(...laziedOptions.map((option) => ({
105
+ ...option,
106
+ httpPathPrefix: toHttpPath(option.path),
107
+ laziedPrefix: getLazyMeta(option.router).prefix
108
+ })));
109
+ }
110
+ async match(method, pathname) {
111
+ if (this.pendingRouters.length) {
112
+ const newPendingRouters = [];
113
+ for (const pendingRouter of this.pendingRouters) {
114
+ if (!pendingRouter.laziedPrefix || pathname.startsWith(pendingRouter.laziedPrefix) || pathname.startsWith(pendingRouter.httpPathPrefix)) {
115
+ const { default: router } = await unlazy(pendingRouter.router);
116
+ this.init(router, pendingRouter.path);
117
+ } else {
118
+ newPendingRouters.push(pendingRouter);
119
+ }
120
+ }
121
+ this.pendingRouters = newPendingRouters;
122
+ }
123
+ const match = findRoute(this.tree, method, pathname);
124
+ if (!match) {
125
+ return void 0;
126
+ }
127
+ if (!match.data.procedure) {
128
+ const { default: maybeProcedure } = await unlazy(getRouter(match.data.router, match.data.path));
129
+ if (!isProcedure(maybeProcedure)) {
130
+ throw new Error(`
131
+ [Contract-First] Missing or invalid implementation for procedure at path: ${toHttpPath(match.data.path)}.
132
+ Ensure that the procedure is correctly defined and matches the expected contract.
133
+ `);
134
+ }
135
+ match.data.procedure = createContractedProcedure(maybeProcedure, match.data.contract);
136
+ }
137
+ return {
138
+ path: match.data.path,
139
+ procedure: match.data.procedure,
140
+ params: match.params ? decodeParams(match.params) : void 0
141
+ };
142
+ }
143
+ }
144
+
145
+ export { StandardOpenAPICodec as S, StandardOpenAPIMatcher as a, decodeParams as d, toRou3Pattern as t };
@@ -0,0 +1,231 @@
1
+ import { isObject, findDeepMatches } from '@orpc/shared';
2
+ import 'json-schema-typed/draft-2020-12';
3
+
4
+ const LOGIC_KEYWORDS = [
5
+ "$dynamicRef",
6
+ "$ref",
7
+ "additionalItems",
8
+ "additionalProperties",
9
+ "allOf",
10
+ "anyOf",
11
+ "const",
12
+ "contains",
13
+ "contentEncoding",
14
+ "contentMediaType",
15
+ "contentSchema",
16
+ "dependencies",
17
+ "dependentRequired",
18
+ "dependentSchemas",
19
+ "else",
20
+ "enum",
21
+ "exclusiveMaximum",
22
+ "exclusiveMinimum",
23
+ "format",
24
+ "if",
25
+ "items",
26
+ "maxContains",
27
+ "maximum",
28
+ "maxItems",
29
+ "maxLength",
30
+ "maxProperties",
31
+ "minContains",
32
+ "minimum",
33
+ "minItems",
34
+ "minLength",
35
+ "minProperties",
36
+ "multipleOf",
37
+ "not",
38
+ "oneOf",
39
+ "pattern",
40
+ "patternProperties",
41
+ "prefixItems",
42
+ "properties",
43
+ "propertyNames",
44
+ "required",
45
+ "then",
46
+ "type",
47
+ "unevaluatedItems",
48
+ "unevaluatedProperties",
49
+ "uniqueItems"
50
+ ];
51
+
52
+ function isFileSchema(schema) {
53
+ return isObject(schema) && schema.type === "string" && typeof schema.contentMediaType === "string";
54
+ }
55
+ function isObjectSchema(schema) {
56
+ return isObject(schema) && schema.type === "object";
57
+ }
58
+ function isAnySchema(schema) {
59
+ if (schema === true) {
60
+ return true;
61
+ }
62
+ if (Object.keys(schema).every((k) => !LOGIC_KEYWORDS.includes(k))) {
63
+ return true;
64
+ }
65
+ return false;
66
+ }
67
+ function separateObjectSchema(schema, separatedProperties) {
68
+ if (Object.keys(schema).some((k) => k !== "type" && k !== "properties" && k !== "required" && LOGIC_KEYWORDS.includes(k))) {
69
+ return [{ type: "object" }, schema];
70
+ }
71
+ const matched = { ...schema };
72
+ const rest = { ...schema };
73
+ matched.properties = schema.properties && Object.entries(schema.properties).filter(([key]) => separatedProperties.includes(key)).reduce((acc, [key, value]) => {
74
+ acc[key] = value;
75
+ return acc;
76
+ }, {});
77
+ matched.required = schema.required?.filter((key) => separatedProperties.includes(key));
78
+ matched.examples = schema.examples?.map((example) => {
79
+ if (!isObject(example)) {
80
+ return example;
81
+ }
82
+ return Object.entries(example).reduce((acc, [key, value]) => {
83
+ if (separatedProperties.includes(key)) {
84
+ acc[key] = value;
85
+ }
86
+ return acc;
87
+ }, {});
88
+ });
89
+ rest.properties = schema.properties && Object.entries(schema.properties).filter(([key]) => !separatedProperties.includes(key)).reduce((acc, [key, value]) => {
90
+ acc[key] = value;
91
+ return acc;
92
+ }, {});
93
+ rest.required = schema.required?.filter((key) => !separatedProperties.includes(key));
94
+ rest.examples = schema.examples?.map((example) => {
95
+ if (!isObject(example)) {
96
+ return example;
97
+ }
98
+ return Object.entries(example).reduce((acc, [key, value]) => {
99
+ if (!separatedProperties.includes(key)) {
100
+ acc[key] = value;
101
+ }
102
+ return acc;
103
+ }, {});
104
+ });
105
+ return [matched, rest];
106
+ }
107
+ function filterSchemaBranches(schema, check, matches = []) {
108
+ if (check(schema)) {
109
+ matches.push(schema);
110
+ return [matches, void 0];
111
+ }
112
+ if (isObject(schema)) {
113
+ for (const keyword of ["anyOf", "oneOf"]) {
114
+ if (schema[keyword] && Object.keys(schema).every(
115
+ (k) => k === keyword || !LOGIC_KEYWORDS.includes(k)
116
+ )) {
117
+ const rest = schema[keyword].map((s) => filterSchemaBranches(s, check, matches)[1]).filter((v) => !!v);
118
+ if (rest.length === 1 && typeof rest[0] === "object") {
119
+ return [matches, { ...schema, [keyword]: void 0, ...rest[0] }];
120
+ }
121
+ return [matches, { ...schema, [keyword]: rest }];
122
+ }
123
+ }
124
+ }
125
+ return [matches, schema];
126
+ }
127
+
128
+ function standardizeHTTPPath(path) {
129
+ return `/${path.replace(/\/{2,}/g, "/").replace(/^\/|\/$/g, "")}`;
130
+ }
131
+ function toOpenAPIPath(path) {
132
+ return standardizeHTTPPath(path).replace(/\/\{\+([^}]+)\}/g, "/{$1}");
133
+ }
134
+ function toOpenAPIMethod(method) {
135
+ return method.toLocaleLowerCase();
136
+ }
137
+ function getDynamicParams(path) {
138
+ return path ? standardizeHTTPPath(path).match(/\/\{([^}]+)\}/g)?.map((v) => v.match(/\{\+?([^}]+)\}/)[1]) : void 0;
139
+ }
140
+ function toOpenAPIContent(schema) {
141
+ const content = {};
142
+ const [matches, restSchema] = filterSchemaBranches(schema, isFileSchema);
143
+ for (const file of matches) {
144
+ content[file.contentMediaType] = {
145
+ schema: toOpenAPISchema(file)
146
+ };
147
+ }
148
+ if (restSchema !== void 0) {
149
+ content["application/json"] = {
150
+ schema: toOpenAPISchema(restSchema)
151
+ };
152
+ const isStillHasFileSchema = findDeepMatches((v) => isObject(v) && isFileSchema(v), restSchema).values.length > 0;
153
+ if (isStillHasFileSchema) {
154
+ content["multipart/form-data"] = {
155
+ schema: toOpenAPISchema(restSchema)
156
+ };
157
+ }
158
+ }
159
+ return content;
160
+ }
161
+ function toOpenAPIEventIteratorContent([yieldsRequired, yieldsSchema], [returnsRequired, returnsSchema]) {
162
+ return {
163
+ "text/event-stream": {
164
+ schema: toOpenAPISchema({
165
+ oneOf: [
166
+ {
167
+ type: "object",
168
+ properties: {
169
+ event: { const: "message" },
170
+ data: yieldsSchema,
171
+ id: { type: "string" },
172
+ retry: { type: "number" }
173
+ },
174
+ required: yieldsRequired ? ["event", "data"] : ["event"]
175
+ },
176
+ {
177
+ type: "object",
178
+ properties: {
179
+ event: { const: "done" },
180
+ data: returnsSchema,
181
+ id: { type: "string" },
182
+ retry: { type: "number" }
183
+ },
184
+ required: returnsRequired ? ["event", "data"] : ["event"]
185
+ },
186
+ {
187
+ type: "object",
188
+ properties: {
189
+ event: { const: "error" },
190
+ data: {},
191
+ id: { type: "string" },
192
+ retry: { type: "number" }
193
+ },
194
+ required: ["event"]
195
+ }
196
+ ]
197
+ })
198
+ }
199
+ };
200
+ }
201
+ function toOpenAPIParameters(schema, parameterIn) {
202
+ const parameters = [];
203
+ for (const key in schema.properties) {
204
+ const keySchema = schema.properties[key];
205
+ parameters.push({
206
+ name: key,
207
+ in: parameterIn,
208
+ required: schema.required?.includes(key),
209
+ style: parameterIn === "query" ? "deepObject" : void 0,
210
+ explode: parameterIn === "query" ? true : void 0,
211
+ schema: toOpenAPISchema(keySchema)
212
+ });
213
+ }
214
+ return parameters;
215
+ }
216
+ function checkParamsSchema(schema, params) {
217
+ const properties = Object.keys(schema.properties ?? {});
218
+ const required = schema.required ?? [];
219
+ if (properties.length !== params.length || properties.some((v) => !params.includes(v))) {
220
+ return false;
221
+ }
222
+ if (required.length !== params.length || required.some((v) => !params.includes(v))) {
223
+ return false;
224
+ }
225
+ return true;
226
+ }
227
+ function toOpenAPISchema(schema) {
228
+ return schema === true ? {} : schema === false ? { not: {} } : schema;
229
+ }
230
+
231
+ export { LOGIC_KEYWORDS as L, toOpenAPIPath as a, toOpenAPIEventIteratorContent as b, isObjectSchema as c, separateObjectSchema as d, checkParamsSchema as e, toOpenAPIParameters as f, getDynamicParams as g, toOpenAPIContent as h, isAnySchema as i, toOpenAPISchema as j, isFileSchema as k, filterSchemaBranches as l, standardizeHTTPPath as s, toOpenAPIMethod as t };