hono-takibi 0.28.0 → 0.30.0
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.
- package/dist/cli.js +8 -8
- package/dist/core/docs/index.d.ts +1 -1
- package/dist/core/docs/index.js +1 -1
- package/dist/core/hooks/index.d.ts +2 -2
- package/dist/core/hooks/index.js +1 -1
- package/dist/core/rpc/index.d.ts +2 -2
- package/dist/core/rpc/index.js +3 -3
- package/dist/core/type/index.d.ts +1 -1
- package/dist/core/type/index.js +5 -4
- package/dist/{core-D141ZWzp.js → core-C-wH_UxC.js} +6 -6
- package/dist/{docs-CDFG1tXT.js → docs-CDp93aXs.js} +6 -5
- package/dist/generator/zod-openapi-hono/openapi/index.d.ts +1 -1
- package/dist/generator/zod-openapi-hono/openapi/index.js +1 -1
- package/dist/{guard-BH6yBr0M.js → guard-BNQ9WfOm.js} +52 -4
- package/dist/{hooks-CKIK30qr.js → hooks-JLvbNojU.js} +3 -3
- package/dist/{index-DvZscmYm.d.ts → index-DN54hj9W.d.ts} +1 -0
- package/dist/{index-8HyUtaew.d.ts → index-nkUsldwj.d.ts} +1 -1
- package/dist/index.js +1 -1
- package/dist/{openapi-imhqgahL.js → openapi-Bk4KBGJZ.js} +901 -380
- package/dist/openapi-DCo11_TE.js +96 -0
- package/dist/{rpc-GDi7a_Ep.js → rpc-B7PiQ1sR.js} +1 -1
- package/dist/{shared-CyBkG8gM.js → shared-BBl5tC8y.js} +17 -6
- package/dist/{utils-CDLiYepO.js → utils-BhQ-YVD3.js} +58 -3
- package/dist/vite-plugin/index.js +4 -4
- package/package.json +7 -7
- package/dist/openapi-tYYvoKiU.js +0 -34
|
@@ -1,39 +1,7 @@
|
|
|
1
|
-
import { A as
|
|
2
|
-
import { S as zodToOpenAPISchema, _ as routeName, a as ensureSuffix, b as uncapitalize, c as escapeRegexLiteral, d as makeSafeKey, f as makeStringLiteral, g as requestParamsArray, h as renderNamedImport, i as decodePercent, m as regexLiteral, o as error, p as normalizeTypes, r as cyclicNodes, t as baseError, y as toIdentifierPascalCase } from "./utils-
|
|
1
|
+
import { A as isPathItemRef, D as isParameterRef, F as isResponses, G as ARROW_FUNCTION_PATTERN, I as isSchemaArray, J as COMPONENT_SUFFIXES$1, K as COMPONENT_NAMES, L as isSchemaObject, M as isRefObject, N as isRefOnly, O as isPathItem, Q as HTTP_METHODS, S as isOperation, U as isUntypedObject, V as isSingleSchema, W as isValidIdent, Y as FORM_MEDIA_TYPES, b as isOffsetTime, c as isAnnotationOnly, d as isDiscriminableBranch, f as isExamplesInput, h as isInheritedName, i as hasNoUserChain, j as isRecord, k as isPathItemEntry, l as isBinaryFile, n as hasMimeAlternatives, p as isHeader, q as COMPONENT_REF_PREFIX, s as hasTypelessConstraint, t as fileMimeTypes, u as isCallbacks, v as isMedia, w as isParameter } from "./guard-BNQ9WfOm.js";
|
|
2
|
+
import { S as zodToOpenAPISchema, _ as routeName, a as ensureSuffix, b as uncapitalize, c as escapeRegexLiteral, d as makeSafeKey, f as makeStringLiteral, g as requestParamsArray, h as renderNamedImport, i as decodePercent, m as regexLiteral, o as error, p as normalizeTypes, r as cyclicNodes, t as baseError, y as toIdentifierPascalCase } from "./utils-BhQ-YVD3.js";
|
|
3
3
|
import path from "node:path";
|
|
4
4
|
import { parseSync, rawTransferSupported, visitorKeys } from "oxc-parser";
|
|
5
|
-
// src/helper/discriminator.ts
|
|
6
|
-
/**
|
|
7
|
-
* The branches of a discriminated `oneOf`, resolved, when `z.discriminatedUnion` stands for
|
|
8
|
-
* it; `undefined` when the `oneOf` is emitted as `z.xor`. The two are equivalent only when
|
|
9
|
-
* every branch is a plain object that `required`s the discriminator and pins it to string
|
|
10
|
-
* literals (see `isDiscriminableBranch`), and no two branches share a literal.
|
|
11
|
-
*/
|
|
12
|
-
function discriminatedBranches(schema, schemas) {
|
|
13
|
-
const discriminator = schema.discriminator?.propertyName;
|
|
14
|
-
if (discriminator === void 0 || schema.oneOf === void 0 || schema.oneOf.length < 2) return;
|
|
15
|
-
const resolved = schema.oneOf.map((s) => {
|
|
16
|
-
if (s.$ref === void 0) return {
|
|
17
|
-
branch: s,
|
|
18
|
-
name: void 0
|
|
19
|
-
};
|
|
20
|
-
if (!(isRefOnly(s) && s.$ref.startsWith(COMPONENT_REF_PREFIX.schemas))) return void 0;
|
|
21
|
-
const name = decodePercent(s.$ref.slice(COMPONENT_REF_PREFIX.schemas.length));
|
|
22
|
-
const branch = schemas?.[name];
|
|
23
|
-
return branch === void 0 ? void 0 : {
|
|
24
|
-
branch,
|
|
25
|
-
name
|
|
26
|
-
};
|
|
27
|
-
});
|
|
28
|
-
const literalsPerBranch = resolved.map((entry) => {
|
|
29
|
-
if (entry === void 0 || !isDiscriminableBranch(entry.branch, discriminator)) return void 0;
|
|
30
|
-
const property = entry.branch.properties?.[discriminator];
|
|
31
|
-
if (property === void 0 || typeof property === "boolean") return void 0;
|
|
32
|
-
return typeof property.const === "string" ? [property.const] : property.enum ?? [];
|
|
33
|
-
});
|
|
34
|
-
const literals = literalsPerBranch.flatMap((values) => values ?? []);
|
|
35
|
-
return literalsPerBranch.every((values) => values !== void 0) && new Set(literals).size === literals.length ? resolved.filter((entry) => entry !== void 0) : void 0;
|
|
36
|
-
}
|
|
37
5
|
// src/helper/wire.ts
|
|
38
6
|
const INTEGER_TEXT = String.raw`/^-?\d+$/`;
|
|
39
7
|
const NUMBER_TEXT = String.raw`/^-?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?$/`;
|
|
@@ -527,6 +495,61 @@ function isEmptyAbsent(parameter, schemas) {
|
|
|
527
495
|
const kinds = wireKinds(parameter.schema, schemas);
|
|
528
496
|
return kinds === void 0 || !kinds.includes("string");
|
|
529
497
|
}
|
|
498
|
+
// src/helper/discriminator.ts
|
|
499
|
+
/**
|
|
500
|
+
* The branches of a discriminated `oneOf`, resolved, when `z.discriminatedUnion` stands for
|
|
501
|
+
* it; `undefined` when the `oneOf` is emitted as `z.xor`. The two are equivalent only when
|
|
502
|
+
* every branch is a plain object that `required`s the discriminator and pins it to string
|
|
503
|
+
* literals (see `isDiscriminableBranch`), and no two branches share a literal.
|
|
504
|
+
*/
|
|
505
|
+
function discriminatedBranches(schema, schemas) {
|
|
506
|
+
const discriminator = schema.discriminator?.propertyName;
|
|
507
|
+
if (discriminator === void 0 || schema.oneOf === void 0 || schema.oneOf.length < 2) return;
|
|
508
|
+
const resolved = schema.oneOf.map((s) => {
|
|
509
|
+
if (s.$ref === void 0) return {
|
|
510
|
+
branch: s,
|
|
511
|
+
name: void 0
|
|
512
|
+
};
|
|
513
|
+
if (!(isRefOnly(s) && s.$ref.startsWith(COMPONENT_REF_PREFIX.schemas))) return void 0;
|
|
514
|
+
const name = decodePercent(s.$ref.slice(COMPONENT_REF_PREFIX.schemas.length));
|
|
515
|
+
const branch = schemas?.[name];
|
|
516
|
+
return branch === void 0 ? void 0 : {
|
|
517
|
+
branch,
|
|
518
|
+
name
|
|
519
|
+
};
|
|
520
|
+
});
|
|
521
|
+
const literalsPerBranch = resolved.map((entry) => {
|
|
522
|
+
if (entry === void 0 || !isDiscriminableBranch(entry.branch, discriminator)) return void 0;
|
|
523
|
+
const property = entry.branch.properties?.[discriminator];
|
|
524
|
+
if (property === void 0 || typeof property === "boolean") return void 0;
|
|
525
|
+
return typeof property.const === "string" ? [property.const] : property.enum ?? [];
|
|
526
|
+
});
|
|
527
|
+
const literals = literalsPerBranch.flatMap((values) => values ?? []);
|
|
528
|
+
return literalsPerBranch.every((values) => values !== void 0) && new Set(literals).size === literals.length ? resolved.filter((entry) => entry !== void 0) : void 0;
|
|
529
|
+
}
|
|
530
|
+
/**
|
|
531
|
+
* The parent's own object, when an `allOf` member names a parent that lists its subtypes
|
|
532
|
+
* in a `oneOf` / `anyOf` whose members `allOf`-extend it back (a discriminator parent of the
|
|
533
|
+
* MongoDB Atlas kind, #402); `undefined` for any other member. Emitted as the component, the
|
|
534
|
+
* member would name the parent as a whole, which names the subtypes, which name the parent:
|
|
535
|
+
* a cycle that never ends at runtime and that TypeScript cannot type. What a subtype inherits
|
|
536
|
+
* is the parent's `properties` and `required`, so the member stands for those alone.
|
|
537
|
+
*/
|
|
538
|
+
function inheritedBase(member, schemas) {
|
|
539
|
+
if (!isRefOnly(member) || member.$ref === void 0) return void 0;
|
|
540
|
+
const parent = resolveSchemaRef(member.$ref, schemas);
|
|
541
|
+
if (parent === void 0) return void 0;
|
|
542
|
+
const branches = parent.oneOf ?? parent.anyOf;
|
|
543
|
+
if (branches === void 0) return void 0;
|
|
544
|
+
if (!branches.some((branch) => {
|
|
545
|
+
return (branch.$ref === void 0 ? branch : resolveSchemaRef(branch.$ref, schemas))?.allOf?.some((part) => part.$ref === member.$ref) ?? false;
|
|
546
|
+
})) return void 0;
|
|
547
|
+
return {
|
|
548
|
+
type: "object",
|
|
549
|
+
...parent.properties === void 0 ? {} : { properties: parent.properties },
|
|
550
|
+
...parent.required === void 0 ? {} : { required: parent.required }
|
|
551
|
+
};
|
|
552
|
+
}
|
|
530
553
|
// src/helper/openapi.ts
|
|
531
554
|
function makeRef($ref) {
|
|
532
555
|
const propertiesMatch = $ref.match(/^#\/components\/schemas\/([^/]+)\/properties\/(.+)$/u);
|
|
@@ -552,21 +575,49 @@ function makeExamples(examples) {
|
|
|
552
575
|
return `${JSON.stringify(k)}:{${result}}`;
|
|
553
576
|
}).join(",")}}`;
|
|
554
577
|
}
|
|
555
|
-
function makeOperationResponses(responses, readonly) {
|
|
578
|
+
function makeOperationResponses(responses, readonly, schemas) {
|
|
556
579
|
return `{${Object.entries(responses).map(([statusCode, res]) => {
|
|
557
580
|
if (!isResponses(res)) return void 0;
|
|
558
|
-
return `${/^\d+$/u.test(statusCode) ? statusCode : `'${statusCode}'`}:${makeResponses(res, readonly)}`;
|
|
581
|
+
return `${/^\d+$/u.test(statusCode) ? statusCode : `'${statusCode}'`}:${makeResponses(res, readonly, schemas)}`;
|
|
559
582
|
}).filter((v) => v !== void 0).join(",")}}`;
|
|
560
583
|
}
|
|
561
584
|
function makeHeaderResponses(headers, readonly) {
|
|
562
|
-
return `z.object({${Object.entries(headers).map(([k, header]) => `${JSON.stringify(k)}:${
|
|
585
|
+
return `z.object({${Object.entries(headers).map(([k, header]) => `${JSON.stringify(k)}:${makeHeaderSchema(header, readonly)}`).join(",")}})`;
|
|
586
|
+
}
|
|
587
|
+
/**
|
|
588
|
+
* The Zod schema of a response header, as a member of the `z.object()` the response's
|
|
589
|
+
* `headers` is: what the Header Object says about itself (`description`, `required`,
|
|
590
|
+
* `example`) is written into the schema's `.openapi()`, since a `z.object()` takes schemas
|
|
591
|
+
* alone. A header may carry its schema under a single media type in `content` instead of
|
|
592
|
+
* `schema` (#410): that schema is the header's, and the media type's example its example. A
|
|
593
|
+
* reference names the component.
|
|
594
|
+
*/
|
|
595
|
+
function makeHeaderSchema(header, readonly) {
|
|
596
|
+
if ("$ref" in header && header.$ref) return makeRef(header.$ref);
|
|
597
|
+
const options = readonly === true ? { readonly: true } : void 0;
|
|
598
|
+
if ("schema" in header && header.schema) return zodToOpenAPI(header.schema, { headers: header }, options);
|
|
599
|
+
const [media] = "content" in header ? Object.values(header.content ?? {}) : [];
|
|
600
|
+
if ("content" in header && media !== void 0 && isMedia(media)) {
|
|
601
|
+
const { content: _content, ...own } = header;
|
|
602
|
+
const meta = {
|
|
603
|
+
...own,
|
|
604
|
+
...media.example === void 0 ? {} : { example: media.example },
|
|
605
|
+
...media.examples === void 0 ? {} : { examples: media.examples }
|
|
606
|
+
};
|
|
607
|
+
return zodToOpenAPI(media.schema, { headers: meta }, options);
|
|
608
|
+
}
|
|
609
|
+
return zodToOpenAPI({}, { headers: header }, options);
|
|
563
610
|
}
|
|
564
|
-
|
|
611
|
+
/**
|
|
612
|
+
* `schemas` are the document's component schemas: a default beside a reference in a body
|
|
613
|
+
* is read against the component it names (#394), as it is in a component.
|
|
614
|
+
*/
|
|
615
|
+
function makeResponses(responses, readonly, schemas) {
|
|
565
616
|
if (responses.$ref) return makeRef(responses.$ref);
|
|
566
617
|
return `{${[
|
|
567
618
|
responses.summary ? `summary:${JSON.stringify(responses.summary)}` : void 0,
|
|
568
619
|
`description:${JSON.stringify(responses.description ?? "")}`,
|
|
569
|
-
responses.content ? `content:{${makeContent(responses.content, readonly).join(",")}}` : void 0,
|
|
620
|
+
responses.content ? `content:{${makeContent(responses.content, readonly, void 0, schemas).join(",")}}` : void 0,
|
|
570
621
|
responses.headers ? `headers:${makeHeaderResponses(responses.headers, readonly)}` : void 0,
|
|
571
622
|
responses.links ? `links:{${Object.entries(responses.links).map(([key, link]) => "$ref" in link && link.$ref ? `${JSON.stringify(key)}:${makeRef(link.$ref)}` : `${JSON.stringify(key)}:${makeLinkOrReference(link)}`).join(",")}}` : void 0
|
|
572
623
|
].filter((v) => v !== void 0).join(",")}}`;
|
|
@@ -582,7 +633,7 @@ function makeHeadersAndReferences(headers, readonly) {
|
|
|
582
633
|
"style" in headers && headers.style ? `style:${JSON.stringify(headers.style)}` : void 0,
|
|
583
634
|
"explode" in headers && headers.explode ? `explode:${JSON.stringify(headers.explode)}` : void 0,
|
|
584
635
|
"schema" in headers && headers.schema ? `schema:${zodToOpenAPI(headers.schema, { headers }, readonly === true ? { readonly: true } : void 0)}` : void 0,
|
|
585
|
-
"content" in headers && headers.content ? `content
|
|
636
|
+
"content" in headers && headers.content ? `content:{${makeContent(headers.content, readonly).join(",")}}` : void 0
|
|
586
637
|
].filter((v) => v !== void 0).join(",")}}`;
|
|
587
638
|
}
|
|
588
639
|
function makeLinkOrReference(linkOrReference) {
|
|
@@ -624,13 +675,13 @@ function makeCallbacks(callbacks, readonly) {
|
|
|
624
675
|
return nestedCode ? `${JSON.stringify(callbackKey)}:{${nestedCode}}` : void 0;
|
|
625
676
|
}).filter((v) => v !== void 0).join(",");
|
|
626
677
|
}
|
|
627
|
-
function makeContent(content, readonly, request) {
|
|
678
|
+
function makeContent(content, readonly, request, schemas) {
|
|
628
679
|
return Object.freeze(Object.entries(content).map(([contentType, mediaOrRef]) => {
|
|
629
680
|
const key = /^[A-Za-z0-9!#$&^_+\-./*;= ]+$/u.test(contentType) ? `'${contentType}'` : JSON.stringify(contentType);
|
|
630
681
|
if (isRefObject(mediaOrRef)) return mediaOrRef.$ref.startsWith(COMPONENT_REF_PREFIX.mediaTypes) ? `${key}:{schema:${makeRef(mediaOrRef.$ref)}}` : `${key}:${makeRef(mediaOrRef.$ref)}`;
|
|
631
682
|
if (isMedia(mediaOrRef)) {
|
|
632
683
|
const mediaType = contentType.toLowerCase();
|
|
633
|
-
return `${key}:${makeMedia(mediaOrRef, readonly, request !== void 0 && FORM_MEDIA_TYPES.some((formType) => mediaType.startsWith(formType)) ? request : void 0)}`;
|
|
684
|
+
return `${key}:${makeMedia(mediaOrRef, readonly, request !== void 0 && FORM_MEDIA_TYPES.some((formType) => mediaType.startsWith(formType)) ? request : void 0, schemas ?? request?.schemas)}`;
|
|
634
685
|
}
|
|
635
686
|
}).filter((v) => v !== void 0));
|
|
636
687
|
}
|
|
@@ -647,14 +698,15 @@ function makeRequestBody(body, readonly, schemas) {
|
|
|
647
698
|
* `multipart/form-data`). Every field of a form arrives as text — or as a file — so its
|
|
648
699
|
* schema reads text where a JSON body is already typed.
|
|
649
700
|
*/
|
|
650
|
-
function makeMedia(media, readonly, form) {
|
|
701
|
+
function makeMedia(media, readonly, form, schemas) {
|
|
702
|
+
const components = schemas ?? form?.schemas;
|
|
651
703
|
const schemaOptions = {
|
|
652
704
|
...readonly === true ? { readonly: true } : {},
|
|
653
705
|
...form === void 0 ? {} : {
|
|
654
706
|
coerce: true,
|
|
655
707
|
form: true
|
|
656
708
|
},
|
|
657
|
-
...
|
|
709
|
+
...components === void 0 ? {} : { schemas: components }
|
|
658
710
|
};
|
|
659
711
|
const encodingCode = media.encoding ? Object.entries(media.encoding).map(([name, encoding]) => `${JSON.stringify(name)}:{${makeEncoding(encoding, readonly)}}`).join(",") : void 0;
|
|
660
712
|
return `{${[
|
|
@@ -820,7 +872,7 @@ function makeRouteProperties(path, method, operation, readonly, schemas) {
|
|
|
820
872
|
operation.externalDocs ? `externalDocs:${JSON.stringify(operation.externalDocs)}` : void 0,
|
|
821
873
|
operation.operationId ? `operationId:${JSON.stringify(operation.operationId)}` : void 0,
|
|
822
874
|
request ? `request:${request}` : void 0,
|
|
823
|
-
operation.responses ? `responses:${makeOperationResponses(operation.responses, readonly)}` : void 0,
|
|
875
|
+
operation.responses ? `responses:${makeOperationResponses(operation.responses, readonly, schemas)}` : void 0,
|
|
824
876
|
operation.callbacks ? `callbacks:{${makeCallbacks(operation.callbacks, readonly)}}` : void 0,
|
|
825
877
|
operation.deprecated ? `deprecated:${JSON.stringify(operation.deprecated)}` : void 0,
|
|
826
878
|
operation.security ? `security:${JSON.stringify(operation.security)}` : void 0,
|
|
@@ -922,7 +974,195 @@ function makeWebhookEntries(openapi, readonly) {
|
|
|
922
974
|
}) : []);
|
|
923
975
|
}
|
|
924
976
|
// src/helper/wrap.ts
|
|
925
|
-
|
|
977
|
+
/**
|
|
978
|
+
* The keys of a Schema Object (OpenAPI 3.1 §4.8.24, the type `.openapi()` and `param.schema`
|
|
979
|
+
* take), plus `x-` extensions. Whatever else a document carries — `$schema`, `$id`,
|
|
980
|
+
* `$defs` (#377), ajv-errors' `errorMessage` (#393) — has no place in the metadata: written
|
|
981
|
+
* there, the call does not type-check. `nullable` is the 3.0 spelling of a `null` type.
|
|
982
|
+
*/
|
|
983
|
+
const SCHEMA_OBJECT_KEYS = /* @__PURE__ */ new Set([
|
|
984
|
+
"$ref",
|
|
985
|
+
"discriminator",
|
|
986
|
+
"readOnly",
|
|
987
|
+
"writeOnly",
|
|
988
|
+
"xml",
|
|
989
|
+
"externalDocs",
|
|
990
|
+
"example",
|
|
991
|
+
"examples",
|
|
992
|
+
"deprecated",
|
|
993
|
+
"type",
|
|
994
|
+
"format",
|
|
995
|
+
"allOf",
|
|
996
|
+
"oneOf",
|
|
997
|
+
"anyOf",
|
|
998
|
+
"not",
|
|
999
|
+
"items",
|
|
1000
|
+
"properties",
|
|
1001
|
+
"additionalProperties",
|
|
1002
|
+
"propertyNames",
|
|
1003
|
+
"description",
|
|
1004
|
+
"default",
|
|
1005
|
+
"title",
|
|
1006
|
+
"multipleOf",
|
|
1007
|
+
"maximum",
|
|
1008
|
+
"const",
|
|
1009
|
+
"exclusiveMaximum",
|
|
1010
|
+
"minimum",
|
|
1011
|
+
"exclusiveMinimum",
|
|
1012
|
+
"maxLength",
|
|
1013
|
+
"minLength",
|
|
1014
|
+
"pattern",
|
|
1015
|
+
"maxItems",
|
|
1016
|
+
"minItems",
|
|
1017
|
+
"uniqueItems",
|
|
1018
|
+
"maxProperties",
|
|
1019
|
+
"minProperties",
|
|
1020
|
+
"required",
|
|
1021
|
+
"enum",
|
|
1022
|
+
"prefixItems",
|
|
1023
|
+
"contentMediaType",
|
|
1024
|
+
"contentEncoding",
|
|
1025
|
+
"nullable"
|
|
1026
|
+
]);
|
|
1027
|
+
/** Whether a key belongs to a Schema Object as written: one of its own, or an extension. */
|
|
1028
|
+
function isSchemaObjectKey(key) {
|
|
1029
|
+
return SCHEMA_OBJECT_KEYS.has(key) || key.startsWith("x-");
|
|
1030
|
+
}
|
|
1031
|
+
const TYPE_NAMES = /* @__PURE__ */ new Set([
|
|
1032
|
+
"integer",
|
|
1033
|
+
"number",
|
|
1034
|
+
"string",
|
|
1035
|
+
"boolean",
|
|
1036
|
+
"object",
|
|
1037
|
+
"null",
|
|
1038
|
+
"array"
|
|
1039
|
+
]);
|
|
1040
|
+
function isTypeName(value) {
|
|
1041
|
+
return typeof value === "string" && TYPE_NAMES.has(value);
|
|
1042
|
+
}
|
|
1043
|
+
/**
|
|
1044
|
+
* What each Schema Object key's value is: the type `.openapi()` and `param.schema` take for
|
|
1045
|
+
* it. A value of another type does not type-check once written (#419) — a `minimum` written
|
|
1046
|
+
* as text (`"'created_at' - 21 days"`, Revolut), a `discriminator` without its
|
|
1047
|
+
* `propertyName` — so it is left out, as a key the Schema Object has not is. `exclusiveMinimum`
|
|
1048
|
+
* and `exclusiveMaximum` are numbers in 3.1 and booleans in 3.0; `type` is a type name or a
|
|
1049
|
+
* list of them. A key absent here (`default`, `example`, `const`) takes any value.
|
|
1050
|
+
*/
|
|
1051
|
+
const SCHEMA_OBJECT_VALUE_TYPES = {
|
|
1052
|
+
$ref: (v) => typeof v === "string",
|
|
1053
|
+
discriminator: (v) => isRecord(v) && typeof v.propertyName === "string",
|
|
1054
|
+
readOnly: (v) => typeof v === "boolean",
|
|
1055
|
+
writeOnly: (v) => typeof v === "boolean",
|
|
1056
|
+
deprecated: (v) => typeof v === "boolean",
|
|
1057
|
+
uniqueItems: (v) => typeof v === "boolean",
|
|
1058
|
+
nullable: (v) => typeof v === "boolean",
|
|
1059
|
+
xml: isRecord,
|
|
1060
|
+
externalDocs: (v) => isRecord(v) && typeof v.url === "string",
|
|
1061
|
+
type: (v) => isTypeName(v) || Array.isArray(v) && v.length > 0 && v.every(isTypeName),
|
|
1062
|
+
format: (v) => typeof v === "string",
|
|
1063
|
+
description: (v) => typeof v === "string",
|
|
1064
|
+
title: (v) => typeof v === "string",
|
|
1065
|
+
pattern: (v) => typeof v === "string",
|
|
1066
|
+
contentMediaType: (v) => typeof v === "string",
|
|
1067
|
+
contentEncoding: (v) => typeof v === "string",
|
|
1068
|
+
multipleOf: (v) => typeof v === "number",
|
|
1069
|
+
maximum: (v) => typeof v === "number",
|
|
1070
|
+
minimum: (v) => typeof v === "number",
|
|
1071
|
+
exclusiveMaximum: (v) => typeof v === "number" || typeof v === "boolean",
|
|
1072
|
+
exclusiveMinimum: (v) => typeof v === "number" || typeof v === "boolean",
|
|
1073
|
+
maxLength: (v) => typeof v === "number",
|
|
1074
|
+
minLength: (v) => typeof v === "number",
|
|
1075
|
+
maxItems: (v) => typeof v === "number",
|
|
1076
|
+
minItems: (v) => typeof v === "number",
|
|
1077
|
+
maxProperties: (v) => typeof v === "number",
|
|
1078
|
+
minProperties: (v) => typeof v === "number",
|
|
1079
|
+
required: Array.isArray,
|
|
1080
|
+
enum: Array.isArray,
|
|
1081
|
+
allOf: Array.isArray,
|
|
1082
|
+
oneOf: Array.isArray,
|
|
1083
|
+
anyOf: Array.isArray,
|
|
1084
|
+
prefixItems: Array.isArray,
|
|
1085
|
+
items: isRecord,
|
|
1086
|
+
not: isRecord,
|
|
1087
|
+
propertyNames: isRecord,
|
|
1088
|
+
additionalProperties: (v) => typeof v === "boolean" || isRecord(v),
|
|
1089
|
+
properties: isRecord
|
|
1090
|
+
};
|
|
1091
|
+
/** Whether a Schema Object key's value has the type the key takes. */
|
|
1092
|
+
function hasSchemaObjectValueType(key, value) {
|
|
1093
|
+
const check = SCHEMA_OBJECT_VALUE_TYPES[key];
|
|
1094
|
+
return check === void 0 || check(value);
|
|
1095
|
+
}
|
|
1096
|
+
const SCHEMA_VALUED_KEYS = /* @__PURE__ */ new Set([
|
|
1097
|
+
"items",
|
|
1098
|
+
"not",
|
|
1099
|
+
"additionalProperties",
|
|
1100
|
+
"propertyNames"
|
|
1101
|
+
]);
|
|
1102
|
+
const SCHEMA_LIST_KEYS = /* @__PURE__ */ new Set([
|
|
1103
|
+
"allOf",
|
|
1104
|
+
"oneOf",
|
|
1105
|
+
"anyOf",
|
|
1106
|
+
"prefixItems"
|
|
1107
|
+
]);
|
|
1108
|
+
const SCHEMA_MAP_KEYS = /* @__PURE__ */ new Set(["properties"]);
|
|
1109
|
+
/**
|
|
1110
|
+
* A schema as a Schema Object for the document: only the keys a Schema Object has, each
|
|
1111
|
+
* with a value of the type it takes, at every level. A `required` member YAML read as a
|
|
1112
|
+
* literal (`null`, `true`) is a string; a 3.0-style `examples` map is its values. The output
|
|
1113
|
+
* is what `.openapi()` is handed, so nothing in it may fail to type-check.
|
|
1114
|
+
*/
|
|
1115
|
+
function pruneSchemaObject(schema) {
|
|
1116
|
+
if (!isRecord(schema)) return schema;
|
|
1117
|
+
const pruned = {};
|
|
1118
|
+
for (const [key, value] of Object.entries(schema)) {
|
|
1119
|
+
if (value === void 0 || !isSchemaObjectKey(key)) continue;
|
|
1120
|
+
if (!hasSchemaObjectValueType(key, value)) continue;
|
|
1121
|
+
if (key === "required" && Array.isArray(value)) {
|
|
1122
|
+
pruned[key] = value.map((v) => typeof v === "string" ? v : String(v));
|
|
1123
|
+
continue;
|
|
1124
|
+
}
|
|
1125
|
+
if (key === "examples") {
|
|
1126
|
+
const list = examplesList(value);
|
|
1127
|
+
if (list !== void 0) pruned[key] = list;
|
|
1128
|
+
continue;
|
|
1129
|
+
}
|
|
1130
|
+
if (key === "discriminator" && isRecord(value)) {
|
|
1131
|
+
const mapping = isRecord(value.mapping) ? Object.entries(value.mapping).filter(([, v]) => typeof v === "string") : void 0;
|
|
1132
|
+
pruned[key] = {
|
|
1133
|
+
propertyName: value.propertyName,
|
|
1134
|
+
...mapping === void 0 ? {} : { mapping: Object.fromEntries(mapping) }
|
|
1135
|
+
};
|
|
1136
|
+
continue;
|
|
1137
|
+
}
|
|
1138
|
+
if (SCHEMA_VALUED_KEYS.has(key)) {
|
|
1139
|
+
pruned[key] = pruneSchemaObject(value);
|
|
1140
|
+
continue;
|
|
1141
|
+
}
|
|
1142
|
+
if (SCHEMA_LIST_KEYS.has(key) && Array.isArray(value)) {
|
|
1143
|
+
pruned[key] = value.map(pruneSchemaObject);
|
|
1144
|
+
continue;
|
|
1145
|
+
}
|
|
1146
|
+
if (SCHEMA_MAP_KEYS.has(key) && isRecord(value)) {
|
|
1147
|
+
pruned[key] = Object.fromEntries(Object.entries(value).map(([name, sub]) => [name, pruneSchemaObject(sub)]));
|
|
1148
|
+
continue;
|
|
1149
|
+
}
|
|
1150
|
+
pruned[key] = value;
|
|
1151
|
+
}
|
|
1152
|
+
return pruned;
|
|
1153
|
+
}
|
|
1154
|
+
/**
|
|
1155
|
+
* `examples` as the Schema Object has it, a list of values: a list is taken as it is, and a
|
|
1156
|
+
* map of Example Objects (the 3.0 shape of a Header or Parameter Object, #398) is reduced to
|
|
1157
|
+
* the values its entries carry. A map whose entries carry none (`externalValue`, `$ref`) has
|
|
1158
|
+
* nothing the schema can state: `undefined`.
|
|
1159
|
+
*/
|
|
1160
|
+
function examplesList(examples) {
|
|
1161
|
+
if (Array.isArray(examples)) return Array.from(examples, (example) => example);
|
|
1162
|
+
if (!isRecord(examples)) return void 0;
|
|
1163
|
+
const values = Object.values(examples).flatMap((example) => isRecord(example) && "value" in example && example.value !== void 0 ? [example.value] : []);
|
|
1164
|
+
return values.length > 0 ? values : void 0;
|
|
1165
|
+
}
|
|
926
1166
|
const zodExpressedProps = /* @__PURE__ */ new Set([
|
|
927
1167
|
"type",
|
|
928
1168
|
"format",
|
|
@@ -975,6 +1215,7 @@ const zodExpressedProps = /* @__PURE__ */ new Set([
|
|
|
975
1215
|
"x-dependentSchemas-message",
|
|
976
1216
|
"x-minLength-message",
|
|
977
1217
|
"x-maxLength-message",
|
|
1218
|
+
"x-contentMediaType-message",
|
|
978
1219
|
"x-minItems-message",
|
|
979
1220
|
"x-maxItems-message",
|
|
980
1221
|
"x-minProperties-message",
|
|
@@ -1083,10 +1324,11 @@ const PARAMETER_KEYS = /* @__PURE__ */ new Set([
|
|
|
1083
1324
|
function makeSerializedParam(param) {
|
|
1084
1325
|
return `{${Object.entries(param).filter(([key, value]) => value !== void 0 && (PARAMETER_KEYS.has(key) || key.startsWith("x-"))).map(([key, value]) => {
|
|
1085
1326
|
if (key === "examples" && isExamplesInput(value)) return `"examples":${makeExamples(value)}`;
|
|
1327
|
+
if (key === "schema") return `"schema":${JSON.stringify(pruneSchemaObject(value))}`;
|
|
1086
1328
|
if (key === "content" && isRecord(value)) return `"content":{${Object.entries(value).map(([mediaType, mediaObj]) => {
|
|
1087
1329
|
if (!isRecord(mediaObj)) return `${JSON.stringify(mediaType)}:${JSON.stringify(mediaObj)}`;
|
|
1088
1330
|
const { examples: mediaExamples, ...mediaRest } = mediaObj;
|
|
1089
|
-
const restEntries = Object.entries(mediaRest).filter(([, v]) => v !== void 0).map(([k, v]) => `${JSON.stringify(k)}:${JSON.stringify(v)}`);
|
|
1331
|
+
const restEntries = Object.entries(mediaRest).filter(([, v]) => v !== void 0).map(([k, v]) => `${JSON.stringify(k)}:${JSON.stringify(k === "schema" ? pruneSchemaObject(v) : v)}`);
|
|
1090
1332
|
const examplesEntry = isExamplesInput(mediaExamples) ? `"examples":${makeExamples(mediaExamples)}` : void 0;
|
|
1091
1333
|
const mediaEntries = examplesEntry ? [...restEntries, examplesEntry] : restEntries;
|
|
1092
1334
|
return `${JSON.stringify(mediaType)}:{${mediaEntries.join(",")}}`;
|
|
@@ -1121,6 +1363,21 @@ function conformDefault(schema, value, schemas, reading = /* @__PURE__ */ new Se
|
|
|
1121
1363
|
...beside
|
|
1122
1364
|
}, value, schemas, /* @__PURE__ */ new Set([...reading, schema.$ref]));
|
|
1123
1365
|
}
|
|
1366
|
+
if (schema.allOf !== void 0 && schema.allOf.length > 0) {
|
|
1367
|
+
const { allOf, default: _default, ...beside } = schema;
|
|
1368
|
+
return [...allOf, beside].reduce((read, member) => read.ok ? conformDefault(member, read.value, schemas, reading) : read, {
|
|
1369
|
+
ok: true,
|
|
1370
|
+
value
|
|
1371
|
+
});
|
|
1372
|
+
}
|
|
1373
|
+
const branches = schema.oneOf ?? schema.anyOf;
|
|
1374
|
+
if (branches !== void 0 && branches.length > 0) {
|
|
1375
|
+
const read = branches.map((branch) => conformDefault(branch, value, schemas, reading));
|
|
1376
|
+
const taken = read.find((result) => result.ok && result.value === value) ?? read.find((result) => result.ok);
|
|
1377
|
+
if (taken !== void 0) return taken;
|
|
1378
|
+
const { oneOf: _oneOf, anyOf: _anyOf, default: _default, ...beside } = schema;
|
|
1379
|
+
return beside.type !== void 0 || beside.enum !== void 0 || beside.const !== void 0 || beside.allOf !== void 0 ? conformDefault(beside, value, schemas, reading) : { ok: false };
|
|
1380
|
+
}
|
|
1124
1381
|
if (schema.enum !== void 0) return schema.enum.some((member) => member === value) ? {
|
|
1125
1382
|
ok: true,
|
|
1126
1383
|
value
|
|
@@ -1156,6 +1413,7 @@ function conformDefault(schema, value, schemas, reading = /* @__PURE__ */ new Se
|
|
|
1156
1413
|
};
|
|
1157
1414
|
}
|
|
1158
1415
|
if (type === "string") {
|
|
1416
|
+
if (isBinaryFile(schema)) return void 0;
|
|
1159
1417
|
if (typeof value === "string") return {
|
|
1160
1418
|
ok: true,
|
|
1161
1419
|
value
|
|
@@ -1212,36 +1470,15 @@ function typeOf(value) {
|
|
|
1212
1470
|
if (isRecord(value)) return "object";
|
|
1213
1471
|
}
|
|
1214
1472
|
function wrap(zod, schema, meta, options) {
|
|
1215
|
-
const unsupportedProps = /* @__PURE__ */ new Set([
|
|
1216
|
-
"$recursiveRef",
|
|
1217
|
-
"$recursiveAnchor",
|
|
1218
|
-
"optional",
|
|
1219
|
-
"min_items",
|
|
1220
|
-
"max_items"
|
|
1221
|
-
]);
|
|
1222
|
-
const filterUnsupportedProps = (obj) => {
|
|
1223
|
-
if (obj === null || typeof obj !== "object") return obj;
|
|
1224
|
-
if (Array.isArray(obj)) return obj.map(filterUnsupportedProps);
|
|
1225
|
-
const filtered = {};
|
|
1226
|
-
for (const [key, value] of Object.entries(obj)) {
|
|
1227
|
-
if (unsupportedProps.has(key)) continue;
|
|
1228
|
-
if (key === "items" && (typeof value === "boolean" || Array.isArray(value))) continue;
|
|
1229
|
-
if (key === "not" && hasNotProperty(value) && typeof value.not === "boolean") continue;
|
|
1230
|
-
if (key === "required" && Array.isArray(value)) {
|
|
1231
|
-
filtered[key] = value.map((v) => typeof v === "string" ? v : String(v));
|
|
1232
|
-
continue;
|
|
1233
|
-
}
|
|
1234
|
-
filtered[key] = filterUnsupportedProps(value);
|
|
1235
|
-
}
|
|
1236
|
-
return filtered;
|
|
1237
|
-
};
|
|
1238
1473
|
const typeList = Array.isArray(schema.type) ? schema.type : schema.type !== void 0 ? [schema.type] : [];
|
|
1239
1474
|
const formatLiteral = (v) => {
|
|
1240
1475
|
if (v === void 0) return "undefined";
|
|
1241
1476
|
if (typeof v === "boolean") return `${v}`;
|
|
1242
1477
|
if (typeof v === "number") {
|
|
1243
|
-
if (
|
|
1244
|
-
|
|
1478
|
+
if (typeList.includes("integer")) {
|
|
1479
|
+
if (schema.format === "int64" || schema.format === "uint64") return `${v}n`;
|
|
1480
|
+
if (schema.format === "bigint") return `BigInt(${v})`;
|
|
1481
|
+
}
|
|
1245
1482
|
return `${v}`;
|
|
1246
1483
|
}
|
|
1247
1484
|
if (schema.type === "date" && typeof v === "string") return `new Date(${JSON.stringify(v)})`;
|
|
@@ -1284,22 +1521,34 @@ function wrap(zod, schema, meta, options) {
|
|
|
1284
1521
|
};
|
|
1285
1522
|
const z = absent(build(around(zod)));
|
|
1286
1523
|
const headerDupKeys = new Set(meta?.headers ? Object.entries(meta.headers).filter(([, v]) => v !== void 0).map(([k]) => k) : []);
|
|
1287
|
-
const
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
...
|
|
1524
|
+
const isBigintInteger = meta?.parameters === void 0 && typeList.includes("integer") && (schema.format === "int64" || schema.format === "uint64" || schema.format === "bigint") && hasNoUserChain(schema);
|
|
1525
|
+
const isFile = isBinaryFile(schema);
|
|
1526
|
+
const args = pruneSchemaObject(Object.fromEntries([
|
|
1527
|
+
...Object.entries(schema).filter(([k, v]) => isSchemaObjectKey(k) && !(zodExpressedProps.has(k) || k === "required" && typeof v === "boolean" || headerDupKeys.has(k))),
|
|
1528
|
+
...droppedDefault && !isBigintInteger ? [["default", schema.default]] : [],
|
|
1529
|
+
...typeof schema.pattern === "string" && (isFile || regexLiteral(schema.pattern) === void 0) ? [["pattern", schema.pattern]] : []
|
|
1291
1530
|
]));
|
|
1292
1531
|
const headerMetaProps = meta?.headers ? [
|
|
1293
1532
|
meta.headers.description ? `description:${JSON.stringify(meta.headers.description)}` : void 0,
|
|
1294
1533
|
meta.headers.deprecated ? `deprecated:${JSON.stringify(meta.headers.deprecated)}` : void 0,
|
|
1295
1534
|
meta.headers.example ? `example:${JSON.stringify(meta.headers.example)}` : void 0,
|
|
1296
|
-
|
|
1535
|
+
...(() => {
|
|
1536
|
+
const list = examplesList(meta.headers.examples);
|
|
1537
|
+
return list === void 0 ? [] : [`examples:${JSON.stringify(list)}`];
|
|
1538
|
+
})()
|
|
1297
1539
|
].filter((v) => v !== void 0) : [];
|
|
1298
1540
|
const openapiSchema = args ? JSON.stringify(args) : void 0;
|
|
1299
1541
|
const openapiSchemaBody = openapiSchema?.startsWith("{") && openapiSchema?.endsWith("}") ? openapiSchema.slice(1, -1) : openapiSchema;
|
|
1300
|
-
const
|
|
1542
|
+
const fileMimes = isFile ? fileMimeTypes(schema) : void 0;
|
|
1543
|
+
const fileMetaProps = isFile ? [
|
|
1544
|
+
isNullable ? "type:[\"string\",\"null\"]" : "type:\"string\"",
|
|
1545
|
+
"format:\"binary\"",
|
|
1546
|
+
...typeof schema.minLength === "number" ? [`minLength:${schema.minLength}`] : [],
|
|
1547
|
+
...typeof schema.maxLength === "number" ? [`maxLength:${schema.maxLength}`] : [],
|
|
1548
|
+
...fileMimes === void 0 ? [] : [`anyOf:${JSON.stringify(fileMimes.map((contentMediaType) => ({ contentMediaType })))}`]
|
|
1549
|
+
] : [];
|
|
1301
1550
|
const timeMetaProps = schema.format === "time" && schema["x-isoOffset"] !== false && typeList.includes("string") && schema.contentEncoding === void 0 && schema.contentMediaType === void 0 && schema.contentSchema === void 0 && hasNoUserChain(schema) ? ["format:\"time\""] : [];
|
|
1302
|
-
const bigintMetaProps =
|
|
1551
|
+
const bigintMetaProps = isBigintInteger ? [
|
|
1303
1552
|
isNullable ? "type:[\"integer\",\"null\"]" : "type:\"integer\"",
|
|
1304
1553
|
`format:${JSON.stringify(schema.format)}`,
|
|
1305
1554
|
...[
|
|
@@ -1548,19 +1797,25 @@ function makePatternPropsStmt(sub) {
|
|
|
1548
1797
|
const patterns = Object.keys(sub.patternProperties);
|
|
1549
1798
|
return `for(const k of Object.keys(o)){for(const p of ${JSON.stringify(patterns)}){if(new RegExp(p).test(k)){e.add(k)}}}`;
|
|
1550
1799
|
}
|
|
1551
|
-
function collectAllOfStmts(list) {
|
|
1552
|
-
return list.flatMap((sub) =>
|
|
1553
|
-
|
|
1554
|
-
|
|
1555
|
-
|
|
1556
|
-
|
|
1800
|
+
function collectAllOfStmts(list, schemas, reading = /* @__PURE__ */ new Set()) {
|
|
1801
|
+
return list.flatMap((sub) => {
|
|
1802
|
+
if (sub.$ref !== void 0) {
|
|
1803
|
+
const target = reading.has(sub.$ref) ? void 0 : resolveSchemaRef(sub.$ref, schemas);
|
|
1804
|
+
return target === void 0 ? [] : collectAllOfStmts([target], schemas, /* @__PURE__ */ new Set([...reading, sub.$ref]));
|
|
1805
|
+
}
|
|
1806
|
+
return [
|
|
1807
|
+
makeOwnPropsStmt(sub),
|
|
1808
|
+
makePatternPropsStmt(sub),
|
|
1809
|
+
...sub.allOf ? collectAllOfStmts(sub.allOf, schemas, reading) : []
|
|
1810
|
+
].filter((s) => s !== void 0);
|
|
1811
|
+
});
|
|
1557
1812
|
}
|
|
1558
1813
|
function conditionalBranchStmt(sub, recurse) {
|
|
1559
1814
|
if (!sub.properties && !sub.patternProperties) return;
|
|
1560
1815
|
const ifBody = [makeOwnPropsStmt(sub), makePatternPropsStmt(sub)].filter((s) => s !== void 0).join(";");
|
|
1561
1816
|
return ifBody ? `if(${recurse(sub)}.safeParse(o).success){${ifBody}}` : void 0;
|
|
1562
1817
|
}
|
|
1563
|
-
function makeUnevaluatedEvaluationStmts(schema, recurse) {
|
|
1818
|
+
function makeUnevaluatedEvaluationStmts(schema, recurse, schemas) {
|
|
1564
1819
|
const branchStmts = (branches) => branches ? branches.map((sub) => conditionalBranchStmt(sub, recurse)).filter((s) => s !== void 0) : [];
|
|
1565
1820
|
const ifSchema = schema.if;
|
|
1566
1821
|
const ifStmts = ifSchema ? (() => {
|
|
@@ -1583,7 +1838,7 @@ function makeUnevaluatedEvaluationStmts(schema, recurse) {
|
|
|
1583
1838
|
"const e=new Set()",
|
|
1584
1839
|
makeOwnPropsStmt(schema),
|
|
1585
1840
|
makePatternPropsStmt(schema),
|
|
1586
|
-
...schema.allOf ? collectAllOfStmts(schema.allOf) : [],
|
|
1841
|
+
...schema.allOf ? collectAllOfStmts(schema.allOf, schemas) : [],
|
|
1587
1842
|
...branchStmts(schema.anyOf),
|
|
1588
1843
|
...branchStmts(schema.oneOf),
|
|
1589
1844
|
...ifStmts,
|
|
@@ -1596,19 +1851,39 @@ function makeUnevaluatedMessageField(schema, messageOverride) {
|
|
|
1596
1851
|
const finalMessage = slotMessage ?? overrideMessage;
|
|
1597
1852
|
return finalMessage !== void 0 ? `,message:${finalMessage}` : "";
|
|
1598
1853
|
}
|
|
1599
|
-
function makeUnevaluatedProperties(schema, recurse, messageOverride) {
|
|
1854
|
+
function makeUnevaluatedProperties(schema, recurse, messageOverride, schemas) {
|
|
1600
1855
|
const up = schema.unevaluatedProperties;
|
|
1601
1856
|
if (up === void 0 || up === true) return "";
|
|
1602
1857
|
const messageField = makeUnevaluatedMessageField(schema, messageOverride);
|
|
1603
1858
|
const finalStmt = up === false ? `for(const k of Object.keys(o)){if(!e.has(k)){ctx.addIssue({code:"custom",path:[k]${messageField}})}}` : `const Schema=${recurse(up)};for(const [k,val] of Object.entries(o)){if(e.has(k)){continue}const result=Schema.safeParse(val);if(!result.success){for(const issue of result.error.issues){ctx.addIssue({...issue,path:[k,...issue.path]})}}}`;
|
|
1604
|
-
return `.superRefine((o,ctx)=>{${[...makeUnevaluatedEvaluationStmts(schema, recurse), finalStmt].join(";")}})`;
|
|
1859
|
+
return `.superRefine((o,ctx)=>{${[...makeUnevaluatedEvaluationStmts(schema, recurse, schemas), finalStmt].join(";")}})`;
|
|
1860
|
+
}
|
|
1861
|
+
const ISSUE_CODES = [
|
|
1862
|
+
"invalid_type",
|
|
1863
|
+
"too_big",
|
|
1864
|
+
"too_small",
|
|
1865
|
+
"invalid_format",
|
|
1866
|
+
"not_multiple_of",
|
|
1867
|
+
"unrecognized_keys",
|
|
1868
|
+
"invalid_union",
|
|
1869
|
+
"invalid_key",
|
|
1870
|
+
"invalid_element",
|
|
1871
|
+
"invalid_value",
|
|
1872
|
+
"custom"
|
|
1873
|
+
];
|
|
1874
|
+
/**
|
|
1875
|
+
* The statement that forwards `issue` into `ctx.issues`, narrowed by its code. `pushArg` is
|
|
1876
|
+
* the raw issue as source, built from `issue` (`{...issue,input:issue.input,path:[...]}`).
|
|
1877
|
+
*/
|
|
1878
|
+
function makeIssueForwarding(pushArg) {
|
|
1879
|
+
return ISSUE_CODES.map((code, i) => `${i === 0 ? "" : "else "}if(issue.code==='${code}'){ctx.issues.push(${pushArg})}`).join("");
|
|
1605
1880
|
}
|
|
1606
|
-
function makeUnevaluatedPropertiesCheck(schema, recurse, messageOverride) {
|
|
1881
|
+
function makeUnevaluatedPropertiesCheck(schema, recurse, messageOverride, schemas) {
|
|
1607
1882
|
const up = schema.unevaluatedProperties;
|
|
1608
1883
|
if (up === void 0 || up === true) return "";
|
|
1609
1884
|
const messageField = makeUnevaluatedMessageField(schema, messageOverride);
|
|
1610
|
-
const finalStmt = up === false ? `for(const k of Object.keys(o)){if(!e.has(k)){ctx.issues.push({code:"custom",path:[k],input:o${messageField}})}}` : `const Schema=${recurse(up)};for(const [k,val] of Object.entries(o)){if(e.has(k)){continue}const result=Schema.safeParse(val);if(!result.success){for(const issue of result.error.issues){
|
|
1611
|
-
return `(ctx)=>{const o=ctx.value;if(typeof o!=='object'||o===null||Array.isArray(o))return;${[...makeUnevaluatedEvaluationStmts(schema, recurse), finalStmt].join(";")}}`;
|
|
1885
|
+
const finalStmt = up === false ? `for(const k of Object.keys(o)){if(!e.has(k)){ctx.issues.push({code:"custom",path:[k],input:o${messageField}})}}` : `const Schema=${recurse(up)};for(const [k,val] of Object.entries(o)){if(e.has(k)){continue}const result=Schema.safeParse(val);if(!result.success){for(const issue of result.error.issues){${makeIssueForwarding("{...issue,path:[k,...issue.path],input:issue.input}")}}}}`;
|
|
1886
|
+
return `(ctx)=>{const o=ctx.value;if(typeof o!=='object'||o===null||Array.isArray(o))return;${[...makeUnevaluatedEvaluationStmts(schema, recurse, schemas), finalStmt].join(";")}}`;
|
|
1612
1887
|
}
|
|
1613
1888
|
function makeBoundErrorArgs(schema, bound, errorMessage) {
|
|
1614
1889
|
const message = schema[`x-${bound}-message`] ?? errorMessage;
|
|
@@ -1671,6 +1946,9 @@ function _enum(schema) {
|
|
|
1671
1946
|
return outerLit(schema.enum[0]);
|
|
1672
1947
|
}
|
|
1673
1948
|
// src/generator/zod-to-openapi/z/integer.ts
|
|
1949
|
+
/** What a 64-bit integer holds, signed and unsigned. */
|
|
1950
|
+
const INT64_RANGE = [-(2n ** 63n), 2n ** 63n - 1n];
|
|
1951
|
+
const UINT64_RANGE = [0n, 2n ** 64n - 1n];
|
|
1674
1952
|
/**
|
|
1675
1953
|
* Generates a Zod schema for integer types (int32 / int64 / bigint), with
|
|
1676
1954
|
* min/max constraints and `x-minimum-message` / `x-maximum-message` vendor
|
|
@@ -1691,7 +1969,12 @@ function integer(schema, options) {
|
|
|
1691
1969
|
const base = bigintBase ? `z.coerce.bigint(${baseErrorArg})` : isInt32 ? `z.${schema.format}(${baseErrorArg})` : isInt64 ? `z.${schema.format}(${baseErrorArg})` : isBigint ? `z.bigint(${baseErrorArg})` : `z.int(${baseErrorArg})`;
|
|
1692
1970
|
const lit = (n) => {
|
|
1693
1971
|
if (schema.format === "bigint") return `BigInt(${n})`;
|
|
1694
|
-
if (schema.format === "int64" || schema.format === "uint64")
|
|
1972
|
+
if (schema.format === "int64" || schema.format === "uint64") {
|
|
1973
|
+
if (!Number.isInteger(n)) return `${n}n`;
|
|
1974
|
+
const [min, max] = schema.format === "uint64" ? UINT64_RANGE : INT64_RANGE;
|
|
1975
|
+
const exact = BigInt(n);
|
|
1976
|
+
return `${exact < min ? min : exact > max ? max : exact}n`;
|
|
1977
|
+
}
|
|
1695
1978
|
return `${n}`;
|
|
1696
1979
|
};
|
|
1697
1980
|
const { arg: minErrorArg, part: minErrorPart, exclusiveArg: exMinErrorArg, exclusivePart: exMinErrorPart } = makeBoundErrorArgs(schema, "minimum", errorMessage);
|
|
@@ -1750,7 +2033,7 @@ function number(schema) {
|
|
|
1750
2033
|
const base = wantsCoerce && !isFloat32 && !isFloat64 ? `z.coerce.number(${baseErrorArg})` : isFloat32 ? `z.float32(${baseErrorArg})` : isFloat64 ? `z.float64(${baseErrorArg})` : `z.number(${baseErrorArg})`;
|
|
1751
2034
|
const { arg: minErrorArg, part: minErrorPart, exclusiveArg: exMinErrorArg, exclusivePart: exMinErrorPart } = makeBoundErrorArgs(schema, "minimum", errorMessage);
|
|
1752
2035
|
const minimum = (() => {
|
|
1753
|
-
if (schema.minimum
|
|
2036
|
+
if (typeof schema.minimum === "number") {
|
|
1754
2037
|
if (schema.minimum === 0 && schema.exclusiveMinimum === true) return `.positive(${exMinErrorArg})`;
|
|
1755
2038
|
if (schema.minimum === 0 && schema.exclusiveMinimum === false) return `.nonnegative(${minErrorArg})`;
|
|
1756
2039
|
if (schema.exclusiveMinimum === true) return `.gt(${schema.minimum}${exMinErrorPart})`;
|
|
@@ -1760,7 +2043,7 @@ function number(schema) {
|
|
|
1760
2043
|
})();
|
|
1761
2044
|
const { arg: maxErrorArg, part: maxErrorPart, exclusiveArg: exMaxErrorArg, exclusivePart: exMaxErrorPart } = makeBoundErrorArgs(schema, "maximum", errorMessage);
|
|
1762
2045
|
const maximum = (() => {
|
|
1763
|
-
if (schema.maximum
|
|
2046
|
+
if (typeof schema.maximum === "number") {
|
|
1764
2047
|
if (schema.maximum === 0 && schema.exclusiveMaximum === true) return `.negative(${exMaxErrorArg})`;
|
|
1765
2048
|
if (schema.maximum === 0 && schema.exclusiveMaximum === false) return `.nonpositive(${maxErrorArg})`;
|
|
1766
2049
|
if (schema.exclusiveMaximum === true) return `.lt(${schema.maximum}${exMaxErrorPart})`;
|
|
@@ -1774,7 +2057,7 @@ function number(schema) {
|
|
|
1774
2057
|
base,
|
|
1775
2058
|
minimum,
|
|
1776
2059
|
maximum,
|
|
1777
|
-
schema.multipleOf
|
|
2060
|
+
typeof schema.multipleOf === "number" ? `.multipleOf(${schema.multipleOf}${multipleOfErrorArg})` : void 0
|
|
1778
2061
|
].filter((v) => v !== void 0).join("");
|
|
1779
2062
|
return wirePipe ? `z.coerce.number(${baseErrorArg}).pipe(${innerChain})` : innerChain;
|
|
1780
2063
|
}
|
|
@@ -1800,7 +2083,7 @@ function object(schema, options) {
|
|
|
1800
2083
|
const thenOverride = thenMessage ? `,message:${JSON.stringify(thenMessage)}` : "";
|
|
1801
2084
|
const elseOverride = elseMessage ? `,message:${JSON.stringify(elseMessage)}` : "";
|
|
1802
2085
|
const propertiesMessage = schema["x-properties-message"];
|
|
1803
|
-
const needsLoose = schema.additionalProperties === void 0 && (schema.patternProperties !== void 0 || schema.propertyNames !== void 0 || schema.unevaluatedProperties !== void 0);
|
|
2086
|
+
const needsLoose = schema.additionalProperties === void 0 && (schema.patternProperties !== void 0 || schema.propertyNames !== void 0 || schema.unevaluatedProperties !== void 0 || Object.keys(schema.properties ?? {}).length === 0);
|
|
1804
2087
|
const objectType = schema.additionalProperties === true ? "looseObject" : schema.additionalProperties === false ? "strictObject" : needsLoose ? "looseObject" : "object";
|
|
1805
2088
|
const propertiesCode = schema.properties ? Object.entries(schema.properties).map(([key, propSchema]) => {
|
|
1806
2089
|
const isRequired = Array.isArray(schema.required) && schema.required.includes(key);
|
|
@@ -1852,7 +2135,7 @@ function object(schema, options) {
|
|
|
1852
2135
|
const elseZod = schema.else ? zodToOpenAPI(schema.else, void 0, options) : "undefined";
|
|
1853
2136
|
if (!(thenMessageSlot !== void 0 || elseMessageSlot !== void 0)) return `.superRefine((o,ctx)=>{const If=${ifZod};const ifOk=If.safeParse(o).success;const Branch=ifOk?${thenZod}:${elseZod};if(!Branch){return}const result=Branch.safeParse(o);if(!result.success){for(const issue of result.error.issues){ctx.addIssue({...issue,path:issue.path${ifMessageOverride}})}}})`;
|
|
1854
2137
|
return `.superRefine((o,ctx)=>{const If=${ifZod};const ifOk=If.safeParse(o).success;if(ifOk){const Branch=${thenZod};if(!Branch){return}const result=Branch.safeParse(o);if(!result.success){for(const issue of result.error.issues){ctx.addIssue({...issue,path:issue.path${thenOverride}})}}}else{const Branch=${elseZod};if(!Branch){return}const result=Branch.safeParse(o);if(!result.success){for(const issue of result.error.issues){ctx.addIssue({...issue,path:issue.path${elseOverride}})}}}})`;
|
|
1855
|
-
})()}${makeUnevaluatedProperties(schema, zodToOpenAPI, errorMessage)}${readonly ? ".readonly()" : ""}`;
|
|
2138
|
+
})()}${makeUnevaluatedProperties(schema, zodToOpenAPI, errorMessage, options?.schemas)}${readonly ? ".readonly()" : ""}`;
|
|
1856
2139
|
}
|
|
1857
2140
|
// src/generator/zod-to-openapi/z/string.ts
|
|
1858
2141
|
const FORMAT_STRING = {
|
|
@@ -1966,7 +2249,7 @@ function string(schema, options) {
|
|
|
1966
2249
|
const enc = schema.contentEncoding;
|
|
1967
2250
|
const mediaType = schema.contentMediaType;
|
|
1968
2251
|
const contentSchema = schema.contentSchema;
|
|
1969
|
-
if ((enc !== void 0 || mediaType !== void 0 || contentSchema !== void 0) && !hashBase) return `${(() => {
|
|
2252
|
+
if ((enc !== void 0 || mediaType !== void 0 || contentSchema !== void 0) && !hashBase && !isBinaryFile(schema)) return `${(() => {
|
|
1970
2253
|
if (enc === "base64") return "z.base64()";
|
|
1971
2254
|
if (enc === "base64url") return "z.base64url()";
|
|
1972
2255
|
return "z.string()";
|
|
@@ -2022,7 +2305,7 @@ function string(schema, options) {
|
|
|
2022
2305
|
const endNormalize = usePipe ? "" : postNormalize;
|
|
2023
2306
|
const patternMessage = schema["x-pattern-message"] ?? errorMessage;
|
|
2024
2307
|
const patternMessagePart = patternMessage ? `,${error(patternMessage)}` : "";
|
|
2025
|
-
const literal = schema.pattern === void 0 ? void 0 : regexLiteral(schema.pattern);
|
|
2308
|
+
const literal = schema.pattern === void 0 || isBinaryFile(schema) ? void 0 : regexLiteral(schema.pattern);
|
|
2026
2309
|
const pattern = literal ? `.regex(/${escapeRegexLiteral(literal.source)}/${literal.flags}${patternMessagePart})` : void 0;
|
|
2027
2310
|
const lengthMessage = schema["x-length-message"] ?? errorMessage;
|
|
2028
2311
|
const lengthMessagePart = lengthMessage ? `,${error(lengthMessage)}` : "";
|
|
@@ -2031,6 +2314,10 @@ function string(schema, options) {
|
|
|
2031
2314
|
const maxLengthMessage = schema["x-maxLength-message"] ?? errorMessage;
|
|
2032
2315
|
const maxLengthMessagePart = maxLengthMessage ? `,${error(maxLengthMessage)}` : "";
|
|
2033
2316
|
const isFixedLength = schema.minLength !== void 0 && schema.maxLength !== void 0 && schema.minLength === schema.maxLength;
|
|
2317
|
+
const mimeTypes = isBinaryFile(schema) ? fileMimeTypes(schema) : void 0;
|
|
2318
|
+
const mimeMessage = schema["x-contentMediaType-message"] ?? errorMessage;
|
|
2319
|
+
const mimeMessagePart = mimeMessage ? `,${error(mimeMessage)}` : "";
|
|
2320
|
+
const mime = mimeTypes === void 0 ? void 0 : `.mime(${JSON.stringify(mimeTypes.length === 1 ? mimeTypes[0] : mimeTypes)}${mimeMessagePart})`;
|
|
2034
2321
|
const includes = schema["x-includes"] !== void 0 ? `.includes(${JSON.stringify(schema["x-includes"])})` : void 0;
|
|
2035
2322
|
const startsWith = schema["x-startsWith"] !== void 0 ? `.startsWith(${JSON.stringify(schema["x-startsWith"])})` : void 0;
|
|
2036
2323
|
const endsWith = schema["x-endsWith"] !== void 0 ? `.endsWith(${JSON.stringify(schema["x-endsWith"])})` : void 0;
|
|
@@ -2046,6 +2333,7 @@ function string(schema, options) {
|
|
|
2046
2333
|
isFixedLength ? `.length(${schema.minLength}${lengthMessagePart})` : void 0,
|
|
2047
2334
|
!isFixedLength && schema.minLength !== void 0 ? `.min(${schema.minLength}${minLengthMessagePart})` : void 0,
|
|
2048
2335
|
!isFixedLength && schema.maxLength !== void 0 ? `.max(${schema.maxLength}${maxLengthMessagePart})` : void 0,
|
|
2336
|
+
mime,
|
|
2049
2337
|
includes,
|
|
2050
2338
|
startsWith,
|
|
2051
2339
|
endsWith,
|
|
@@ -2130,50 +2418,31 @@ function zodToOpenAPI(schema, meta, options) {
|
|
|
2130
2418
|
...schema.required ? { required: schema.required } : {}
|
|
2131
2419
|
}] : schema.allOf;
|
|
2132
2420
|
if (effectiveAllOf.length === 0) return done("z.any()", schema);
|
|
2133
|
-
const nullable = schema.nullable === true || (Array.isArray(schema.type) ? schema.type.includes("null") : schema.type === "null") || effectiveAllOf.some((s) => s.type === "null" || s.nullable === true &&
|
|
2134
|
-
const nonNull = effectiveAllOf.filter((s) => !(s.type === "null" || s.nullable === true && Object.keys(s).length === 1));
|
|
2135
|
-
|
|
2136
|
-
|
|
2137
|
-
|
|
2138
|
-
});
|
|
2139
|
-
const schemas = nonNull.map(child);
|
|
2140
|
-
if (schemas.length === 1 && nonNull.every(isRefOnly) && Object.keys(schema).every((k) => k === "allOf" || k === "nullable" || k === "type")) return done(schemas[0], {
|
|
2421
|
+
const nullable = schema.nullable === true || (Array.isArray(schema.type) ? schema.type.includes("null") : schema.type === "null") || effectiveAllOf.some((s) => s.type === "null" || s.nullable === true && isAnnotationOnly(s));
|
|
2422
|
+
const nonNull = effectiveAllOf.filter((s) => !(s.type === "null" || s.nullable === true && Object.keys(s).length === 1)).map((s) => inheritedBase(s, childOptions?.schemas) ?? s);
|
|
2423
|
+
const members = nonNull.filter((s) => !isAnnotationOnly(s));
|
|
2424
|
+
const emitted = {
|
|
2425
|
+
...nonNull.filter(isAnnotationOnly).reduce((acc, s) => Object.assign(acc, s), {}),
|
|
2141
2426
|
...schema,
|
|
2142
2427
|
nullable
|
|
2143
|
-
}
|
|
2428
|
+
};
|
|
2429
|
+
if (members.length === 0) return done("z.any()", emitted);
|
|
2430
|
+
const schemas = members.map(child);
|
|
2431
|
+
if (schemas.length === 1 && members.every(isRefOnly) && Object.keys(schema).every((k) => k === "allOf" || k === "nullable" || k === "type")) return done(schemas[0], emitted, true);
|
|
2144
2432
|
const z = schemas.reduce((acc, s, i) => i === 0 ? s : `${acc}.and(${s})`);
|
|
2145
2433
|
const allOfMessage = schema["x-allOf-message"] ?? schema["x-error-message"];
|
|
2146
2434
|
const unevalCheck = makeUnevaluatedPropertiesCheck({
|
|
2147
2435
|
...schema,
|
|
2148
2436
|
allOf: effectiveAllOf
|
|
2149
|
-
}, (s) => zodToOpenAPI(s, void 0, childOptions), schema["x-error-message"]);
|
|
2437
|
+
}, (s) => zodToOpenAPI(s, void 0, childOptions), schema["x-error-message"], childOptions?.schemas);
|
|
2150
2438
|
if (allOfMessage || unevalCheck) return done(`(()=>{const Schema=${z};return z.unknown().check((ctx)=>{${(() => {
|
|
2151
2439
|
const isArrow = allOfMessage ? ARROW_FUNCTION_PATTERN.test(allOfMessage) : false;
|
|
2152
2440
|
const msgExpr = allOfMessage ? isArrow ? `(${allOfMessage})(issue)` : JSON.stringify(allOfMessage) : void 0;
|
|
2153
|
-
const
|
|
2154
|
-
|
|
2155
|
-
|
|
2156
|
-
"too_big",
|
|
2157
|
-
"too_small",
|
|
2158
|
-
"invalid_format",
|
|
2159
|
-
"not_multiple_of",
|
|
2160
|
-
"unrecognized_keys",
|
|
2161
|
-
"invalid_union",
|
|
2162
|
-
"invalid_key",
|
|
2163
|
-
"invalid_element",
|
|
2164
|
-
"invalid_value",
|
|
2165
|
-
"custom"
|
|
2166
|
-
].map((c, i) => `${i === 0 ? "" : "else "}if(issue.code==='${c}'){ctx.issues.push(${pushArg})}`).join("")}}}`;
|
|
2167
|
-
})()}${unevalCheck ? `;(${unevalCheck})(ctx)` : ""}}).pipe(Schema)})()`, {
|
|
2168
|
-
...schema,
|
|
2169
|
-
nullable
|
|
2170
|
-
});
|
|
2171
|
-
return done(z, {
|
|
2172
|
-
...schema,
|
|
2173
|
-
nullable
|
|
2174
|
-
}, schemas.length === 1 && nonNull.every(isRefOnly));
|
|
2441
|
+
return `const result=Schema.safeParse(ctx.value);if(!result.success){for(const issue of result.error.issues){${makeIssueForwarding(msgExpr ? `{...issue,input:issue.input,message:${msgExpr}}` : "{...issue,input:issue.input}")}}}`;
|
|
2442
|
+
})()}${unevalCheck ? `;(${unevalCheck})(ctx)` : ""}}).pipe(Schema)})()`, emitted);
|
|
2443
|
+
return done(z, emitted, schemas.length === 1 && members.every(isRefOnly));
|
|
2175
2444
|
}
|
|
2176
|
-
if (schema.anyOf !== void 0) {
|
|
2445
|
+
if (schema.anyOf !== void 0 && !(isBinaryFile(schema) && hasMimeAlternatives(schema))) {
|
|
2177
2446
|
if (schema.anyOf.length === 0) return done("z.any()", schema);
|
|
2178
2447
|
const anyOfSchemas = schema.anyOf.map(child);
|
|
2179
2448
|
const anyOfMessage = schema["x-implication-message"] ?? schema["x-anyOf-message"] ?? schema["x-error-message"];
|
|
@@ -2549,10 +2818,74 @@ function nestedSchemas(schema) {
|
|
|
2549
2818
|
schema.not
|
|
2550
2819
|
].flatMap(nestedSchemas)];
|
|
2551
2820
|
}
|
|
2552
|
-
function findDiscriminatedBranches(schemas, schemaNames) {
|
|
2553
|
-
|
|
2821
|
+
function findDiscriminatedBranches(schemas, schemaNames, document) {
|
|
2822
|
+
const inDocument = document === void 0 ? [] : unionNodes(document);
|
|
2823
|
+
return new Set([...schemaNames.flatMap((n) => nestedSchemas(schemas[n])), ...inDocument].flatMap((schema) => discriminatedBranches(schema, schemas) ?? []).flatMap(({ name }) => name === void 0 ? [] : [name]));
|
|
2554
2824
|
}
|
|
2555
|
-
|
|
2825
|
+
/** Every object under `node` that has a `oneOf` and a `discriminator`: a union the generator may route by key. */
|
|
2826
|
+
function unionNodes(node) {
|
|
2827
|
+
if (Array.isArray(node)) return node.flatMap(unionNodes);
|
|
2828
|
+
if (!isRecord(node)) return [];
|
|
2829
|
+
const below = Object.values(node).flatMap(unionNodes);
|
|
2830
|
+
return isDiscriminatedUnion(node) ? [node, ...below] : below;
|
|
2831
|
+
}
|
|
2832
|
+
function isDiscriminatedUnion(node) {
|
|
2833
|
+
return Array.isArray(node.oneOf) && isRecord(node.discriminator);
|
|
2834
|
+
}
|
|
2835
|
+
/**
|
|
2836
|
+
* How deep a component schema nests before it is declared with an explicit type. A chain of
|
|
2837
|
+
* 15 components, each an object with a property of the next, makes `createRoute` instantiate
|
|
2838
|
+
* a type TypeScript gives up on (TS2589, #407); 14 do not. Past this depth a component is
|
|
2839
|
+
* annotated `z.ZodType<XType>`, as a recursive one is, so that what refers to it reads a
|
|
2840
|
+
* named type instead of the whole inferred one. Half the limit leaves room for what a route
|
|
2841
|
+
* and its handler add around the schema.
|
|
2842
|
+
*/
|
|
2843
|
+
const DEEP_SCHEMA_DEPTH = 8;
|
|
2844
|
+
/**
|
|
2845
|
+
* How many objects and arrays a value of the schema nests, at most: a property or an item is
|
|
2846
|
+
* one level deeper than the schema it belongs to, a member of `allOf` / `oneOf` / `anyOf`
|
|
2847
|
+
* is as deep as the schema itself, and a reference is as deep as the component it names. A
|
|
2848
|
+
* reference back into a component being measured is a cycle, which is typed in its own right.
|
|
2849
|
+
*/
|
|
2850
|
+
function schemaDepth(schema, schemas, depths, measuring) {
|
|
2851
|
+
if (schema === void 0 || typeof schema === "boolean") return 0;
|
|
2852
|
+
if (schema.$ref !== void 0) {
|
|
2853
|
+
const name = resolveSchemaRef(schema.$ref, schemas) === void 0 ? void 0 : refName(schema.$ref);
|
|
2854
|
+
if (name === void 0 || measuring.has(name)) return 0;
|
|
2855
|
+
return componentDepth(name, schemas, depths, measuring);
|
|
2856
|
+
}
|
|
2857
|
+
const depth = (s) => schemaDepth(s, schemas, depths, measuring);
|
|
2858
|
+
const nested = [
|
|
2859
|
+
...Object.values(schema.properties ?? {}),
|
|
2860
|
+
...Object.values(schema.patternProperties ?? {}),
|
|
2861
|
+
...schema.prefixItems ?? [],
|
|
2862
|
+
...isSchemaArray(schema.items) ? schema.items : [schema.items],
|
|
2863
|
+
schema.additionalProperties
|
|
2864
|
+
].map((s) => s === void 0 || typeof s === "boolean" ? 0 : 1 + depth(s));
|
|
2865
|
+
const beside = [
|
|
2866
|
+
...schema.allOf ?? [],
|
|
2867
|
+
...schema.anyOf ?? [],
|
|
2868
|
+
...schema.oneOf ?? []
|
|
2869
|
+
].map(depth);
|
|
2870
|
+
return Math.max(0, ...nested, ...beside);
|
|
2871
|
+
}
|
|
2872
|
+
function componentDepth(name, schemas, depths, measuring) {
|
|
2873
|
+
const known = depths.get(name);
|
|
2874
|
+
if (known !== void 0) return known;
|
|
2875
|
+
const depth = schemaDepth(schemas[name], schemas, depths, /* @__PURE__ */ new Set([...measuring, name]));
|
|
2876
|
+
depths.set(name, depth);
|
|
2877
|
+
return depth;
|
|
2878
|
+
}
|
|
2879
|
+
function refName($ref) {
|
|
2880
|
+
const name = $ref.split("/").at(-1);
|
|
2881
|
+
return name === void 0 ? void 0 : decodePercent(name);
|
|
2882
|
+
}
|
|
2883
|
+
/** The component schemas nested at least `DEEP_SCHEMA_DEPTH` levels deep (#407). */
|
|
2884
|
+
function findDeepSchemas(schemas, schemaNames) {
|
|
2885
|
+
const depths = /* @__PURE__ */ new Map();
|
|
2886
|
+
return new Set(schemaNames.filter((name) => componentDepth(name, schemas, depths, /* @__PURE__ */ new Set()) >= DEEP_SCHEMA_DEPTH));
|
|
2887
|
+
}
|
|
2888
|
+
function analyzeCircularSchemas(schemas, schemaNames, readonly, document) {
|
|
2556
2889
|
const varNameSet = new Set(schemaNames.map((n) => toIdentifierPascalCase(ensureSuffix(n, "Schema"))));
|
|
2557
2890
|
const varNameToName = new Map(schemaNames.map((n) => [toIdentifierPascalCase(ensureSuffix(n, "Schema")), n]));
|
|
2558
2891
|
const zSchemaMap = new Map(schemaNames.map((n) => [n, zodToOpenAPI(schemas[n], void 0, {
|
|
@@ -2578,7 +2911,8 @@ function analyzeCircularSchemas(schemas, schemaNames, readonly) {
|
|
|
2578
2911
|
cyclicSchemas,
|
|
2579
2912
|
extendedCyclicSchemas,
|
|
2580
2913
|
cyclicGroupPascal: new Set([...extendedCyclicSchemas].map(toIdentifierPascalCase)),
|
|
2581
|
-
|
|
2914
|
+
deepSchemas: findDeepSchemas(schemas, schemaNames),
|
|
2915
|
+
discriminatedBranches: findDiscriminatedBranches(schemas, schemaNames, document),
|
|
2582
2916
|
varNameToName
|
|
2583
2917
|
};
|
|
2584
2918
|
}
|
|
@@ -2706,78 +3040,421 @@ function makeImports(code, fromFile, components, split = false, honoExtras = [])
|
|
|
2706
3040
|
""
|
|
2707
3041
|
].filter(Boolean).join("\n");
|
|
2708
3042
|
}
|
|
2709
|
-
// src/helper/
|
|
2710
|
-
|
|
2711
|
-
|
|
2712
|
-
|
|
2713
|
-
|
|
2714
|
-
|
|
2715
|
-
|
|
2716
|
-
|
|
2717
|
-
|
|
2718
|
-
|
|
2719
|
-
|
|
2720
|
-
|
|
2721
|
-
|
|
2722
|
-
|
|
2723
|
-
|
|
2724
|
-
|
|
2725
|
-
|
|
2726
|
-
|
|
2727
|
-
|
|
2728
|
-
|
|
2729
|
-
|
|
2730
|
-
|
|
2731
|
-
|
|
2732
|
-
return
|
|
2733
|
-
|
|
2734
|
-
|
|
2735
|
-
|
|
2736
|
-
|
|
2737
|
-
|
|
2738
|
-
|
|
2739
|
-
|
|
2740
|
-
|
|
2741
|
-
|
|
2742
|
-
|
|
2743
|
-
|
|
2744
|
-
|
|
2745
|
-
|
|
2746
|
-
|
|
2747
|
-
|
|
2748
|
-
|
|
2749
|
-
|
|
2750
|
-
|
|
2751
|
-
|
|
2752
|
-
|
|
2753
|
-
|
|
2754
|
-
|
|
2755
|
-
|
|
2756
|
-
|
|
2757
|
-
|
|
2758
|
-
|
|
2759
|
-
|
|
2760
|
-
|
|
2761
|
-
|
|
2762
|
-
|
|
2763
|
-
|
|
2764
|
-
|
|
2765
|
-
|
|
2766
|
-
|
|
2767
|
-
|
|
2768
|
-
|
|
2769
|
-
|
|
2770
|
-
|
|
2771
|
-
|
|
2772
|
-
|
|
2773
|
-
|
|
2774
|
-
|
|
2775
|
-
|
|
2776
|
-
|
|
2777
|
-
|
|
2778
|
-
|
|
2779
|
-
|
|
2780
|
-
|
|
3043
|
+
// src/helper/names.ts
|
|
3044
|
+
/**
|
|
3045
|
+
* Renames the components whose identifiers would collide, and every `$ref` to them.
|
|
3046
|
+
*
|
|
3047
|
+
* An identifier is made of the letters and digits of a component name, so
|
|
3048
|
+
* `api-response-common-failure` and `api_response_common_failure` (Cloudflare) are both
|
|
3049
|
+
* `ApiResponseCommonFailureSchema`: one declaration was silently lost, and a type alias
|
|
3050
|
+
* came to name itself (`type X = X`). The first component in document order keeps its
|
|
3051
|
+
* name; every later one that would share an identifier is numbered
|
|
3052
|
+
* (`api_response_common_failure2`, so `ApiResponseCommonFailure2Schema`), and the
|
|
3053
|
+
* references to it follow. The document that is emitted names the schema the new way too.
|
|
3054
|
+
*
|
|
3055
|
+
* Security schemes are left alone: `security` requirements name them, and a `$ref` does not.
|
|
3056
|
+
*/
|
|
3057
|
+
function uniqueComponentNames(document) {
|
|
3058
|
+
const components = document.components;
|
|
3059
|
+
if (!isRecord(components)) return document;
|
|
3060
|
+
const renames = COMPONENT_NAMES.flatMap((section) => {
|
|
3061
|
+
if (section === "securitySchemes") return [];
|
|
3062
|
+
const entries = components[section];
|
|
3063
|
+
if (!isRecord(entries)) return [];
|
|
3064
|
+
const identifier = (name) => toIdentifierPascalCase(ensureSuffix(name, COMPONENT_SUFFIXES$1[section]));
|
|
3065
|
+
const taken = /* @__PURE__ */ new Set();
|
|
3066
|
+
return Object.keys(entries).flatMap((name) => {
|
|
3067
|
+
const own = identifier(name);
|
|
3068
|
+
if (!taken.has(own)) {
|
|
3069
|
+
taken.add(own);
|
|
3070
|
+
return [];
|
|
3071
|
+
}
|
|
3072
|
+
const renamed = numbered$1(name, (candidate) => !taken.has(identifier(candidate)));
|
|
3073
|
+
taken.add(identifier(renamed));
|
|
3074
|
+
return [{
|
|
3075
|
+
section,
|
|
3076
|
+
name,
|
|
3077
|
+
renamed
|
|
3078
|
+
}];
|
|
3079
|
+
});
|
|
3080
|
+
});
|
|
3081
|
+
if (renames.length === 0) return document;
|
|
3082
|
+
const renamedSections = Object.fromEntries(COMPONENT_NAMES.flatMap((section) => {
|
|
3083
|
+
const entries = components[section];
|
|
3084
|
+
const own = renames.filter((rename) => rename.section === section);
|
|
3085
|
+
if (!isRecord(entries) || own.length === 0) return [];
|
|
3086
|
+
return [[section, Object.fromEntries(Object.entries(entries).map(([name, value]) => [own.find((rename) => rename.name === name)?.renamed ?? name, value]))]];
|
|
3087
|
+
}));
|
|
3088
|
+
const refs = new Map(renames.map((rename) => [`#/components/${rename.section}/${rename.name}`, rename]));
|
|
3089
|
+
const rewriteRef = (ref) => {
|
|
3090
|
+
if (!ref.startsWith("#/components/")) return ref;
|
|
3091
|
+
const segments = ref.split("/");
|
|
3092
|
+
const section = segments[2];
|
|
3093
|
+
const encoded = segments[3];
|
|
3094
|
+
const rest = segments.slice(4);
|
|
3095
|
+
if (section === void 0 || encoded === void 0) return ref;
|
|
3096
|
+
const rename = refs.get(`#/components/${section}/${decodePercent(encoded)}`);
|
|
3097
|
+
if (rename === void 0) return ref;
|
|
3098
|
+
return [
|
|
3099
|
+
"#",
|
|
3100
|
+
"components",
|
|
3101
|
+
section,
|
|
3102
|
+
encoded.includes("%") ? encodeURIComponent(rename.renamed) : rename.renamed,
|
|
3103
|
+
...rest
|
|
3104
|
+
].join("/");
|
|
3105
|
+
};
|
|
3106
|
+
const rewrite = (node) => {
|
|
3107
|
+
if (Array.isArray(node)) return node.map(rewrite);
|
|
3108
|
+
if (!isRecord(node)) return node;
|
|
3109
|
+
return Object.fromEntries(Object.entries(node).map(([key, value]) => {
|
|
3110
|
+
if (key === "$ref" && typeof value === "string") return [key, rewriteRef(value)];
|
|
3111
|
+
if (key === "mapping" && isRecord(value)) return [key, Object.fromEntries(Object.entries(value).map(([k, v]) => [k, typeof v === "string" ? rewriteRef(v) : v]))];
|
|
3112
|
+
return [key, rewrite(value)];
|
|
3113
|
+
}));
|
|
3114
|
+
};
|
|
3115
|
+
const rewritten = rewrite({
|
|
3116
|
+
...document,
|
|
3117
|
+
components: {
|
|
3118
|
+
...components,
|
|
3119
|
+
...renamedSections
|
|
3120
|
+
}
|
|
3121
|
+
});
|
|
3122
|
+
return isRecord(rewritten) ? {
|
|
3123
|
+
...document,
|
|
3124
|
+
...rewritten
|
|
3125
|
+
} : document;
|
|
3126
|
+
}
|
|
3127
|
+
/** `name2`, `name3`, ...: the first that `isFree`. */
|
|
3128
|
+
function numbered$1(name, isFree) {
|
|
3129
|
+
const candidates = (n) => isFree(`${name}${n}`) ? `${name}${n}` : candidates(n + 1);
|
|
3130
|
+
return candidates(2);
|
|
3131
|
+
}
|
|
3132
|
+
// src/helper/pointer.ts
|
|
3133
|
+
/**
|
|
3134
|
+
* Inlines every `$ref` whose pointer names no component, so that what reaches the
|
|
3135
|
+
* generators is either a component (`#/components/<section>/<name>`, emitted as the
|
|
3136
|
+
* identifier it is declared under) or the schema itself.
|
|
3137
|
+
*
|
|
3138
|
+
* A bundler keeps internal references as they are, and a document may refer to an inline
|
|
3139
|
+
* schema wherever it sits: `#/paths/~1partners~1upsert/put/requestBody/content/
|
|
3140
|
+
* application~1json/schema` (freee), or `#/components/parameters/Page/schema`. Named after
|
|
3141
|
+
* its last segment, such a reference became `SchemaSchema`, which nothing declares. The
|
|
3142
|
+
* target is already in the document, so it is written in place of the reference, with the
|
|
3143
|
+
* keywords beside the `$ref` (a `description`) kept over the target's own. A pointer that
|
|
3144
|
+
* names nothing, or that comes back to itself, is left as written.
|
|
3145
|
+
*/
|
|
3146
|
+
function inlinePointerRefs(document) {
|
|
3147
|
+
if (!hasInlinePointer(document)) return document;
|
|
3148
|
+
const inline = (node, inlining) => {
|
|
3149
|
+
if (Array.isArray(node)) return node.map((item) => inline(item, inlining));
|
|
3150
|
+
if (!isRecord(node)) return node;
|
|
3151
|
+
const walked = (record) => Object.fromEntries(Object.entries(record).map(([key, value]) => [key, inline(value, inlining)]));
|
|
3152
|
+
const { $ref, ...beside } = node;
|
|
3153
|
+
if (typeof $ref === "string" && isInlinePointer($ref) && !inlining.has($ref)) {
|
|
3154
|
+
const target = resolvePointer(document, $ref);
|
|
3155
|
+
if (isRecord(target)) {
|
|
3156
|
+
const inlined = inline(target, /* @__PURE__ */ new Set([...inlining, $ref]));
|
|
3157
|
+
if (isRecord(inlined)) return {
|
|
3158
|
+
...inlined,
|
|
3159
|
+
...walked(beside)
|
|
3160
|
+
};
|
|
3161
|
+
}
|
|
3162
|
+
}
|
|
3163
|
+
return walked(node);
|
|
3164
|
+
};
|
|
3165
|
+
return {
|
|
3166
|
+
...document,
|
|
3167
|
+
...Object.fromEntries(Object.entries(document).map(([key, value]) => [key, inline(value, /* @__PURE__ */ new Set())]))
|
|
3168
|
+
};
|
|
3169
|
+
}
|
|
3170
|
+
/** Whether any `$ref` under `node` is an inline pointer. */
|
|
3171
|
+
function hasInlinePointer(node) {
|
|
3172
|
+
if (Array.isArray(node)) return node.some(hasInlinePointer);
|
|
3173
|
+
if (!isRecord(node)) return false;
|
|
3174
|
+
const { $ref } = node;
|
|
3175
|
+
if (typeof $ref === "string" && isInlinePointer($ref)) return true;
|
|
3176
|
+
return Object.values(node).some(hasInlinePointer);
|
|
3177
|
+
}
|
|
3178
|
+
/** A local pointer that does not name a component, nor a property of a component schema. */
|
|
3179
|
+
function isInlinePointer(ref) {
|
|
3180
|
+
if (!ref.startsWith("#/")) return false;
|
|
3181
|
+
const segments = pointerSegments(ref);
|
|
3182
|
+
if (segments[0] !== "components") return true;
|
|
3183
|
+
if (segments.length === 3) return false;
|
|
3184
|
+
return !(segments[1] === "schemas" && segments[3] === "properties" && segments.length > 4);
|
|
3185
|
+
}
|
|
3186
|
+
/** The segments of a JSON Pointer fragment, decoded: percent-encoding, then `~1` and `~0` (RFC 6901 §6). */
|
|
3187
|
+
function pointerSegments(ref) {
|
|
3188
|
+
return ref.slice(2).split("/").map((segment) => decodePercent(segment).replaceAll("~1", "/").replaceAll("~0", "~"));
|
|
3189
|
+
}
|
|
3190
|
+
function resolvePointer(document, ref) {
|
|
3191
|
+
return pointerSegments(ref).reduce((node, segment) => {
|
|
3192
|
+
if (Array.isArray(node)) return node[Number(segment)];
|
|
3193
|
+
if (isRecord(node)) return Object.hasOwn(node, segment) ? node[segment] : void 0;
|
|
3194
|
+
}, document);
|
|
3195
|
+
}
|
|
3196
|
+
/**
|
|
3197
|
+
* Moves the schema a recursive inline pointer names into `components.schemas`, and names it
|
|
3198
|
+
* there in every `$ref`. A `definitions` entry of an externally referenced JSON Schema that
|
|
3199
|
+
* reaches itself (`Node.children.items` → `Node`, Tyk) cannot be inlined where it is used:
|
|
3200
|
+
* the copy would never end, so `inlinePointerRefs` leaves the reference inside the copy as
|
|
3201
|
+
* written, and `makeRef` named it `NodeSchema`, which nothing declared (#404). As a component
|
|
3202
|
+
* it is declared, with the `z.lazy()` and the type a recursive component gets.
|
|
3203
|
+
*
|
|
3204
|
+
* The component is named after the pointer's last segment, numbered when the name is taken.
|
|
3205
|
+
* A pointer is recursive when its target, read through the inline pointers under it, comes
|
|
3206
|
+
* back to the pointer itself.
|
|
3207
|
+
*/
|
|
3208
|
+
function hoistRecursivePointers(document) {
|
|
3209
|
+
if (!hasInlinePointer(document)) return document;
|
|
3210
|
+
const recursive = [...new Set(inlinePointers(document))].filter((pointer) => isRecursivePointer(document, pointer));
|
|
3211
|
+
if (recursive.length === 0) return document;
|
|
3212
|
+
const existing = document.components?.schemas ?? {};
|
|
3213
|
+
const taken = new Set(Object.keys(existing));
|
|
3214
|
+
const names = new Map(recursive.map((pointer) => {
|
|
3215
|
+
const base = pointerSegments(pointer).at(-1) ?? "Schema";
|
|
3216
|
+
const name = taken.has(base) ? numbered(base, (candidate) => !taken.has(candidate)) : base;
|
|
3217
|
+
taken.add(name);
|
|
3218
|
+
return [pointer, name];
|
|
3219
|
+
}));
|
|
3220
|
+
const rename = (node) => {
|
|
3221
|
+
if (Array.isArray(node)) return node.map(rename);
|
|
3222
|
+
if (!isRecord(node)) return node;
|
|
3223
|
+
return Object.fromEntries(Object.entries(node).map(([key, value]) => {
|
|
3224
|
+
const name = key === "$ref" && typeof value === "string" ? names.get(value) : void 0;
|
|
3225
|
+
return [key, name === void 0 ? rename(value) : `#/components/schemas/${name}`];
|
|
3226
|
+
}));
|
|
3227
|
+
};
|
|
3228
|
+
const hoisted = Object.fromEntries([...names].flatMap(([pointer, name]) => {
|
|
3229
|
+
const target = resolvePointer(document, pointer);
|
|
3230
|
+
return isRecord(target) ? [[name, target]] : [];
|
|
3231
|
+
}));
|
|
3232
|
+
const renamed = rename({
|
|
3233
|
+
...document,
|
|
3234
|
+
components: {
|
|
3235
|
+
...document.components,
|
|
3236
|
+
schemas: {
|
|
3237
|
+
...existing,
|
|
3238
|
+
...hoisted
|
|
3239
|
+
}
|
|
3240
|
+
}
|
|
3241
|
+
});
|
|
3242
|
+
return isOpenAPI$1(renamed) ? renamed : document;
|
|
3243
|
+
}
|
|
3244
|
+
function isOpenAPI$1(value) {
|
|
3245
|
+
return isRecord(value) && "paths" in value;
|
|
3246
|
+
}
|
|
3247
|
+
/** Every inline pointer a `$ref` under `node` names, in document order, duplicates included. */
|
|
3248
|
+
function inlinePointers(node) {
|
|
3249
|
+
if (Array.isArray(node)) return node.flatMap(inlinePointers);
|
|
3250
|
+
if (!isRecord(node)) return [];
|
|
3251
|
+
const { $ref } = node;
|
|
3252
|
+
return [...typeof $ref === "string" && isInlinePointer($ref) ? [$ref] : [], ...Object.values(node).flatMap(inlinePointers)];
|
|
3253
|
+
}
|
|
3254
|
+
/** Whether the target of `pointer`, read through the inline pointers under it, names `pointer` again. */
|
|
3255
|
+
function isRecursivePointer(document, pointer) {
|
|
3256
|
+
const visited = /* @__PURE__ */ new Set();
|
|
3257
|
+
const reaches = (node) => {
|
|
3258
|
+
if (Array.isArray(node)) return node.some(reaches);
|
|
3259
|
+
if (!isRecord(node)) return false;
|
|
3260
|
+
const { $ref } = node;
|
|
3261
|
+
if (typeof $ref === "string" && isInlinePointer($ref)) {
|
|
3262
|
+
if ($ref === pointer) return true;
|
|
3263
|
+
if (!visited.has($ref)) {
|
|
3264
|
+
visited.add($ref);
|
|
3265
|
+
if (reaches(resolvePointer(document, $ref))) return true;
|
|
3266
|
+
}
|
|
3267
|
+
}
|
|
3268
|
+
return Object.values(node).some(reaches);
|
|
3269
|
+
};
|
|
3270
|
+
return reaches(resolvePointer(document, pointer));
|
|
3271
|
+
}
|
|
3272
|
+
/** `name2`, `name3`, ...: the first that `isFree`. */
|
|
3273
|
+
function numbered(name, isFree) {
|
|
3274
|
+
const candidates = (n) => isFree(`${name}${n}`) ? `${name}${n}` : candidates(n + 1);
|
|
3275
|
+
return candidates(2);
|
|
3276
|
+
}
|
|
3277
|
+
/**
|
|
3278
|
+
* Resolves the `$ref`s of an embedded JSON Schema resource against the resource. A schema
|
|
3279
|
+
* with an `$id` (or Draft 4's `id`) is a resource of its own, and a `#/definitions/Tag` inside
|
|
3280
|
+
* it names its own `definitions`, not the document's (RFC 3986 §5, JSON Schema §8.2). A
|
|
3281
|
+
* bundler that copies such a schema into the document keeps those pointers as written, so
|
|
3282
|
+
* read against the document they name nothing (Tyk's OpenAPI 3.0 meta-schema, #404). Each is
|
|
3283
|
+
* written as the pointer to the same place in the document, where `inlinePointerRefs` and
|
|
3284
|
+
* `hoistRecursivePointers` read it. A pointer the document resolves as it is is left alone.
|
|
3285
|
+
*/
|
|
3286
|
+
function resolveEmbeddedRefs(document) {
|
|
3287
|
+
if (!hasInlinePointer(document)) return document;
|
|
3288
|
+
let changed = false;
|
|
3289
|
+
const walk = (node, path, resource) => {
|
|
3290
|
+
if (Array.isArray(node)) return node.map((item, i) => walk(item, `${path}/${i}`, resource));
|
|
3291
|
+
if (!isRecord(node)) return node;
|
|
3292
|
+
const own = typeof node.$id === "string" || typeof node.id === "string" ? path : resource;
|
|
3293
|
+
return Object.fromEntries(Object.entries(node).map(([key, value]) => {
|
|
3294
|
+
const segment = key.replaceAll("~", "~0").replaceAll("/", "~1");
|
|
3295
|
+
if (key === "$ref" && typeof value === "string" && own !== void 0 && own !== "#" && value.startsWith("#/") && resolvePointer(document, value) === void 0) {
|
|
3296
|
+
const inResource = `${own}${value.slice(1)}`;
|
|
3297
|
+
if (resolvePointer(document, inResource) !== void 0) {
|
|
3298
|
+
changed = true;
|
|
3299
|
+
return [key, inResource];
|
|
3300
|
+
}
|
|
3301
|
+
}
|
|
3302
|
+
return [key, walk(value, `${path}/${segment}`, own)];
|
|
3303
|
+
}));
|
|
3304
|
+
};
|
|
3305
|
+
const walked = walk(document, "#", void 0);
|
|
3306
|
+
return changed && isOpenAPI$1(walked) ? walked : document;
|
|
3307
|
+
}
|
|
3308
|
+
// src/helper/document.ts
|
|
3309
|
+
/**
|
|
3310
|
+
* The document as every generator reads it: the pointers of an embedded schema resource read
|
|
3311
|
+
* against the resource, inline pointers written out where they stand, recursive ones declared
|
|
3312
|
+
* as components, components whose names would make one identifier
|
|
3313
|
+
* told apart, and the Specification Extensions of the Paths, Responses and Callback Objects
|
|
3314
|
+
* left out. A document none of this touches comes back as it is.
|
|
3315
|
+
*/
|
|
3316
|
+
function normalizeOpenAPI(document) {
|
|
3317
|
+
return withoutExtensions(uniqueComponentNames(inlinePointerRefs(hoistRecursivePointers(resolveEmbeddedRefs(document)))));
|
|
3318
|
+
}
|
|
3319
|
+
/**
|
|
3320
|
+
* The document without the Specification Extensions (`x-` keys) of the Paths Object, of the
|
|
3321
|
+
* Responses Object of every operation and of every Callback Object (OpenAPI 3.1 §4.8.8,
|
|
3322
|
+
* §4.8.16, §4.8.18). Those objects are maps that may be extended, so an `x-` key there is not
|
|
3323
|
+
* a path, a status code or a callback expression (#416): read as one, `paths.x-vendor` became
|
|
3324
|
+
* a route at the path `x-vendor`, and `responses.x-vendor` a response. The webhooks and the
|
|
3325
|
+
* component maps are not extensible: a key of theirs is a name, whatever it starts with.
|
|
3326
|
+
*/
|
|
3327
|
+
function withoutExtensions(document) {
|
|
3328
|
+
if (!hasExtensionEntry(document)) return document;
|
|
3329
|
+
const paths = isRecord(document.paths) ? Object.fromEntries(Object.entries(document.paths).filter(([key]) => !isExtensionKey(key)).map(([key, item]) => [key, pathItemWithoutExtensions(item)])) : document.paths;
|
|
3330
|
+
const webhooks = isRecord(document.webhooks) ? Object.fromEntries(Object.entries(document.webhooks).map(([key, item]) => [key, pathItemWithoutExtensions(item)])) : document.webhooks;
|
|
3331
|
+
const components = isRecord(document.components) ? {
|
|
3332
|
+
...document.components,
|
|
3333
|
+
...isRecord(document.components.pathItems) ? { pathItems: Object.fromEntries(Object.entries(document.components.pathItems).map(([key, item]) => [key, pathItemWithoutExtensions(item)])) } : {},
|
|
3334
|
+
...isRecord(document.components.callbacks) ? { callbacks: Object.fromEntries(Object.entries(document.components.callbacks).map(([key, callback]) => [key, callbackWithoutExtensions(callback)])) } : {}
|
|
3335
|
+
} : document.components;
|
|
3336
|
+
const result = {
|
|
3337
|
+
...document,
|
|
3338
|
+
paths,
|
|
3339
|
+
...webhooks === void 0 ? {} : { webhooks },
|
|
3340
|
+
...components === void 0 ? {} : { components }
|
|
3341
|
+
};
|
|
3342
|
+
return isOpenAPI(result) ? result : document;
|
|
3343
|
+
}
|
|
3344
|
+
function isOpenAPI(value) {
|
|
3345
|
+
return isRecord(value) && "paths" in value;
|
|
3346
|
+
}
|
|
3347
|
+
function isExtensionKey(key) {
|
|
3348
|
+
return key.startsWith("x-");
|
|
3349
|
+
}
|
|
3350
|
+
function pathItemWithoutExtensions(item) {
|
|
3351
|
+
if (!isRecord(item)) return item;
|
|
3352
|
+
return Object.fromEntries(Object.entries(item).map(([key, value]) => HTTP_METHODS.some((method) => method === key) ? [key, operationWithoutExtensions(value)] : [key, value]));
|
|
3353
|
+
}
|
|
3354
|
+
function operationWithoutExtensions(operation) {
|
|
3355
|
+
if (!isRecord(operation)) return operation;
|
|
3356
|
+
const responses = isRecord(operation.responses) ? Object.fromEntries(Object.entries(operation.responses).filter(([key]) => !isExtensionKey(key))) : operation.responses;
|
|
3357
|
+
const callbacks = isRecord(operation.callbacks) ? Object.fromEntries(Object.entries(operation.callbacks).map(([key, callback]) => [key, callbackWithoutExtensions(callback)])) : operation.callbacks;
|
|
3358
|
+
return {
|
|
3359
|
+
...operation,
|
|
3360
|
+
...responses === void 0 ? {} : { responses },
|
|
3361
|
+
...callbacks === void 0 ? {} : { callbacks }
|
|
3362
|
+
};
|
|
3363
|
+
}
|
|
3364
|
+
function callbackWithoutExtensions(callback) {
|
|
3365
|
+
if (!isRecord(callback) || typeof callback.$ref === "string") return callback;
|
|
3366
|
+
return Object.fromEntries(Object.entries(callback).filter(([key]) => !isExtensionKey(key)).map(([key, item]) => [key, pathItemWithoutExtensions(item)]));
|
|
3367
|
+
}
|
|
3368
|
+
/** Whether any of the maps `withoutExtensions` reads has an `x-` key: most documents have none. */
|
|
3369
|
+
function hasExtensionEntry(document) {
|
|
3370
|
+
return isRecord(document.paths) && (Object.keys(document.paths).some(isExtensionKey) || Object.values(document.paths).some(hasExtensionInPathItem)) || hasExtensionInMap(document.webhooks, hasExtensionInPathItem) || hasExtensionInMap(document.components?.pathItems, hasExtensionInPathItem) || hasExtensionInMap(document.components?.callbacks, hasExtensionInCallback);
|
|
3371
|
+
}
|
|
3372
|
+
function hasExtensionInMap(map, each) {
|
|
3373
|
+
return isRecord(map) && Object.values(map).some(each);
|
|
3374
|
+
}
|
|
3375
|
+
function hasExtensionInPathItem(item) {
|
|
3376
|
+
return isRecord(item) && HTTP_METHODS.some((method) => {
|
|
3377
|
+
const operation = item[method];
|
|
3378
|
+
return isRecord(operation) && (isRecord(operation.responses) && Object.keys(operation.responses).some(isExtensionKey) || isRecord(operation.callbacks) && Object.values(operation.callbacks).some(hasExtensionInCallback));
|
|
3379
|
+
});
|
|
3380
|
+
}
|
|
3381
|
+
function hasExtensionInCallback(callback) {
|
|
3382
|
+
return isRecord(callback) && typeof callback.$ref !== "string" && (Object.keys(callback).some(isExtensionKey) || Object.values(callback).some(hasExtensionInPathItem));
|
|
3383
|
+
}
|
|
3384
|
+
// src/helper/type.ts
|
|
3385
|
+
function makeTypeString(schema, selfTypeName, cyclicGroup, readonly) {
|
|
3386
|
+
if (!schema) return "unknown";
|
|
3387
|
+
if (Object.keys(schema).length === 0) return "unknown";
|
|
3388
|
+
const types = normalizeType(schema);
|
|
3389
|
+
const isNullable = schema.nullable === true || types.includes("null") || schema.default === null || (schema.enum?.includes(null) ?? false);
|
|
3390
|
+
const baseType = makeNonNullTypeString(schema, types.filter((t) => t !== "null"), selfTypeName, cyclicGroup, readonly);
|
|
3391
|
+
if (!isNullable || baseType === "null") return baseType;
|
|
3392
|
+
return `(${baseType}|null)`;
|
|
3393
|
+
}
|
|
3394
|
+
function makeNonNullTypeString(schema, types, selfTypeName, cyclicGroup, readonly) {
|
|
3395
|
+
if (schema.$ref) return makeRefTypeString(schema.$ref, selfTypeName);
|
|
3396
|
+
if (schema.oneOf && schema.oneOf.length > 0) return makeUnionTypeString(schema.oneOf, selfTypeName, cyclicGroup, "|", readonly);
|
|
3397
|
+
if (schema.anyOf && schema.anyOf.length > 0) return makeUnionTypeString(schema.anyOf, selfTypeName, cyclicGroup, "|", readonly);
|
|
3398
|
+
if (schema.allOf && schema.allOf.length > 0) return makeUnionTypeString(schema.allOf, selfTypeName, cyclicGroup, "&", readonly);
|
|
3399
|
+
if (schema.enum && schema.enum.length > 0) {
|
|
3400
|
+
const values = schema.enum.filter((v) => v !== null);
|
|
3401
|
+
if (values.length === 0) return "null";
|
|
3402
|
+
return values.map((v) => typeof v === "string" ? makeStringLiteral(v) : String(v)).join("|");
|
|
3403
|
+
}
|
|
3404
|
+
if (schema.const !== void 0) {
|
|
3405
|
+
if (typeof schema.const === "string") return makeStringLiteral(schema.const);
|
|
3406
|
+
if (typeof schema.const === "number" || typeof schema.const === "boolean") return String(schema.const);
|
|
3407
|
+
return JSON.stringify(schema.const);
|
|
3408
|
+
}
|
|
3409
|
+
return makeBaseTypeString(schema, types, selfTypeName, cyclicGroup, readonly);
|
|
3410
|
+
}
|
|
3411
|
+
function makeRefTypeString(ref, selfTypeName) {
|
|
3412
|
+
const propertiesMatch = ref.match(/^#\/components\/schemas\/([^/]+)\/properties\//u);
|
|
3413
|
+
if (propertiesMatch) {
|
|
3414
|
+
const parentName = toIdentifierPascalCase(decodePercent(propertiesMatch[1]));
|
|
3415
|
+
if (parentName === selfTypeName) return `${parentName}Type`;
|
|
3416
|
+
return `z.infer<typeof ${parentName}Schema>`;
|
|
3417
|
+
}
|
|
3418
|
+
const rawRef = ref.split("/").at(-1) ?? "";
|
|
3419
|
+
const refName = toIdentifierPascalCase(decodePercent(rawRef));
|
|
3420
|
+
if (refName === selfTypeName) return `${refName}Type`;
|
|
3421
|
+
return `z.infer<typeof ${refName}Schema>`;
|
|
3422
|
+
}
|
|
3423
|
+
function makeUnionTypeString(schemas, selfTypeName, cyclicGroup, separator, readonly) {
|
|
3424
|
+
const types = schemas.filter(Boolean).map((s) => makeTypeString(s, selfTypeName, cyclicGroup, readonly));
|
|
3425
|
+
return types.length === 0 ? "unknown" : types.length === 1 ? types[0] : `(${types.join(separator)})`;
|
|
3426
|
+
}
|
|
3427
|
+
function normalizeType(schema) {
|
|
3428
|
+
if (!schema.type) return isUntypedObject(schema) ? ["object"] : [];
|
|
3429
|
+
return Array.isArray(schema.type) ? schema.type : [schema.type];
|
|
3430
|
+
}
|
|
3431
|
+
function makeBaseTypeString(schema, types, selfTypeName, cyclicGroup, readonly) {
|
|
3432
|
+
if (types.length > 1) return types.map((t) => makeSingleTypeString(schema, t, selfTypeName, cyclicGroup, readonly)).join("|");
|
|
3433
|
+
const [type] = types;
|
|
3434
|
+
if (type === void 0) return schema.type === "null" ? "null" : "unknown";
|
|
3435
|
+
return makeSingleTypeString(schema, type, selfTypeName, cyclicGroup, readonly);
|
|
3436
|
+
}
|
|
3437
|
+
function makeSingleTypeString(schema, type, selfTypeName, cyclicGroup, readonly) {
|
|
3438
|
+
if (type === "string") return isBinaryFile(schema) ? "File" : "string";
|
|
3439
|
+
if (type === "number") return "number";
|
|
3440
|
+
if (type === "integer") return isBigintFormat(schema) ? "bigint" : "number";
|
|
3441
|
+
if (type === "boolean") return "boolean";
|
|
3442
|
+
if (type === "null") return "null";
|
|
3443
|
+
if (type === "array") return makeArrayTypeString(schema, selfTypeName, cyclicGroup, readonly);
|
|
3444
|
+
if (type === "object") return makeObjectTypeString(schema, selfTypeName, cyclicGroup, readonly);
|
|
3445
|
+
return "unknown";
|
|
3446
|
+
}
|
|
3447
|
+
function isBigintFormat(schema) {
|
|
3448
|
+
return schema.format === "int64" || schema.format === "uint64" || schema.format === "bigint";
|
|
3449
|
+
}
|
|
3450
|
+
function wrapForArrayElement(type) {
|
|
3451
|
+
return type.startsWith("readonly ") || type.includes("|") && !type.startsWith("(") ? `(${type})` : type;
|
|
3452
|
+
}
|
|
3453
|
+
function makeArrayTypeString(schema, selfTypeName, cyclicGroup, readonly) {
|
|
3454
|
+
const prefix = readonly ? "readonly " : "";
|
|
3455
|
+
if (!schema.items) return `${prefix}unknown[]`;
|
|
3456
|
+
const items = schema.items;
|
|
3457
|
+
if (typeof items === "boolean") return items ? `${prefix}unknown[]` : readonly ? "readonly []" : "[]";
|
|
2781
3458
|
if (isSchemaArray(items)) {
|
|
2782
3459
|
const firstItem = items[0];
|
|
2783
3460
|
if (items.length > 1) {
|
|
@@ -2833,7 +3510,7 @@ function makeSchemaInfo(schemaName, schema, analysis) {
|
|
|
2833
3510
|
const safeSchemaName = toIdentifierPascalCase(schemaName);
|
|
2834
3511
|
const variableName = toIdentifierPascalCase(ensureSuffix(schemaName, "Schema"));
|
|
2835
3512
|
const isCircular = analysis.cyclicSchemas.has(schemaName);
|
|
2836
|
-
const isSelfReferencing =
|
|
3513
|
+
const isSelfReferencing = new RegExp(String.raw`\b${variableName}\b`, "u").test(zSchema);
|
|
2837
3514
|
const needsLazy = isCircular || isSelfReferencing;
|
|
2838
3515
|
return {
|
|
2839
3516
|
schemaName,
|
|
@@ -2842,7 +3519,7 @@ function makeSchemaInfo(schemaName, schema, analysis) {
|
|
|
2842
3519
|
safeSchemaName,
|
|
2843
3520
|
variableName,
|
|
2844
3521
|
needsLazy,
|
|
2845
|
-
needsTypeDef: needsLazy || analysis.extendedCyclicSchemas.has(schemaName),
|
|
3522
|
+
needsTypeDef: needsLazy || analysis.extendedCyclicSchemas.has(schemaName) || analysis.deepSchemas.has(schemaName),
|
|
2846
3523
|
isDiscriminatedBranch: analysis.discriminatedBranches.has(schemaName)
|
|
2847
3524
|
};
|
|
2848
3525
|
}
|
|
@@ -2917,14 +3594,8 @@ function headersCode(components, exportHeaders, exportHeadersTypes, readonly) {
|
|
|
2917
3594
|
return zodToOpenAPISchema(schemaName, refName, exportHeaders, exportHeadersTypes, true);
|
|
2918
3595
|
}
|
|
2919
3596
|
if (isHeader(header)) {
|
|
2920
|
-
|
|
2921
|
-
|
|
2922
|
-
return zodToOpenAPISchema(schemaName, schema, exportHeaders, exportHeadersTypes, true);
|
|
2923
|
-
}
|
|
2924
|
-
if (header.content) {
|
|
2925
|
-
const content = makeContent(header.content, readonly);
|
|
2926
|
-
return zodToOpenAPISchema(schemaName, `{${content.join(",")}}`, exportHeaders, exportHeadersTypes, true);
|
|
2927
|
-
}
|
|
3597
|
+
const schema = makeHeaderSchema(header, readonly);
|
|
3598
|
+
return zodToOpenAPISchema(schemaName, schema, exportHeaders, exportHeadersTypes, true);
|
|
2928
3599
|
}
|
|
2929
3600
|
return "";
|
|
2930
3601
|
}).filter(Boolean).join("\n\n");
|
|
@@ -3098,7 +3769,7 @@ function responsesCode(components, exportResponses, readonly) {
|
|
|
3098
3769
|
const asConst = readonly ? " as const" : "";
|
|
3099
3770
|
return Object.keys(responses).map((k) => {
|
|
3100
3771
|
const isRef = responses[k].$ref !== void 0;
|
|
3101
|
-
return `${makeConst(exportResponses, k, "Response")}${makeResponses(responses[k])}${isRef ? "" : asConst}`;
|
|
3772
|
+
return `${makeConst(exportResponses, k, "Response")}${makeResponses(responses[k], void 0, components.schemas)}${isRef ? "" : asConst}`;
|
|
3102
3773
|
}).join("\n\n");
|
|
3103
3774
|
}
|
|
3104
3775
|
// src/generator/zod-openapi-hono/openapi/components/schemas.ts
|
|
@@ -3118,12 +3789,12 @@ function responsesCode(components, exportResponses, readonly) {
|
|
|
3118
3789
|
* // → 'export const UserSchema = z.object({...}).readonly().openapi("User")\n\nexport type User = z.infer<typeof UserSchema>'
|
|
3119
3790
|
* ```
|
|
3120
3791
|
*/
|
|
3121
|
-
function schemasCode(components, exportSchemas, exportSchemasTypes, readonly) {
|
|
3792
|
+
function schemasCode(components, exportSchemas, exportSchemasTypes, readonly, document) {
|
|
3122
3793
|
const { schemas } = components;
|
|
3123
3794
|
if (!schemas) return "";
|
|
3124
3795
|
const schemaNames = Object.keys(schemas);
|
|
3125
3796
|
if (schemaNames.length === 0) return "";
|
|
3126
|
-
const analysis = analyzeCircularSchemas(schemas, schemaNames, readonly);
|
|
3797
|
+
const analysis = analyzeCircularSchemas(schemas, schemaNames, readonly, document);
|
|
3127
3798
|
const infos = makeSchemaInfos(schemas, schemaNames, analysis);
|
|
3128
3799
|
const typeDefs = makeTypeDefinitions(infos, schemas, analysis.cyclicGroupPascal, readonly);
|
|
3129
3800
|
const schemaBlocks = infos.map((info) => makeSchemaCode(info, {
|
|
@@ -3160,9 +3831,9 @@ function securitySchemesCode(components, exportSecuritySchemes, readonly) {
|
|
|
3160
3831
|
}
|
|
3161
3832
|
// src/generator/zod-openapi-hono/openapi/components/index.ts
|
|
3162
3833
|
function componentsCode(components, options) {
|
|
3163
|
-
const { readonly, exportSchemas = false, exportSchemasTypes = false, exportResponses = false, exportParameters = false, exportParametersTypes = false, exportExamples = false, exportRequestBodies = false, exportHeaders = false, exportHeadersTypes = false, exportSecuritySchemes = false, exportLinks = false, exportCallbacks = false, exportPathItems = false, exportMediaTypes = false, exportMediaTypesTypes = false } = options;
|
|
3834
|
+
const { readonly, exportSchemas = false, exportSchemasTypes = false, exportResponses = false, exportParameters = false, exportParametersTypes = false, exportExamples = false, exportRequestBodies = false, exportHeaders = false, exportHeadersTypes = false, exportSecuritySchemes = false, exportLinks = false, exportCallbacks = false, exportPathItems = false, exportMediaTypes = false, exportMediaTypesTypes = false, document } = options;
|
|
3164
3835
|
return ast([
|
|
3165
|
-
schemasCode(components, exportSchemas, exportSchemasTypes, readonly),
|
|
3836
|
+
schemasCode(components, exportSchemas, exportSchemasTypes, readonly, document),
|
|
3166
3837
|
responsesCode(components, exportResponses, readonly),
|
|
3167
3838
|
parametersCode(components, exportParameters, exportParametersTypes, readonly),
|
|
3168
3839
|
examplesCode(components, exportExamples, readonly),
|
|
@@ -3179,167 +3850,17 @@ function componentsCode(components, options) {
|
|
|
3179
3850
|
function routeCode(openapi, readonly) {
|
|
3180
3851
|
return makeRouteEntries(openapi, readonly).map((entry) => entry.code).join("\n\n");
|
|
3181
3852
|
}
|
|
3182
|
-
// src/helper/names.ts
|
|
3183
|
-
/**
|
|
3184
|
-
* Renames the components whose identifiers would collide, and every `$ref` to them.
|
|
3185
|
-
*
|
|
3186
|
-
* An identifier is made of the letters and digits of a component name, so
|
|
3187
|
-
* `api-response-common-failure` and `api_response_common_failure` (Cloudflare) are both
|
|
3188
|
-
* `ApiResponseCommonFailureSchema`: one declaration was silently lost, and a type alias
|
|
3189
|
-
* came to name itself (`type X = X`). The first component in document order keeps its
|
|
3190
|
-
* name; every later one that would share an identifier is numbered
|
|
3191
|
-
* (`api_response_common_failure2`, so `ApiResponseCommonFailure2Schema`), and the
|
|
3192
|
-
* references to it follow. The document that is emitted names the schema the new way too.
|
|
3193
|
-
*
|
|
3194
|
-
* Security schemes are left alone: `security` requirements name them, and a `$ref` does not.
|
|
3195
|
-
*/
|
|
3196
|
-
function uniqueComponentNames(document) {
|
|
3197
|
-
const components = document.components;
|
|
3198
|
-
if (!isRecord(components)) return document;
|
|
3199
|
-
const renames = COMPONENT_NAMES.flatMap((section) => {
|
|
3200
|
-
if (section === "securitySchemes") return [];
|
|
3201
|
-
const entries = components[section];
|
|
3202
|
-
if (!isRecord(entries)) return [];
|
|
3203
|
-
const identifier = (name) => toIdentifierPascalCase(ensureSuffix(name, COMPONENT_SUFFIXES$1[section]));
|
|
3204
|
-
const taken = /* @__PURE__ */ new Set();
|
|
3205
|
-
return Object.keys(entries).flatMap((name) => {
|
|
3206
|
-
const own = identifier(name);
|
|
3207
|
-
if (!taken.has(own)) {
|
|
3208
|
-
taken.add(own);
|
|
3209
|
-
return [];
|
|
3210
|
-
}
|
|
3211
|
-
const renamed = numbered(name, (candidate) => !taken.has(identifier(candidate)));
|
|
3212
|
-
taken.add(identifier(renamed));
|
|
3213
|
-
return [{
|
|
3214
|
-
section,
|
|
3215
|
-
name,
|
|
3216
|
-
renamed
|
|
3217
|
-
}];
|
|
3218
|
-
});
|
|
3219
|
-
});
|
|
3220
|
-
if (renames.length === 0) return document;
|
|
3221
|
-
const renamedSections = Object.fromEntries(COMPONENT_NAMES.flatMap((section) => {
|
|
3222
|
-
const entries = components[section];
|
|
3223
|
-
const own = renames.filter((rename) => rename.section === section);
|
|
3224
|
-
if (!isRecord(entries) || own.length === 0) return [];
|
|
3225
|
-
return [[section, Object.fromEntries(Object.entries(entries).map(([name, value]) => [own.find((rename) => rename.name === name)?.renamed ?? name, value]))]];
|
|
3226
|
-
}));
|
|
3227
|
-
const refs = new Map(renames.map((rename) => [`#/components/${rename.section}/${rename.name}`, rename]));
|
|
3228
|
-
const rewriteRef = (ref) => {
|
|
3229
|
-
if (!ref.startsWith("#/components/")) return ref;
|
|
3230
|
-
const segments = ref.split("/");
|
|
3231
|
-
const section = segments[2];
|
|
3232
|
-
const encoded = segments[3];
|
|
3233
|
-
const rest = segments.slice(4);
|
|
3234
|
-
if (section === void 0 || encoded === void 0) return ref;
|
|
3235
|
-
const rename = refs.get(`#/components/${section}/${decodePercent(encoded)}`);
|
|
3236
|
-
if (rename === void 0) return ref;
|
|
3237
|
-
return [
|
|
3238
|
-
"#",
|
|
3239
|
-
"components",
|
|
3240
|
-
section,
|
|
3241
|
-
encoded.includes("%") ? encodeURIComponent(rename.renamed) : rename.renamed,
|
|
3242
|
-
...rest
|
|
3243
|
-
].join("/");
|
|
3244
|
-
};
|
|
3245
|
-
const rewrite = (node) => {
|
|
3246
|
-
if (Array.isArray(node)) return node.map(rewrite);
|
|
3247
|
-
if (!isRecord(node)) return node;
|
|
3248
|
-
return Object.fromEntries(Object.entries(node).map(([key, value]) => {
|
|
3249
|
-
if (key === "$ref" && typeof value === "string") return [key, rewriteRef(value)];
|
|
3250
|
-
if (key === "mapping" && isRecord(value)) return [key, Object.fromEntries(Object.entries(value).map(([k, v]) => [k, typeof v === "string" ? rewriteRef(v) : v]))];
|
|
3251
|
-
return [key, rewrite(value)];
|
|
3252
|
-
}));
|
|
3253
|
-
};
|
|
3254
|
-
const rewritten = rewrite({
|
|
3255
|
-
...document,
|
|
3256
|
-
components: {
|
|
3257
|
-
...components,
|
|
3258
|
-
...renamedSections
|
|
3259
|
-
}
|
|
3260
|
-
});
|
|
3261
|
-
return isRecord(rewritten) ? {
|
|
3262
|
-
...document,
|
|
3263
|
-
...rewritten
|
|
3264
|
-
} : document;
|
|
3265
|
-
}
|
|
3266
|
-
/** `name2`, `name3`, ...: the first that `isFree`. */
|
|
3267
|
-
function numbered(name, isFree) {
|
|
3268
|
-
const candidates = (n) => isFree(`${name}${n}`) ? `${name}${n}` : candidates(n + 1);
|
|
3269
|
-
return candidates(2);
|
|
3270
|
-
}
|
|
3271
|
-
// src/helper/pointer.ts
|
|
3272
|
-
/**
|
|
3273
|
-
* Inlines every `$ref` whose pointer names no component, so that what reaches the
|
|
3274
|
-
* generators is either a component (`#/components/<section>/<name>`, emitted as the
|
|
3275
|
-
* identifier it is declared under) or the schema itself.
|
|
3276
|
-
*
|
|
3277
|
-
* A bundler keeps internal references as they are, and a document may refer to an inline
|
|
3278
|
-
* schema wherever it sits: `#/paths/~1partners~1upsert/put/requestBody/content/
|
|
3279
|
-
* application~1json/schema` (freee), or `#/components/parameters/Page/schema`. Named after
|
|
3280
|
-
* its last segment, such a reference became `SchemaSchema`, which nothing declares. The
|
|
3281
|
-
* target is already in the document, so it is written in place of the reference, with the
|
|
3282
|
-
* keywords beside the `$ref` (a `description`) kept over the target's own. A pointer that
|
|
3283
|
-
* names nothing, or that comes back to itself, is left as written.
|
|
3284
|
-
*/
|
|
3285
|
-
function inlinePointerRefs(document) {
|
|
3286
|
-
if (!hasInlinePointer(document)) return document;
|
|
3287
|
-
const inline = (node, inlining) => {
|
|
3288
|
-
if (Array.isArray(node)) return node.map((item) => inline(item, inlining));
|
|
3289
|
-
if (!isRecord(node)) return node;
|
|
3290
|
-
const walked = (record) => Object.fromEntries(Object.entries(record).map(([key, value]) => [key, inline(value, inlining)]));
|
|
3291
|
-
const { $ref, ...beside } = node;
|
|
3292
|
-
if (typeof $ref === "string" && isInlinePointer($ref) && !inlining.has($ref)) {
|
|
3293
|
-
const target = resolvePointer(document, $ref);
|
|
3294
|
-
if (isRecord(target)) {
|
|
3295
|
-
const inlined = inline(target, /* @__PURE__ */ new Set([...inlining, $ref]));
|
|
3296
|
-
if (isRecord(inlined)) return {
|
|
3297
|
-
...inlined,
|
|
3298
|
-
...walked(beside)
|
|
3299
|
-
};
|
|
3300
|
-
}
|
|
3301
|
-
}
|
|
3302
|
-
return walked(node);
|
|
3303
|
-
};
|
|
3304
|
-
return {
|
|
3305
|
-
...document,
|
|
3306
|
-
...Object.fromEntries(Object.entries(document).map(([key, value]) => [key, inline(value, /* @__PURE__ */ new Set())]))
|
|
3307
|
-
};
|
|
3308
|
-
}
|
|
3309
|
-
/** Whether any `$ref` under `node` is an inline pointer. */
|
|
3310
|
-
function hasInlinePointer(node) {
|
|
3311
|
-
if (Array.isArray(node)) return node.some(hasInlinePointer);
|
|
3312
|
-
if (!isRecord(node)) return false;
|
|
3313
|
-
const { $ref } = node;
|
|
3314
|
-
if (typeof $ref === "string" && isInlinePointer($ref)) return true;
|
|
3315
|
-
return Object.values(node).some(hasInlinePointer);
|
|
3316
|
-
}
|
|
3317
|
-
/** A local pointer that does not name a component, nor a property of a component schema. */
|
|
3318
|
-
function isInlinePointer(ref) {
|
|
3319
|
-
if (!ref.startsWith("#/")) return false;
|
|
3320
|
-
const segments = pointerSegments(ref);
|
|
3321
|
-
if (segments[0] !== "components") return true;
|
|
3322
|
-
if (segments.length === 3) return false;
|
|
3323
|
-
return !(segments[1] === "schemas" && segments[3] === "properties" && segments.length > 4);
|
|
3324
|
-
}
|
|
3325
|
-
/** The segments of a JSON Pointer fragment, decoded: percent-encoding, then `~1` and `~0` (RFC 6901 §6). */
|
|
3326
|
-
function pointerSegments(ref) {
|
|
3327
|
-
return ref.slice(2).split("/").map((segment) => decodePercent(segment).replaceAll("~1", "/").replaceAll("~0", "~"));
|
|
3328
|
-
}
|
|
3329
|
-
function resolvePointer(document, ref) {
|
|
3330
|
-
return pointerSegments(ref).reduce((node, segment) => {
|
|
3331
|
-
if (Array.isArray(node)) return node[Number(segment)];
|
|
3332
|
-
if (isRecord(node)) return Object.hasOwn(node, segment) ? node[segment] : void 0;
|
|
3333
|
-
}, document);
|
|
3334
|
-
}
|
|
3335
3853
|
// src/generator/zod-openapi-hono/openapi/webhooks/index.ts
|
|
3336
3854
|
function webhookCode(openapi, readonly) {
|
|
3337
3855
|
return makeWebhookEntries(openapi, readonly).map((entry) => entry.code).join("\n\n");
|
|
3338
3856
|
}
|
|
3339
3857
|
// src/generator/zod-openapi-hono/openapi/index.ts
|
|
3340
3858
|
function zodOpenAPIHono(document, options = {}) {
|
|
3341
|
-
const openapi =
|
|
3342
|
-
const components = openapi.components ? componentsCode(openapi.components,
|
|
3859
|
+
const openapi = normalizeOpenAPI(document);
|
|
3860
|
+
const components = openapi.components ? componentsCode(openapi.components, {
|
|
3861
|
+
...options,
|
|
3862
|
+
document: openapi
|
|
3863
|
+
}) : "";
|
|
3343
3864
|
const routes = routeCode(openapi, options.readonly);
|
|
3344
3865
|
const webhooks = webhookCode(openapi, options.readonly);
|
|
3345
3866
|
const output = [
|
|
@@ -3349,4 +3870,4 @@ function zodOpenAPIHono(document, options = {}) {
|
|
|
3349
3870
|
].filter((v) => v.length > 0).join("\n\n");
|
|
3350
3871
|
return `import{${routes.length > 0 || webhooks.length > 0 ? "createRoute,z" : "z"}}from'@hono/zod-openapi'\n\n${output}`;
|
|
3351
3872
|
}
|
|
3352
|
-
export {
|
|
3873
|
+
export { resolveParameter as A, zodToOpenAPI as C, makeRouteEntries as D, makeRef as E, makeRouteProperties as O, textOf as S, makePathItem as T, declarationOf as _, responsesCode as a, parseModule as b, headersCode as c, makeConst as d, makeExportConst as f, ast as g, analyzeCircularSchemas as h, schemasCode as i, resolvePathItem as j, makeWebhookEntries as k, makeSplitSchemaFile as l, makeModuleSpec as m, routeCode as n, requestBodiesCode as o, makeImports as p, componentsCode as r, parametersCode as s, zodOpenAPIHono as t, normalizeOpenAPI as u, descendantsWhere as v, makeCallback as w, parseSource as x, identifierNames as y };
|