@temporary-name/server 1.9.3-alpha.4275e976ddda4d8be107c2cfde9899bdea9a337d → 1.9.3-alpha.4c6c68e5af7355d5a6dff1179055586e1093ac2d

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 (41) hide show
  1. package/dist/adapters/aws-lambda/index.d.mts +12 -8
  2. package/dist/adapters/aws-lambda/index.d.ts +12 -8
  3. package/dist/adapters/aws-lambda/index.mjs +12 -4
  4. package/dist/adapters/fetch/index.d.mts +15 -87
  5. package/dist/adapters/fetch/index.d.ts +15 -87
  6. package/dist/adapters/fetch/index.mjs +23 -161
  7. package/dist/adapters/node/index.d.mts +15 -64
  8. package/dist/adapters/node/index.d.ts +15 -64
  9. package/dist/adapters/node/index.mjs +21 -126
  10. package/dist/adapters/standard/index.d.mts +27 -14
  11. package/dist/adapters/standard/index.d.ts +27 -14
  12. package/dist/adapters/standard/index.mjs +9 -101
  13. package/dist/helpers/index.mjs +3 -29
  14. package/dist/index.d.mts +120 -583
  15. package/dist/index.d.ts +120 -583
  16. package/dist/index.mjs +213 -449
  17. package/dist/openapi/index.d.mts +204 -0
  18. package/dist/openapi/index.d.ts +204 -0
  19. package/dist/openapi/index.mjs +692 -0
  20. package/dist/shared/server.BbUmcWIW.d.mts +41 -0
  21. package/dist/shared/server.BfraJHay.d.mts +373 -0
  22. package/dist/shared/server.BfraJHay.d.ts +373 -0
  23. package/dist/shared/server.C1RJffw4.mjs +30 -0
  24. package/dist/shared/server.CHugaZ_Y.d.ts +41 -0
  25. package/dist/shared/server.CQIFwyhc.mjs +40 -0
  26. package/dist/shared/server.CYa9puL2.mjs +403 -0
  27. package/dist/shared/server.ChOv1yG3.mjs +319 -0
  28. package/dist/shared/server.Cza0RB3u.mjs +160 -0
  29. package/dist/shared/server.YUvuxHty.mjs +48 -0
  30. package/package.json +18 -30
  31. package/dist/plugins/index.d.mts +0 -160
  32. package/dist/plugins/index.d.ts +0 -160
  33. package/dist/plugins/index.mjs +0 -288
  34. package/dist/shared/server.BEQrAa3A.mjs +0 -207
  35. package/dist/shared/server.Bo94xDTv.d.mts +0 -73
  36. package/dist/shared/server.Btxrgkj5.d.ts +0 -73
  37. package/dist/shared/server.C1YnHvvf.d.mts +0 -192
  38. package/dist/shared/server.C1YnHvvf.d.ts +0 -192
  39. package/dist/shared/server.D6K9uoPI.mjs +0 -35
  40. package/dist/shared/server.DZ5BIITo.mjs +0 -9
  41. package/dist/shared/server.X0YaZxSJ.mjs +0 -13
@@ -0,0 +1,692 @@
1
+ import { isObject, stringifyJSON, findDeepMatches, toArray, clone, value, fallbackContractConfig, toHttpPath, isORPCErrorStatus } from '@temporary-name/shared';
2
+ import { j as jsonSerialize } from '../shared/server.CQIFwyhc.mjs';
3
+ import '@temporary-name/standard-server';
4
+ import { g as getEventIteratorSchemaDetails } from '../shared/server.YUvuxHty.mjs';
5
+ import { s as standardizeHTTPPath, r as resolveContractProcedures, g as getDynamicParams } from '../shared/server.ChOv1yG3.mjs';
6
+ import { TypeName } from '@temporary-name/interop/json-schema-typed/draft-2020-12';
7
+ export { ContentEncoding as JSONSchemaContentEncoding, Format as JSONSchemaFormat, TypeName as JSONSchemaTypeName } from '@temporary-name/interop/json-schema-typed/draft-2020-12';
8
+ import '@temporary-name/zod';
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 middleware of contract["~orpc"].middlewares) {
27
+ const maybeExtender = getCustomOpenAPIOperation(middleware);
28
+ if (maybeExtender) {
29
+ operationCustoms.push(maybeExtender);
30
+ }
31
+ }
32
+ let currentOperation = operation;
33
+ for (const custom of operationCustoms) {
34
+ if (typeof custom === "function") {
35
+ currentOperation = custom(currentOperation, contract);
36
+ } else {
37
+ currentOperation = {
38
+ ...currentOperation,
39
+ ...custom
40
+ };
41
+ }
42
+ }
43
+ return currentOperation;
44
+ }
45
+
46
+ const LOGIC_KEYWORDS = [
47
+ "$dynamicRef",
48
+ "$ref",
49
+ "additionalItems",
50
+ "additionalProperties",
51
+ "allOf",
52
+ "anyOf",
53
+ "const",
54
+ "contains",
55
+ "contentEncoding",
56
+ "contentMediaType",
57
+ "contentSchema",
58
+ "dependencies",
59
+ "dependentRequired",
60
+ "dependentSchemas",
61
+ "else",
62
+ "enum",
63
+ "exclusiveMaximum",
64
+ "exclusiveMinimum",
65
+ "format",
66
+ "if",
67
+ "items",
68
+ "maxContains",
69
+ "maximum",
70
+ "maxItems",
71
+ "maxLength",
72
+ "maxProperties",
73
+ "minContains",
74
+ "minimum",
75
+ "minItems",
76
+ "minLength",
77
+ "minProperties",
78
+ "multipleOf",
79
+ "not",
80
+ "oneOf",
81
+ "pattern",
82
+ "patternProperties",
83
+ "prefixItems",
84
+ "properties",
85
+ "propertyNames",
86
+ "required",
87
+ "then",
88
+ "type",
89
+ "unevaluatedItems",
90
+ "unevaluatedProperties",
91
+ "uniqueItems"
92
+ ];
93
+
94
+ function isFileSchema(schema) {
95
+ return isObject(schema) && schema.type === "string" && typeof schema.contentMediaType === "string";
96
+ }
97
+ function isObjectSchema(schema) {
98
+ return isObject(schema) && schema.type === "object";
99
+ }
100
+ function isAnySchema(schema) {
101
+ if (schema === true) {
102
+ return true;
103
+ }
104
+ if (Object.keys(schema).every((k) => !LOGIC_KEYWORDS.includes(k))) {
105
+ return true;
106
+ }
107
+ return false;
108
+ }
109
+ function separateObjectSchema(schema, separatedProperties) {
110
+ if (Object.keys(schema).some(
111
+ (k) => !["type", "properties", "required", "additionalProperties"].includes(k) && LOGIC_KEYWORDS.includes(k) && schema[k] !== void 0
112
+ )) {
113
+ return [{ type: "object" }, schema];
114
+ }
115
+ const matched = { ...schema };
116
+ const rest = { ...schema };
117
+ matched.properties = separatedProperties.reduce((acc, key) => {
118
+ const keySchema = schema.properties?.[key] ?? schema.additionalProperties;
119
+ if (keySchema !== void 0) {
120
+ acc[key] = keySchema;
121
+ }
122
+ return acc;
123
+ }, {});
124
+ matched.required = schema.required?.filter((key) => separatedProperties.includes(key));
125
+ matched.examples = schema.examples?.map((example) => {
126
+ if (!isObject(example)) {
127
+ return example;
128
+ }
129
+ return Object.entries(example).reduce(
130
+ (acc, [key, value]) => {
131
+ if (separatedProperties.includes(key)) {
132
+ acc[key] = value;
133
+ }
134
+ return acc;
135
+ },
136
+ {}
137
+ );
138
+ });
139
+ rest.properties = schema.properties && Object.entries(schema.properties).filter(([key]) => !separatedProperties.includes(key)).reduce(
140
+ (acc, [key, value]) => {
141
+ acc[key] = value;
142
+ return acc;
143
+ },
144
+ {}
145
+ );
146
+ rest.required = schema.required?.filter((key) => !separatedProperties.includes(key));
147
+ rest.examples = schema.examples?.map((example) => {
148
+ if (!isObject(example)) {
149
+ return example;
150
+ }
151
+ return Object.entries(example).reduce(
152
+ (acc, [key, value]) => {
153
+ if (!separatedProperties.includes(key)) {
154
+ acc[key] = value;
155
+ }
156
+ return acc;
157
+ },
158
+ {}
159
+ );
160
+ });
161
+ return [matched, rest];
162
+ }
163
+ function filterSchemaBranches(schema, check, matches = []) {
164
+ if (check(schema)) {
165
+ matches.push(schema);
166
+ return [matches, void 0];
167
+ }
168
+ if (isObject(schema)) {
169
+ for (const keyword of ["anyOf", "oneOf"]) {
170
+ if (schema[keyword] && Object.keys(schema).every((k) => k === keyword || !LOGIC_KEYWORDS.includes(k))) {
171
+ const rest = schema[keyword].map((s) => filterSchemaBranches(s, check, matches)[1]).filter((v) => !!v);
172
+ if (rest.length === 1 && typeof rest[0] === "object") {
173
+ return [matches, { ...schema, [keyword]: void 0, ...rest[0] }];
174
+ }
175
+ return [matches, { ...schema, [keyword]: rest }];
176
+ }
177
+ }
178
+ }
179
+ return [matches, schema];
180
+ }
181
+ function applySchemaOptionality(required, schema) {
182
+ if (required) {
183
+ return schema;
184
+ }
185
+ return {
186
+ anyOf: [schema, { not: {} }]
187
+ };
188
+ }
189
+ function expandUnionSchema(schema) {
190
+ if (typeof schema === "object") {
191
+ for (const keyword of ["anyOf", "oneOf"]) {
192
+ if (schema[keyword] && Object.keys(schema).every((k) => k === keyword || !LOGIC_KEYWORDS.includes(k))) {
193
+ return schema[keyword].flatMap((s) => expandUnionSchema(s));
194
+ }
195
+ }
196
+ }
197
+ return [schema];
198
+ }
199
+ function expandArrayableSchema(schema) {
200
+ const schemas = expandUnionSchema(schema);
201
+ if (schemas.length !== 2) {
202
+ return void 0;
203
+ }
204
+ const arraySchema = schemas.find(
205
+ (s) => typeof s === "object" && s.type === "array" && Object.keys(s).filter((k) => LOGIC_KEYWORDS.includes(k)).every((k) => k === "type" || k === "items")
206
+ );
207
+ if (arraySchema === void 0) {
208
+ return void 0;
209
+ }
210
+ const items1 = arraySchema.items;
211
+ const items2 = schemas.find((s) => s !== arraySchema);
212
+ if (stringifyJSON(items1) !== stringifyJSON(items2)) {
213
+ return void 0;
214
+ }
215
+ return [items2, arraySchema];
216
+ }
217
+ const PRIMITIVE_SCHEMA_TYPES = /* @__PURE__ */ new Set([
218
+ TypeName.String,
219
+ TypeName.Number,
220
+ TypeName.Integer,
221
+ TypeName.Boolean,
222
+ TypeName.Null
223
+ ]);
224
+ function isPrimitiveSchema(schema) {
225
+ return expandUnionSchema(schema).every((s) => {
226
+ if (typeof s === "boolean") {
227
+ return false;
228
+ }
229
+ if (typeof s.type === "string" && PRIMITIVE_SCHEMA_TYPES.has(s.type)) {
230
+ return true;
231
+ }
232
+ if (s.const !== void 0) {
233
+ return true;
234
+ }
235
+ return false;
236
+ });
237
+ }
238
+
239
+ function toOpenAPIPath(path) {
240
+ return standardizeHTTPPath(path).replace(/\/\{\+([^}]+)\}/g, "/{$1}");
241
+ }
242
+ function toOpenAPIMethod(method) {
243
+ return method.toLocaleLowerCase();
244
+ }
245
+ function toOpenAPIContent(schema) {
246
+ const content = {};
247
+ const [matches, restSchema] = filterSchemaBranches(schema, isFileSchema);
248
+ for (const file of matches) {
249
+ content[file.contentMediaType] = {
250
+ schema: toOpenAPISchema(file)
251
+ };
252
+ }
253
+ if (restSchema !== void 0) {
254
+ content["application/json"] = {
255
+ schema: toOpenAPISchema(restSchema)
256
+ };
257
+ const isStillHasFileSchema = findDeepMatches((v) => isObject(v) && isFileSchema(v), restSchema).values.length > 0;
258
+ if (isStillHasFileSchema) {
259
+ content["multipart/form-data"] = {
260
+ schema: toOpenAPISchema(restSchema)
261
+ };
262
+ }
263
+ }
264
+ return content;
265
+ }
266
+ function toOpenAPIEventIteratorContent([yieldsRequired, yieldsSchema], [returnsRequired, returnsSchema]) {
267
+ return {
268
+ "text/event-stream": {
269
+ schema: toOpenAPISchema({
270
+ oneOf: [
271
+ {
272
+ type: "object",
273
+ properties: {
274
+ event: { const: "message" },
275
+ data: yieldsSchema,
276
+ id: { type: "string" },
277
+ retry: { type: "number" }
278
+ },
279
+ required: yieldsRequired ? ["event", "data"] : ["event"]
280
+ },
281
+ {
282
+ type: "object",
283
+ properties: {
284
+ event: { const: "done" },
285
+ data: returnsSchema,
286
+ id: { type: "string" },
287
+ retry: { type: "number" }
288
+ },
289
+ required: returnsRequired ? ["event", "data"] : ["event"]
290
+ },
291
+ {
292
+ type: "object",
293
+ properties: {
294
+ event: { const: "error" },
295
+ data: {},
296
+ id: { type: "string" },
297
+ retry: { type: "number" }
298
+ },
299
+ required: ["event"]
300
+ }
301
+ ]
302
+ })
303
+ }
304
+ };
305
+ }
306
+ function toOpenAPIParameters(schema, parameterIn) {
307
+ const parameters = [];
308
+ for (const key in schema.properties) {
309
+ const keySchema = schema.properties[key];
310
+ let isDeepObjectStyle = true;
311
+ if (parameterIn !== "query") {
312
+ isDeepObjectStyle = false;
313
+ } else if (isPrimitiveSchema(keySchema)) {
314
+ isDeepObjectStyle = false;
315
+ } else {
316
+ const [item] = expandArrayableSchema(keySchema) ?? [];
317
+ if (item !== void 0 && isPrimitiveSchema(item)) {
318
+ isDeepObjectStyle = false;
319
+ }
320
+ }
321
+ parameters.push({
322
+ name: key,
323
+ in: parameterIn,
324
+ required: schema.required?.includes(key),
325
+ schema: toOpenAPISchema(keySchema),
326
+ style: isDeepObjectStyle ? "deepObject" : void 0,
327
+ explode: isDeepObjectStyle ? true : void 0,
328
+ allowEmptyValue: parameterIn === "query" ? true : void 0,
329
+ allowReserved: parameterIn === "query" ? true : void 0
330
+ });
331
+ }
332
+ return parameters;
333
+ }
334
+ function checkParamsSchema(schema, params) {
335
+ const properties = Object.keys(schema.properties ?? {});
336
+ const required = schema.required ?? [];
337
+ if (properties.length !== params.length || properties.some((v) => !params.includes(v))) {
338
+ return false;
339
+ }
340
+ if (required.length !== params.length || required.some((v) => !params.includes(v))) {
341
+ return false;
342
+ }
343
+ return true;
344
+ }
345
+ function toOpenAPISchema(schema) {
346
+ return schema === true ? {} : schema === false ? { not: {} } : schema;
347
+ }
348
+ const OPENAPI_JSON_SCHEMA_REF_PREFIX = "#/components/schemas/";
349
+ function resolveOpenAPIJsonSchemaRef(doc, schema) {
350
+ if (typeof schema !== "object" || !schema.$ref?.startsWith(OPENAPI_JSON_SCHEMA_REF_PREFIX)) {
351
+ return schema;
352
+ }
353
+ const name = schema.$ref.slice(OPENAPI_JSON_SCHEMA_REF_PREFIX.length);
354
+ const resolved = doc.components?.schemas?.[name];
355
+ return resolved ?? schema;
356
+ }
357
+
358
+ class CompositeSchemaConverter {
359
+ converters;
360
+ constructor(converters) {
361
+ this.converters = converters;
362
+ }
363
+ async convert(schema, options) {
364
+ for (const converter of this.converters) {
365
+ if (await converter.condition(schema, options)) {
366
+ return converter.convert(schema, options);
367
+ }
368
+ }
369
+ return [false, {}];
370
+ }
371
+ }
372
+
373
+ class OpenAPIGeneratorError extends Error {
374
+ }
375
+ class OpenAPIGenerator {
376
+ converter;
377
+ constructor(options = {}) {
378
+ this.converter = new CompositeSchemaConverter(toArray(options.schemaConverters));
379
+ }
380
+ /**
381
+ * Generates OpenAPI specifications from oRPC routers/contracts.
382
+ *
383
+ * @see {@link https://orpc.unnoq.com/docs/openapi/openapi-specification OpenAPI Specification Docs}
384
+ */
385
+ async generate(router, options = {}) {
386
+ const filter = options.filter ?? (({ contract, path }) => {
387
+ return !(options.exclude?.(contract, path) ?? false);
388
+ });
389
+ const doc = {
390
+ ...clone(options),
391
+ info: options.info ?? { title: "API Reference", version: "0.0.0" },
392
+ openapi: "3.1.1",
393
+ exclude: void 0,
394
+ filter: void 0,
395
+ commonSchemas: void 0
396
+ };
397
+ const { baseSchemaConvertOptions, undefinedErrorJsonSchema } = await this.#resolveCommonSchemas(
398
+ doc,
399
+ options.commonSchemas
400
+ );
401
+ const contracts = [];
402
+ await resolveContractProcedures({ path: [], router }, (traverseOptions) => {
403
+ if (!value(filter, traverseOptions)) {
404
+ return;
405
+ }
406
+ contracts.push(traverseOptions);
407
+ });
408
+ const errors = [];
409
+ for (const { contract, path } of contracts) {
410
+ const stringPath = path.join(".");
411
+ try {
412
+ const def = contract["~orpc"];
413
+ const method = toOpenAPIMethod(fallbackContractConfig("defaultMethod", def.route.method));
414
+ const httpPath = toOpenAPIPath(def.route.path ?? toHttpPath(path));
415
+ let operationObjectRef;
416
+ if (def.route.spec !== void 0 && typeof def.route.spec !== "function") {
417
+ operationObjectRef = def.route.spec;
418
+ } else {
419
+ operationObjectRef = {
420
+ operationId: def.route.operationId ?? stringPath,
421
+ summary: def.route.summary,
422
+ description: def.route.description,
423
+ deprecated: def.route.deprecated,
424
+ tags: def.route.tags?.map((tag) => tag)
425
+ };
426
+ await this.#request(doc, operationObjectRef, def, baseSchemaConvertOptions);
427
+ await this.#successResponse(doc, operationObjectRef, def, baseSchemaConvertOptions);
428
+ }
429
+ if (typeof def.route.spec === "function") {
430
+ operationObjectRef = def.route.spec(operationObjectRef);
431
+ }
432
+ doc.paths ??= {};
433
+ doc.paths[httpPath] ??= {};
434
+ doc.paths[httpPath][method] = applyCustomOpenAPIOperation(operationObjectRef, contract);
435
+ } catch (e) {
436
+ if (!(e instanceof OpenAPIGeneratorError)) {
437
+ throw e;
438
+ }
439
+ errors.push(
440
+ `[OpenAPIGenerator] Error occurred while generating OpenAPI for procedure at path: ${stringPath}
441
+ ${e.message}`
442
+ );
443
+ }
444
+ }
445
+ if (errors.length) {
446
+ throw new OpenAPIGeneratorError(
447
+ `Some error occurred during OpenAPI generation:
448
+
449
+ ${errors.join("\n\n")}`
450
+ );
451
+ }
452
+ return jsonSerialize(doc)[0];
453
+ }
454
+ async #resolveCommonSchemas(doc, commonSchemas) {
455
+ let undefinedErrorJsonSchema = {
456
+ type: "object",
457
+ properties: {
458
+ defined: { const: false },
459
+ code: { type: "string" },
460
+ status: { type: "number" },
461
+ message: { type: "string" },
462
+ data: {}
463
+ },
464
+ required: ["defined", "code", "status", "message"]
465
+ };
466
+ const baseSchemaConvertOptions = {};
467
+ if (commonSchemas) {
468
+ baseSchemaConvertOptions.components = [];
469
+ for (const key in commonSchemas) {
470
+ const options = commonSchemas[key];
471
+ if (options.schema === void 0) {
472
+ continue;
473
+ }
474
+ const { schema, strategy = "input" } = options;
475
+ const [required, json] = await this.converter.convert(schema, { strategy });
476
+ const allowedStrategies = [strategy];
477
+ if (strategy === "input") {
478
+ const [outputRequired, outputJson] = await this.converter.convert(schema, { strategy: "output" });
479
+ if (outputRequired === required && stringifyJSON(outputJson) === stringifyJSON(json)) {
480
+ allowedStrategies.push("output");
481
+ }
482
+ } else if (strategy === "output") {
483
+ const [inputRequired, inputJson] = await this.converter.convert(schema, { strategy: "input" });
484
+ if (inputRequired === required && stringifyJSON(inputJson) === stringifyJSON(json)) {
485
+ allowedStrategies.push("input");
486
+ }
487
+ }
488
+ baseSchemaConvertOptions.components.push({
489
+ schema,
490
+ required,
491
+ ref: `#/components/schemas/${key}`,
492
+ allowedStrategies
493
+ });
494
+ }
495
+ doc.components ??= {};
496
+ doc.components.schemas ??= {};
497
+ for (const key in commonSchemas) {
498
+ const options = commonSchemas[key];
499
+ if (options.schema === void 0) {
500
+ if (options.error === "UndefinedError") {
501
+ doc.components.schemas[key] = toOpenAPISchema(undefinedErrorJsonSchema);
502
+ undefinedErrorJsonSchema = { $ref: `#/components/schemas/${key}` };
503
+ }
504
+ continue;
505
+ }
506
+ const { schema, strategy = "input" } = options;
507
+ const [, json] = await this.converter.convert(schema, {
508
+ ...baseSchemaConvertOptions,
509
+ strategy,
510
+ minStructureDepthForRef: 1
511
+ // not allow use $ref for root schemas
512
+ });
513
+ doc.components.schemas[key] = toOpenAPISchema(json);
514
+ }
515
+ }
516
+ return { baseSchemaConvertOptions, undefinedErrorJsonSchema };
517
+ }
518
+ async #request(doc, ref, def, baseSchemaConvertOptions) {
519
+ const method = fallbackContractConfig("defaultMethod", def.route.method);
520
+ const dynamicParams = getDynamicParams(def.route.path)?.map((v) => v.name);
521
+ const [_pathRequired, pathSchema] = await this.converter.convert(def.schemas.pathSchema, {
522
+ ...baseSchemaConvertOptions,
523
+ strategy: "input",
524
+ minStructureDepthForRef: 1
525
+ });
526
+ if (dynamicParams?.length) {
527
+ const error = new OpenAPIGeneratorError(
528
+ // TODO: fix this error
529
+ 'When input structure is "compact", and path has dynamic params, input schema must be an object with all dynamic params as required.'
530
+ );
531
+ if (!isObjectSchema(pathSchema)) {
532
+ throw error;
533
+ }
534
+ if (!checkParamsSchema(pathSchema, dynamicParams)) {
535
+ throw error;
536
+ }
537
+ ref.parameters ??= [];
538
+ ref.parameters.push(...toOpenAPIParameters(pathSchema, "path"));
539
+ } else {
540
+ const error = new OpenAPIGeneratorError("Params set via path do not match those on the route");
541
+ if (!isObjectSchema(pathSchema)) {
542
+ console.log("FOO", pathSchema);
543
+ throw error;
544
+ }
545
+ if (!checkParamsSchema(pathSchema, [])) {
546
+ console.log("BAR", pathSchema);
547
+ throw error;
548
+ }
549
+ }
550
+ const [_queryRequired, querySchema] = await this.converter.convert(def.schemas.querySchema, {
551
+ ...baseSchemaConvertOptions,
552
+ strategy: "input",
553
+ minStructureDepthForRef: 0
554
+ });
555
+ if (!isAnySchema(querySchema)) {
556
+ const resolvedSchema = resolveOpenAPIJsonSchemaRef(doc, querySchema);
557
+ if (!isObjectSchema(resolvedSchema)) {
558
+ throw new OpenAPIGeneratorError("Query param schema must satisfy: object | any | unknown");
559
+ }
560
+ ref.parameters ??= [];
561
+ ref.parameters.push(...toOpenAPIParameters(resolvedSchema, "query"));
562
+ }
563
+ if (method !== "GET") {
564
+ const details = getEventIteratorSchemaDetails(def.schemas.bodySchema);
565
+ if (details) {
566
+ ref.requestBody = {
567
+ required: true,
568
+ content: toOpenAPIEventIteratorContent(
569
+ await this.converter.convert(details.yields, { ...baseSchemaConvertOptions, strategy: "input" }),
570
+ await this.converter.convert(details.returns, { ...baseSchemaConvertOptions, strategy: "input" })
571
+ )
572
+ };
573
+ } else {
574
+ const [bodyRequired, bodySchema] = await this.converter.convert(def.schemas.bodySchema, {
575
+ ...baseSchemaConvertOptions,
576
+ strategy: "input",
577
+ minStructureDepthForRef: 0
578
+ });
579
+ if (isAnySchema(bodySchema)) {
580
+ return;
581
+ }
582
+ ref.requestBody = {
583
+ required: bodyRequired,
584
+ content: toOpenAPIContent(bodySchema)
585
+ };
586
+ }
587
+ }
588
+ }
589
+ async #successResponse(doc, ref, def, baseSchemaConvertOptions) {
590
+ const outputSchema = def.schemas.outputSchema;
591
+ const status = fallbackContractConfig("defaultSuccessStatus", def.route.successStatus);
592
+ const description = fallbackContractConfig("defaultSuccessDescription", def.route?.successDescription);
593
+ const eventIteratorSchemaDetails = getEventIteratorSchemaDetails(outputSchema);
594
+ const outputStructure = fallbackContractConfig("defaultOutputStructure", def.route.outputStructure);
595
+ if (eventIteratorSchemaDetails) {
596
+ ref.responses ??= {};
597
+ ref.responses[status] = {
598
+ description,
599
+ content: toOpenAPIEventIteratorContent(
600
+ await this.converter.convert(eventIteratorSchemaDetails.yields, {
601
+ ...baseSchemaConvertOptions,
602
+ strategy: "output"
603
+ }),
604
+ await this.converter.convert(eventIteratorSchemaDetails.returns, {
605
+ ...baseSchemaConvertOptions,
606
+ strategy: "output"
607
+ })
608
+ )
609
+ };
610
+ return;
611
+ }
612
+ const [required, json] = await this.converter.convert(outputSchema, {
613
+ ...baseSchemaConvertOptions,
614
+ strategy: "output",
615
+ minStructureDepthForRef: outputStructure === "detailed" ? 1 : 0
616
+ });
617
+ if (outputStructure === "compact") {
618
+ ref.responses ??= {};
619
+ ref.responses[status] = {
620
+ description
621
+ };
622
+ ref.responses[status].content = toOpenAPIContent(applySchemaOptionality(required, json));
623
+ return;
624
+ }
625
+ const handledStatuses = /* @__PURE__ */ new Set();
626
+ for (const item of expandUnionSchema(json)) {
627
+ const error = new OpenAPIGeneratorError(`
628
+ When output structure is "detailed", output schema must satisfy:
629
+ {
630
+ status?: number, // must be a literal number and in the range of 200-399
631
+ headers?: Record<string, unknown>,
632
+ body?: unknown
633
+ }
634
+
635
+ But got: ${stringifyJSON(item)}
636
+ `);
637
+ if (!isObjectSchema(item)) {
638
+ throw error;
639
+ }
640
+ let schemaStatus;
641
+ let schemaDescription;
642
+ if (item.properties?.status !== void 0) {
643
+ const statusSchema = resolveOpenAPIJsonSchemaRef(doc, item.properties.status);
644
+ if (typeof statusSchema !== "object" || statusSchema.const === void 0 || typeof statusSchema.const !== "number" || !Number.isInteger(statusSchema.const) || isORPCErrorStatus(statusSchema.const)) {
645
+ throw error;
646
+ }
647
+ schemaStatus = statusSchema.const;
648
+ schemaDescription = statusSchema.description;
649
+ }
650
+ const itemStatus = schemaStatus ?? status;
651
+ const itemDescription = schemaDescription ?? description;
652
+ if (handledStatuses.has(itemStatus)) {
653
+ throw new OpenAPIGeneratorError(`
654
+ When output structure is "detailed", each success status must be unique.
655
+ But got status: ${itemStatus} used more than once.
656
+ `);
657
+ }
658
+ handledStatuses.add(itemStatus);
659
+ ref.responses ??= {};
660
+ ref.responses[itemStatus] = {
661
+ description: itemDescription
662
+ };
663
+ if (item.properties?.headers !== void 0) {
664
+ const headersSchema = resolveOpenAPIJsonSchemaRef(doc, item.properties.headers);
665
+ if (!isObjectSchema(headersSchema)) {
666
+ throw error;
667
+ }
668
+ for (const key in headersSchema.properties) {
669
+ const headerSchema = headersSchema.properties[key];
670
+ if (headerSchema !== void 0) {
671
+ ref.responses[itemStatus].headers ??= {};
672
+ ref.responses[itemStatus].headers[key] = {
673
+ schema: toOpenAPISchema(headerSchema),
674
+ required: item.required?.includes("headers") && headersSchema.required?.includes(key)
675
+ };
676
+ }
677
+ }
678
+ }
679
+ if (item.properties?.body !== void 0) {
680
+ ref.responses[itemStatus].content = toOpenAPIContent(
681
+ applySchemaOptionality(item.required?.includes("body") ?? false, item.properties.body)
682
+ );
683
+ }
684
+ }
685
+ }
686
+ }
687
+
688
+ const oo = {
689
+ spec: customOpenAPIOperation
690
+ };
691
+
692
+ 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 };