@temporary-name/server 1.9.3-alpha.6ef4729e23affbe6454d37025d1dfc4d998b0649 → 1.9.3-alpha.72daecd600ae901064d3c4f8ab780582c1335ffe

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 (45) hide show
  1. package/dist/adapters/aws-lambda/index.d.mts +11 -7
  2. package/dist/adapters/aws-lambda/index.d.ts +11 -7
  3. package/dist/adapters/aws-lambda/index.mjs +11 -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 +22 -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 +20 -126
  10. package/dist/handler/index.d.mts +28 -0
  11. package/dist/handler/index.d.ts +28 -0
  12. package/dist/handler/index.mjs +8 -0
  13. package/dist/helpers/index.mjs +3 -29
  14. package/dist/index.d.mts +373 -546
  15. package/dist/index.d.ts +373 -546
  16. package/dist/index.mjs +547 -470
  17. package/dist/openapi/index.d.mts +185 -0
  18. package/dist/openapi/index.d.ts +185 -0
  19. package/dist/openapi/index.mjs +782 -0
  20. package/dist/shared/server.BwcJq6aP.d.mts +808 -0
  21. package/dist/shared/server.BwcJq6aP.d.ts +808 -0
  22. package/dist/shared/server.C1RJffw4.mjs +30 -0
  23. package/dist/shared/server.CjPiuQYH.d.mts +51 -0
  24. package/dist/shared/server.CjPiuQYH.d.ts +51 -0
  25. package/dist/shared/server.D1LXM1bf.mjs +523 -0
  26. package/dist/shared/server.DEC2sW8B.mjs +496 -0
  27. package/dist/shared/server.Deg5phAY.d.ts +39 -0
  28. package/dist/shared/server.H11763QX.mjs +315 -0
  29. package/dist/shared/server.gSXsB9Bn.mjs +156 -0
  30. package/dist/shared/server.hAH-LVh_.d.mts +39 -0
  31. package/package.json +20 -31
  32. package/dist/adapters/standard/index.d.mts +0 -16
  33. package/dist/adapters/standard/index.d.ts +0 -16
  34. package/dist/adapters/standard/index.mjs +0 -101
  35. package/dist/plugins/index.d.mts +0 -160
  36. package/dist/plugins/index.d.ts +0 -160
  37. package/dist/plugins/index.mjs +0 -288
  38. package/dist/shared/server.BEQrAa3A.mjs +0 -207
  39. package/dist/shared/server.Bo94xDTv.d.mts +0 -73
  40. package/dist/shared/server.Btxrgkj5.d.ts +0 -73
  41. package/dist/shared/server.C1YnHvvf.d.mts +0 -192
  42. package/dist/shared/server.C1YnHvvf.d.ts +0 -192
  43. package/dist/shared/server.D6K9uoPI.mjs +0 -35
  44. package/dist/shared/server.DZ5BIITo.mjs +0 -9
  45. package/dist/shared/server.X0YaZxSJ.mjs +0 -13
@@ -0,0 +1,782 @@
1
+ import { isObject, stringifyJSON, findDeepMatches, clone, value, fallbackContractConfig, toHttpPath, assertNever } from '@temporary-name/shared';
2
+ import * as z from '@temporary-name/zod';
3
+ import { s as standardizeHTTPPath, r as resolveContractProcedures, g as getDynamicParams, i as isAPIErrorStatus } from '../shared/server.DEC2sW8B.mjs';
4
+ import { Z as ZodToJsonSchemaConverter, g as getEventIteratorSchemaDetails } from '../shared/server.D1LXM1bf.mjs';
5
+ import { TypeName } from '@temporary-name/interop/json-schema-typed/draft-2020-12';
6
+ export { ContentEncoding as JSONSchemaContentEncoding, Format as JSONSchemaFormat, TypeName as JSONSchemaTypeName } from '@temporary-name/interop/json-schema-typed/draft-2020-12';
7
+ import '@temporary-name/standard-server';
8
+ import '@temporary-name/server/openapi';
9
+ import 'zod/v4/core';
10
+
11
+ const OPERATION_EXTENDER_SYMBOL = Symbol("ORPC_OPERATION_EXTENDER");
12
+ function customOpenAPIOperation(o, extend) {
13
+ return new Proxy(o, {
14
+ get(target, prop, receiver) {
15
+ if (prop === OPERATION_EXTENDER_SYMBOL) {
16
+ return extend;
17
+ }
18
+ return Reflect.get(target, prop, receiver);
19
+ }
20
+ });
21
+ }
22
+ function getCustomOpenAPIOperation(o) {
23
+ return o[OPERATION_EXTENDER_SYMBOL];
24
+ }
25
+ function applyCustomOpenAPIOperation(operation, contract) {
26
+ const operationCustoms = [];
27
+ for (const middleware of contract["~orpc"].middlewares) {
28
+ const maybeExtender = getCustomOpenAPIOperation(middleware);
29
+ if (maybeExtender) {
30
+ operationCustoms.push(maybeExtender);
31
+ }
32
+ }
33
+ let currentOperation = operation;
34
+ for (const custom of operationCustoms) {
35
+ if (typeof custom === "function") {
36
+ currentOperation = custom(currentOperation, contract);
37
+ } else {
38
+ currentOperation = {
39
+ ...currentOperation,
40
+ ...custom
41
+ };
42
+ }
43
+ }
44
+ return currentOperation;
45
+ }
46
+
47
+ const LOGIC_KEYWORDS = [
48
+ "$dynamicRef",
49
+ "$ref",
50
+ "additionalItems",
51
+ "additionalProperties",
52
+ "allOf",
53
+ "anyOf",
54
+ "const",
55
+ "contains",
56
+ "contentEncoding",
57
+ "contentMediaType",
58
+ "contentSchema",
59
+ "dependencies",
60
+ "dependentRequired",
61
+ "dependentSchemas",
62
+ "else",
63
+ "enum",
64
+ "exclusiveMaximum",
65
+ "exclusiveMinimum",
66
+ "format",
67
+ "if",
68
+ "items",
69
+ "maxContains",
70
+ "maximum",
71
+ "maxItems",
72
+ "maxLength",
73
+ "maxProperties",
74
+ "minContains",
75
+ "minimum",
76
+ "minItems",
77
+ "minLength",
78
+ "minProperties",
79
+ "multipleOf",
80
+ "not",
81
+ "oneOf",
82
+ "pattern",
83
+ "patternProperties",
84
+ "prefixItems",
85
+ "properties",
86
+ "propertyNames",
87
+ "required",
88
+ "then",
89
+ "type",
90
+ "unevaluatedItems",
91
+ "unevaluatedProperties",
92
+ "uniqueItems"
93
+ ];
94
+
95
+ function isFileSchema(schema) {
96
+ return isObject(schema) && schema.type === "string" && typeof schema.contentMediaType === "string";
97
+ }
98
+ function isObjectSchema(schema) {
99
+ return isObject(schema) && schema.type === "object";
100
+ }
101
+ function isAnySchema(schema) {
102
+ if (schema === true) {
103
+ return true;
104
+ }
105
+ if (Object.keys(schema).every((k) => !LOGIC_KEYWORDS.includes(k))) {
106
+ return true;
107
+ }
108
+ return false;
109
+ }
110
+ function separateObjectSchema(schema, separatedProperties) {
111
+ if (Object.keys(schema).some(
112
+ (k) => !["type", "properties", "required", "additionalProperties"].includes(k) && LOGIC_KEYWORDS.includes(k) && schema[k] !== void 0
113
+ )) {
114
+ return [{ type: "object" }, schema];
115
+ }
116
+ const matched = { ...schema };
117
+ const rest = { ...schema };
118
+ matched.properties = separatedProperties.reduce((acc, key) => {
119
+ const keySchema = schema.properties?.[key] ?? schema.additionalProperties;
120
+ if (keySchema !== void 0) {
121
+ acc[key] = keySchema;
122
+ }
123
+ return acc;
124
+ }, {});
125
+ matched.required = schema.required?.filter((key) => separatedProperties.includes(key));
126
+ matched.examples = schema.examples?.map((example) => {
127
+ if (!isObject(example)) {
128
+ return example;
129
+ }
130
+ return Object.entries(example).reduce(
131
+ (acc, [key, value]) => {
132
+ if (separatedProperties.includes(key)) {
133
+ acc[key] = value;
134
+ }
135
+ return acc;
136
+ },
137
+ {}
138
+ );
139
+ });
140
+ rest.properties = schema.properties && Object.entries(schema.properties).filter(([key]) => !separatedProperties.includes(key)).reduce(
141
+ (acc, [key, value]) => {
142
+ acc[key] = value;
143
+ return acc;
144
+ },
145
+ {}
146
+ );
147
+ rest.required = schema.required?.filter((key) => !separatedProperties.includes(key));
148
+ rest.examples = schema.examples?.map((example) => {
149
+ if (!isObject(example)) {
150
+ return example;
151
+ }
152
+ return Object.entries(example).reduce(
153
+ (acc, [key, value]) => {
154
+ if (!separatedProperties.includes(key)) {
155
+ acc[key] = value;
156
+ }
157
+ return acc;
158
+ },
159
+ {}
160
+ );
161
+ });
162
+ return [matched, rest];
163
+ }
164
+ function filterSchemaBranches(schema, check, matches = []) {
165
+ if (check(schema)) {
166
+ matches.push(schema);
167
+ return [matches, void 0];
168
+ }
169
+ if (isObject(schema)) {
170
+ for (const keyword of ["anyOf", "oneOf"]) {
171
+ if (schema[keyword] && Object.keys(schema).every((k) => k === keyword || !LOGIC_KEYWORDS.includes(k))) {
172
+ const rest = schema[keyword].map((s) => filterSchemaBranches(s, check, matches)[1]).filter((v) => !!v);
173
+ if (rest.length === 1 && typeof rest[0] === "object") {
174
+ return [matches, { ...schema, [keyword]: void 0, ...rest[0] }];
175
+ }
176
+ return [matches, { ...schema, [keyword]: rest }];
177
+ }
178
+ }
179
+ }
180
+ return [matches, schema];
181
+ }
182
+ function applySchemaOptionality(required, schema) {
183
+ if (required) {
184
+ return schema;
185
+ }
186
+ return {
187
+ anyOf: [schema, { not: {} }]
188
+ };
189
+ }
190
+ function expandUnionSchema(schema) {
191
+ if (typeof schema === "object") {
192
+ for (const keyword of ["anyOf", "oneOf"]) {
193
+ if (schema[keyword] && Object.keys(schema).every((k) => k === keyword || !LOGIC_KEYWORDS.includes(k))) {
194
+ return schema[keyword].flatMap((s) => expandUnionSchema(s));
195
+ }
196
+ }
197
+ }
198
+ return [schema];
199
+ }
200
+ function expandArrayableSchema(schema) {
201
+ const schemas = expandUnionSchema(schema);
202
+ if (schemas.length !== 2) {
203
+ return void 0;
204
+ }
205
+ const arraySchema = schemas.find(
206
+ (s) => typeof s === "object" && s.type === "array" && Object.keys(s).filter((k) => LOGIC_KEYWORDS.includes(k)).every((k) => k === "type" || k === "items")
207
+ );
208
+ if (arraySchema === void 0) {
209
+ return void 0;
210
+ }
211
+ const items1 = arraySchema.items;
212
+ const items2 = schemas.find((s) => s !== arraySchema);
213
+ if (stringifyJSON(items1) !== stringifyJSON(items2)) {
214
+ return void 0;
215
+ }
216
+ return [items2, arraySchema];
217
+ }
218
+ const PRIMITIVE_SCHEMA_TYPES = /* @__PURE__ */ new Set([
219
+ TypeName.String,
220
+ TypeName.Number,
221
+ TypeName.Integer,
222
+ TypeName.Boolean,
223
+ TypeName.Null
224
+ ]);
225
+ function isPrimitiveSchema(schema) {
226
+ return expandUnionSchema(schema).every((s) => {
227
+ if (typeof s === "boolean") {
228
+ return false;
229
+ }
230
+ if (typeof s.type === "string" && PRIMITIVE_SCHEMA_TYPES.has(s.type)) {
231
+ return true;
232
+ }
233
+ if (s.const !== void 0) {
234
+ return true;
235
+ }
236
+ return false;
237
+ });
238
+ }
239
+
240
+ function toOpenAPIPath(path) {
241
+ return standardizeHTTPPath(path).replace(/\/\{\+([^}]+)\}/g, "/{$1}");
242
+ }
243
+ function toOpenAPIMethod(method) {
244
+ return method.toLocaleLowerCase();
245
+ }
246
+ function toOpenAPIContent(schema) {
247
+ const content = {};
248
+ const [matches, restSchema] = filterSchemaBranches(schema, isFileSchema);
249
+ for (const file of matches) {
250
+ content[file.contentMediaType] = {
251
+ schema: toOpenAPISchema(file)
252
+ };
253
+ }
254
+ if (restSchema !== void 0) {
255
+ content["application/json"] = {
256
+ schema: toOpenAPISchema(restSchema)
257
+ };
258
+ const isStillHasFileSchema = findDeepMatches((v) => isObject(v) && isFileSchema(v), restSchema).values.length > 0;
259
+ if (isStillHasFileSchema) {
260
+ content["multipart/form-data"] = {
261
+ schema: toOpenAPISchema(restSchema)
262
+ };
263
+ }
264
+ }
265
+ return content;
266
+ }
267
+ function toOpenAPIEventIteratorContent([yieldsRequired, yieldsSchema], [returnsRequired, returnsSchema]) {
268
+ return {
269
+ "text/event-stream": {
270
+ schema: toOpenAPISchema({
271
+ oneOf: [
272
+ {
273
+ type: "object",
274
+ properties: {
275
+ event: { const: "message" },
276
+ data: yieldsSchema,
277
+ id: { type: "string" },
278
+ retry: { type: "number" }
279
+ },
280
+ required: yieldsRequired ? ["event", "data"] : ["event"]
281
+ },
282
+ {
283
+ type: "object",
284
+ properties: {
285
+ event: { const: "done" },
286
+ data: returnsSchema,
287
+ id: { type: "string" },
288
+ retry: { type: "number" }
289
+ },
290
+ required: returnsRequired ? ["event", "data"] : ["event"]
291
+ },
292
+ {
293
+ type: "object",
294
+ properties: {
295
+ event: { const: "error" },
296
+ data: {},
297
+ id: { type: "string" },
298
+ retry: { type: "number" }
299
+ },
300
+ required: ["event"]
301
+ }
302
+ ]
303
+ })
304
+ }
305
+ };
306
+ }
307
+ function toOpenAPIParameters(schema, parameterIn) {
308
+ const parameters = [];
309
+ for (const key in schema.properties) {
310
+ const keySchema = schema.properties[key];
311
+ let isDeepObjectStyle = true;
312
+ if (parameterIn !== "query") {
313
+ isDeepObjectStyle = false;
314
+ } else if (isPrimitiveSchema(keySchema)) {
315
+ isDeepObjectStyle = false;
316
+ } else {
317
+ const [item] = expandArrayableSchema(keySchema) ?? [];
318
+ if (item !== void 0 && isPrimitiveSchema(item)) {
319
+ isDeepObjectStyle = false;
320
+ }
321
+ }
322
+ parameters.push({
323
+ name: key,
324
+ in: parameterIn,
325
+ required: schema.required?.includes(key),
326
+ schema: toOpenAPISchema(keySchema),
327
+ style: isDeepObjectStyle ? "deepObject" : void 0,
328
+ explode: isDeepObjectStyle ? true : void 0,
329
+ allowEmptyValue: parameterIn === "query" ? true : void 0,
330
+ allowReserved: parameterIn === "query" ? true : void 0
331
+ });
332
+ }
333
+ return parameters;
334
+ }
335
+ function checkParamsSchema(schema, params) {
336
+ const properties = Object.keys(schema.properties ?? {});
337
+ const required = schema.required ?? [];
338
+ if (properties.length !== params.length || properties.some((v) => !params.includes(v))) {
339
+ return false;
340
+ }
341
+ if (required.length !== params.length || required.some((v) => !params.includes(v))) {
342
+ return false;
343
+ }
344
+ return true;
345
+ }
346
+ function toOpenAPISchema(schema) {
347
+ return schema === true ? {} : schema === false ? { not: {} } : schema;
348
+ }
349
+ const OPENAPI_JSON_SCHEMA_REF_PREFIX = "#/components/schemas/";
350
+ function resolveOpenAPIJsonSchemaRef(doc, schema) {
351
+ if (typeof schema !== "object" || !schema.$ref?.startsWith(OPENAPI_JSON_SCHEMA_REF_PREFIX)) {
352
+ return schema;
353
+ }
354
+ const name = schema.$ref.slice(OPENAPI_JSON_SCHEMA_REF_PREFIX.length);
355
+ const resolved = doc.components?.schemas?.[name];
356
+ return resolved ?? schema;
357
+ }
358
+
359
+ class OpenAPIGeneratorError extends Error {
360
+ }
361
+ async function generateOpenApiSpec(router, options = {}) {
362
+ const converter = typeof options.schemaConverter === "function" ? options.schemaConverter : new ZodToJsonSchemaConverter(options.schemaConverter ?? {}).convert;
363
+ const filter = options.filter ?? (({ contract, path }) => {
364
+ return !(options.exclude?.(contract, path) ?? false);
365
+ });
366
+ const doc = {
367
+ ...clone(options.spec),
368
+ info: options.spec?.info ?? { title: "API Reference", version: "0.0.0" },
369
+ openapi: "3.1.1"
370
+ };
371
+ const { baseSchemaConvertOptions } = await resolveCommonSchemas(doc, options.commonSchemas, converter);
372
+ const contracts = [];
373
+ await resolveContractProcedures({ path: [], router }, (traverseOptions) => {
374
+ if (!value(filter, traverseOptions)) {
375
+ return;
376
+ }
377
+ contracts.push(traverseOptions);
378
+ });
379
+ const namesByAuthConfig = /* @__PURE__ */ new Map();
380
+ const authConfigNames = /* @__PURE__ */ new Set();
381
+ for (const { contract } of contracts) {
382
+ for (const authConfig of contract["~orpc"].authConfigs) {
383
+ if (authConfig.type === "none" || namesByAuthConfig.has(authConfig)) {
384
+ continue;
385
+ }
386
+ const oasNameBase = authConfig.oasName ?? `${authConfig.type}Auth`;
387
+ let oasName = oasNameBase;
388
+ for (let i = 2; authConfigNames.has(oasName); i++) {
389
+ oasName = `${oasNameBase}${i}`;
390
+ }
391
+ namesByAuthConfig.set(authConfig, oasName);
392
+ authConfigNames.add(oasName);
393
+ }
394
+ }
395
+ if (namesByAuthConfig.size > 0) {
396
+ doc.components ??= {};
397
+ const schemes = doc.components.securitySchemes ??= {};
398
+ for (const [authConfig, name] of namesByAuthConfig) {
399
+ schemes[name] ??= authConfigToSecurityScheme(authConfig);
400
+ }
401
+ }
402
+ const errors = [];
403
+ for (const { contract, path } of contracts) {
404
+ const stringPath = path.join(".");
405
+ try {
406
+ const def = contract["~orpc"];
407
+ const method = toOpenAPIMethod(fallbackContractConfig("defaultMethod", def.route.method));
408
+ const httpPath = toOpenAPIPath(def.route.path ?? toHttpPath(path));
409
+ let operationObjectRef;
410
+ if (def.route.spec !== void 0 && typeof def.route.spec !== "function") {
411
+ operationObjectRef = def.route.spec;
412
+ } else {
413
+ operationObjectRef = {
414
+ operationId: def.route.operationId ?? stringPath,
415
+ summary: def.route.summary,
416
+ description: def.route.description,
417
+ deprecated: def.route.deprecated,
418
+ tags: def.route.tags?.map((tag) => tag)
419
+ };
420
+ const security = def.authConfigs.map(
421
+ (authConfig) => authConfig.type === "none" ? {} : { [namesByAuthConfig.get(authConfig)]: [] }
422
+ );
423
+ if (security.length > 0) {
424
+ operationObjectRef.security = security;
425
+ }
426
+ await handleRequest(doc, operationObjectRef, def, baseSchemaConvertOptions, converter);
427
+ await handleSuccessResponse(doc, operationObjectRef, def, baseSchemaConvertOptions, converter);
428
+ await handleErrorResponse(doc, operationObjectRef, def, baseSchemaConvertOptions, converter);
429
+ }
430
+ if (typeof def.route.spec === "function") {
431
+ operationObjectRef = def.route.spec(operationObjectRef);
432
+ }
433
+ doc.paths ??= {};
434
+ doc.paths[httpPath] ??= {};
435
+ doc.paths[httpPath][method] = applyCustomOpenAPIOperation(operationObjectRef, contract);
436
+ } catch (e) {
437
+ if (!(e instanceof OpenAPIGeneratorError)) {
438
+ throw e;
439
+ }
440
+ errors.push(
441
+ `[OpenAPIGenerator] Error occurred while generating OpenAPI for procedure at path: ${stringPath}
442
+ ${e.message}`
443
+ );
444
+ }
445
+ }
446
+ if (errors.length) {
447
+ throw new OpenAPIGeneratorError(
448
+ `Some error occurred during OpenAPI generation:
449
+
450
+ ${errors.join("\n\n")}`
451
+ );
452
+ }
453
+ return doc;
454
+ }
455
+ async function resolveCommonSchemas(doc, commonSchemas, converter) {
456
+ let undefinedErrorJsonSchema = {
457
+ type: "object",
458
+ properties: {
459
+ code: { type: "string" },
460
+ status: { type: "number" },
461
+ message: { type: "string" },
462
+ data: {}
463
+ },
464
+ required: ["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 converter(schema, { strategy });
476
+ const allowedStrategies = [strategy];
477
+ if (strategy === "input") {
478
+ const [outputRequired, outputJson] = await converter(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 converter(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 converter(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 function handleRequest(doc, ref, def, baseSchemaConvertOptions, converter) {
519
+ const method = fallbackContractConfig("defaultMethod", def.route.method);
520
+ const dynamicParams = getDynamicParams(def.route.path)?.map((v) => v.name);
521
+ const [_pathRequired, pathSchema] = await converter(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
+ throw error;
543
+ }
544
+ if (!checkParamsSchema(pathSchema, [])) {
545
+ throw error;
546
+ }
547
+ }
548
+ const [_queryRequired, querySchema] = await converter(def.schemas.querySchema, {
549
+ ...baseSchemaConvertOptions,
550
+ strategy: "input",
551
+ minStructureDepthForRef: 0
552
+ });
553
+ if (!isAnySchema(querySchema)) {
554
+ const resolvedSchema = resolveOpenAPIJsonSchemaRef(doc, querySchema);
555
+ if (!isObjectSchema(resolvedSchema)) {
556
+ throw new OpenAPIGeneratorError("Query param schema must satisfy: object | any | unknown");
557
+ }
558
+ ref.parameters ??= [];
559
+ ref.parameters.push(...toOpenAPIParameters(resolvedSchema, "query"));
560
+ }
561
+ if (method !== "GET") {
562
+ const details = getEventIteratorSchemaDetails(def.schemas.bodySchema);
563
+ if (details) {
564
+ ref.requestBody = {
565
+ required: true,
566
+ content: toOpenAPIEventIteratorContent(
567
+ await converter(details.yields, { ...baseSchemaConvertOptions, strategy: "input" }),
568
+ await converter(details.returns, { ...baseSchemaConvertOptions, strategy: "input" })
569
+ )
570
+ };
571
+ } else {
572
+ const [bodyRequired, bodySchema] = await converter(def.schemas.bodySchema, {
573
+ ...baseSchemaConvertOptions,
574
+ strategy: "input",
575
+ minStructureDepthForRef: 0
576
+ });
577
+ if (isAnySchema(bodySchema)) {
578
+ return;
579
+ }
580
+ ref.requestBody = {
581
+ required: bodyRequired,
582
+ content: toOpenAPIContent(bodySchema)
583
+ };
584
+ }
585
+ }
586
+ }
587
+ async function handleSuccessResponse(doc, ref, def, baseSchemaConvertOptions, converter) {
588
+ const outputSchema = def.schemas.outputSchema;
589
+ const status = fallbackContractConfig("defaultSuccessStatus", def.route.successStatus);
590
+ const description = fallbackContractConfig("defaultSuccessDescription", def.route?.successDescription);
591
+ const eventIteratorSchemaDetails = getEventIteratorSchemaDetails(outputSchema);
592
+ const outputStructure = fallbackContractConfig("defaultOutputStructure", def.route.outputStructure);
593
+ if (eventIteratorSchemaDetails) {
594
+ ref.responses ??= {};
595
+ ref.responses[status] = {
596
+ description,
597
+ content: toOpenAPIEventIteratorContent(
598
+ await converter(eventIteratorSchemaDetails.yields, {
599
+ ...baseSchemaConvertOptions,
600
+ strategy: "output"
601
+ }),
602
+ await converter(eventIteratorSchemaDetails.returns, {
603
+ ...baseSchemaConvertOptions,
604
+ strategy: "output"
605
+ })
606
+ )
607
+ };
608
+ return;
609
+ }
610
+ const [required, json] = await converter(outputSchema, {
611
+ ...baseSchemaConvertOptions,
612
+ strategy: "output",
613
+ minStructureDepthForRef: outputStructure === "detailed" ? 1 : 0
614
+ });
615
+ if (outputStructure === "compact") {
616
+ ref.responses ??= {};
617
+ ref.responses[status] = {
618
+ description
619
+ };
620
+ ref.responses[status].content = toOpenAPIContent(applySchemaOptionality(required, json));
621
+ return;
622
+ }
623
+ const handledStatuses = /* @__PURE__ */ new Set();
624
+ for (const item of expandUnionSchema(json)) {
625
+ const error = new OpenAPIGeneratorError(`
626
+ When output structure is "detailed", output schema must satisfy:
627
+ {
628
+ status?: number, // must be a literal number and in the range of 200-399
629
+ headers?: Record<string, unknown>,
630
+ body?: unknown
631
+ }
632
+
633
+ But got: ${stringifyJSON(item)}
634
+ `);
635
+ if (!isObjectSchema(item)) {
636
+ throw error;
637
+ }
638
+ let schemaStatus;
639
+ let schemaDescription;
640
+ if (item.properties?.status !== void 0) {
641
+ const statusSchema = resolveOpenAPIJsonSchemaRef(doc, item.properties.status);
642
+ if (typeof statusSchema !== "object" || statusSchema.const === void 0 || typeof statusSchema.const !== "number" || !Number.isInteger(statusSchema.const) || isAPIErrorStatus(statusSchema.const)) {
643
+ throw error;
644
+ }
645
+ schemaStatus = statusSchema.const;
646
+ schemaDescription = statusSchema.description;
647
+ }
648
+ const itemStatus = schemaStatus ?? status;
649
+ const itemDescription = schemaDescription ?? description;
650
+ if (handledStatuses.has(itemStatus)) {
651
+ throw new OpenAPIGeneratorError(`
652
+ When output structure is "detailed", each success status must be unique.
653
+ But got status: ${itemStatus} used more than once.
654
+ `);
655
+ }
656
+ handledStatuses.add(itemStatus);
657
+ ref.responses ??= {};
658
+ ref.responses[itemStatus] = {
659
+ description: itemDescription
660
+ };
661
+ if (item.properties?.headers !== void 0) {
662
+ const headersSchema = resolveOpenAPIJsonSchemaRef(doc, item.properties.headers);
663
+ if (!isObjectSchema(headersSchema)) {
664
+ throw error;
665
+ }
666
+ for (const key in headersSchema.properties) {
667
+ const headerSchema = headersSchema.properties[key];
668
+ if (headerSchema !== void 0) {
669
+ ref.responses[itemStatus].headers ??= {};
670
+ ref.responses[itemStatus].headers[key] = {
671
+ schema: toOpenAPISchema(headerSchema),
672
+ required: item.required?.includes("headers") && headersSchema.required?.includes(key)
673
+ };
674
+ }
675
+ }
676
+ }
677
+ if (item.properties?.body !== void 0) {
678
+ ref.responses[itemStatus].content = toOpenAPIContent(
679
+ applySchemaOptionality(item.required?.includes("body") ?? false, item.properties.body)
680
+ );
681
+ }
682
+ }
683
+ }
684
+ function authConfigToSecurityScheme(authConfig) {
685
+ switch (authConfig.type) {
686
+ case "basic":
687
+ return {
688
+ type: "http",
689
+ scheme: "basic",
690
+ description: authConfig.oasDescription
691
+ };
692
+ case "bearer":
693
+ return {
694
+ type: "http",
695
+ scheme: "bearer",
696
+ description: authConfig.oasDescription,
697
+ bearerFormat: authConfig.oasBearerFormat
698
+ };
699
+ case "header":
700
+ return {
701
+ type: "apiKey",
702
+ in: "header",
703
+ name: authConfig.name,
704
+ description: authConfig.oasDescription
705
+ };
706
+ case "query":
707
+ return {
708
+ type: "apiKey",
709
+ in: "query",
710
+ name: authConfig.name,
711
+ description: authConfig.oasDescription
712
+ };
713
+ case "cookie":
714
+ return {
715
+ type: "apiKey",
716
+ in: "cookie",
717
+ name: authConfig.name,
718
+ description: authConfig.oasDescription
719
+ };
720
+ default:
721
+ assertNever(authConfig, `Unsupported auth config type: ${authConfig.type}`);
722
+ }
723
+ }
724
+ async function handleErrorResponse(doc, ref, def, baseSchemaConvertOptions, converter) {
725
+ const errorMap = def.errorMap;
726
+ const errorResponsesByStatus = {};
727
+ for (const code in errorMap) {
728
+ const errorClass = errorMap[code];
729
+ if (!errorClass) {
730
+ continue;
731
+ }
732
+ const status = errorClass.status;
733
+ const type = errorClass.type;
734
+ const defaultMessage = errorClass.defaultMessage;
735
+ errorResponsesByStatus[status] ??= { status, errorSchemaVariants: [] };
736
+ const extraZod = z.object(errorClass.extraSchema).strict();
737
+ const [, extraSchema] = await converter(extraZod, {
738
+ ...baseSchemaConvertOptions,
739
+ strategy: "output"
740
+ });
741
+ if (!isObjectSchema(extraSchema)) {
742
+ throw new OpenAPIGeneratorError(
743
+ `Error response extra schema must be an object, but got: ${stringifyJSON(extraSchema)}`
744
+ );
745
+ }
746
+ errorResponsesByStatus[status].errorSchemaVariants.push({
747
+ type: "object",
748
+ properties: {
749
+ type: { const: type },
750
+ message: { type: "string", default: defaultMessage },
751
+ ...extraSchema.properties
752
+ },
753
+ required: ["type", "message", ...extraSchema.required ?? []]
754
+ });
755
+ }
756
+ ref.responses ??= {};
757
+ for (const statusString in errorResponsesByStatus) {
758
+ const errorResponse = errorResponsesByStatus[statusString];
759
+ if (statusString === "500") {
760
+ console.log(
761
+ errorResponse.errorSchemaVariants,
762
+ toOpenAPIContent({
763
+ oneOf: errorResponse.errorSchemaVariants
764
+ })
765
+ );
766
+ }
767
+ ref.responses[statusString] = {
768
+ description: statusString,
769
+ content: toOpenAPIContent(
770
+ errorResponse.errorSchemaVariants.length === 1 ? errorResponse.errorSchemaVariants[0] : {
771
+ oneOf: errorResponse.errorSchemaVariants
772
+ }
773
+ )
774
+ };
775
+ }
776
+ }
777
+
778
+ const oo = {
779
+ spec: customOpenAPIOperation
780
+ };
781
+
782
+ export { LOGIC_KEYWORDS, applyCustomOpenAPIOperation, applySchemaOptionality, checkParamsSchema, customOpenAPIOperation, expandArrayableSchema, expandUnionSchema, filterSchemaBranches, generateOpenApiSpec, getCustomOpenAPIOperation, isAnySchema, isFileSchema, isObjectSchema, isPrimitiveSchema, oo, resolveOpenAPIJsonSchemaRef, separateObjectSchema, toOpenAPIContent, toOpenAPIEventIteratorContent, toOpenAPIMethod, toOpenAPIParameters, toOpenAPIPath, toOpenAPISchema };