hono-takibi 0.24.0 → 0.26.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.
@@ -1,5 +1,5 @@
1
- import { i as FORM_MEDIA_TYPES, r as COMPONENT_REF_PREFIX, s as HTTP_METHODS, t as ARROW_FUNCTION_PATTERN } from "./constants-Bz8YiPum.js";
2
- import { $ as isSchemaArray, A as isExamplesInput, C as hasNoUserChain, D as hasTypelessConstraint, F as isMedia, G as isPathItem, J as isRecord, K as isPathItemEntry, L as isOffsetTime, N as isInheritedName, O as isCallbacks, Q as isResponses, V as isParameter, W as isParameterRef, X as isRefOnly, Y as isRefObject, a as ensureSuffix, c as escapeRegexLiteral, d as makeSafeKey, et as isSchemaObject, f as makeStringLiteral, g as requestParamsArray, h as renderNamedImport, i as decodePercent, it as isSingleSchema, j as isHeader, k as isDiscriminableBranch, m as normalizeTypes, o as error, ot as isValidIdent, p as methodPath, q as isPathItemRef, r as cyclicNodes, t as baseError, v as toIdentifierPascalCase, w as hasNotProperty, x as zodToOpenAPISchema, y as uncapitalize, z as isOperation } from "./utils-Dznx-EnJ.js";
1
+ import { a as FORM_MEDIA_TYPES, c as HTTP_METHODS, i as COMPONENT_SUFFIXES$1, n as COMPONENT_NAMES, r as COMPONENT_REF_PREFIX, t as ARROW_FUNCTION_PATTERN } from "./constants-hwmOoQfI.js";
2
+ import { $ as isResponses, A as isCallbacks, B as isOperation, C as discriminatedBranches, E as hasNotProperty, G as isParameterRef, H as isParameter, I as isMedia, J as isPathItemRef, K as isPathItem, M as isHeader, P as isInheritedName, R as isOffsetTime, S as zodToOpenAPISchema, T as hasNoUserChain, X as isRefObject, Y as isRecord, Z as isRefOnly, _ as routeName, a as ensureSuffix, at as isSingleSchema, b as uncapitalize, c as escapeRegexLiteral, d as makeSafeKey, et as isSchemaArray, f as makeStringLiteral, g as requestParamsArray, h as renderNamedImport, i as decodePercent, j as isExamplesInput, k as hasTypelessConstraint, m as regexLiteral, o as error, p as normalizeTypes, q as isPathItemEntry, r as cyclicNodes, st as isValidIdent, t as baseError, tt as isSchemaObject, y as toIdentifierPascalCase } from "./utils-Bw0Q2Ozg.js";
3
3
  import path from "node:path";
4
4
  import { parseSync, visitorKeys } from "oxc-parser";
5
5
  //#region src/helper/wire.ts
@@ -498,59 +498,14 @@ function isEmptyAbsent(parameter, schemas) {
498
498
  //#endregion
499
499
  //#region src/helper/openapi.ts
500
500
  function makeRef($ref) {
501
- const COMPONENT_SUFFIX_MAP = [
502
- {
503
- prefix: COMPONENT_REF_PREFIX.schemas,
504
- suffix: "Schema"
505
- },
506
- {
507
- prefix: COMPONENT_REF_PREFIX.parameters,
508
- suffix: "ParamsSchema"
509
- },
510
- {
511
- prefix: COMPONENT_REF_PREFIX.headers,
512
- suffix: "HeaderSchema"
513
- },
514
- {
515
- prefix: COMPONENT_REF_PREFIX.securitySchemes,
516
- suffix: "SecurityScheme"
517
- },
518
- {
519
- prefix: COMPONENT_REF_PREFIX.requestBodies,
520
- suffix: "RequestBody"
521
- },
522
- {
523
- prefix: COMPONENT_REF_PREFIX.responses,
524
- suffix: "Response"
525
- },
526
- {
527
- prefix: COMPONENT_REF_PREFIX.examples,
528
- suffix: "Example"
529
- },
530
- {
531
- prefix: COMPONENT_REF_PREFIX.links,
532
- suffix: "Link"
533
- },
534
- {
535
- prefix: COMPONENT_REF_PREFIX.callbacks,
536
- suffix: "Callback"
537
- },
538
- {
539
- prefix: COMPONENT_REF_PREFIX.pathItems,
540
- suffix: "PathItem"
541
- },
542
- {
543
- prefix: COMPONENT_REF_PREFIX.mediaTypes,
544
- suffix: "MediaTypeSchema"
545
- }
546
- ];
547
501
  const propertiesMatch = $ref.match(/^#\/components\/schemas\/([^/]+)\/properties\/(.+)$/u);
548
502
  if (propertiesMatch) return `z.lazy(()=>${toIdentifierPascalCase(ensureSuffix(decodePercent(propertiesMatch[1]), "Schema"))})`;
549
503
  const rawRef = $ref.split("/").at(-1);
550
504
  if (!rawRef) return "Schema";
551
505
  const decodedRef = decodePercent(rawRef);
552
- const match = COMPONENT_SUFFIX_MAP.find(({ prefix }) => $ref.startsWith(prefix));
553
- return toIdentifierPascalCase(ensureSuffix(decodedRef, match?.suffix ?? "Schema"));
506
+ const section = COMPONENT_NAMES.find((name) => $ref.startsWith(COMPONENT_REF_PREFIX[name]));
507
+ const suffix = section === void 0 ? "Schema" : COMPONENT_SUFFIXES$1[section];
508
+ return toIdentifierPascalCase(ensureSuffix(decodedRef, suffix));
554
509
  }
555
510
  function makeExamples(examples) {
556
511
  return `{${Object.entries(examples).map(([k, example]) => {
@@ -900,7 +855,7 @@ function makeRouteEntries(openapi, readonly) {
900
855
  parameters
901
856
  } : operation, readonly, openapi.components?.schemas);
902
857
  const asConst = readonly ? " as const" : "";
903
- const entryName = methodPath(method, path);
858
+ const entryName = routeName(method, path, openapi.paths);
904
859
  return [{
905
860
  name: entryName,
906
861
  code: `export const ${entryName}Route=createRoute({${properties}}${asConst})`
@@ -937,6 +892,7 @@ function makeWebhookEntries(openapi, readonly) {
937
892
  }
938
893
  //#endregion
939
894
  //#region src/helper/wrap.ts
895
+ const structuralProps = /* @__PURE__ */ new Set(["$defs", "definitions"]);
940
896
  const zodExpressedProps = /* @__PURE__ */ new Set([
941
897
  "type",
942
898
  "format",
@@ -1078,8 +1034,24 @@ const decorationProps = /* @__PURE__ */ new Set([
1078
1034
  function undecorated(schema) {
1079
1035
  return Object.entries(schema).reduce((kept, [key, value]) => zodExpressedProps.has(key) && !decorationProps.has(key) ? Object.assign(kept, { [key]: value }) : kept, {});
1080
1036
  }
1037
+ /** The keys of a Parameter Object (OpenAPI 3.1 §4.8.12); a document may carry others. */
1038
+ const PARAMETER_KEYS = /* @__PURE__ */ new Set([
1039
+ "name",
1040
+ "in",
1041
+ "description",
1042
+ "required",
1043
+ "deprecated",
1044
+ "allowEmptyValue",
1045
+ "style",
1046
+ "explode",
1047
+ "allowReserved",
1048
+ "schema",
1049
+ "content",
1050
+ "example",
1051
+ "examples"
1052
+ ]);
1081
1053
  function makeSerializedParam(param) {
1082
- return `{${Object.entries(param).filter(([, value]) => value !== void 0).map(([key, value]) => {
1054
+ return `{${Object.entries(param).filter(([key, value]) => value !== void 0 && (PARAMETER_KEYS.has(key) || key.startsWith("x-"))).map(([key, value]) => {
1083
1055
  if (key === "examples" && isExamplesInput(value)) return `"examples":${makeExamples(value)}`;
1084
1056
  if (key === "content" && isRecord(value)) return `"content":{${Object.entries(value).map(([mediaType, mediaObj]) => {
1085
1057
  if (!isRecord(mediaObj)) return `${JSON.stringify(mediaType)}:${JSON.stringify(mediaObj)}`;
@@ -1092,6 +1064,96 @@ function makeSerializedParam(param) {
1092
1064
  return `${JSON.stringify(key)}:${JSON.stringify(value)}`;
1093
1065
  }).join(",")}}`;
1094
1066
  }
1067
+ /**
1068
+ * The default as a value of its schema, or that it is not one. A string that spells a
1069
+ * boolean (`'true'`) or a number (`'10'`) for a schema of that type is read as the value
1070
+ * (YAML and query strings arrive as text); a number for a string is written as text. An
1071
+ * enum or const takes only what it lists; an array takes an array whose every item
1072
+ * conforms. A schema with no type of its own (a reference, a `oneOf`) is not checked.
1073
+ */
1074
+ function conformDefault(schema, value) {
1075
+ if (value === void 0) return { ok: false };
1076
+ if (value === null) return {
1077
+ ok: true,
1078
+ value
1079
+ };
1080
+ if (schema.enum !== void 0) return schema.enum.some((member) => member === value) ? {
1081
+ ok: true,
1082
+ value
1083
+ } : { ok: false };
1084
+ if (schema.const !== void 0) return JSON.stringify(schema.const) === JSON.stringify(value) ? {
1085
+ ok: true,
1086
+ value
1087
+ } : { ok: false };
1088
+ const types = (Array.isArray(schema.type) ? schema.type : [schema.type]).filter((t) => t !== void 0 && t !== "null");
1089
+ if (types.length === 0) return {
1090
+ ok: true,
1091
+ value
1092
+ };
1093
+ const read = (type) => {
1094
+ if (type === "boolean") {
1095
+ if (typeof value === "boolean") return {
1096
+ ok: true,
1097
+ value
1098
+ };
1099
+ if (value === "true" || value === "false") return {
1100
+ ok: true,
1101
+ value: value === "true"
1102
+ };
1103
+ return;
1104
+ }
1105
+ if (type === "number" || type === "integer") {
1106
+ const number = typeof value === "number" ? value : typeof value === "string" && value.trim() !== "" && Number.isFinite(Number(value)) ? Number(value) : void 0;
1107
+ if (number === void 0) return void 0;
1108
+ if (type === "integer" && !Number.isInteger(number)) return void 0;
1109
+ return {
1110
+ ok: true,
1111
+ value: number
1112
+ };
1113
+ }
1114
+ if (type === "string") {
1115
+ if (typeof value === "string") return {
1116
+ ok: true,
1117
+ value
1118
+ };
1119
+ if (typeof value === "number" || typeof value === "boolean") return {
1120
+ ok: true,
1121
+ value: String(value)
1122
+ };
1123
+ return;
1124
+ }
1125
+ if (type === "array") {
1126
+ if (!Array.isArray(value)) return void 0;
1127
+ const items = schema.items;
1128
+ if (items === void 0 || typeof items === "boolean" || isSchemaArray(items)) return {
1129
+ ok: true,
1130
+ value
1131
+ };
1132
+ const readItems = value.map((item) => conformDefault(items, item));
1133
+ return readItems.every((item) => item.ok) ? {
1134
+ ok: true,
1135
+ value: readItems.map((item) => item.ok ? item.value : void 0)
1136
+ } : void 0;
1137
+ }
1138
+ if (type === "object") return isRecord(value) ? {
1139
+ ok: true,
1140
+ value
1141
+ } : void 0;
1142
+ return {
1143
+ ok: true,
1144
+ value
1145
+ };
1146
+ };
1147
+ const asIs = types.find((type) => typeOf(value) === type);
1148
+ return (asIs === void 0 ? void 0 : read(asIs)) ?? types.map(read).find((result) => result !== void 0) ?? { ok: false };
1149
+ }
1150
+ function typeOf(value) {
1151
+ if (typeof value === "boolean") return "boolean";
1152
+ if (typeof value === "number") return Number.isInteger(value) ? "integer" : "number";
1153
+ if (typeof value === "string") return "string";
1154
+ if (Array.isArray(value)) return "array";
1155
+ if (isRecord(value)) return "object";
1156
+ }
1095
1157
  function wrap(zod, schema, meta, options) {
1096
1158
  const unsupportedProps = /* @__PURE__ */ new Set([
1097
1159
  "$recursiveRef",
@@ -1136,11 +1198,14 @@ function wrap(zod, schema, meta, options) {
1136
1198
  const style = parameter === void 0 ? void 0 : wireStyle(parameter, typeList.includes("array"));
1137
1199
  const readers = [...options?.readers ?? [], ...style === void 0 ? [] : [style]];
1138
1200
  const acceptBothArities = (inner) => readers.reduceRight((read, reader) => `z.preprocess(${reader},${read})`, inner);
1139
- const isNullable = schema.nullable === true || (Array.isArray(schema.type) ? schema.type.includes("null") : schema.type === "null");
1201
+ const conformed = conformDefault(schema, schema.default);
1202
+ const defaultValue = conformed.ok ? conformed.value : void 0;
1203
+ const droppedDefault = schema.default !== void 0 && !conformed.ok;
1204
+ const isNullable = schema.nullable === true || typeList.includes("null") || defaultValue === null;
1140
1205
  const build = (core) => {
1141
1206
  const typed = isNullable ? `${acceptBothArities(core)}.nullable()` : acceptBothArities(core);
1142
1207
  const n = options?.nullRead === "first" ? `z.preprocess(${WIRE_NULL},${typed})` : options?.nullRead === "last" ? `((schema)=>z.union([schema,z.preprocess(${WIRE_NULL},schema)]))(${typed})` : typed;
1143
- const d = schema.default !== void 0 ? `${n}.default(${formatLiteral(schema.default)})` : n;
1208
+ const d = defaultValue !== void 0 ? `${n}.default(${formatLiteral(defaultValue)})` : n;
1144
1209
  const pf = schema["x-prefault"] !== void 0 ? `${d}.prefault(${formatLiteral(schema["x-prefault"])})` : d;
1145
1210
  const c = schema["x-catch"] !== void 0 ? `${pf}.catch(${formatLiteral(schema["x-catch"])})` : pf;
1146
1211
  const superRefineChain = `${`${schema["x-readonly"] === true ? `${c}.readonly()` : c}${schema["x-refine"] ?? ""}`}${schema["x-superRefine"] ?? ""}`;
@@ -1157,21 +1222,21 @@ function wrap(zod, schema, meta, options) {
1157
1222
  const absentReaders = [...options?.inheritedAbsent === true ? [WIRE_INHERITED] : [], ...options?.emptyAbsent === true ? [WIRE_EMPTY] : []];
1158
1223
  if (absentReaders.length === 0) return chain;
1159
1224
  const read = (inner) => absentReaders.reduceRight((inside, reader) => `z.preprocess(${reader},${inside})`, inner);
1160
- if (schema.default !== void 0) return `${read(chain)}.default(${formatLiteral(schema.default)})`;
1225
+ if (defaultValue !== void 0) return `${read(chain)}.default(${formatLiteral(defaultValue)})`;
1161
1226
  return read(`${chain}${(parameter === void 0 ? options?.isOptional !== true : parameter.required === true) ? "" : ".optional()"}`);
1162
1227
  };
1163
1228
  const z = absent(build(around(zod)));
1164
1229
  const headerDupKeys = new Set(meta?.headers ? Object.entries(meta.headers).filter(([, v]) => v !== void 0).map(([k]) => k) : []);
1165
- const args = filterUnsupportedProps(Object.fromEntries(Object.entries(schema).filter(([k, v]) => !(zodExpressedProps.has(k) || k === "required" && typeof v === "boolean" || headerDupKeys.has(k)))));
1230
+ const args = filterUnsupportedProps(Object.fromEntries([
1231
+ ...Object.entries(schema).filter(([k, v]) => !(zodExpressedProps.has(k) || structuralProps.has(k) || k === "required" && typeof v === "boolean" || headerDupKeys.has(k))),
1232
+ ...droppedDefault ? [["default", schema.default]] : [],
1233
+ ...typeof schema.pattern === "string" && regexLiteral(schema.pattern) === void 0 ? [["pattern", schema.pattern]] : []
1234
+ ]));
1166
1235
  const headerMetaProps = meta?.headers ? [
1167
1236
  meta.headers.description ? `description:${JSON.stringify(meta.headers.description)}` : void 0,
1168
1237
  meta.headers.deprecated ? `deprecated:${JSON.stringify(meta.headers.deprecated)}` : void 0,
1169
1238
  meta.headers.example ? `example:${JSON.stringify(meta.headers.example)}` : void 0,
1170
- meta.headers.examples ? `examples:${makeExamples(meta.headers.examples)}` : void 0,
1171
- meta.headers.style ? `style:${JSON.stringify(meta.headers.style)}` : void 0,
1172
- meta.headers.explode ? `explode:${JSON.stringify(meta.headers.explode)}` : void 0,
1173
- meta.headers.allowReserved ? `allowReserved:${JSON.stringify(meta.headers.allowReserved)}` : void 0,
1174
- meta.headers.content ? `content:${JSON.stringify(meta.headers.content)}` : void 0
1239
+ meta.headers.examples ? `examples:${makeExamples(meta.headers.examples)}` : void 0
1175
1240
  ].filter((v) => v !== void 0) : [];
1176
1241
  const openapiSchema = args ? JSON.stringify(args) : void 0;
1177
1242
  const openapiSchemaBody = openapiSchema?.startsWith("{") && openapiSchema?.endsWith("}") ? openapiSchema.slice(1, -1) : openapiSchema;
@@ -1271,8 +1336,10 @@ function issueObj(messageExpr, pathExpr) {
1271
1336
  return `{${parts.join(",")}}`;
1272
1337
  }
1273
1338
  function makeObjectChecks(schema, recurse) {
1274
- const ownKeysJson = JSON.stringify(Object.keys(schema.properties ?? {}));
1275
- const patternsJson = JSON.stringify(Object.keys(schema.patternProperties ?? {}));
1339
+ const ownKeys = Object.keys(schema.properties ?? {});
1340
+ const patterns = Object.keys(schema.patternProperties ?? {});
1341
+ const declared = [...ownKeys.length > 0 ? [`!${JSON.stringify(ownKeys)}.includes(k)`] : [], ...patterns.length > 0 ? [`!${JSON.stringify(patterns)}.some((p)=>new RegExp(p).test(k))`] : []];
1342
+ const forUndeclaredKeys = (body) => `for(const k of Object.keys(val)){${declared.length === 0 ? body : `if(${declared.join("&&")}){${body}}`}}`;
1276
1343
  const requiredMessage = messageFor(schema, "required");
1277
1344
  const requiredChecks = Array.isArray(schema.required) ? schema.required.map((key) => `if(!Object.hasOwn(val,${JSON.stringify(key)})){ctx.addIssue(${issueObj(requiredMessage)})}`) : [];
1278
1345
  const minPropertiesCheck = typeof schema.minProperties === "number" ? `if(Object.keys(val).length<${schema.minProperties}){ctx.addIssue(${issueObj(messageFor(schema, "minProperties"))})}` : void 0;
@@ -1281,8 +1348,8 @@ function makeObjectChecks(schema, recurse) {
1281
1348
  const propertyChecks = schema.properties ? Object.entries(schema.properties).map(([key, sub]) => `if(Object.hasOwn(val,${JSON.stringify(key)})){const Schema=${recurse(sub)};if(!Schema.safeParse(Reflect.get(val,${JSON.stringify(key)})).success){ctx.addIssue(${issueObj(propertiesMessage)})}}`) : [];
1282
1349
  const additionalPropertiesMessage = messageFor(schema, "additionalProperties");
1283
1350
  const additionalPropertiesCheck = (() => {
1284
- if (schema.additionalProperties === false) return `for(const k of Object.keys(val)){if(!${ownKeysJson}.includes(k)&&!${patternsJson}.some((p)=>new RegExp(p).test(k))){ctx.addIssue(${issueObj(additionalPropertiesMessage)})}}`;
1285
- if (isSchemaObject(schema.additionalProperties)) return `{const Schema=${recurse(schema.additionalProperties)};for(const k of Object.keys(val)){if(!${ownKeysJson}.includes(k)&&!${patternsJson}.some((p)=>new RegExp(p).test(k))){if(!Schema.safeParse(Reflect.get(val,k)).success){ctx.addIssue(${issueObj(additionalPropertiesMessage)})}}}}`;
1351
+ if (schema.additionalProperties === false) return forUndeclaredKeys(`ctx.addIssue(${issueObj(additionalPropertiesMessage)})`);
1352
+ if (isSchemaObject(schema.additionalProperties)) return `{const Schema=${recurse(schema.additionalProperties)};${forUndeclaredKeys(`if(!Schema.safeParse(Reflect.get(val,k)).success){ctx.addIssue(${issueObj(additionalPropertiesMessage)})}`)}}`;
1286
1353
  })();
1287
1354
  const patternPropertiesMessage = messageFor(schema, "patternProperties");
1288
1355
  const patternPropertiesChecks = schema.patternProperties ? Object.entries(schema.patternProperties).map(([pattern, sub]) => `{const Schema=${recurse(sub)};for(const k of Object.keys(val)){if(new RegExp(${JSON.stringify(pattern)}).test(k)){if(!Schema.safeParse(Reflect.get(val,k)).success){ctx.addIssue(${issueObj(patternPropertiesMessage)})}}}}`) : [];
@@ -1295,7 +1362,7 @@ function makeObjectChecks(schema, recurse) {
1295
1362
  const dependentSchemasMessage = messageFor(schema, "dependentSchemas");
1296
1363
  const dependentSchemasMessageField = dependentSchemasMessage !== void 0 ? `,message:${JSON.stringify(dependentSchemasMessage)}` : "";
1297
1364
  const dependentSchemasChecks = schema.dependentSchemas ? Object.entries(schema.dependentSchemas).map(([key, sub]) => `if(Object.hasOwn(val,${JSON.stringify(key)})){const Schema=${recurse(sub)};const result=Schema.safeParse(val);if(!result.success){for(const issue of result.error.issues){ctx.addIssue({...issue,path:issue.path${dependentSchemasMessageField}})}}}`) : [];
1298
- const unevaluatedPropertiesCheck = schema.unevaluatedProperties === false ? `for(const k of Object.keys(val)){if(!${ownKeysJson}.includes(k)&&!${patternsJson}.some((p)=>new RegExp(p).test(k))){ctx.addIssue(${issueObj(messageFor(schema, "unevaluatedProperties"))})}}` : void 0;
1365
+ const unevaluatedPropertiesCheck = schema.unevaluatedProperties === false ? forUndeclaredKeys(`ctx.addIssue(${issueObj(messageFor(schema, "unevaluatedProperties"))})`) : void 0;
1299
1366
  return [
1300
1367
  ...requiredChecks,
1301
1368
  minPropertiesCheck,
@@ -1903,9 +1970,9 @@ function string(schema, options) {
1903
1970
  const endUpper = usePipe ? "" : postUpper;
1904
1971
  const endNormalize = usePipe ? "" : postNormalize;
1905
1972
  const patternMessage = schema["x-pattern-message"] ?? errorMessage;
1906
- const hasUnicodeProperty = schema.pattern && /\\[pP]\{/u.test(schema.pattern);
1907
1973
  const patternMessagePart = patternMessage ? `,${error(patternMessage)}` : "";
1908
- const pattern = schema.pattern ? `.regex(/${escapeRegexLiteral(schema.pattern)}/${hasUnicodeProperty ? "u" : ""}${patternMessagePart})` : void 0;
1974
+ const literal = schema.pattern === void 0 ? void 0 : regexLiteral(schema.pattern);
1975
+ const pattern = literal ? `.regex(/${escapeRegexLiteral(literal.source)}/${literal.flags}${patternMessagePart})` : void 0;
1909
1976
  const lengthMessage = schema["x-length-message"] ?? errorMessage;
1910
1977
  const lengthMessagePart = lengthMessage ? `,${error(lengthMessage)}` : "";
1911
1978
  const minLengthMessage = schema["x-minLength-message"] ?? errorMessage;
@@ -2074,16 +2141,7 @@ function zodToOpenAPI(schema, meta, options) {
2074
2141
  const discriminator = schema.discriminator?.propertyName;
2075
2142
  const oneOfMessage = schema["x-oneOf-message"] ?? schema["x-error-message"];
2076
2143
  const oneOfErrorArg = oneOfMessage ? `,${error(oneOfMessage)}` : "";
2077
- const branches = schema.oneOf.map((s) => s.$ref === void 0 ? s : isRefOnly(s) && s.$ref.startsWith(COMPONENT_REF_PREFIX.schemas) ? options?.schemas?.[decodePercent(s.$ref.slice(COMPONENT_REF_PREFIX.schemas.length))] : void 0);
2078
- const literalsPerBranch = branches.map((branch) => {
2079
- if (discriminator === void 0 || branch === void 0) return void 0;
2080
- if (!isDiscriminableBranch(branch, discriminator)) return void 0;
2081
- const property = branch.properties?.[discriminator];
2082
- if (property === void 0 || typeof property === "boolean") return void 0;
2083
- return typeof property.const === "string" ? [property.const] : property.enum ?? [];
2084
- });
2085
- const literals = literalsPerBranch.flatMap((values) => values ?? []);
2086
- return done(discriminator !== void 0 && branches.length >= 2 && literalsPerBranch.every((values) => values !== void 0) && new Set(literals).size === literals.length ? `z.discriminatedUnion(${makeStringLiteral(discriminator)},[${oneOfSchemas.join(",")}]${oneOfErrorArg})` : `z.xor([${oneOfSchemas.join(",")}]${oneOfErrorArg})`, schema);
2144
+ return done(discriminator !== void 0 && discriminatedBranches(schema, options?.schemas) !== void 0 ? `z.discriminatedUnion(${makeStringLiteral(discriminator)},[${oneOfSchemas.join(",")}]${oneOfErrorArg})` : `z.xor([${oneOfSchemas.join(",")}]${oneOfErrorArg})`, schema);
2087
2145
  }
2088
2146
  if (schema.not !== void 0) {
2089
2147
  const notMessage = schema["x-not-message"] ?? schema["x-error-message"];
@@ -2418,18 +2476,24 @@ function findCyclicSchemas(names, deps) {
2418
2476
  const nameDeps = new Map(names.map((n) => [n, (deps.get(n) ?? []).map((v) => var2name.get(v)).filter((x) => x !== void 0)]));
2419
2477
  return cyclicNodes(nameDeps);
2420
2478
  }
2479
+ /** Every schema under `schema`, itself first: the shapes a schema nests another in. */
2480
+ function nestedSchemas(schema) {
2481
+ if (schema === void 0 || typeof schema === "boolean") return [];
2482
+ const items = isSchemaArray(schema.items) ? schema.items : [schema.items];
2483
+ return [schema, ...[
2484
+ ...Object.values(schema.properties ?? {}),
2485
+ ...Object.values(schema.patternProperties ?? {}),
2486
+ ...schema.prefixItems ?? [],
2487
+ ...items,
2488
+ schema.additionalProperties,
2489
+ ...schema.allOf ?? [],
2490
+ ...schema.anyOf ?? [],
2491
+ ...schema.oneOf ?? [],
2492
+ schema.not
2493
+ ].flatMap(nestedSchemas)];
2494
+ }
2421
2495
  function findDiscriminatedBranches(schemas, schemaNames) {
2422
- return new Set(schemaNames.flatMap((n) => {
2423
- const schema = schemas[n];
2424
- const discriminator = schema?.discriminator?.propertyName;
2425
- if (discriminator === void 0 || schema?.oneOf === void 0) return [];
2426
- return schema.oneOf.flatMap((branch) => {
2427
- if (!(isRefOnly(branch) && branch.$ref?.startsWith(COMPONENT_REF_PREFIX.schemas))) return [];
2428
- const name = decodePercent(branch.$ref.slice(COMPONENT_REF_PREFIX.schemas.length));
2429
- const target = schemas[name];
2430
- return target && isDiscriminableBranch(target, discriminator) ? [name] : [];
2431
- });
2432
- }));
2496
+ return new Set(schemaNames.flatMap((n) => nestedSchemas(schemas[n])).flatMap((schema) => discriminatedBranches(schema, schemas) ?? []).flatMap(({ name }) => name === void 0 ? [] : [name]));
2433
2497
  }
2434
2498
  function analyzeCircularSchemas(schemas, schemaNames, readonly) {
2435
2499
  const varNameSet = new Set(schemaNames.map((n) => toIdentifierPascalCase(ensureSuffix(n, "Schema"))));
@@ -2590,20 +2654,29 @@ function makeImports(code, fromFile, components, split = false, honoExtras = [])
2590
2654
  //#region src/helper/type.ts
2591
2655
  function makeTypeString(schema, selfTypeName, cyclicGroup, readonly) {
2592
2656
  if (!schema) return "unknown";
2657
+ if (Object.keys(schema).length === 0) return "unknown";
2658
+ const types = normalizeType(schema);
2659
+ const isNullable = schema.nullable === true || types.includes("null") || schema.default === null || (schema.enum?.includes(null) ?? false);
2660
+ const baseType = makeNonNullTypeString(schema, types.filter((t) => t !== "null"), selfTypeName, cyclicGroup, readonly);
2661
+ if (!isNullable || baseType === "null") return baseType;
2662
+ return `(${baseType}|null)`;
2663
+ }
2664
+ function makeNonNullTypeString(schema, types, selfTypeName, cyclicGroup, readonly) {
2593
2665
  if (schema.$ref) return makeRefTypeString(schema.$ref, selfTypeName);
2594
2666
  if (schema.oneOf && schema.oneOf.length > 0) return makeUnionTypeString(schema.oneOf, selfTypeName, cyclicGroup, "|", readonly);
2595
2667
  if (schema.anyOf && schema.anyOf.length > 0) return makeUnionTypeString(schema.anyOf, selfTypeName, cyclicGroup, "|", readonly);
2596
2668
  if (schema.allOf && schema.allOf.length > 0) return makeUnionTypeString(schema.allOf, selfTypeName, cyclicGroup, "&", readonly);
2597
- if (schema.enum && schema.enum.length > 0) return schema.enum.map((v) => typeof v === "string" ? makeStringLiteral(v) : String(v)).join("|");
2669
+ if (schema.enum && schema.enum.length > 0) {
2670
+ const values = schema.enum.filter((v) => v !== null);
2671
+ if (values.length === 0) return "null";
2672
+ return values.map((v) => typeof v === "string" ? makeStringLiteral(v) : String(v)).join("|");
2673
+ }
2598
2674
  if (schema.const !== void 0) {
2599
2675
  if (typeof schema.const === "string") return makeStringLiteral(schema.const);
2600
2676
  if (typeof schema.const === "number" || typeof schema.const === "boolean") return String(schema.const);
2601
2677
  return JSON.stringify(schema.const);
2602
2678
  }
2603
- const types = normalizeType(schema);
2604
- const isNullable = schema.nullable === true || types.includes("null");
2605
- const baseType = makeBaseTypeString(schema, types.filter((t) => t !== "null"), selfTypeName, cyclicGroup, readonly);
2606
- return isNullable ? `(${baseType}|null)` : baseType;
2679
+ return makeBaseTypeString(schema, types, selfTypeName, cyclicGroup, readonly);
2607
2680
  }
2608
2681
  function makeRefTypeString(ref, selfTypeName) {
2609
2682
  const propertiesMatch = ref.match(/^#\/components\/schemas\/([^/]+)\/properties\//u);
@@ -2632,15 +2705,18 @@ function makeBaseTypeString(schema, types, selfTypeName, cyclicGroup, readonly)
2632
2705
  function makeSingleTypeString(schema, type, selfTypeName, cyclicGroup, readonly) {
2633
2706
  if (type === "string") return "string";
2634
2707
  if (type === "number") return "number";
2635
- if (type === "integer") return "number";
2708
+ if (type === "integer") return isBigintFormat(schema) ? "bigint" : "number";
2636
2709
  if (type === "boolean") return "boolean";
2637
2710
  if (type === "null") return "null";
2638
2711
  if (type === "array") return makeArrayTypeString(schema, selfTypeName, cyclicGroup, readonly);
2639
2712
  if (type === "object") return makeObjectTypeString(schema, selfTypeName, cyclicGroup, readonly);
2640
2713
  return "unknown";
2641
2714
  }
2715
+ function isBigintFormat(schema) {
2716
+ return schema.format === "int64" || schema.format === "uint64" || schema.format === "bigint";
2717
+ }
2642
2718
  function wrapForArrayElement(type) {
2643
- return type.startsWith("readonly ") ? `(${type})` : type;
2719
+ return type.startsWith("readonly ") || type.includes("|") && !type.startsWith("(") ? `(${type})` : type;
2644
2720
  }
2645
2721
  function makeArrayTypeString(schema, selfTypeName, cyclicGroup, readonly) {
2646
2722
  const prefix = readonly ? "readonly " : "";
@@ -2656,18 +2732,6 @@ function makeArrayTypeString(schema, selfTypeName, cyclicGroup, readonly) {
2656
2732
  if (firstItem !== void 0) return `${prefix}${wrapForArrayElement(makeTypeString(firstItem, selfTypeName, cyclicGroup, readonly))}[]`;
2657
2733
  return `${prefix}unknown[]`;
2658
2734
  }
2659
- if (items.$ref) {
2660
- const propertiesMatch = items.$ref.match(/^#\/components\/schemas\/([^/]+)\/properties\//u);
2661
- if (propertiesMatch) {
2662
- const parentName = toIdentifierPascalCase(decodePercent(propertiesMatch[1]));
2663
- if (parentName === selfTypeName) return `${prefix}${parentName}Type[]`;
2664
- return `${prefix}z.infer<typeof ${parentName}Schema>[]`;
2665
- }
2666
- const rawRef = items.$ref.split("/").at(-1) ?? "";
2667
- const refName = toIdentifierPascalCase(decodePercent(rawRef));
2668
- if (refName === selfTypeName) return `${prefix}${refName}Type[]`;
2669
- return `${prefix}z.infer<typeof ${refName}Schema>[]`;
2670
- }
2671
2735
  return `${prefix}${wrapForArrayElement(makeTypeString(items, selfTypeName, cyclicGroup, readonly))}[]`;
2672
2736
  }
2673
2737
  function makeObjectTypeString(schema, selfTypeName, cyclicGroup, readonly) {
@@ -2703,7 +2767,10 @@ function makeObjectTypeString(schema, selfTypeName, cyclicGroup, readonly) {
2703
2767
  */
2704
2768
  function zodType(schema, typeName, cyclicGroup, readonly) {
2705
2769
  const isRecordLike = (Array.isArray(schema.type) ? schema.type.includes("object") : schema.type === "object") && schema.additionalProperties && (!schema.properties || Object.keys(schema.properties).length === 0);
2706
- if (cyclicGroup && cyclicGroup.size > 0 && isRecordLike) return `type ${typeName}Type = {[key:string]:${makeTypeString(typeof schema.additionalProperties === "object" ? schema.additionalProperties : {}, typeName, cyclicGroup, readonly)}}`;
2770
+ if (cyclicGroup && cyclicGroup.size > 0 && isRecordLike) {
2771
+ const record = `{[key:string]:${makeTypeString(typeof schema.additionalProperties === "object" ? schema.additionalProperties : {}, typeName, cyclicGroup, readonly)}}`;
2772
+ return `type ${typeName}Type = ${schema.nullable === true || Array.isArray(schema.type) && schema.type.includes("null") ? `${record}|null` : record}`;
2773
+ }
2707
2774
  return `type ${typeName}Type=${makeTypeString(schema, typeName, cyclicGroup, readonly)}`;
2708
2775
  }
2709
2776
  //#endregion
@@ -3073,13 +3140,160 @@ function routeCode(openapi, readonly) {
3073
3140
  return makeRouteEntries(openapi, readonly).map((entry) => entry.code).join("\n\n");
3074
3141
  }
3075
3142
  //#endregion
3143
+ //#region src/helper/names.ts
3144
+ /**
3145
+ * Renames the components whose identifiers would collide, and every `$ref` to them.
3146
+ *
3147
+ * An identifier is made of the letters and digits of a component name, so
3148
+ * `api-response-common-failure` and `api_response_common_failure` (Cloudflare) are both
3149
+ * `ApiResponseCommonFailureSchema`: one declaration was silently lost, and a type alias
3150
+ * came to name itself (`type X = X`). The first component in document order keeps its
3151
+ * name; every later one that would share an identifier is numbered
3152
+ * (`api_response_common_failure2`, so `ApiResponseCommonFailure2Schema`), and the
3153
+ * references to it follow. The document that is emitted names the schema the new way too.
3154
+ *
3155
+ * Security schemes are left alone: `security` requirements name them, and a `$ref` does not.
3156
+ */
3157
+ function uniqueComponentNames(document) {
3158
+ const components = document.components;
3159
+ if (!isRecord(components)) return document;
3160
+ const renames = COMPONENT_NAMES.flatMap((section) => {
3161
+ if (section === "securitySchemes") return [];
3162
+ const entries = components[section];
3163
+ if (!isRecord(entries)) return [];
3164
+ const identifier = (name) => toIdentifierPascalCase(ensureSuffix(name, COMPONENT_SUFFIXES$1[section]));
3165
+ const taken = /* @__PURE__ */ new Set();
3166
+ return Object.keys(entries).flatMap((name) => {
3167
+ const own = identifier(name);
3168
+ if (!taken.has(own)) {
3169
+ taken.add(own);
3170
+ return [];
3171
+ }
3172
+ const renamed = numbered(name, (candidate) => !taken.has(identifier(candidate)));
3173
+ taken.add(identifier(renamed));
3174
+ return [{
3175
+ section,
3176
+ name,
3177
+ renamed
3178
+ }];
3179
+ });
3180
+ });
3181
+ if (renames.length === 0) return document;
3182
+ const renamedSections = Object.fromEntries(COMPONENT_NAMES.flatMap((section) => {
3183
+ const entries = components[section];
3184
+ const own = renames.filter((rename) => rename.section === section);
3185
+ if (!isRecord(entries) || own.length === 0) return [];
3186
+ return [[section, Object.fromEntries(Object.entries(entries).map(([name, value]) => [own.find((rename) => rename.name === name)?.renamed ?? name, value]))]];
3187
+ }));
3188
+ const refs = new Map(renames.map((rename) => [`#/components/${rename.section}/${rename.name}`, rename]));
3189
+ const rewriteRef = (ref) => {
3190
+ if (!ref.startsWith("#/components/")) return ref;
3191
+ const segments = ref.split("/");
3192
+ const section = segments[2];
3193
+ const encoded = segments[3];
3194
+ const rest = segments.slice(4);
3195
+ if (section === void 0 || encoded === void 0) return ref;
3196
+ const rename = refs.get(`#/components/${section}/${decodePercent(encoded)}`);
3197
+ if (rename === void 0) return ref;
3198
+ return [
3199
+ "#",
3200
+ "components",
3201
+ section,
3202
+ encoded.includes("%") ? encodeURIComponent(rename.renamed) : rename.renamed,
3203
+ ...rest
3204
+ ].join("/");
3205
+ };
3206
+ const rewrite = (node) => {
3207
+ if (Array.isArray(node)) return node.map(rewrite);
3208
+ if (!isRecord(node)) return node;
3209
+ return Object.fromEntries(Object.entries(node).map(([key, value]) => {
3210
+ if (key === "$ref" && typeof value === "string") return [key, rewriteRef(value)];
3211
+ if (key === "mapping" && isRecord(value)) return [key, Object.fromEntries(Object.entries(value).map(([k, v]) => [k, typeof v === "string" ? rewriteRef(v) : v]))];
3212
+ return [key, rewrite(value)];
3213
+ }));
3214
+ };
3215
+ const rewritten = rewrite({
3216
+ ...document,
3217
+ components: {
3218
+ ...components,
3219
+ ...renamedSections
3220
+ }
3221
+ });
3222
+ return isRecord(rewritten) ? {
3223
+ ...document,
3224
+ ...rewritten
3225
+ } : document;
3226
+ }
3227
+ /** `name2`, `name3`, ...: the first that `isFree`. */
3228
+ function numbered(name, isFree) {
3229
+ const candidates = (n) => isFree(`${name}${n}`) ? `${name}${n}` : candidates(n + 1);
3230
+ return candidates(2);
3231
+ }
3232
+ //#endregion
3233
+ //#region src/helper/pointer.ts
3234
+ /**
3235
+ * Inlines every `$ref` whose pointer names no component, so that what reaches the
3236
+ * generators is either a component (`#/components/<section>/<name>`, emitted as the
3237
+ * identifier it is declared under) or the schema itself.
3238
+ *
3239
+ * A bundler keeps internal references as they are, and a document may refer to an inline
3240
+ * schema wherever it sits: `#/paths/~1partners~1upsert/put/requestBody/content/
3241
+ * application~1json/schema` (freee), or `#/components/parameters/Page/schema`. Named after
3242
+ * its last segment, such a reference became `SchemaSchema`, which nothing declares. The
3243
+ * target is already in the document, so it is written in place of the reference, with the
3244
+ * keywords beside the `$ref` (a `description`) kept over the target's own. A pointer that
3245
+ * names nothing, or that comes back to itself, is left as written.
3246
+ */
3247
+ function inlinePointerRefs(document) {
3248
+ const inline = (node, inlining) => {
3249
+ if (Array.isArray(node)) return node.map((item) => inline(item, inlining));
3250
+ if (!isRecord(node)) return node;
3251
+ const walked = (record) => Object.fromEntries(Object.entries(record).map(([key, value]) => [key, inline(value, inlining)]));
3252
+ const { $ref, ...beside } = node;
3253
+ if (typeof $ref === "string" && isInlinePointer($ref) && !inlining.has($ref)) {
3254
+ const target = resolvePointer(document, $ref);
3255
+ if (isRecord(target)) {
3256
+ const inlined = inline(target, /* @__PURE__ */ new Set([...inlining, $ref]));
3257
+ if (isRecord(inlined)) return {
3258
+ ...inlined,
3259
+ ...walked(beside)
3260
+ };
3261
+ }
3262
+ }
3263
+ return walked(node);
3264
+ };
3265
+ return {
3266
+ ...document,
3267
+ ...Object.fromEntries(Object.entries(document).map(([key, value]) => [key, inline(value, /* @__PURE__ */ new Set())]))
3268
+ };
3269
+ }
3270
+ /** A local pointer that does not name a component, nor a property of a component schema. */
3271
+ function isInlinePointer(ref) {
3272
+ if (!ref.startsWith("#/")) return false;
3273
+ const segments = pointerSegments(ref);
3274
+ if (segments[0] !== "components") return true;
3275
+ if (segments.length === 3) return false;
3276
+ return !(segments[1] === "schemas" && segments[3] === "properties" && segments.length > 4);
3277
+ }
3278
+ /** The segments of a JSON Pointer fragment, decoded: percent-encoding, then `~1` and `~0` (RFC 6901 §6). */
3279
+ function pointerSegments(ref) {
3280
+ return ref.slice(2).split("/").map((segment) => decodePercent(segment).replaceAll("~1", "/").replaceAll("~0", "~"));
3281
+ }
3282
+ function resolvePointer(document, ref) {
3283
+ return pointerSegments(ref).reduce((node, segment) => {
3284
+ if (Array.isArray(node)) return node[Number(segment)];
3285
+ if (isRecord(node)) return Object.hasOwn(node, segment) ? node[segment] : void 0;
3286
+ }, document);
3287
+ }
3288
+ //#endregion
3076
3289
  //#region src/generator/zod-openapi-hono/openapi/webhooks/index.ts
3077
3290
  function webhookCode(openapi, readonly) {
3078
3291
  return makeWebhookEntries(openapi, readonly).map((entry) => entry.code).join("\n\n");
3079
3292
  }
3080
3293
  //#endregion
3081
3294
  //#region src/generator/zod-openapi-hono/openapi/index.ts
3082
- function zodOpenAPIHono(openapi, options = {}) {
3295
+ function zodOpenAPIHono(document, options = {}) {
3296
+ const openapi = uniqueComponentNames(inlinePointerRefs(document));
3083
3297
  const components = openapi.components ? componentsCode(openapi.components, options) : "";
3084
3298
  const routes = routeCode(openapi, options.readonly);
3085
3299
  const webhooks = webhookCode(openapi, options.readonly);
@@ -24,7 +24,11 @@ function parseOpenAPI(input) {
24
24
  if (!document) throw new Error(`TypeSpec emitted no OpenAPI document: ${input}`);
25
25
  return document;
26
26
  },
27
- catch: (error) => new OpenAPIError({ message: error instanceof Error ? error.message : String(error) })
27
+ catch: (error) => {
28
+ if (!(error instanceof Error)) return new OpenAPIError({ message: String(error) });
29
+ const code = "ioErrorCode" in error ? error.ioErrorCode : void 0;
30
+ return new OpenAPIError({ message: (!error.message.trim() || error.message.trimEnd().endsWith(":")) && typeof code === "string" && code ? `${error.message}${code}` : error.message });
31
+ }
28
32
  });
29
33
  }
30
34
  //#endregion
@@ -1,5 +1,5 @@
1
- import { i as FORM_MEDIA_TYPES, u as JSON_MEDIA_TYPE } from "./constants-Bz8YiPum.js";
2
- import { B as isOperationLike, J as isRecord, U as isParameterObject, Y as isRefObject, ot as isValidIdent, tt as isSchemaProperty } from "./utils-Dznx-EnJ.js";
1
+ import { a as FORM_MEDIA_TYPES, d as JSON_MEDIA_TYPE } from "./constants-hwmOoQfI.js";
2
+ import { V as isOperationLike, W as isParameterObject, X as isRefObject, Y as isRecord, nt as isSchemaProperty, st as isValidIdent } from "./utils-Bw0Q2Ozg.js";
3
3
  //#region src/helper/group.ts
4
4
  const RESERVED = /* @__PURE__ */ new Set([
5
5
  "arguments",