@roomle/web-sdk 6.0.0-alpha.3 → 6.0.0-alpha.5
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/lib/ConfiguratorKernel.wasm +0 -0
- package/lib/RoomleCore.js +4 -4
- package/lib/RoomleCore.wasm +0 -0
- package/lib/RoomleToolsCore.wasm +0 -0
- package/lib/{api-CfHIG8XG.mjs → api-D1x-GnXP.mjs} +2 -2
- package/lib/{api-CfHIG8XG.mjs.map → api-D1x-GnXP.mjs.map} +1 -1
- package/lib/{asset-loader.worker-CE4O0JU-.mjs → asset-loader.worker-Ct8sEbaT.mjs} +1 -1
- package/lib/{asset-loader.worker-CE4O0JU-.mjs.map → asset-loader.worker-Ct8sEbaT.mjs.map} +1 -1
- package/lib/{budgeteer.sw-yR2xApHT.mjs → budgeteer.sw-C1IOfc0T.mjs} +1 -1
- package/lib/{budgeteer.sw-yR2xApHT.mjs.map → budgeteer.sw-C1IOfc0T.mjs.map} +1 -1
- package/lib/{component-raycast-helper-DmNjzxSD.mjs → component-raycast-helper-Bjf5x6Qp.mjs} +2 -2
- package/lib/{component-raycast-helper-DmNjzxSD.mjs.map → component-raycast-helper-Bjf5x6Qp.mjs.map} +1 -1
- package/lib/configurator-DAlOYY1G.mjs +2 -0
- package/lib/{configurator-vJ5idG1h.mjs → configurator-FnqdWPyc.mjs} +4 -4
- package/lib/{configurator-vJ5idG1h.mjs.map → configurator-FnqdWPyc.mjs.map} +1 -1
- package/lib/{continuous-drawing-helper-BPe83b9-.mjs → continuous-drawing-helper-LPDWkQn5.mjs} +1 -1
- package/lib/{continuous-drawing-helper-BPe83b9-.mjs.map → continuous-drawing-helper-LPDWkQn5.mjs.map} +1 -1
- package/lib/{glb-viewer-C2U_66OO.mjs → glb-viewer-BOC1_L14.mjs} +4 -4
- package/lib/{glb-viewer-C2U_66OO.mjs.map → glb-viewer-BOC1_L14.mjs.map} +1 -1
- package/lib/glb-viewer-b8y6FHyW.mjs +2 -0
- package/lib/hi-mcp-server-Bfxxay_N.mjs +5301 -0
- package/lib/hi-mcp-server-Bfxxay_N.mjs.map +1 -0
- package/lib/{highlight-coordinator-DDyo_U8P.mjs → highlight-coordinator-Dqcq3yh_.mjs} +3 -3
- package/lib/{highlight-coordinator-DDyo_U8P.mjs.map → highlight-coordinator-Dqcq3yh_.mjs.map} +1 -1
- package/lib/{homag-intelligence-CzTJI_Bo.mjs → homag-intelligence-CgictL2u.mjs} +14 -3
- package/lib/homag-intelligence-CgictL2u.mjs.map +1 -0
- package/lib/{material-viewer-1TdW2e5Q.mjs → material-viewer-BDO3436Q.mjs} +4 -4
- package/lib/{material-viewer-1TdW2e5Q.mjs.map → material-viewer-BDO3436Q.mjs.map} +1 -1
- package/lib/{packages-DbCxjl5Y.mjs → packages-CM3Y2HjP.mjs} +5 -5
- package/lib/packages-CM3Y2HjP.mjs.map +1 -0
- package/lib/{planner-BWxMYEwu.mjs → planner-Cw7BpR_J.mjs} +3 -3
- package/lib/{planner-BWxMYEwu.mjs.map → planner-Cw7BpR_J.mjs.map} +1 -1
- package/lib/planner-EIi7lAHf.mjs +2 -0
- package/lib/roomle-headless.d.ts +174 -10
- package/lib/roomle-headless.js +9 -9
- package/lib/roomle-renderer-nCUrLU_S.mjs.map +1 -1
- package/lib/{roomle-sdk-BIGMLwuJ.mjs → roomle-sdk-B3FDzb1a.mjs} +3807 -3551
- package/lib/roomle-sdk-B3FDzb1a.mjs.map +1 -0
- package/lib/roomle-sdk.d.ts +174 -10
- package/lib/roomle-sdk.js +7 -7
- package/lib/{roomle-webgpu-renderer-BQuRMtn8.mjs → roomle-webgpu-renderer-ZT__n9mA.mjs} +429 -428
- package/lib/{roomle-webgpu-renderer-BQuRMtn8.mjs.map → roomle-webgpu-renderer-ZT__n9mA.mjs.map} +1 -1
- package/lib/{scene-renderer-DdVBP89m.mjs → scene-renderer-3S4aBupw.mjs} +2 -2
- package/lib/{scene-renderer-DdVBP89m.mjs.map → scene-renderer-3S4aBupw.mjs.map} +1 -1
- package/lib/{script-loader-DOhxnpYD.mjs → script-loader-U9UqaQz5.mjs} +2 -2
- package/lib/{script-loader-DOhxnpYD.mjs.map → script-loader-U9UqaQz5.mjs.map} +1 -1
- package/lib/static/roomle-core-hsc/node_modules/roomle-core-hsc/package.json +1 -1
- package/lib/static/roomle-core-hsc/node_modules/roomle-core-hsc/src/embind/plannerCoreInterface.d.ts +48 -0
- package/lib/static/roomle-core-hsc/node_modules/roomle-core-hsc/wasm_modern/ConfiguratorKernel.wasm +0 -0
- package/lib/static/roomle-core-hsc/node_modules/roomle-core-hsc/wasm_modern/RoomleCore.js +4 -4
- package/lib/static/roomle-core-hsc/node_modules/roomle-core-hsc/wasm_modern/RoomleCore.wasm +0 -0
- package/lib/static/roomle-core-hsc/node_modules/roomle-core-hsc/wasm_modern/RoomleToolsCore.wasm +0 -0
- package/lib/{stats-helper-DYmtEOGb.mjs → stats-helper-tcYuZsXn.mjs} +2 -2
- package/lib/{stats-helper-DYmtEOGb.mjs.map → stats-helper-tcYuZsXn.mjs.map} +1 -1
- package/lib/{threejs-utils-Dy-rm1a9.mjs → threejs-utils-DyIt_Zd4.mjs} +2 -4
- package/lib/threejs-utils-DyIt_Zd4.mjs.map +1 -0
- package/lib/{tools-core-DscrDxxP.mjs → tools-core-BqYt1d2R.mjs} +3 -3
- package/lib/{tools-core-DscrDxxP.mjs.map → tools-core-BqYt1d2R.mjs.map} +1 -1
- package/lib/workers-DfusgkFA.mjs +6 -0
- package/lib/{workers-B-AqdQMe.mjs.map → workers-DfusgkFA.mjs.map} +1 -1
- package/package.json +2 -2
- package/lib/configurator-DXd3P_DJ.mjs +0 -2
- package/lib/glb-viewer-DiHXOqau.mjs +0 -2
- package/lib/homag-intelligence-CzTJI_Bo.mjs.map +0 -1
- package/lib/packages-DbCxjl5Y.mjs.map +0 -1
- package/lib/planner-Bwo0xEWJ.mjs +0 -2
- package/lib/roomle-sdk-BIGMLwuJ.mjs.map +0 -1
- package/lib/threejs-utils-Dy-rm1a9.mjs.map +0 -1
- package/lib/workers-B-AqdQMe.mjs +0 -6
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"hi-mcp-server-Bfxxay_N.mjs","names":["isObject","_a","util.jsonStringifyReplacer","initializer","core.$ZodAsyncError","util.finalizeIssue","core.config","parse","errors.$ZodRealError","parseAsync","safeParse","safeParseAsync","validateAsync","encode","decode","encodeAsync","decodeAsync","safeEncode","safeDecode","safeEncodeAsync","safeDecodeAsync","_emoji","number","boolean","util.nullish","util.floatSafeRemainder","util.NUMBER_FORMAT_RANGES","util.codePointLength","util.getLengthableOrigin","regexes.lowercase","regexes.uppercase","util.escapeRegex","util.aborted","util.explicitlyAborted","core.$ZodAsyncError","util.hide","util.finalizeIssue","core.config","regexes.anyString","regexes.guid","regexes.uuid","regexes.email","regexes.emoji","regexes.nanoid","regexes.nanoidOfLength","regexes.cuid","regexes.cuid2","regexes.ulid","regexes.xid","regexes.ksuid","regexes.datetime","regexes.date","regexes.time","regexes.duration","regexes.ipv4","regexes.ipv6","regexes.cidrv4","regexes.cidrv6","regexes.e164","regexes.number","regexes.boolean","util.prefixIssues","util.optionalKeys","util.cached","util.isObject","util.esc","allowsEval","util.allowsEval","util.cleanRegex","util.isPlainObject","util.getEnumValues","util.escapeRegex","core.$ZodEncodeError","util.issue","util.rawShape","util.parsedType","util.stringifyPrimitive","util.joinValues","util.normalizeParams","checks.$ZodCheckLessThan","checks.$ZodCheckGreaterThan","checks.$ZodCheckMultipleOf","checks.$ZodCheckMaxLength","checks.$ZodCheckMinLength","checks.$ZodCheckLengthEquals","checks.$ZodCheckRegex","checks.$ZodCheckLowerCase","checks.$ZodCheckUpperCase","checks.$ZodCheckIncludes","checks.$ZodCheckStartsWith","checks.$ZodCheckEndsWith","checks.$ZodCheckOverwrite","util.slugify","issue","util.issue","checks.$ZodCheck","describe","meta","regexes.base64","regexes.base64url","regexes.number","regexes.integer","core.formatError","core.flattenError","util.jsonStringifyReplacer","en","core.memoizer","util.mergeDefs","core.clone","checks.overwrite","util.hide","core.standardProps","parse.parse","parse.parseAsync","parse.safeParse","parse.safeParseAsync","parse.validate","parse.validateAsync","parse.encode","parse.decode","parse.encodeAsync","parse.decodeAsync","parse.safeEncode","parse.safeDecode","parse.safeEncodeAsync","parse.safeDecodeAsync","processors.stringProcessor","processors.aggregateChecks","checks.regex","checks.includes","checks.startsWith","checks.endsWith","checks.minLength","checks.maxLength","checks.length","checks.lowercase","checks.uppercase","checks.trim","checks.normalize","checks.toLowerCase","checks.toUpperCase","checks.slugify","core._email","core._url","core._jwt","core._emoji","core._guid","core._uuid","core._uuidv4","core._uuidv6","core._uuidv7","core._nanoid","core._cuid","core._cuid2","core._ulid","core._base64","core._base64url","core._xid","core._ksuid","core._ipv4","core._ipv6","core._cidrv4","core._cidrv6","core._e164","core._isoDateTime","core._isoDate","core._isoTime","core._isoDuration","core._string","processors.numberProcessor","checks.gt","checks.gte","checks.lt","checks.lte","checks.multipleOf","core._number","core._int","processors.booleanProcessor","core._boolean","processors.unknownProcessor","core._unknown","processors.neverProcessor","core._never","processors.arrayProcessor","core._array","processors.objectProcessor","util.extend","util.safeExtend","util.merge","util.pick","util.omit","util.partial","util.required","util.normalizeParams","processors.unionProcessor","processors.intersectionProcessor","processors.tupleProcessor","core.$ZodType","processors.recordProcessor","processors.enumProcessor","processors.transformProcessor","core.$ZodEncodeError","issue","util.issue","processors.optionalProcessor","processors.nullableProcessor","processors.defaultProcessor","util.shallowClone","processors.prefaultProcessor","processors.nonoptionalProcessor","processors.catchProcessor","core.util.constantCatch","processors.pipeProcessor","processors.readonlyProcessor","processors.customProcessor","core._refine","core._superRefine","core.describe","core.meta"],"sources":["../../../../node_modules/zod/v4/core/util.js","../../../../node_modules/zod/v4/core/core.js","../../../../node_modules/zod/v4/core/errors.js","../../../../node_modules/zod/v4/core/parse.js","../../../../node_modules/zod/v4/core/regexes.js","../../../../node_modules/zod/v4/core/checks.js","../../../../node_modules/zod/v4/core/doc.js","../../../../node_modules/zod/v4/core/versions.js","../../../../node_modules/zod/v4/core/schemas.js","../../../../node_modules/zod/v4/core/memoizer.js","../../../../node_modules/zod/v4/locales/en.js","../../../../node_modules/zod/v4/core/registries.js","../../../../node_modules/zod/v4/core/api.js","../../../../node_modules/zod/v4/core/to-json-schema.js","../../../../node_modules/zod/v4/core/json-schema-processors.js","../../../../node_modules/zod/v4/classic/errors.js","../../../../node_modules/zod/v4/classic/parse.js","../../../../node_modules/zod/v4/classic/schemas.js","../../packages/homag-intelligence/src/hi-mcp/mcp-tool.ts","../../packages/homag-intelligence/src/hi-mcp/plan-history.ts","../../packages/homag-intelligence/src/hi-mcp/planner-api.ts","../../packages/homag-intelligence/src/hi-mcp/skills/image-planning/SKILL.md?raw","../../packages/homag-intelligence/src/hi-mcp/skills/kitchen-planning/SKILL.md?raw","../../packages/homag-intelligence/src/hi-mcp/skills/kitchen-planning/references/planning-reference.md?raw","../../packages/homag-intelligence/src/hi-mcp/skills/kitchen-planning/references/source-catalog.md?raw","../../packages/homag-intelligence/src/hi-mcp/skills/kitchen-planning-fr/SKILL.md?raw","../../packages/homag-intelligence/src/hi-mcp/skills/kitchen-planning-fr/references/planning-reference.md?raw","../../packages/homag-intelligence/src/hi-mcp/skills/kitchen-planning-fr/references/source-catalog.md?raw","../../packages/homag-intelligence/src/hi-mcp/skills/living-room-planning/SKILL.md?raw","../../packages/homag-intelligence/src/hi-mcp/skills/living-room-planning/references/planning-reference.md?raw","../../packages/homag-intelligence/src/hi-mcp/skills/living-room-planning/references/source-catalog.md?raw","../../packages/homag-intelligence/src/hi-mcp/skills.ts","../../packages/homag-intelligence/src/hi-mcp/agent-facing.ts","../../packages/homag-intelligence/src/hi-mcp/tool-executors.ts","../../packages/homag-intelligence/src/hi-mcp/hi-mcp-server.ts"],"sourcesContent":["import { globalConfig } from \"./core.js\";\n// functions\nexport function assertEqual(val) {\n return val;\n}\nexport function assertNotEqual(val) {\n return val;\n}\nexport function toZod() {\n return (schema) => schema;\n}\nexport function assertIs(_arg) { }\nexport function assertNever(_x) {\n throw new Error(\"Unexpected value in exhaustive check\");\n}\nexport function assert(_) { }\nexport function getEnumValues(entries) {\n const numericValues = Object.values(entries).filter((v) => typeof v === \"number\");\n const values = Object.entries(entries)\n .filter(([k, _]) => numericValues.indexOf(+k) === -1)\n .map(([_, v]) => v);\n return values;\n}\nexport function joinValues(array, separator = \"|\") {\n return array.map((val) => stringifyPrimitive(val)).join(separator);\n}\nexport function jsonStringifyReplacer(_, value) {\n if (typeof value === \"bigint\")\n return value.toString();\n return value;\n}\n// the accessor lives on a shared prototype: an own accessor makes every box a dictionary-mode object (~360 B and a slow load per read against ~100 B and an inlined getter here)\nclass Cached {\n constructor(getter) {\n this._getter = getter;\n this._value = undefined;\n }\n get value() {\n const getter = this._getter;\n if (getter !== undefined) {\n this._value = getter();\n this._getter = undefined;\n }\n return this._value;\n }\n}\nexport function cached(getter) {\n return new Cached(getter);\n}\nexport function nullish(input) {\n return input === null || input === undefined;\n}\nexport function cleanRegex(source) {\n const start = source.startsWith(\"^\") ? 1 : 0;\n const end = source.endsWith(\"$\") ? source.length - 1 : source.length;\n return source.slice(start, end);\n}\nexport function floatSafeRemainder(val, step) {\n const ratio = val / step;\n const roundedRatio = Math.round(ratio);\n // `val` and `step` each round to a double before the division rounds again, so a true decimal multiple's quotient can sit up to 1.5 of these scaled epsilons from the integer. A 1x tolerance therefore rejected 2.03 as a multiple of 0.07; 4x covers the worst case with margin.\n const tolerance = 4 * Number.EPSILON * Math.max(Math.abs(ratio), 1);\n if (Math.abs(ratio - roundedRatio) < tolerance)\n return 0;\n return ratio - roundedRatio;\n}\nconst EVALUATING = /* @__PURE__*/ Symbol(\"evaluating\");\nexport function defineLazy(object, key, getter) {\n let value = undefined;\n Object.defineProperty(object, key, {\n get() {\n if (value === EVALUATING) {\n // Circular reference detected, return undefined to break the cycle\n return undefined;\n }\n if (value === undefined) {\n value = EVALUATING;\n value = getter();\n }\n return value;\n },\n set(v) {\n Object.defineProperty(object, key, {\n value: v,\n // configurable: true,\n });\n // object[key] = v;\n },\n configurable: true,\n });\n}\nexport function objectClone(obj) {\n return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj));\n}\nexport function assignProp(target, prop, value) {\n Object.defineProperty(target, prop, {\n value,\n writable: true,\n enumerable: true,\n configurable: true,\n });\n}\n/**\n * Whichever object a def's `shape` currently answers from: the one the caller passed until the first read, the frozen copy after it.\n *\n * Its keys and descriptors read without invoking anything, which is what lets a discriminated union check its discriminator, and the cycle walk read a shape, without resolving a getter that references the schema being constructed. A def that answers `shape` from an accessor of its own has none.\n */\nexport function rawShape(def) {\n const desc = Object.getOwnPropertyDescriptor(def, \"shape\");\n return desc?.get ? desc.get.raw : desc?.value;\n}\n// where a builder reads its source's keys and descriptors, resolving only a shape a def answers for itself. A shape resolves by object spread, so only its enumerable keys are ever part of it.\nfunction sourceShape(schema) {\n return rawShape(schema._zod.def) ?? schema._zod.def.shape;\n}\n// a key whose value is not settled yet, self-caching so every read after the first gets the same one\nfunction deferProp(target, key, getter) {\n Object.defineProperty(target, key, {\n get() {\n const value = getter();\n assignProp(this, key, value);\n return value;\n },\n enumerable: true,\n configurable: true,\n });\n}\n// Writes a settled key. A plain assignment is much cheaper than `defineProperty` and produces the same descriptor, but it runs whatever setter already answers to the key — an accessor this shape deferred, or an inherited one, which `__proto__` has on every object and prototype pollution can add for any name.\nfunction putProp(target, key, value) {\n if (key in target)\n assignProp(target, key, value);\n else\n target[key] = value;\n}\n/**\n * Copies `keys` of `source`'s shape onto `target`, each value passed through `wrap`.\n *\n * A key the source has resolved is copied through now, so the derived shape states it outright and nothing has to resolve it to learn what it holds. A key the source still defers stays deferred, and reads back through the source's own `shape`, so it resolves once and both shapes get that one schema.\n */\nfunction mirrorShape(target, source, keys, wrap) {\n const raw = sourceShape(source);\n for (const key of keys) {\n const desc = Object.getOwnPropertyDescriptor(raw, key);\n if (!desc.enumerable)\n continue;\n if (desc.get) {\n deferProp(target, key, () => {\n const value = source._zod.def.shape[key];\n return wrap ? wrap(value, key) : value;\n });\n }\n else\n putProp(target, key, wrap ? wrap(desc.value, key) : desc.value);\n }\n}\n// same, for a plain shape a caller passed rather than a schema's\nfunction mirrorProps(target, source) {\n for (const key of Reflect.ownKeys(source)) {\n const desc = Object.getOwnPropertyDescriptor(source, key);\n if (!desc.enumerable)\n continue;\n if (desc.get)\n deferProp(target, key, () => source[key]);\n else\n putProp(target, key, desc.value);\n }\n}\nexport function mergeDefs(...defs) {\n const mergedDescriptors = {};\n for (const def of defs) {\n const descriptors = Object.getOwnPropertyDescriptors(def);\n Object.assign(mergedDescriptors, descriptors);\n }\n return Object.defineProperties({}, mergedDescriptors);\n}\nexport function cloneDef(schema) {\n return mergeDefs(schema._zod.def);\n}\nexport function getElementAtPath(obj, path) {\n if (!path)\n return obj;\n return path.reduce((acc, key) => acc?.[key], obj);\n}\nexport function promiseAllObject(promisesObj) {\n const keys = Object.keys(promisesObj);\n const promises = keys.map((key) => promisesObj[key]);\n return Promise.all(promises).then((results) => {\n const resolvedObj = {};\n for (let i = 0; i < keys.length; i++) {\n resolvedObj[keys[i]] = results[i];\n }\n return resolvedObj;\n });\n}\nexport function randomString(length = 10) {\n const chars = \"abcdefghijklmnopqrstuvwxyz\";\n let str = \"\";\n for (let i = 0; i < length; i++) {\n str += chars[Math.floor(Math.random() * chars.length)];\n }\n return str;\n}\nexport function esc(str) {\n return JSON.stringify(str);\n}\nexport function slugify(input) {\n return input\n .toLowerCase()\n .trim()\n .replace(/[^\\w\\s-]/g, \"\")\n .replace(/[\\s_-]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\n}\nexport const captureStackTrace = (\"captureStackTrace\" in Error ? Error.captureStackTrace : (..._args) => { });\nexport function isObject(data) {\n return typeof data === \"object\" && data !== null && !Array.isArray(data);\n}\nexport const allowsEval = /* @__PURE__*/ cached(() => {\n // Skip the probe under `jitless`: strict CSPs report the caught `new Function` as a `securitypolicyviolation` even though the throw is swallowed.\n if (globalConfig.jitless) {\n return false;\n }\n // @ts-ignore\n if (typeof navigator !== \"undefined\" && navigator?.userAgent?.includes(\"Cloudflare\")) {\n return false;\n }\n try {\n const F = Function;\n new F(\"\");\n return true;\n }\n catch (_) {\n return false;\n }\n});\nexport function isPlainObject(o) {\n if (isObject(o) === false)\n return false;\n // modified constructor\n const ctor = o.constructor;\n if (ctor === undefined)\n return true;\n if (typeof ctor !== \"function\")\n return true;\n // modified prototype\n const prot = ctor.prototype;\n if (isObject(prot) === false)\n return false;\n // ctor doesn't have static `isPrototypeOf`\n if (Object.prototype.hasOwnProperty.call(prot, \"isPrototypeOf\") === false) {\n return false;\n }\n return true;\n}\nexport function shallowClone(o) {\n if (isPlainObject(o))\n return { ...o };\n if (Array.isArray(o))\n return [...o];\n if (o instanceof Map)\n return new Map(o);\n if (o instanceof Set)\n return new Set(o);\n return o;\n}\nexport function numKeys(data) {\n let keyCount = 0;\n for (const key in data) {\n if (Object.prototype.hasOwnProperty.call(data, key)) {\n keyCount++;\n }\n }\n return keyCount;\n}\nexport const getParsedType = (data) => {\n const t = typeof data;\n switch (t) {\n case \"undefined\":\n return \"undefined\";\n case \"string\":\n return \"string\";\n case \"number\":\n return Number.isNaN(data) ? \"nan\" : \"number\";\n case \"boolean\":\n return \"boolean\";\n case \"function\":\n return \"function\";\n case \"bigint\":\n return \"bigint\";\n case \"symbol\":\n return \"symbol\";\n case \"object\":\n if (Array.isArray(data)) {\n return \"array\";\n }\n if (data === null) {\n return \"null\";\n }\n if (data.then && typeof data.then === \"function\" && data.catch && typeof data.catch === \"function\") {\n return \"promise\";\n }\n if (typeof Map !== \"undefined\" && data instanceof Map) {\n return \"map\";\n }\n if (typeof Set !== \"undefined\" && data instanceof Set) {\n return \"set\";\n }\n if (typeof Date !== \"undefined\" && data instanceof Date) {\n return \"date\";\n }\n // @ts-ignore\n if (typeof File !== \"undefined\" && data instanceof File) {\n return \"file\";\n }\n return \"object\";\n default:\n throw new Error(`Unknown data type: ${t}`);\n }\n};\nexport const propertyKeyTypes = /* @__PURE__*/ new Set([\"string\", \"number\", \"symbol\"]);\nexport const primitiveTypes = /* @__PURE__*/ new Set([\n \"string\",\n \"number\",\n \"bigint\",\n \"boolean\",\n \"symbol\",\n \"undefined\",\n]);\nexport function escapeRegex(str) {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n// zod-specific utils\nexport function clone(inst, def, params) {\n const cl = new inst._zod.constr(def ?? inst._zod.def);\n if (!def || params?.parent)\n cl._zod.parent = inst;\n return cl;\n}\nexport function normalizeParams(_params) {\n const params = _params;\n if (!params)\n return {};\n if (typeof params === \"string\")\n return { error: () => params };\n if (params?.message !== undefined) {\n if (params?.error !== undefined)\n throw new Error(\"Cannot specify both `message` and `error` params\");\n params.error = params.message;\n }\n delete params.message;\n if (typeof params.error === \"string\")\n return { ...params, error: () => params.error };\n return params;\n}\nexport function createTransparentProxy(getter) {\n let target;\n return new Proxy({}, {\n get(_, prop, receiver) {\n target ?? (target = getter());\n return Reflect.get(target, prop, receiver);\n },\n set(_, prop, value, receiver) {\n target ?? (target = getter());\n return Reflect.set(target, prop, value, receiver);\n },\n has(_, prop) {\n target ?? (target = getter());\n return Reflect.has(target, prop);\n },\n deleteProperty(_, prop) {\n target ?? (target = getter());\n return Reflect.deleteProperty(target, prop);\n },\n ownKeys(_) {\n target ?? (target = getter());\n return Reflect.ownKeys(target);\n },\n getOwnPropertyDescriptor(_, prop) {\n target ?? (target = getter());\n return Reflect.getOwnPropertyDescriptor(target, prop);\n },\n defineProperty(_, prop, descriptor) {\n target ?? (target = getter());\n return Reflect.defineProperty(target, prop, descriptor);\n },\n });\n}\nexport function stringifyPrimitive(value) {\n if (typeof value === \"bigint\")\n return value.toString() + \"n\";\n if (typeof value === \"string\")\n return `\"${value}\"`;\n return `${value}`;\n}\nexport function optionalKeys(shape) {\n return Object.keys(shape).filter((k) => {\n return shape[k]._zod.optin !== undefined && shape[k]._zod.optout === \"optional\";\n });\n}\n// Wrapped in a `@__PURE__` IIFE: esbuild never tree-shakes a top-level initializer that contains a member access on `Number`, so the bare object literal survived into every bundle.\nexport const NUMBER_FORMAT_RANGES = /*@__PURE__*/ (() => ({\n safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],\n int32: [-2147483648, 2147483647],\n uint32: [0, 4294967295],\n float32: [-3.4028234663852886e38, 3.4028234663852886e38],\n float64: [-Number.MAX_VALUE, Number.MAX_VALUE],\n}))();\nexport const BIGINT_FORMAT_RANGES = {\n int64: [/* @__PURE__*/ BigInt(\"-9223372036854775808\"), /* @__PURE__*/ BigInt(\"9223372036854775807\")],\n uint64: [/* @__PURE__*/ BigInt(0), /* @__PURE__*/ BigInt(\"18446744073709551615\")],\n};\nexport function pick(schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".pick() cannot be used on object schemas containing refinements\");\n }\n const newShape = {};\n mirrorShape(newShape, schema, maskedKeys(schema, mask));\n return clone(schema, mergeDefs(currDef, { shape: newShape, checks: [] }));\n}\n// the mask keys that select something, checked against the source's shape without resolving it\nfunction maskedKeys(schema, mask) {\n const raw = sourceShape(schema);\n const keys = [];\n // `for...in` skips symbols, so a symbol in the mask would select nothing\n for (const key of Reflect.ownKeys(mask)) {\n if (!Object.getOwnPropertyDescriptor(raw, key)?.enumerable) {\n throw new Error(`Unrecognized key: \"${String(key)}\"`);\n }\n if (mask[key])\n keys.push(key);\n }\n return keys;\n}\nexport function omit(schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".omit() cannot be used on object schemas containing refinements\");\n }\n const omitted = new Set(maskedKeys(schema, mask));\n const newShape = {};\n mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)).filter((key) => !omitted.has(key)));\n return clone(schema, mergeDefs(currDef, { shape: newShape, checks: [] }));\n}\nexport function extend(schema, shape) {\n if (!isPlainObject(shape)) {\n throw new Error(\"Invalid input to extend: expected a plain object\");\n }\n const checks = schema._zod.def.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n // Only throw if new shape overlaps with existing shape. Use getOwnPropertyDescriptor to check key existence without accessing values\n const existingShape = sourceShape(schema);\n for (const key of Reflect.ownKeys(shape)) {\n if (Object.getOwnPropertyDescriptor(existingShape, key) !== undefined) {\n throw new Error(\"Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.\");\n }\n }\n }\n return clone(schema, mergeDefs(schema._zod.def, { shape: extended(schema, shape) }));\n}\n// the source's keys, then the caller's overlaid on top\nfunction extended(schema, shape) {\n const newShape = {};\n mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)));\n mirrorProps(newShape, shape);\n return newShape;\n}\nexport function safeExtend(schema, shape) {\n if (!isPlainObject(shape)) {\n throw new Error(\"Invalid input to safeExtend: expected a plain object\");\n }\n return clone(schema, mergeDefs(schema._zod.def, { shape: extended(schema, shape) }));\n}\nexport function merge(a, b) {\n if (!b?._zod?.def) {\n throw new Error(\"Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.\");\n }\n if (a._zod.def.checks?.length) {\n throw new Error(\".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.\");\n }\n const newShape = {};\n mirrorShape(newShape, a, Reflect.ownKeys(sourceShape(a)));\n mirrorShape(newShape, b, Reflect.ownKeys(sourceShape(b)));\n const def = mergeDefs(a._zod.def, {\n shape: newShape,\n get catchall() {\n return b._zod.def.catchall;\n },\n checks: b._zod.def.checks ?? [],\n });\n return clone(a, def);\n}\nexport function partial(Class, schema, mask, name = \"partial\") {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(`.${name}() cannot be used on object schemas containing refinements`);\n }\n const selected = mask ? new Set(maskedKeys(schema, mask)) : undefined;\n const newShape = {};\n mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)), Class &&\n ((value, key) => (selected && !selected.has(key) ? value : new Class({ type: \"optional\", innerType: value }))));\n return clone(schema, mergeDefs(schema._zod.def, { shape: newShape, checks: [] }));\n}\nexport function required(Class, schema, mask) {\n const selected = mask ? new Set(maskedKeys(schema, mask)) : undefined;\n const newShape = {};\n mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)), (value, key) => \n // overwrite with non-optional\n selected && !selected.has(key) ? value : new Class({ type: \"nonoptional\", innerType: value }));\n return clone(schema, mergeDefs(schema._zod.def, { shape: newShape }));\n}\n// invalid_type | too_big | too_small | invalid_format | not_multiple_of | unrecognized_keys | invalid_union | invalid_key | invalid_element | invalid_value | custom\nexport function aborted(x, startIndex = 0) {\n if (x.aborted === true)\n return true;\n for (let i = startIndex; i < x.issues.length; i++) {\n if (x.issues[i]?.continue !== true) {\n return true;\n }\n }\n return false;\n}\n// Checks for explicit abort (continue === false), as opposed to implicit abort (continue === undefined). Used to respect `abort: true` in .refine() even for checks that have a `when` function.\nexport function explicitlyAborted(x, startIndex = 0) {\n if (x.aborted === true)\n return true;\n for (let i = startIndex; i < x.issues.length; i++) {\n if (x.issues[i]?.continue === false) {\n return true;\n }\n }\n return false;\n}\nexport function prefixIssues(path, issues) {\n return issues.map((iss) => {\n var _a;\n (_a = iss).path ?? (_a.path = []);\n iss.path.unshift(path);\n return iss;\n });\n}\nexport function unwrapMessage(message) {\n return typeof message === \"string\" ? message : message?.message;\n}\n/* A check holds no link back to the schema it is attached to — the same check instance is shared by every clone of that schema — so the owner is stamped onto the issues a check just raised, at the only point where both are in scope. Runs on the failure path only; `start` is the issue count from before the check ran. */\nexport function attachSchema(issues, start, inst) {\n var _a;\n for (let i = start; i < issues.length; i++) {\n (_a = issues[i]).schema ?? (_a.schema = inst);\n }\n}\nexport function finalizeIssue(iss, ctx, config) {\n var _a;\n // A schema that raised an issue itself owns it outright, and outranks any stamp an enclosing check left in `attachSchema`. String formats and z.custom() are schema and check at once, so when they act as a check they defer to that stamp instead.\n const traits = iss.inst?._zod?.traits;\n if (traits?.has(\"$ZodType\")) {\n if (traits.has(\"$ZodCheck\"))\n (_a = iss).schema ?? (_a.schema = iss.inst);\n else\n iss.schema = iss.inst;\n }\n // Decreasing specificity, first map to return a message wins. `inst` is whatever raised the issue, so a check's own map outranks the owning schema's.\n const schemaError = iss.schema !== iss.inst ? iss.schema?._zod.def?.error : undefined;\n const message = iss.message\n ? iss.message\n : (unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ??\n unwrapMessage(schemaError?.(iss)) ??\n unwrapMessage(ctx?.error?.(iss)) ??\n unwrapMessage(config.customError?.(iss)) ??\n unwrapMessage(config.localeError?.(iss)) ??\n \"Invalid input\");\n // an explicit own-key copy beats object rest with excluded keys, which v8 routes through a generic runtime call; Object.keys rather than for-in so an issue pushed with a prototype does not leak inherited keys, and an own __proto__ key is dropped rather than assigned through the setter\n const full = {};\n for (const k of Object.keys(iss)) {\n if (k === \"inst\" || k === \"schema\" || k === \"continue\" || k === \"input\" || k === \"__proto__\")\n continue;\n full[k] = iss[k];\n }\n full.path ?? (full.path = []);\n full.message = message;\n if (ctx?.reportInput) {\n full.input = iss.input;\n }\n return full;\n}\nexport function getSizableOrigin(input) {\n if (input instanceof Set)\n return \"set\";\n if (input instanceof Map)\n return \"map\";\n // @ts-ignore\n if (input instanceof File)\n return \"file\";\n return \"unknown\";\n}\nconst highSurrogate = /[\\uD800-\\uDBFF]/;\n// Code points in `str`: a surrogate pair counts once, a lone surrogate as itself. Hand-rolled because the string iterator allocates and runs ~250x slower on this path; the regex probe exits ~50x quicker for a string with no astral characters.\nexport function codePointLength(str) {\n const units = str.length;\n if (!highSurrogate.test(str))\n return units;\n let count = units;\n for (let i = 0; i < units - 1; i++) {\n if ((str.charCodeAt(i) & 0xfc00) === 0xd800 && (str.charCodeAt(i + 1) & 0xfc00) === 0xdc00) {\n count--;\n i++;\n }\n }\n return count;\n}\nexport function getLengthableOrigin(input) {\n if (Array.isArray(input))\n return \"array\";\n if (typeof input === \"string\")\n return \"string\";\n return \"unknown\";\n}\nexport function parsedType(data) {\n const t = typeof data;\n switch (t) {\n case \"number\": {\n return Number.isNaN(data) ? \"nan\" : \"number\";\n }\n case \"object\": {\n if (data === null) {\n return \"null\";\n }\n if (Array.isArray(data)) {\n return \"array\";\n }\n const obj = data;\n if (obj && Object.getPrototypeOf(obj) !== Object.prototype && \"constructor\" in obj && obj.constructor) {\n return obj.constructor.name;\n }\n }\n }\n return t;\n}\nexport function issue(...args) {\n const [iss, input, inst] = args;\n if (typeof iss === \"string\") {\n return {\n message: iss,\n code: \"custom\",\n input,\n inst,\n };\n }\n return { ...iss };\n}\nexport function cleanEnum(obj) {\n return Object.entries(obj)\n .filter(([k, _]) => {\n // return true if NaN, meaning it's not a number, thus a string key\n return Number.isNaN(Number.parseInt(k, 10));\n })\n .map((el) => el[1]);\n}\n// Codec utility functions\nexport function base64ToUint8Array(base64) {\n const binaryString = atob(base64);\n const bytes = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n bytes[i] = binaryString.charCodeAt(i);\n }\n return bytes;\n}\nexport function uint8ArrayToBase64(bytes) {\n let binaryString = \"\";\n for (let i = 0; i < bytes.length; i++) {\n binaryString += String.fromCharCode(bytes[i]);\n }\n return btoa(binaryString);\n}\nexport function base64urlToUint8Array(base64url) {\n const base64 = base64url.replace(/-/g, \"+\").replace(/_/g, \"/\");\n const padding = \"=\".repeat((4 - (base64.length % 4)) % 4);\n return base64ToUint8Array(base64 + padding);\n}\nexport function uint8ArrayToBase64url(bytes) {\n return uint8ArrayToBase64(bytes).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=/g, \"\");\n}\nexport function hexToUint8Array(hex) {\n const cleanHex = hex.replace(/^0x/, \"\");\n if (cleanHex.length % 2 !== 0) {\n throw new Error(\"Invalid hex string length\");\n }\n const bytes = new Uint8Array(cleanHex.length / 2);\n for (let i = 0; i < cleanHex.length; i += 2) {\n bytes[i / 2] = Number.parseInt(cleanHex.slice(i, i + 2), 16);\n }\n return bytes;\n}\nexport function uint8ArrayToHex(bytes) {\n return Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n// instanceof\nexport class Class {\n constructor(..._args) { }\n}\n////////// PROTOTYPE INSTALLERS //////////\n//\n// Members live on the prototype and materialize per instance on first read, which keeps own-property count under the step where V8 stops using inline slots. Changing anything here means re-measuring runtime, memory and bundle size together — see \"The three axes\" in AGENTS.md.\n/**\n * Installs a trait's members on its prototype. Each value builds that member for the instance on first read; the built value shadows the accessor as an own property, so a detached `const { parse } = schema` keeps working.\n *\n * Call this from a `proto` initializer, which runs once per prototype — never per instance.\n */\nexport function members(proto, table) {\n for (const key in table) {\n const desc = Object.getOwnPropertyDescriptor(table, key);\n // a getter installs as written, so it stays live: `description` reads through to the registry on every access. not enumerable: an object literal's is, and a prototype member never was\n if (desc.get)\n Object.defineProperty(proto, key, { ...desc, enumerable: false });\n // a method materializes bound on first read, which is what keeps a detached member working: `const opt = schema.optional; opt()`\n else\n defineBound(proto, key, desc.value);\n }\n}\n/** Shadows a prototype member with an own value, so a getter that builds from the instance runs once. */\nexport function own(inst, key, value, enumerable = true) {\n Object.defineProperty(inst, key, { configurable: true, writable: true, enumerable, value });\n return value;\n}\n/** Like {@link own}, for a member that was never an own data property and has to stay out of `Object.keys`. */\nexport function hide(inst, key, value) {\n return own(inst, key, value, false);\n}\n/** Adds members a table derives from the instance: each builds on first read and shadows as own data, and assignment shadows the same way, as when these were own properties. */\nexport /*@__NO_SIDE_EFFECTS__*/ function derived(computes, table) {\n for (const key in computes) {\n const compute = computes[key];\n // an object literal's accessor is configurable and enumerable, and `members` copies the descriptor as written\n Object.defineProperty(table, key, {\n configurable: true,\n enumerable: true,\n get() {\n return own(this, key, compute(this));\n },\n set(value) {\n own(this, key, value);\n },\n });\n }\n return table;\n}\nfunction defineBound(proto, key, fn) {\n Object.defineProperty(proto, key, {\n configurable: true,\n get() {\n // vitest's spyOn calls a prototype getter bare to find the function it wraps, so a nullish receiver answers the raw method\n return this == null ? fn : own(this, key, fn.bind(this));\n },\n set(value) {\n own(this, key, value);\n },\n });\n}\n/** Returns the prototype to install on, or `undefined` if this group is already installed on it. */\nfunction claim(inst, sentinel) {\n const proto = Object.getPrototypeOf(inst);\n // Runs on every construction, so `in` rather than the costlier `hasOwnProperty.call`. Sentinels are keys the group itself defines.\n return sentinel in proto ? undefined : proto;\n}\n// The internals whose init chain is installing. A second call for the same one is a derived constructor overriding its base, so it must not construct another schema in between or the override is dropped.\nlet installing;\n// Set while a getter is running, so a value that resolved through a recursion break is not memoized. One shared descriptor shadows the key for the duration, which costs no per-key allocation.\nlet broke = false;\nconst breaker = {\n configurable: true,\n get() {\n broke = true;\n return undefined;\n },\n};\n/**\n * Installs a lazily-derived internal on the `_zod` prototype of `inst`'s\n * constructor, computed from the internals object itself and cached there on\n * first read. One accessor per constructor rather than one per instance.\n */\nexport function defineLazyInternal(inst, key, compute) {\n const proto = Object.getPrototypeOf(inst._zod);\n if (key in proto && installing !== inst._zod) {\n // A repeat construction: everything is installed already. Cleared here so the reference is not held past the first construction of every type.\n installing = undefined;\n return;\n }\n installing = inst._zod;\n Object.defineProperty(proto, key, {\n configurable: true,\n get() {\n // Shadowed before computing so a re-entrant read from a recursive schema resolves to undefined instead of running the getter again.\n Object.defineProperty(this, key, breaker);\n const outer = broke;\n broke = false;\n try {\n const value = compute(this);\n // A result that resolved through a recursion break is recomputed once the graph is complete; everything else memoizes, undefined included.\n if (broke)\n delete this[key];\n else\n Object.defineProperty(this, key, { configurable: true, writable: true, value });\n broke = broke || outer;\n return value;\n }\n catch (err) {\n // A compute that threw memoizes nothing, so a later read runs it again and fails the same way. The shadow goes with it, since leaving it installed would answer undefined for every later read.\n delete this[key];\n broke = broke || outer;\n throw err;\n }\n },\n set(value) {\n Object.defineProperty(this, key, { configurable: true, writable: true, value });\n },\n });\n}\n/**\n * Installs `key` on `inst`'s prototype, computed by `make` on first read and cached there as an own\n * data property. One accessor per constructor rather than one per instance, because an own accessor\n * puts every instance after the first into v8 dictionary mode. The key doubles as the sentinel.\n */\nexport function installLazyProp(inst, key, make, enumerable) {\n const proto = claim(inst, key);\n if (!proto)\n return;\n Object.defineProperty(proto, key, {\n configurable: true,\n get() {\n // Shadowed before computing, so a re-entrant read from a self-referential shape resolves to undefined instead of running the getter again. A data property rather than an accessor: an own accessor is the dictionary-mode transition this exists to avoid.\n const desc = { configurable: true, writable: true, enumerable, value: undefined };\n Object.defineProperty(this, key, desc);\n // a compute that throws leaves the shadow behind, so later reads answer undefined instead of re-throwing; `defineLazy` did the same, and `defineLazyInternal`'s delete-on-catch would cost bytes in every bundle for a case only a throwing user getter reaches\n desc.value = make(this);\n Object.defineProperty(this, key, desc);\n return desc.value;\n },\n set(value) {\n Object.defineProperty(this, key, { configurable: true, writable: true, enumerable, value });\n },\n });\n}\n/** Marks the thunk `_catch` synthesises for a constant catch value. `Function.length` cannot tell that thunk from a user callback — rest and defaulted parameters both report arity 0 — and a user callback reads `ctx.error`, whose issues only finalize correctly against the caller's per-parse error map. Provenance can say what arity cannot. A plain string key rather than `Symbol.for`, whose call at module scope no bundler can prove pure — the same shape that anchored `urlCanParse` into every build. */\nexport const CONSTANT_CATCH = \"~constantCatch\";\n/** Wraps a constant catch value in a thunk tagged with {@link CONSTANT_CATCH}. */\nexport function constantCatch(value) {\n const fn = () => value;\n fn[CONSTANT_CATCH] = true;\n return fn;\n}\n","var _a;\nimport { members as installMembers } from \"./util.js\";\n/** A special constant with type `never` */\nexport const NEVER = /*@__PURE__*/ Object.freeze({\n status: \"aborted\",\n});\n/* Shared descriptor for installing `_zod`; defineProperty reads it\n * synchronously, so reusing one object avoids a per-instance allocation. */\nconst _zodDesc = { value: undefined, enumerable: false };\n// null where suppressing the capture would be unrecoverable: `parse()` puts the frames back with `captureStackTrace`, so without it the throw would lose its stack. also latched to null once `stackTraceLimit` proves unassignable, which a realm can do at any point by hardening Error\nlet _E = \"captureStackTrace\" in Error ? Error : null;\n// v8 captures a stack trace inside the Error constructor, which dominates a failed parse; costs only the frames, and parse() restores those. the constructor must RUN: Object.create is cheaper and passes instanceof, but Error.isError and util.types.isNativeError check an internal slot\nfunction newError(Definition) {\n const E = _E;\n if (E) {\n const saved = E.stackTraceLimit;\n if (typeof saved === \"number\") {\n try {\n E.stackTraceLimit = 0;\n }\n catch {\n _E = null;\n return new Definition();\n }\n try {\n return new Definition();\n }\n finally {\n E.stackTraceLimit = saved;\n }\n }\n }\n return new Definition();\n}\nexport /*@__NO_SIDE_EFFECTS__*/ function $constructor(name, initializer, \n/** This trait's members, installed once on every prototype that composes it. They cannot be declared in the initializer above: that runs per instance, and the prototype is shared. */\nproto, params) {\n // Prototype for this constructor's `_zod` internals. Lazily-derived fields (`values`, `pattern`, `optin`, …) install here once rather than as an accessor on every instance.\n const zodProto = {};\n // Assigning the fields in the constructor body is what gives instances in-object slots; building the object literally and reparenting it costs a second allocation and a generic property copy.\n function Internals(def) {\n this.def = def;\n this.constr = _;\n this.traits = new Set();\n }\n Internals.prototype = zodProto;\n const protoMembers = proto;\n // One trait's members land on every prototype whose chain composes it, so the answer is per prototype rather than per trait.\n const initialized = protoMembers && new WeakSet();\n function init(inst, def) {\n if (!inst._zod) {\n _zodDesc.value = new Internals(def);\n try {\n Object.defineProperty(inst, \"_zod\", _zodDesc);\n }\n finally {\n // Cleared even on throw, so the shared descriptor never leaks one instance's internals into the next.\n _zodDesc.value = undefined;\n }\n }\n else if (inst._zod.traits.has(name)) {\n return;\n }\n inst._zod.traits.add(name);\n initializer(inst, def);\n if (initialized) {\n // `super(def)` from a user subclass gives `this` a prototype the subclass owns, and installing there would overwrite whatever the subclass declared. `constr` built the instance, so its prototype is the one below the subclass's that should carry the members. A receiver whose chain never reaches that prototype installs on its own, which for a plain object handed straight to `init` means `Object.prototype` — unchanged from before.\n const own = Object.getPrototypeOf(inst);\n const ctorProto = inst._zod.constr.prototype;\n let up = own;\n while (up && up !== ctorProto)\n up = Object.getPrototypeOf(up);\n const target = up ?? own;\n if (!initialized.has(target)) {\n initialized.add(target);\n installMembers(target, protoMembers);\n }\n }\n // support prototype modifications; for-in avoids the array allocation of Object.keys on the (usually empty) prototype\n const proto = _.prototype;\n for (const k in proto) {\n if (!Object.prototype.hasOwnProperty.call(proto, k))\n continue;\n if (!(k in inst)) {\n inst[k] = proto[k].bind(inst);\n }\n }\n }\n // doesn't work if Parent has a constructor with arguments\n const Parent = params?.Parent ?? Object;\n class Definition extends Parent {\n }\n Object.defineProperty(Definition, \"name\", { value: name });\n function _(def) {\n const inst = params?.Parent ? newError(Definition) : this;\n init(inst, def);\n const deferred = inst._zod.deferred;\n if (deferred) {\n for (const fn of deferred) {\n fn();\n }\n // Released: initializers run once, and the list would otherwise be retained for the schema's lifetime.\n inst._zod.deferred = undefined;\n }\n // Global post-processor hook. Internal: installed by `import \"zod/compile\"` to enable AOT compilation for every constructed schema. Runs last, once the instance is fully built, because it hands the instance to compile(). The post-processor is expected to be reentrancy-guarded by its own implementation.\n const pp = globalThis.__zod_globalConfig?.postProcessor;\n if (pp)\n pp(inst);\n return inst;\n }\n Object.defineProperty(_, \"init\", { value: init });\n Object.defineProperty(_, Symbol.hasInstance, {\n value: (inst) => {\n if (params?.Parent && inst instanceof params.Parent)\n return true;\n return inst?._zod?.traits?.has(name);\n },\n });\n Object.defineProperty(_, \"name\", { value: name });\n return _;\n}\n////////////////////////////// UTILITIES ///////////////////////////////////////\nexport const $brand = /*@__PURE__*/ Symbol(\"zod_brand\");\nexport class $ZodAsyncError extends Error {\n constructor() {\n super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);\n }\n}\nexport class $ZodEncodeError extends Error {\n constructor(name) {\n super(`Encountered unidirectional transform during encode: ${name}`);\n this.name = \"ZodEncodeError\";\n }\n}\n(_a = globalThis).__zod_globalConfig ?? (_a.__zod_globalConfig = {});\nexport const globalConfig = globalThis.__zod_globalConfig;\nexport function config(newConfig) {\n if (newConfig)\n Object.assign(globalConfig, newConfig);\n return globalConfig;\n}\n","import { $constructor } from \"./core.js\";\nimport * as util from \"./util.js\";\n/* Computing the message eagerly is expensive (pretty-printed JSON of all\n * issues), so defer it until first read. The accessor functions and\n * descriptors are shared across instances to keep error construction\n * cheap; the computed message is cached on the internals object. The\n * setter preserves plain assignment semantics for consumers that\n * overwrite `message`. */\nfunction _getMessage() {\n const internals = this._zod;\n internals.message ?? (internals.message = JSON.stringify(internals.def, util.jsonStringifyReplacer, 2));\n return internals.message;\n}\nfunction _setMessage(value) {\n this._zod.message = value;\n}\nconst _messageDesc = {\n get: _getMessage,\n set: _setMessage,\n enumerable: true,\n configurable: true,\n};\nconst _issuesDesc = { value: undefined, enumerable: false };\n/* Prototypes that already carry the lazy `toString`. Seeded with the\n * intrinsics so that `init` on a foreign object — it accepts any object —\n * can never install an accessor onto a prototype we do not own. */\nconst _installedToString = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]);\nconst initializer = (inst, def) => {\n inst.name = \"$ZodError\";\n // `_zod` is already non-enumerable: $constructor's init defined it with this same descriptor\n _issuesDesc.value = def;\n Object.defineProperty(inst, \"issues\", _issuesDesc);\n // Clear the shared slot; a retained `value` pins the last error's issues.\n _issuesDesc.value = undefined;\n Object.defineProperty(inst, \"message\", _messageDesc);\n /* `toString` lives as a non-enumerable lazy getter on the shared\n * prototype; on first access it caches a per-instance closure so\n * detached usage still works. */\n const proto = Object.getPrototypeOf(inst);\n if (!_installedToString.has(proto)) {\n _installedToString.add(proto);\n Object.defineProperty(proto, \"toString\", {\n configurable: true,\n enumerable: false,\n get() {\n const value = () => this.message;\n Object.defineProperty(this, \"toString\", { value, configurable: true, writable: true });\n return value;\n },\n set(value) {\n Object.defineProperty(this, \"toString\", { value, configurable: true, writable: true });\n },\n });\n }\n};\nexport const $ZodError = $constructor(\"$ZodError\", initializer);\nexport const $ZodRealError = $constructor(\"$ZodError\", initializer, undefined, {\n Parent: Error,\n});\n/** Get-or-create `obj[key]` as an own data property. A path segment naming an inherited member\n * (\"toString\", \"constructor\") would otherwise read through to the prototype, and assigning\n * \"__proto__\" would hit the setter instead of creating a key. */\nfunction node(obj, key, make) {\n if (!Object.prototype.hasOwnProperty.call(obj, key)) {\n if (key === \"__proto__\") {\n Object.defineProperty(obj, key, { value: make(), writable: true, enumerable: true, configurable: true });\n }\n else {\n obj[key] = make();\n }\n }\n return obj[key];\n}\nexport function flattenError(error, mapper = (issue) => issue.message) {\n const fieldErrors = {};\n const formErrors = [];\n for (const sub of error.issues) {\n if (sub.path.length > 0) {\n node(fieldErrors, sub.path[0], () => []).push(mapper(sub));\n }\n else {\n formErrors.push(mapper(sub));\n }\n }\n return { formErrors, fieldErrors };\n}\nexport function formatError(error, mapper = (issue) => issue.message) {\n const fieldErrors = { _errors: [] };\n const processError = (error, path = []) => {\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\" && issue.errors.length) {\n issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path]));\n }\n else if (issue.code === \"invalid_key\") {\n processError({ issues: issue.issues }, [...path, ...issue.path]);\n }\n else if (issue.code === \"invalid_element\") {\n processError({ issues: issue.issues }, [...path, ...issue.path]);\n }\n else {\n const fullpath = [...path, ...issue.path];\n if (fullpath.length === 0) {\n fieldErrors._errors.push(mapper(issue));\n }\n else {\n let curr = fieldErrors;\n let i = 0;\n while (i < fullpath.length) {\n const el = fullpath[i];\n const terminal = i === fullpath.length - 1;\n // `_errors` is reserved by this legacy format, so merge a matching path segment into the current node instead of treating its array as a child.\n if (el === \"_errors\") {\n if (terminal)\n curr._errors.push(mapper(issue));\n i++;\n continue;\n }\n // A path element may collide with an inherited property name such as\n // \"__proto__\" or \"constructor\". Truthiness checks read the prototype\n // (so no node is created, then ._errors.push throws), and bracket\n // assignment of \"__proto__\" hits the setter instead of creating an\n // own key. Guard the read with hasOwnProperty and create the node\n // with defineProperty so any path element becomes a real own key.\n if (!Object.prototype.hasOwnProperty.call(curr, el)) {\n Object.defineProperty(curr, el, {\n value: { _errors: [] },\n enumerable: true,\n writable: true,\n configurable: true,\n });\n }\n const node = curr[el];\n if (terminal) {\n node._errors.push(mapper(issue));\n }\n curr = node;\n i++;\n }\n }\n }\n }\n };\n processError(error);\n return fieldErrors;\n}\nexport function treeifyError(error, mapper = (issue) => issue.message) {\n const result = { errors: [] };\n const processError = (error, path = []) => {\n var _a;\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\" && issue.errors.length) {\n // regular union error\n issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path]));\n }\n else if (issue.code === \"invalid_key\") {\n processError({ issues: issue.issues }, [...path, ...issue.path]);\n }\n else if (issue.code === \"invalid_element\") {\n processError({ issues: issue.issues }, [...path, ...issue.path]);\n }\n else {\n const fullpath = [...path, ...issue.path];\n if (fullpath.length === 0) {\n result.errors.push(mapper(issue));\n continue;\n }\n let curr = result;\n let i = 0;\n while (i < fullpath.length) {\n const el = fullpath[i];\n const terminal = i === fullpath.length - 1;\n if (typeof el === \"string\") {\n curr.properties ?? (curr.properties = {});\n // el may collide with an inherited property name (\"__proto__\",\n // \"constructor\", ...); ??= reads the prototype so the node is never\n // created and curr.errors.push throws. Guard with hasOwnProperty and\n // create the node with defineProperty so \"__proto__\" becomes a real\n // own key rather than invoking the prototype setter.\n if (!Object.prototype.hasOwnProperty.call(curr.properties, el)) {\n Object.defineProperty(curr.properties, el, {\n value: { errors: [] },\n enumerable: true,\n writable: true,\n configurable: true,\n });\n }\n curr = curr.properties[el];\n }\n else {\n curr.items ?? (curr.items = []);\n (_a = curr.items)[el] ?? (_a[el] = { errors: [] });\n curr = curr.items[el];\n }\n if (terminal) {\n curr.errors.push(mapper(issue));\n }\n i++;\n }\n }\n }\n };\n processError(error);\n return result;\n}\n/** Format a ZodError as a human-readable string in the following form.\n *\n * From\n *\n * ```ts\n * ZodError {\n * issues: [\n * {\n * expected: 'string',\n * code: 'invalid_type',\n * path: [ 'username' ],\n * message: 'Invalid input: expected string'\n * },\n * {\n * expected: 'number',\n * code: 'invalid_type',\n * path: [ 'favoriteNumbers', 1 ],\n * message: 'Invalid input: expected number'\n * }\n * ];\n * }\n * ```\n *\n * to\n *\n * ```\n * username\n * ✖ Expected number, received string at \"username\n * favoriteNumbers[0]\n * ✖ Invalid input: expected number\n * ```\n */\nexport function toDotPath(_path) {\n const segs = [];\n const path = _path.map((seg) => (typeof seg === \"object\" ? seg.key : seg));\n for (const seg of path) {\n if (typeof seg === \"number\")\n segs.push(`[${seg}]`);\n else if (typeof seg === \"symbol\")\n segs.push(`[${JSON.stringify(String(seg))}]`);\n else if (/[^\\w$]/.test(seg))\n segs.push(`[${JSON.stringify(seg)}]`);\n else {\n if (segs.length)\n segs.push(\".\");\n segs.push(seg);\n }\n }\n return segs.join(\"\");\n}\nexport function prettifyError(error) {\n const lines = [];\n // sort by path length\n const issues = [...error.issues].sort((a, b) => (a.path ?? []).length - (b.path ?? []).length);\n // Process each issue\n for (const issue of issues) {\n lines.push(`✖ ${issue.message}`);\n if (issue.path?.length)\n lines.push(` → at ${toDotPath(issue.path)}`);\n }\n // Convert Map to formatted string\n return lines.join(\"\\n\");\n}\n","import * as core from \"./core.js\";\nimport * as errors from \"./errors.js\";\nimport * as util from \"./util.js\";\n// Always both keys, so the `_params` read site in `_parse` sees one object shape rather than two.\nfunction finalizeParams(callee, params) {\n return { callee: params?.callee ?? callee, Err: params?.Err };\n}\nexport const _parse = (_Err) => {\n const fn = (schema, value, _ctx, _params) => {\n const ctx = _ctx ? { ..._ctx, async: false } : { async: false };\n const result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n if (result.issues.length) {\n const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));\n util.captureStackTrace(e, _params?.callee ?? fn);\n throw e;\n }\n return result.value;\n };\n return fn;\n};\nexport const parse = /* @__PURE__*/ _parse(errors.$ZodRealError);\nexport const _parseAsync = (_Err) => {\n const fn = async (schema, value, _ctx, params) => {\n const ctx = _ctx ? { ..._ctx, async: true } : { async: true };\n let result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise)\n result = await result;\n if (result.issues.length) {\n const e = new (params?.Err ?? _Err)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));\n util.captureStackTrace(e, params?.callee ?? fn);\n throw e;\n }\n return result.value;\n };\n return fn;\n};\nexport const parseAsync = /* @__PURE__*/ _parseAsync(errors.$ZodRealError);\nexport const _safeParse = (_Err) => (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, async: false } : { async: false };\n const result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n return result.issues.length ? failure(_Err, result.issues, ctx) : { success: true, data: result.value };\n};\nexport const safeParse = /* @__PURE__*/ _safeParse(errors.$ZodRealError);\n// the error is built on the first read of `error`: finalizing the issues and constructing the instance is most of a failing parse, and a caller that only branches on `success` never pays it. a getter in the literal keeps this small; the alternative, one shared accessor descriptor plus a hidden state slot, reads ~15% faster but costs ~75 B gzipped in every bundle\nfunction failure(Err, issues, ctx) {\n let error;\n return {\n success: false,\n get error() {\n if (!error) {\n error = new Err(issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));\n // finalizeIssue drops `input`, so the built error holds nothing; keeping the raw issues past this point pins the parsed value for the life of the result\n issues = undefined;\n ctx = undefined;\n }\n return error;\n },\n set error(e) {\n error = e;\n // a replacement makes the getter's branch unreachable, so the captures have to go here too\n issues = undefined;\n ctx = undefined;\n },\n };\n}\nexport const _safeParseAsync = (_Err) => async (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, async: true } : { async: true };\n let result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise)\n result = await result;\n return result.issues.length ? failure(_Err, result.issues, ctx) : { success: true, data: result.value };\n};\nexport const safeParseAsync = /* @__PURE__*/ _safeParseAsync(errors.$ZodRealError);\n// registry mirrors of the compiler's sentinels, so this module never imports the compiler\nconst COMPILE_INVALID = /* @__PURE__ */ Symbol.for(\"zod.compile.invalid\");\nconst COMPILE_FALLBACK = /* @__PURE__ */ Symbol.for(\"zod.compile.fallback\");\n// Deliberately tiny, because v8 will not inline a body carrying the fallback's object literals and throw. Everything that is not the compiled happy path lives in validateFallback, and that split is worth ~35% on a compiled schema.\nexport const validate = ((schema, value, _ctx) => {\n const validator = schema._zod.bag.validator;\n if (validator !== undefined) {\n if (validator(value) !== COMPILE_INVALID)\n return true;\n // a definite sentinel means the runtime would reject, so skip the re-parse; a ctx can still change the answer\n if (validator.definite === true && _ctx === undefined)\n return false;\n }\n return validateFallback(schema, value, _ctx);\n});\nfunction validateFallback(schema, value, _ctx) {\n const ctx = _ctx\n ? { ..._ctx, async: false, abortEarly: true }\n : { async: false, abortEarly: true };\n const fallbackRun = schema._zod.bag.fallbackRun;\n let result;\n if (fallbackRun) {\n // skip nested fast paths on the fallback, so user callbacks keep the at-most-twice bound\n ctx[COMPILE_FALLBACK] = true;\n result = fallbackRun({ value, issues: [] }, ctx);\n }\n else {\n result = schema._zod.run({ value, issues: [] }, ctx);\n }\n if (result instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n return result.issues.length === 0;\n}\n// no fast path: the compiler keeps async parses on the runtime, because a promise-returning callback that is not declared async compiles to a throw\nexport const validateAsync = async (schema, value, _ctx) => {\n const ctx = _ctx\n ? { ..._ctx, async: true, abortEarly: true }\n : { async: true, abortEarly: true };\n let result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise)\n result = await result;\n return result.issues.length === 0;\n};\nexport const _encode = (_Err) => {\n const parse = _parse(_Err);\n const fn = (schema, value, _ctx, _params) => {\n const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n return parse(schema, value, ctx, finalizeParams(fn, _params));\n };\n return fn;\n};\nexport const encode = /* @__PURE__*/ _encode(errors.$ZodRealError);\nexport const _decode = (_Err) => {\n const parse = _parse(_Err);\n const fn = (schema, value, _ctx, _params) => {\n return parse(schema, value, _ctx, finalizeParams(fn, _params));\n };\n return fn;\n};\nexport const decode = /* @__PURE__*/ _decode(errors.$ZodRealError);\nexport const _encodeAsync = (_Err) => {\n const parseAsync = _parseAsync(_Err);\n const fn = async (schema, value, _ctx, _params) => {\n const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n return (await parseAsync(schema, value, ctx, finalizeParams(fn, _params)));\n };\n return fn;\n};\nexport const encodeAsync = /* @__PURE__*/ _encodeAsync(errors.$ZodRealError);\nexport const _decodeAsync = (_Err) => {\n const parseAsync = _parseAsync(_Err);\n const fn = async (schema, value, _ctx, _params) => {\n return await parseAsync(schema, value, _ctx, finalizeParams(fn, _params));\n };\n return fn;\n};\nexport const decodeAsync = /* @__PURE__*/ _decodeAsync(errors.$ZodRealError);\nexport const _safeEncode = (_Err) => (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n return _safeParse(_Err)(schema, value, ctx);\n};\nexport const safeEncode = /* @__PURE__*/ _safeEncode(errors.$ZodRealError);\nexport const _safeDecode = (_Err) => (schema, value, _ctx) => {\n return _safeParse(_Err)(schema, value, _ctx);\n};\nexport const safeDecode = /* @__PURE__*/ _safeDecode(errors.$ZodRealError);\nexport const _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n return _safeParseAsync(_Err)(schema, value, ctx);\n};\nexport const safeEncodeAsync = /* @__PURE__*/ _safeEncodeAsync(errors.$ZodRealError);\nexport const _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => {\n return _safeParseAsync(_Err)(schema, value, _ctx);\n};\nexport const safeDecodeAsync = /* @__PURE__*/ _safeDecodeAsync(errors.$ZodRealError);\n","import * as util from \"./util.js\";\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link cuid2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport const cuid = /^[cC][0-9a-z]{6,}$/;\nexport const cuid2 = /^[0-9a-z]+$/;\nexport const ulid = /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/;\nexport const xid = /^[0-9a-vA-V]{20}$/;\nexport const ksuid = /^[A-Za-z0-9]{27}$/;\nexport const nanoid = /^[a-zA-Z0-9_-]{21}$/;\nexport function nanoidOfLength(length) {\n return new RegExp(`^[a-zA-Z0-9_-]{${length}}$`);\n}\n/** ISO 8601-1 duration regex. Does not support the 8601-2 extensions like negative durations or fractional/negative components. */\nexport const duration = /^P(?:(\\d+W)|(?!.*W)(?=\\d|T\\d)(\\d+Y)?(\\d+M)?(\\d+D)?(T(?=\\d)(\\d+H)?(\\d+M)?(\\d+([.,]\\d+)?S)?)?)$/;\n/** Implements ISO 8601-2 extensions like explicit +- prefixes, mixing weeks with other units, and fractional/negative components. */\nexport const extendedDuration = /^[-+]?P(?!$)(?:(?:[-+]?\\d+Y)|(?:[-+]?\\d+[.,]\\d+Y$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:(?:[-+]?\\d+W)|(?:[-+]?\\d+[.,]\\d+W$))?(?:(?:[-+]?\\d+D)|(?:[-+]?\\d+[.,]\\d+D$))?(?:T(?=[\\d+-])(?:(?:[-+]?\\d+H)|(?:[-+]?\\d+[.,]\\d+H$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:[-+]?\\d+(?:[.,]\\d+)?S)?)??$/;\n/** A regex for any UUID-like identifier: 8-4-4-4-12 hex pattern */\nexport const guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;\n/** Returns a regex for validating an RFC 9562/4122 UUID.\n *\n * @param version Optionally specify a version 1-8. If no version is specified, all versions are supported. */\nexport const uuid = (version) => {\n if (!version)\n return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;\n return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);\n};\nexport const uuid4 = /*@__PURE__*/ uuid(4);\nexport const uuid6 = /*@__PURE__*/ uuid(6);\nexport const uuid7 = /*@__PURE__*/ uuid(7);\n/** Practical email validation */\nexport const email = /^(?:[A-Za-z0-9_'+\\-]+\\.)*[A-Za-z0-9_'+\\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$/;\n/** Equivalent to the HTML5 input[type=email] validation implemented by browsers. Source: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email */\nexport const html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n/** The classic emailregex.com regex for RFC 5322-compliant emails */\nexport const rfc5322Email = /^(([^<>()\\[\\]\\\\.,;:\\s@\"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/;\n/** A loose regex that allows Unicode characters, enforces length limits, and that's about it. */\nexport const unicodeEmail = /^[^\\s@\"]{1,64}@[^\\s@]{1,255}$/u;\nexport const idnEmail = unicodeEmail;\nexport const browserEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression\n// Single character class, not an alternation: the two properties overlap (U+1F9B0-U+1F9B3), so `(A|B)+` backtracks exponentially on a failed match. The leading lookahead then demands one anchor — a pictograph, a regional indicator, or the enclosing keycap — because `\\p{Emoji_Component}` on its own covers ASCII digits, `#`, `*`, ZWJ, variation selectors and skin tone modifiers, none of which is an emoji without a base.\nconst _emoji = `^(?=[\\\\s\\\\S]*[\\\\p{Extended_Pictographic}\\\\p{Regional_Indicator}\\\\u20E3])[\\\\p{Extended_Pictographic}\\\\p{Emoji_Component}]+$`;\nexport function emoji() {\n return new RegExp(_emoji, \"u\");\n}\nexport const ipv4 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;\nexport const ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;\nexport const mac = (delimiter) => {\n const escapedDelim = util.escapeRegex(delimiter ?? \":\");\n return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`);\n};\nexport const cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\/([0-9]|[1-2][0-9]|3[0-2])$/;\nexport const cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;\n// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript\nexport const base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;\nexport const base64url = /^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/;\n// based on https://stackoverflow.com/questions/106179/regular-expression-to-match-dns-hostname-or-ip-address\n// export const hostname: RegExp = /^([a-zA-Z0-9-]+\\.)*[a-zA-Z0-9-]+$/;\nexport const hostname = /^(?=.{1,253}\\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\\.?$/;\nexport const domain = /^(?=.{1,253}$)([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,63}$/;\nexport const httpProtocol = /^https?$/;\n// https://blog.stevenlevithan.com/archives/validate-phone-number#r4-3 (regex sans spaces) E.164: leading digit must be 1-9; total digits (excluding '+') between 7-15\nexport const e164 = /^\\+[1-9]\\d{6,14}$/;\n// Credit card shape: 12–19 digits, optionally separated by single spaces or single hyphens. ISO/IEC 7812 caps the PAN at 19 digits; 12 is the shortest issued length (Maestro).\nexport const creditCard = /^\\d(?:[ -]?\\d){11,18}$/;\n// ISO 4217 alpha codes from the SIX list, regenerated by scripts/update-iso-4217.ts\nexport const currencyCode = /^(?:AED|AFN|ALL|AMD|AOA|ARS|AUD|AWG|AZN|BAM|BBD|BDT|BHD|BIF|BMD|BND|BOB|BOV|BRL|BSD|BTN|BWP|BYN|BZD|CAD|CDF|CHE|CHF|CHW|CLF|CLP|CNY|COP|COU|CRC|CUP|CVE|CZK|DJF|DKK|DOP|DZD|EGP|ERN|ETB|EUR|FJD|FKP|GBP|GEL|GHS|GIP|GMD|GNF|GTQ|GYD|HKD|HNL|HTG|HUF|IDR|ILS|INR|IQD|IRR|ISK|JMD|JOD|JPY|KES|KGS|KHR|KMF|KPW|KRW|KWD|KYD|KZT|LAK|LBP|LKR|LRD|LSL|LYD|MAD|MDL|MGA|MKD|MMK|MNT|MOP|MRU|MUR|MVR|MWK|MXN|MXV|MYR|MZN|NAD|NGN|NIO|NOK|NPR|NZD|OMR|PAB|PEN|PGK|PHP|PKR|PLN|PYG|QAR|RON|RSD|RUB|RWF|SAR|SBD|SCR|SDG|SEK|SGD|SHP|SLE|SOS|SRD|SSP|STN|SVC|SYP|SZL|THB|TJS|TMT|TND|TOP|TRY|TTD|TWD|TZS|UAH|UGX|USD|USN|UYI|UYU|UYW|UZS|VED|VES|VND|VUV|WST|XAD|XAF|XAG|XAU|XBA|XBB|XBC|XBD|XCD|XCG|XDR|XOF|XPD|XPF|XPT|XSU|XTS|XUA|XXX|YER|ZAR|ZMW|ZWG)$/;\n// iban electronic format: 2-letter country, check digits 02-98 (the only values `98 - remainder` can produce), 11-30 bban characters\nexport const iban = /^[A-Z]{2}(?!00|01|99)\\d{2}[A-Z0-9]{11,30}$/;\nconst dateSource = `(?:(?:\\\\d\\\\d[2468][048]|\\\\d\\\\d[13579][26]|\\\\d\\\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\\\d|30)|(?:02)-(?:0[1-9]|1\\\\d|2[0-8])))`;\n/** Anchors a pattern source. The interpolation lives here rather than at the call site because\n * esbuild will not drop a `@__PURE__` call whose own argument interpolates a variable, but it\n * will drop `anchor(dateSource)`. Keeping it inline pinned `date` into every bundle. */\nfunction anchor(source) {\n return new RegExp(`^${source}$`);\n}\nexport const date = /*@__PURE__*/ anchor(dateSource);\nfunction timeSource(args) {\n const hhmm = `(?:[01]\\\\d|2[0-3]):[0-5]\\\\d`;\n const regex = typeof args.precision === \"number\"\n ? args.precision === -1\n ? `${hhmm}`\n : args.precision === 0\n ? `${hhmm}:[0-5]\\\\d`\n : `${hhmm}:[0-5]\\\\d\\\\.\\\\d{${args.precision}}`\n : args.seconds\n ? `${hhmm}:[0-5]\\\\d(?:\\\\.\\\\d+)?`\n : `${hhmm}(?::[0-5]\\\\d(?:\\\\.\\\\d+)?)?`;\n return regex;\n}\nexport function time(args) {\n return new RegExp(`^${timeSource(args)}$`);\n}\n// Adapted from https://stackoverflow.com/a/3143231\nexport function datetime(args) {\n const opts = [\"Z\"];\n // if (args.offset) opts.push(`([+-]\\\\d{2}:\\\\d{2})`);\n if (args.offset)\n opts.push(`([+-](?:[01]\\\\d|2[0-3]):[0-5]\\\\d)`);\n // RFC 3339 mandates seconds wherever the time carries a `Z` or an offset, so only the unqualified form `local` adds may omit them\n const qualified = `${timeSource({ precision: args.precision, seconds: true })}(?:${opts.join(\"|\")})`;\n const timeRegex = args.local ? `${qualified}|${timeSource({ precision: args.precision })}` : qualified;\n return new RegExp(`^${dateSource}T(?:${timeRegex})$`);\n}\n// the unbounded form of `string()` as a literal, so every plain string shares one instance instead of building its own\nexport const anyString = /^[\\s\\S]{0,}$/;\nexport const string = (params) => {\n const regex = params ? `[\\\\s\\\\S]{${params?.minimum ?? 0},${params?.maximum ?? \"\"}}` : `[\\\\s\\\\S]*`;\n return new RegExp(`^${regex}$`);\n};\nexport const bigint = /^-?\\d+n?$/;\nexport const integer = /^-?\\d+$/;\nexport const number = /^-?\\d+(?:\\.\\d+)?$/;\nexport const boolean = /^(?:true|false)$/i;\nconst _null = /^null$/i;\nexport { _null as null };\nconst _undefined = /^undefined$/i;\nexport { _undefined as undefined };\n// regex for string with no uppercase letters\nexport const lowercase = /^[^A-Z]*$/;\n// regex for string with no lowercase letters\nexport const uppercase = /^[^a-z]*$/;\n// regex for hexadecimal strings (any length)\nexport const hex = /^[0-9a-fA-F]*$/;\n// Hash regexes for different algorithms and encodings\n// Helper function to create base64 regex with exact length and padding\nfunction fixedBase64(bodyLength, padding) {\n return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding}$`);\n}\n// Helper function to create base64url regex with exact length (no padding)\nfunction fixedBase64url(length) {\n return new RegExp(`^[A-Za-z0-9_-]{${length}}$`);\n}\n// MD5 (16 bytes): base64 = 24 chars total (22 + \"==\")\nexport const md5_hex = /^[0-9a-fA-F]{32}$/;\nexport const md5_base64 = /*@__PURE__*/ fixedBase64(22, \"==\");\nexport const md5_base64url = /*@__PURE__*/ fixedBase64url(22);\n// SHA1 (20 bytes): base64 = 28 chars total (27 + \"=\")\nexport const sha1_hex = /^[0-9a-fA-F]{40}$/;\nexport const sha1_base64 = /*@__PURE__*/ fixedBase64(27, \"=\");\nexport const sha1_base64url = /*@__PURE__*/ fixedBase64url(27);\n// SHA256 (32 bytes): base64 = 44 chars total (43 + \"=\")\nexport const sha256_hex = /^[0-9a-fA-F]{64}$/;\nexport const sha256_base64 = /*@__PURE__*/ fixedBase64(43, \"=\");\nexport const sha256_base64url = /*@__PURE__*/ fixedBase64url(43);\n// SHA384 (48 bytes): base64 = 64 chars total (no padding)\nexport const sha384_hex = /^[0-9a-fA-F]{96}$/;\nexport const sha384_base64 = /*@__PURE__*/ fixedBase64(64, \"\");\nexport const sha384_base64url = /*@__PURE__*/ fixedBase64url(64);\n// SHA512 (64 bytes): base64 = 88 chars total (86 + \"==\")\nexport const sha512_hex = /^[0-9a-fA-F]{128}$/;\nexport const sha512_base64 = /*@__PURE__*/ fixedBase64(86, \"==\");\nexport const sha512_base64url = /*@__PURE__*/ fixedBase64url(86);\n","// import { $ZodType } from \"./schemas.js\";\nimport * as core from \"./core.js\";\nimport * as regexes from \"./regexes.js\";\nimport * as util from \"./util.js\";\nexport const $ZodCheck = /*@__PURE__*/ core.$constructor(\"$ZodCheck\", (inst, def) => {\n var _a;\n inst._zod ?? (inst._zod = {});\n inst._zod.def = def;\n (_a = inst._zod).onattach ?? (_a.onattach = []);\n});\n/** Default `when` for size-based checks: run only on non-nullish values with a `size`. */\nconst _whenHasSize = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.size !== undefined;\n};\n/** Default `when` for length-based checks: run only on non-nullish values with a `length`. */\nconst _whenHasLength = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.length !== undefined;\n};\nconst numericOriginMap = {\n number: \"number\",\n bigint: \"bigint\",\n object: \"date\",\n};\nexport const $ZodCheckLessThan = /*@__PURE__*/ core.$constructor(\"$ZodCheckLessThan\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const origin = numericOriginMap[typeof def.value];\n inst._zod.check = (payload) => {\n if (def.inclusive ? payload.value <= def.value : payload.value < def.value) {\n return;\n }\n payload.issues.push({\n origin: numericOriginMap[typeof payload.value] ?? origin,\n code: \"too_big\",\n maximum: typeof def.value === \"object\" ? def.value.getTime() : def.value,\n input: payload.value,\n inclusive: def.inclusive,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckGreaterThan = /*@__PURE__*/ core.$constructor(\"$ZodCheckGreaterThan\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const origin = numericOriginMap[typeof def.value];\n inst._zod.check = (payload) => {\n if (def.inclusive ? payload.value >= def.value : payload.value > def.value) {\n return;\n }\n payload.issues.push({\n origin: numericOriginMap[typeof payload.value] ?? origin,\n code: \"too_small\",\n minimum: typeof def.value === \"object\" ? def.value.getTime() : def.value,\n input: payload.value,\n inclusive: def.inclusive,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMultipleOf = \n/*@__PURE__*/ core.$constructor(\"$ZodCheckMultipleOf\", (inst, def) => {\n $ZodCheck.init(inst, def);\n inst._zod.check = (payload) => {\n if (typeof payload.value !== typeof def.value)\n throw new Error(\"Cannot mix number and bigint in multiple_of check.\");\n const isMultiple = typeof payload.value === \"bigint\"\n ? // `value % 0n` throws, and nothing is a multiple of zero — the number branch already fails this way via NaN\n def.value !== BigInt(0) && payload.value % def.value === BigInt(0)\n : util.floatSafeRemainder(payload.value, def.value) === 0;\n if (isMultiple)\n return;\n payload.issues.push({\n origin: typeof payload.value,\n code: \"not_multiple_of\",\n divisor: def.value,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckNumberFormat = /*@__PURE__*/ core.$constructor(\"$ZodCheckNumberFormat\", (inst, def) => {\n $ZodCheck.init(inst, def); // no format checks\n def.format = def.format || \"float64\";\n const isInt = def.format?.includes(\"int\");\n const origin = isInt ? \"int\" : \"number\";\n const [minimum, maximum] = util.NUMBER_FORMAT_RANGES[def.format];\n inst._zod.check = (payload) => {\n const input = payload.value;\n if (isInt) {\n if (!Number.isInteger(input)) {\n // invalid_format issue\n // payload.issues.push({\n // expected: def.format,\n // format: def.format,\n // code: \"invalid_format\",\n // input,\n // inst,\n // });\n // invalid_type issue\n payload.issues.push({\n expected: origin,\n format: def.format,\n code: \"invalid_type\",\n continue: false,\n input,\n inst,\n });\n return;\n // not_multiple_of issue\n // payload.issues.push({\n // code: \"not_multiple_of\",\n // origin: \"number\",\n // input,\n // inst,\n // divisor: 1,\n // });\n }\n if (!Number.isSafeInteger(input)) {\n if (input > 0) {\n // too_big\n payload.issues.push({\n input,\n code: \"too_big\",\n maximum: Number.MAX_SAFE_INTEGER,\n note: \"Integers must be within the safe integer range.\",\n inst,\n origin,\n inclusive: true,\n continue: !def.abort,\n });\n }\n else {\n // too_small\n payload.issues.push({\n input,\n code: \"too_small\",\n minimum: Number.MIN_SAFE_INTEGER,\n note: \"Integers must be within the safe integer range.\",\n inst,\n origin,\n inclusive: true,\n continue: !def.abort,\n });\n }\n return;\n }\n }\n if (input < minimum) {\n payload.issues.push({\n origin: \"number\",\n input,\n code: \"too_small\",\n minimum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n if (input > maximum) {\n payload.issues.push({\n origin: \"number\",\n input,\n code: \"too_big\",\n maximum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodCheckBigIntFormat = /*@__PURE__*/ core.$constructor(\"$ZodCheckBigIntFormat\", (inst, def) => {\n $ZodCheck.init(inst, def); // no format checks\n const [minimum, maximum] = util.BIGINT_FORMAT_RANGES[def.format];\n inst._zod.check = (payload) => {\n const input = payload.value;\n if (input < minimum) {\n payload.issues.push({\n origin: \"bigint\",\n input,\n code: \"too_small\",\n minimum: minimum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n if (input > maximum) {\n payload.issues.push({\n origin: \"bigint\",\n input,\n code: \"too_big\",\n maximum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodCheckMaxSize = /*@__PURE__*/ core.$constructor(\"$ZodCheckMaxSize\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = _whenHasSize);\n inst._zod.check = (payload) => {\n const input = payload.value;\n const size = input.size;\n if (size <= def.maximum)\n return;\n payload.issues.push({\n origin: util.getSizableOrigin(input),\n code: \"too_big\",\n maximum: def.maximum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMinSize = /*@__PURE__*/ core.$constructor(\"$ZodCheckMinSize\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = _whenHasSize);\n inst._zod.check = (payload) => {\n const input = payload.value;\n const size = input.size;\n if (size >= def.minimum)\n return;\n payload.issues.push({\n origin: util.getSizableOrigin(input),\n code: \"too_small\",\n minimum: def.minimum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckSizeEquals = /*@__PURE__*/ core.$constructor(\"$ZodCheckSizeEquals\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = _whenHasSize);\n inst._zod.check = (payload) => {\n const input = payload.value;\n const size = input.size;\n if (size === def.size)\n return;\n const tooBig = size > def.size;\n payload.issues.push({\n origin: util.getSizableOrigin(input),\n ...(tooBig ? { code: \"too_big\", maximum: def.size } : { code: \"too_small\", minimum: def.size }),\n inclusive: true,\n exact: true,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMaxLength = /*@__PURE__*/ core.$constructor(\"$ZodCheckMaxLength\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = _whenHasLength);\n inst._zod.check = (payload) => {\n const input = payload.value;\n const units = input.length;\n // Strings are measured in Unicode code points, not UTF-16 units. A code point is at most two units, so a string that already fits in units fits in code points; only an overflow has to be counted.\n const length = typeof input === \"string\" && units > def.maximum ? util.codePointLength(input) : units;\n if (length <= def.maximum)\n return;\n const origin = util.getLengthableOrigin(input);\n payload.issues.push({\n origin,\n code: \"too_big\",\n maximum: def.maximum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMinLength = /*@__PURE__*/ core.$constructor(\"$ZodCheckMinLength\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = _whenHasLength);\n inst._zod.check = (payload) => {\n const input = payload.value;\n const units = input.length;\n // A code point is one or two UTF-16 units, so fewer units than the floor can never reach it and twice the floor always clears it. Only in between is the exact count in doubt.\n const length = typeof input === \"string\" && units >= def.minimum && units < def.minimum * 2\n ? util.codePointLength(input)\n : units;\n if (length >= def.minimum)\n return;\n const origin = util.getLengthableOrigin(input);\n payload.issues.push({\n origin,\n code: \"too_small\",\n minimum: def.minimum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckLengthEquals = /*@__PURE__*/ core.$constructor(\"$ZodCheckLengthEquals\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = _whenHasLength);\n inst._zod.check = (payload) => {\n const input = payload.value;\n const units = input.length;\n // A code point is one or two UTF-16 units, so outside `[length, length * 2]` units the target is missed either way — and missed in the same direction in both measures.\n const length = typeof input === \"string\" && units >= def.length && units <= def.length * 2\n ? util.codePointLength(input)\n : units;\n if (length === def.length)\n return;\n const origin = util.getLengthableOrigin(input);\n const tooBig = length > def.length;\n payload.issues.push({\n origin,\n ...(tooBig ? { code: \"too_big\", maximum: def.length } : { code: \"too_small\", minimum: def.length }),\n inclusive: true,\n exact: true,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodCheckStringFormat\", (inst, def) => {\n var _a, _b;\n $ZodCheck.init(inst, def);\n if (def.pattern)\n (_a = inst._zod).check ?? (_a.check = (payload) => {\n def.pattern.lastIndex = 0;\n if (def.pattern.test(payload.value))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: def.format,\n input: payload.value,\n ...(def.pattern ? { pattern: def.pattern.toString() } : {}),\n inst,\n continue: !def.abort,\n });\n });\n else\n (_b = inst._zod).check ?? (_b.check = () => { });\n});\nexport const $ZodCheckRegex = /*@__PURE__*/ core.$constructor(\"$ZodCheckRegex\", (inst, def) => {\n $ZodCheckStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n def.pattern.lastIndex = 0;\n if (def.pattern.test(payload.value))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"regex\",\n input: payload.value,\n pattern: def.pattern.toString(),\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckLowerCase = /*@__PURE__*/ core.$constructor(\"$ZodCheckLowerCase\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.lowercase);\n $ZodCheckStringFormat.init(inst, def);\n});\nexport const $ZodCheckUpperCase = /*@__PURE__*/ core.$constructor(\"$ZodCheckUpperCase\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.uppercase);\n $ZodCheckStringFormat.init(inst, def);\n});\nexport const $ZodCheckIncludes = /*@__PURE__*/ core.$constructor(\"$ZodCheckIncludes\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const escapedRegex = util.escapeRegex(def.includes);\n // `String.prototype.includes(sub, position)` matches `sub` at `position`\n // OR LATER, so the pattern must allow at least `position` leading chars\n // (`{N,}`), not exactly `position` chars (`{N}`).\n const pattern = new RegExp(typeof def.position === \"number\" ? `^.{${def.position},}${escapedRegex}` : escapedRegex);\n def.pattern = pattern;\n inst._zod.check = (payload) => {\n if (payload.value.includes(def.includes, def.position))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"includes\",\n includes: def.includes,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckStartsWith = /*@__PURE__*/ core.$constructor(\"$ZodCheckStartsWith\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const pattern = new RegExp(`^${util.escapeRegex(def.prefix)}.*`);\n def.pattern ?? (def.pattern = pattern);\n inst._zod.check = (payload) => {\n if (payload.value.startsWith(def.prefix))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"starts_with\",\n prefix: def.prefix,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckEndsWith = /*@__PURE__*/ core.$constructor(\"$ZodCheckEndsWith\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const pattern = new RegExp(`.*${util.escapeRegex(def.suffix)}$`);\n def.pattern ?? (def.pattern = pattern);\n inst._zod.check = (payload) => {\n if (payload.value.endsWith(def.suffix))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"ends_with\",\n suffix: def.suffix,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\n///////////////////////////////////\n///// $ZodCheckProperty /////\n///////////////////////////////////\nfunction handleCheckPropertyResult(result, payload, property) {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(property, result.issues));\n }\n}\nexport const $ZodCheckProperty = /*@__PURE__*/ core.$constructor(\"$ZodCheckProperty\", (inst, def) => {\n $ZodCheck.init(inst, def);\n inst._zod.check = (payload) => {\n const result = def.schema._zod.run({\n value: payload.value[def.property],\n issues: [],\n }, {});\n if (result instanceof Promise) {\n return result.then((result) => handleCheckPropertyResult(result, payload, def.property));\n }\n handleCheckPropertyResult(result, payload, def.property);\n return;\n };\n});\nexport const $ZodCheckProperties = /*@__PURE__*/ core.$constructor(\"$ZodCheckProperties\", (inst, def) => {\n $ZodCheck.init(inst, def);\n util.hide(inst, Symbol.iterator, function* () {\n yield inst;\n });\n // key and schema snapshotted together: reading one live and the other cached lets a later mutation of the caller's shape object pair a stale key with a missing schema\n let entries;\n inst._zod.check = (payload) => {\n // the base schema already typed the value, so only a nullish one is rejected here: the properties read on a primitive too, matching z.property() on a string's length\n if (payload.value == null) {\n payload.issues.push({ expected: \"object\", code: \"invalid_type\", input: payload.value, inst });\n return undefined;\n }\n entries ?? (entries = Reflect.ownKeys(def.shape).map((key) => [key, def.shape[key]]));\n const input = payload.value;\n let proms;\n for (const [key, schema] of entries) {\n const result = schema._zod.run({ value: input[key], issues: [] }, {});\n if (result instanceof Promise) {\n proms ?? (proms = []);\n proms.push(result.then((result) => handleCheckPropertyResult(result, payload, key)));\n }\n else {\n handleCheckPropertyResult(result, payload, key);\n }\n }\n if (proms)\n return Promise.all(proms).then(() => undefined);\n return undefined;\n };\n});\nexport const $ZodCheckMimeType = /*@__PURE__*/ core.$constructor(\"$ZodCheckMimeType\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const mimeSet = new Set(def.mime);\n inst._zod.check = (payload) => {\n if (mimeSet.has(payload.value.type))\n return;\n payload.issues.push({\n code: \"invalid_value\",\n values: def.mime,\n input: payload.value.type,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckOverwrite = /*@__PURE__*/ core.$constructor(\"$ZodCheckOverwrite\", (inst, def) => {\n $ZodCheck.init(inst, def);\n inst._zod.check = (payload) => {\n payload.value = def.tx(payload.value);\n };\n});\n","export class Doc {\n constructor(args = [], closed = {}) {\n this.content = [];\n this.indent = 0;\n this.args = args;\n this.closed = closed;\n }\n // the compiler catches a child's throw and keeps writing into this doc, so the indent has to unwind with it\n indented(fn) {\n this.indent += 1;\n try {\n fn(this);\n }\n finally {\n this.indent -= 1;\n }\n }\n write(arg) {\n if (typeof arg === \"function\") {\n arg(this, { execution: \"sync\" });\n arg(this, { execution: \"async\" });\n return;\n }\n const content = arg;\n const lines = content.split(\"\\n\").filter((x) => x);\n const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length));\n const dedented = lines.map((x) => x.slice(minIndent)).map((x) => \" \".repeat(this.indent * 2) + x);\n for (const line of dedented) {\n this.content.push(line);\n }\n }\n compile() {\n const F = Function;\n const content = this?.content ?? [``];\n const factory = new F(...Object.keys(this.closed), `return function (${this.args.join(\", \")}) {\\n${content.join(\"\\n\")}\\n};`);\n return factory(...Object.values(this.closed));\n }\n}\n","export const version = {\n major: 4,\n minor: 6,\n patch: 5,\n};\n","import * as checks from \"./checks.js\";\nimport * as core from \"./core.js\";\nimport { Doc } from \"./doc.js\";\nimport { parse, parseAsync } from \"./parse.js\";\nimport * as regexes from \"./regexes.js\";\nimport * as util from \"./util.js\";\nimport { version } from \"./versions.js\";\nexport const $ZodType = /*@__PURE__*/ core.$constructor(\"$ZodType\", (inst, def) => {\n var _a;\n inst ?? (inst = {});\n inst._zod.def = def; // set _def property\n inst._zod.bag = inst._zod.bag || {}; // initialize _bag object\n inst._zod.version = version;\n const defChecks = inst._zod.def.checks;\n // if inst is itself a checks.$ZodCheck, run it as a check\n const checks = inst._zod.traits.has(\"$ZodCheck\")\n ? [inst, ...(defChecks ?? [])]\n : defChecks?.length\n ? [...defChecks]\n : [];\n for (const ch of checks) {\n for (const fn of ch._zod.onattach) {\n fn(inst);\n }\n }\n if (checks.length === 0) {\n // deferred initializer inst._zod.parse is not yet defined\n (_a = inst._zod).deferred ?? (_a.deferred = []);\n inst._zod.deferred?.push(() => {\n inst._zod.run = inst._zod.parse;\n });\n }\n else {\n const runChecks = (payload, checks, ctx) => {\n if (payload.memo)\n return payload;\n let isAborted = util.aborted(payload);\n let asyncResult;\n for (const ch of checks) {\n if (ch._zod.def.when) {\n if (util.explicitlyAborted(payload))\n continue;\n const shouldRun = ch._zod.def.when(payload);\n if (!shouldRun)\n continue;\n }\n else if (isAborted) {\n continue;\n }\n const currLen = payload.issues.length;\n const _ = ch._zod.check(payload);\n if (_ instanceof Promise && ctx?.async === false) {\n throw new core.$ZodAsyncError();\n }\n if (asyncResult || _ instanceof Promise) {\n asyncResult = (asyncResult ?? Promise.resolve()).then(async () => {\n await _;\n const nextLen = payload.issues.length;\n if (nextLen === currLen)\n return;\n util.attachSchema(payload.issues, currLen, inst);\n if (!isAborted)\n isAborted = util.aborted(payload, currLen);\n });\n }\n else {\n const nextLen = payload.issues.length;\n if (nextLen === currLen)\n continue;\n util.attachSchema(payload.issues, currLen, inst);\n if (!isAborted)\n isAborted = util.aborted(payload, currLen);\n }\n }\n if (asyncResult) {\n return asyncResult.then(() => {\n return payload;\n });\n }\n return payload;\n };\n const handleCanaryResult = (canary, payload, ctx) => {\n // abort if the canary is aborted\n if (util.aborted(canary)) {\n canary.aborted = true;\n return canary;\n }\n // run checks first, then\n const checkResult = runChecks(payload, checks, ctx);\n if (checkResult instanceof Promise) {\n if (ctx.async === false)\n throw new core.$ZodAsyncError();\n return checkResult.then((checkResult) => inst._zod.parse(checkResult, ctx));\n }\n return inst._zod.parse(checkResult, ctx);\n };\n inst._zod.run = (payload, ctx) => {\n if (ctx.skipChecks) {\n return inst._zod.parse(payload, ctx);\n }\n if (ctx.direction === \"backward\") {\n // run canary initial pass (no checks)\n const canary = inst._zod.parse({ value: payload.value, issues: [] }, { ...ctx, skipChecks: true });\n if (canary instanceof Promise) {\n return canary.then((canary) => {\n return handleCanaryResult(canary, payload, ctx);\n });\n }\n return handleCanaryResult(canary, payload, ctx);\n }\n // forward\n const result = inst._zod.parse(payload, ctx);\n if (result instanceof Promise) {\n if (ctx.async === false)\n throw new core.$ZodAsyncError();\n return result.then((result) => runChecks(result, checks, ctx));\n }\n return runChecks(result, checks, ctx);\n };\n }\n}, {\n // Wrappers extend this by installing a richer factory over it; reading it eagerly would defeat the laziness.\n get \"~standard\"() {\n return util.hide(this, \"~standard\", standardProps(this));\n },\n set \"~standard\"(value) {\n util.own(this, \"~standard\", value);\n },\n});\n/** The Standard Schema surface for `inst`. Shared so wrappers can extend it without forcing it. */\n// a Standard Schema result only reports issues, so a failure finalizes them straight off the raw payload: no ZodError, and no lazy result to read through\nconst toStandardResult = (r, ctx) => r.issues.length ? { issues: r.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())) } : { value: r.value };\nasync function validateAsync(inst, value) {\n const ctx = { async: true };\n return toStandardResult((await inst._zod.run({ value, issues: [] }, ctx)), ctx);\n}\nexport function standardProps(inst) {\n return {\n validate: (value) => {\n const ctx = { async: false };\n try {\n const r = inst._zod.run({ value, issues: [] }, ctx);\n if (!(r instanceof Promise))\n return toStandardResult(r, ctx);\n }\n catch (_) { }\n // async function so a synchronously throwing check rejects instead of escaping validate\n return validateAsync(inst, value);\n },\n vendor: \"zod\",\n version: 1,\n };\n}\nexport { clone } from \"./util.js\";\nexport const $ZodString = /*@__PURE__*/ core.$constructor(\"$ZodString\", (inst, def) => {\n $ZodType.init(inst, def);\n // a format's own pattern, else unbounded; a template literal derives the check-aware form itself\n inst._zod.pattern = def.pattern ?? regexes.anyString;\n inst._zod.parse = (payload, _) => {\n if (def.coerce)\n try {\n payload.value = String(payload.value);\n }\n catch (_) { }\n if (typeof payload.value === \"string\")\n return payload;\n payload.issues.push({\n expected: \"string\",\n code: \"invalid_type\",\n input: payload.value,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodStringFormat\", (inst, def) => {\n // check initialization must come first\n checks.$ZodCheckStringFormat.init(inst, def);\n $ZodString.init(inst, def);\n});\nexport const $ZodGUID = /*@__PURE__*/ core.$constructor(\"$ZodGUID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.guid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodUUID = /*@__PURE__*/ core.$constructor(\"$ZodUUID\", (inst, def) => {\n if (def.version) {\n const versionMap = {\n v1: 1,\n v2: 2,\n v3: 3,\n v4: 4,\n v5: 5,\n v6: 6,\n v7: 7,\n v8: 8,\n };\n const v = versionMap[def.version];\n if (v === undefined)\n throw new Error(`Invalid UUID version: \"${def.version}\"`);\n def.pattern ?? (def.pattern = regexes.uuid(v));\n }\n else\n def.pattern ?? (def.pattern = regexes.uuid());\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodEmail = /*@__PURE__*/ core.$constructor(\"$ZodEmail\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.email);\n $ZodStringFormat.init(inst, def);\n});\n/** The `://` guard rejected the input before the URL constructor saw it. */\nexport const URL_BAD_FORMAT = 1;\n/** The URL parser rejected the input. */\nexport const URL_UNPARSEABLE = 2;\nexport function canParseURL(input) {\n try {\n if (typeof URL !== \"undefined\" && typeof URL.canParse === \"function\")\n return URL.canParse(input);\n new URL(input);\n return true;\n }\n catch {\n return false;\n }\n}\nexport function validateURL(trimmed, def) {\n if (!(\"normalize\" in def) && !(\"hostname\" in def) && !(\"protocol\" in def)) {\n return canParseURL(trimmed) || URL_UNPARSEABLE;\n }\n return parseURLObject(trimmed, def);\n}\n/** Parses a URL while preserving the non-normalizing HTTP guard. */\nexport function parseURLObject(trimmed, def) {\n // When normalize is off, require :// for http/https URLs. This prevents strings like \"http:example.com\" or \"https:/path\" from being silently accepted\n if (!def.normalize && def.protocol?.source === regexes.httpProtocol.source && !/^https?:\\/\\//i.test(trimmed)) {\n return URL_BAD_FORMAT;\n }\n try {\n if (typeof URL !== \"undefined\") {\n const URLStatic = URL;\n if (typeof URLStatic.parse === \"function\")\n return URLStatic.parse(trimmed) ?? URL_UNPARSEABLE;\n }\n // @ts-ignore\n return new URL(trimmed);\n }\n catch {\n return URL_UNPARSEABLE;\n }\n}\nconst asciiTabOrNewline = /[\\t\\n\\r]/g;\n/** The URL parser deletes every ASCII tab, LF and CR from its input before it parses, so `new URL(\"https://exa\\nmple.com\")` reports on `example.com`. Applying the same deletion to the returned value closes the half of that divergence which can move the host; the parser's other rewrite, stripping C0 controls at the edges, cannot. */\nexport function stripTabAndNewline(value) {\n return value.replace(asciiTabOrNewline, \"\");\n}\nexport function urlHostnameOk(url, hostname) {\n hostname.lastIndex = 0;\n return hostname.test(url.hostname);\n}\nexport function urlProtocolOk(url, protocol) {\n protocol.lastIndex = 0;\n return protocol.test(url.protocol.endsWith(\":\") ? url.protocol.slice(0, -1) : url.protocol);\n}\nexport const $ZodURL = /*@__PURE__*/ core.$constructor(\"$ZodURL\", (inst, def) => {\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n try {\n // Trim whitespace from input\n const trimmed = payload.value.trim();\n const url = validateURL(trimmed, def);\n if (url === URL_BAD_FORMAT) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n note: \"Invalid URL format\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n return;\n }\n if (url === URL_UNPARSEABLE) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n return;\n }\n if (url === true) {\n payload.value = stripTabAndNewline(trimmed);\n return;\n }\n if (def.hostname && !urlHostnameOk(url, def.hostname)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n note: \"Invalid hostname\",\n pattern: def.hostname.source,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n if (def.protocol && !urlProtocolOk(url, def.protocol)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n note: \"Invalid protocol\",\n pattern: def.protocol.source,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n // Set the output value based on normalize flag\n payload.value = def.normalize ? url.href : stripTabAndNewline(trimmed);\n return;\n }\n catch (_) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodEmoji = /*@__PURE__*/ core.$constructor(\"$ZodEmoji\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.emoji());\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodNanoID = /*@__PURE__*/ core.$constructor(\"$ZodNanoID\", (inst, def) => {\n if (def.length !== undefined && (!Number.isInteger(def.length) || def.length < 1))\n throw new Error(`Invalid nanoid length: ${def.length}`);\n def.pattern ?? (def.pattern = def.length === undefined ? regexes.nanoid : regexes.nanoidOfLength(def.length));\n $ZodStringFormat.init(inst, def);\n});\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link $ZodCUID2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport const $ZodCUID = /*@__PURE__*/ core.$constructor(\"$ZodCUID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cuid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodCUID2 = /*@__PURE__*/ core.$constructor(\"$ZodCUID2\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cuid2);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodULID = /*@__PURE__*/ core.$constructor(\"$ZodULID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ulid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodXID = /*@__PURE__*/ core.$constructor(\"$ZodXID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.xid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodKSUID = /*@__PURE__*/ core.$constructor(\"$ZodKSUID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ksuid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODateTime = /*@__PURE__*/ core.$constructor(\"$ZodISODateTime\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.datetime(def));\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODate = /*@__PURE__*/ core.$constructor(\"$ZodISODate\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.date);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISOTime = /*@__PURE__*/ core.$constructor(\"$ZodISOTime\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.time(def));\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODuration = /*@__PURE__*/ core.$constructor(\"$ZodISODuration\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.duration);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodIPv4 = /*@__PURE__*/ core.$constructor(\"$ZodIPv4\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ipv4);\n $ZodStringFormat.init(inst, def);\n});\n/** An IPv6 address is written with hex digits, colons and dots, and nothing else. The guard is what makes the check below an IPv6 check: `new URL(\"http://[...]\")` parses an authority, not an address, so `@` and `\\` re-delimit it and `\"::@1\\\\\"` validates against the host `0.0.0.1`. The URL parser also deletes ASCII tab, LF and CR rather than failing, which is how `\"::1\\n\"` validated as `::1`. */\nconst ipv6Alphabet = /^[0-9a-fA-F:.]+$/;\nexport function isValidIPv6(value) {\n if (!ipv6Alphabet.test(value))\n return false;\n return canParseURL(`http://[${value}]`);\n}\nexport const $ZodIPv6 = /*@__PURE__*/ core.$constructor(\"$ZodIPv6\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ipv6);\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (!isValidIPv6(payload.value)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"ipv6\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodMAC = /*@__PURE__*/ core.$constructor(\"$ZodMAC\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.mac(def.delimiter));\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodCIDRv4 = /*@__PURE__*/ core.$constructor(\"$ZodCIDRv4\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cidrv4);\n $ZodStringFormat.init(inst, def);\n});\nexport function isValidCIDRv6(value) {\n const parts = value.split(\"/\");\n if (parts.length !== 2)\n return false;\n const [address, prefix] = parts;\n if (!prefix)\n return false;\n const prefixNum = Number(prefix);\n if (`${prefixNum}` !== prefix)\n return false;\n if (prefixNum < 0 || prefixNum > 128)\n return false;\n return isValidIPv6(address);\n}\nexport const $ZodCIDRv6 = /*@__PURE__*/ core.$constructor(\"$ZodCIDRv6\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cidrv6); // not used for validation\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (!isValidCIDRv6(payload.value)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"cidrv6\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\n////////////////////////////// ZodBase64 //////////////////////////////\nexport function isValidBase64(data) {\n if (data === \"\")\n return true;\n // atob ignores whitespace, so reject it up front.\n if (/\\s/.test(data))\n return false;\n if (data.length % 4 !== 0)\n return false;\n try {\n // @ts-ignore\n atob(data);\n return true;\n }\n catch {\n return false;\n }\n}\n// lax on purpose: the quantified regexes.base64 overflows the regex stack on multi-MB input and its leading ^$| alternation leaks through template-literal composition; isValidBase64 enforces length and padding\nexport const base64Charset = /^[0-9a-zA-Z+/]*={0,2}$/;\nexport const $ZodBase64 = /*@__PURE__*/ core.$constructor(\"$ZodBase64\", (inst, def) => {\n def.pattern ?? (def.pattern = base64Charset);\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (isValidBase64(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"base64\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\n////////////////////////////// ZodBase64URL //////////////////////////////\n// lax on purpose: the quantified regexes.base64url overflows the regex stack on multi-MB input; isValidBase64 enforces length on the padded string\nexport const base64urlCharset = /^[A-Za-z0-9_-]*$/;\nexport function isValidBase64URL(data) {\n if (!base64urlCharset.test(data))\n return false;\n const base64 = data.replace(/[-_]/g, (c) => (c === \"-\" ? \"+\" : \"/\"));\n const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, \"=\");\n return isValidBase64(padded);\n}\nexport const $ZodBase64URL = /*@__PURE__*/ core.$constructor(\"$ZodBase64URL\", (inst, def) => {\n def.pattern ?? (def.pattern = base64urlCharset);\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (isValidBase64URL(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"base64url\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodE164 = /*@__PURE__*/ core.$constructor(\"$ZodE164\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.e164);\n $ZodStringFormat.init(inst, def);\n});\n////////////////////////////// ZodCreditCard //////////////////////////////\nconst CC_SANITIZE = /[- ]/g;\n/** Luhn checksum on a digit-only string. Adapted from valibot (MIT). */\nfunction isLuhnAlgo(digits) {\n let length = digits.length;\n let bit = 1;\n let sum = 0;\n while (length) {\n const value = digits.charCodeAt(--length) - 48;\n bit ^= 1;\n sum += bit ? [0, 2, 4, 6, 8, 1, 3, 5, 7, 9][value] : value;\n }\n return sum % 10 === 0;\n}\nexport function isValidCreditCard(input) {\n if (!regexes.creditCard.test(input))\n return false;\n return isLuhnAlgo(input.replace(CC_SANITIZE, \"\"));\n}\nexport const $ZodCreditCard = /*@__PURE__*/ core.$constructor(\"$ZodCreditCard\", (inst, def) => {\n // Shape only — the Luhn check below is not expressible as a pattern, so consumers of `pattern` (JSON Schema, template literals) get the length and separator rules alone.\n def.pattern ?? (def.pattern = regexes.creditCard);\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (isValidCreditCard(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"credit_card\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\n////////////////////////////// ZodIBAN //////////////////////////////\n// iso 7064 mod 97-10 checksum without BigInt\nfunction isIso7064Mod97(iban) {\n let remainder = 0;\n const len = iban.length;\n for (let i = 4; i < len; i++) {\n const code = iban.charCodeAt(i);\n remainder = (code >= 65 ? remainder * 100 + (code - 55) : remainder * 10 + (code - 48)) % 97;\n }\n for (let i = 0; i < 4; i++) {\n const code = iban.charCodeAt(i);\n remainder = (code >= 65 ? remainder * 100 + (code - 55) : remainder * 10 + (code - 48)) % 97;\n }\n return remainder === 1;\n}\nexport function isValidIBAN(input) {\n if (!regexes.iban.test(input))\n return false;\n return isIso7064Mod97(input);\n}\nexport const $ZodIBAN = /*@__PURE__*/ core.$constructor(\"$ZodIBAN\", (inst, def) => {\n // shape only — checksum is not expressible as a pattern\n def.pattern ?? (def.pattern = regexes.iban);\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (isValidIBAN(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"iban\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\n////////////////////////////// ZodJWT //////////////////////////////\nexport function isValidJWT(token, algorithm = null) {\n try {\n const tokensParts = token.split(\".\");\n if (tokensParts.length !== 3)\n return false;\n const [header] = tokensParts;\n if (!header)\n return false;\n // @ts-ignore\n const parsedHeader = JSON.parse(atob(header));\n if (\"typ\" in parsedHeader && parsedHeader?.typ !== \"JWT\")\n return false;\n if (!parsedHeader.alg)\n return false;\n if (algorithm && (!(\"alg\" in parsedHeader) || parsedHeader.alg !== algorithm))\n return false;\n return true;\n }\n catch {\n return false;\n }\n}\nexport const $ZodJWT = /*@__PURE__*/ core.$constructor(\"$ZodJWT\", (inst, def) => {\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (isValidJWT(payload.value, def.alg))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"jwt\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCustomStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodCustomStringFormat\", (inst, def) => {\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (def.fn(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: def.format,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodNumber = /*@__PURE__*/ core.$constructor(\"$ZodNumber\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.number;\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce)\n try {\n payload.value = Number(payload.value);\n }\n catch (_) { }\n const input = payload.value;\n if (typeof input === \"number\" && !Number.isNaN(input) && Number.isFinite(input)) {\n return payload;\n }\n const received = typeof input === \"number\"\n ? Number.isNaN(input)\n ? \"NaN\"\n : !Number.isFinite(input)\n ? String(input)\n : undefined\n : undefined;\n payload.issues.push({\n expected: \"number\",\n code: \"invalid_type\",\n input,\n inst,\n ...(received ? { received } : {}),\n });\n return payload;\n };\n});\nexport const $ZodNumberFormat = /*@__PURE__*/ core.$constructor(\"$ZodNumberFormat\", (inst, def) => {\n checks.$ZodCheckNumberFormat.init(inst, def);\n $ZodNumber.init(inst, def); // no format checks\n});\nexport const $ZodBoolean = /*@__PURE__*/ core.$constructor(\"$ZodBoolean\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.boolean;\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce)\n try {\n payload.value = Boolean(payload.value);\n }\n catch (_) { }\n const input = payload.value;\n if (typeof input === \"boolean\")\n return payload;\n payload.issues.push({\n expected: \"boolean\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodBigInt = /*@__PURE__*/ core.$constructor(\"$ZodBigInt\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.bigint;\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce)\n try {\n payload.value = BigInt(payload.value);\n }\n catch (_) { }\n if (typeof payload.value === \"bigint\")\n return payload;\n payload.issues.push({\n expected: \"bigint\",\n code: \"invalid_type\",\n input: payload.value,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodBigIntFormat = /*@__PURE__*/ core.$constructor(\"$ZodBigIntFormat\", (inst, def) => {\n checks.$ZodCheckBigIntFormat.init(inst, def);\n $ZodBigInt.init(inst, def); // no format checks\n});\nexport const $ZodSymbol = /*@__PURE__*/ core.$constructor(\"$ZodSymbol\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (typeof input === \"symbol\")\n return payload;\n payload.issues.push({\n expected: \"symbol\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodUndefined = /*@__PURE__*/ core.$constructor(\"$ZodUndefined\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.undefined;\n inst._zod.values = new Set([undefined]);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (typeof input === \"undefined\")\n return payload;\n payload.issues.push({\n expected: \"undefined\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodNull = /*@__PURE__*/ core.$constructor(\"$ZodNull\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.null;\n inst._zod.values = new Set([null]);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (input === null)\n return payload;\n payload.issues.push({\n expected: \"null\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodAny = /*@__PURE__*/ core.$constructor(\"$ZodAny\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload) => payload;\n});\nexport const $ZodUnknown = /*@__PURE__*/ core.$constructor(\"$ZodUnknown\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload) => payload;\n});\nexport const $ZodNever = /*@__PURE__*/ core.$constructor(\"$ZodNever\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n payload.issues.push({\n expected: \"never\",\n code: \"invalid_type\",\n input: payload.value,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodVoid = /*@__PURE__*/ core.$constructor(\"$ZodVoid\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (typeof input === \"undefined\")\n return payload;\n payload.issues.push({\n expected: \"void\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodDate = /*@__PURE__*/ core.$constructor(\"$ZodDate\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce) {\n try {\n payload.value = new Date(payload.value);\n }\n catch (_err) { }\n }\n const input = payload.value;\n const isDate = input instanceof Date;\n const isValidDate = isDate && !Number.isNaN(input.getTime());\n if (isValidDate)\n return payload;\n payload.issues.push({\n expected: \"date\",\n code: \"invalid_type\",\n input,\n ...(isDate ? { received: \"Invalid Date\" } : {}),\n inst,\n });\n return payload;\n };\n});\nfunction handleArrayResult(result, final, index) {\n if (result.issues.length) {\n final.issues.push(...util.prefixIssues(index, result.issues));\n }\n final.value[index] = result.value;\n}\nexport const $ZodArray = /*@__PURE__*/ core.$constructor(\"$ZodArray\", (inst, def) => {\n $ZodType.init(inst, def);\n const memo = core.globalConfig.memoizer;\n memo?.attach(inst);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!Array.isArray(input)) {\n payload.issues.push({\n expected: \"array\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n payload.value = memo ? memo.alloc(inst, payload, Array(input.length), ctx) : Array(input.length);\n const proms = [];\n const abortEarly = ctx?.abortEarly;\n for (let i = 0; i < input.length; i++) {\n const item = input[i];\n const result = def.element._zod.run({\n value: item,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => handleArrayResult(result, payload, i)));\n }\n else {\n handleArrayResult(result, payload, i);\n // the element's payload is authoritative here, since handleArrayResult forwards every issue; an object's is not, because it drops a failed absent optional\n if (abortEarly && result.issues.length !== 0 && util.aborted(result))\n break;\n }\n }\n if (proms.length) {\n return Promise.all(proms).then(() => payload);\n }\n return payload; //handleArrayResultsAsync(parseResults, final);\n };\n});\nfunction handlePropertyResult(result, final, key, input, optin, optout) {\n const isPresent = key in input;\n const isOptionalOut = optout === \"optional\";\n // The middle rung means \"absence permitted, nothing supplied in its place\", so an absent key contributes nothing — whatever the schema made of `undefined` is invented, not substituted. Only `optional` reaches this with a value: `defaulted` substitutes, and a schema that isn't optional-out has to keep the key.\n if (!isPresent && isOptionalOut && optin === \"optional\") {\n return;\n }\n if (result.issues.length) {\n // For optional-in/out schemas, ignore errors on absent keys.\n if (optin !== undefined && isOptionalOut && !isPresent) {\n return;\n }\n final.issues.push(...util.prefixIssues(key, result.issues));\n }\n if (!isPresent && optin === undefined) {\n if (!result.issues.length) {\n final.issues.push({\n code: \"invalid_type\",\n expected: \"nonoptional\",\n input: undefined,\n path: [key],\n });\n }\n return;\n }\n if (result.value === undefined) {\n if (isPresent || (optin === \"defaulted\" && !isOptionalOut)) {\n final.value[key] = undefined;\n }\n }\n else {\n final.value[key] = result.value;\n }\n}\n// one shared instance; a fresh [] per schema cost 56 bytes retained\nconst NO_SYMBOL_KEYS = [];\nfunction normalizeDef(def) {\n const keys = Object.keys(def.shape);\n const ownSymbols = Object.getOwnPropertySymbols(def.shape);\n const symbolKeys = ownSymbols.length ? ownSymbols : NO_SYMBOL_KEYS;\n // aliases `keys` when there are no symbols, so a string-only shape keeps one array\n const allKeys = symbolKeys.length ? [...keys, ...symbolKeys] : keys;\n for (const k of allKeys) {\n if (!def.shape?.[k]?._zod?.traits?.has(\"$ZodType\")) {\n throw new Error(`Invalid element at key \"${String(k)}\": expected a Zod schema`);\n }\n }\n const okeys = util.optionalKeys(def.shape);\n return {\n ...def,\n allKeys,\n symbolKeys,\n // string-only: handleCatchall matches it against `for...in`, which never yields a symbol\n keySet: new Set(keys),\n numKeys: keys.length,\n optionalKeys: new Set(okeys),\n };\n}\nfunction handleCatchall(proms, input, payload, ctx, def, inst, abortEarly) {\n const unrecognized = [];\n const keySet = def.keySet;\n const _catchall = def.catchall._zod;\n const t = _catchall.def.type;\n const optin = _catchall.optin;\n const optout = _catchall.optout;\n // starts at 0, not the current length: the shape phase already ran and may have aborted\n let seen = 0;\n for (const key in input) {\n if (abortEarly && payload.issues.length !== seen) {\n if (util.aborted(payload, seen))\n break;\n seen = payload.issues.length;\n }\n // Must precede the __proto__ branch: a declared key is not unrecognized, even though the shape loop deliberately strips __proto__ from the parsed output.\n if (keySet.has(key))\n continue;\n // Don't copy an undeclared __proto__ into the result; assignment to a plain {} would replace the result prototype. But in strict mode it is still an unknown key, so report it before skipping.\n if (key === \"__proto__\") {\n if (t === \"never\")\n unrecognized.push(key);\n continue;\n }\n if (t === \"never\") {\n unrecognized.push(key);\n continue;\n }\n const r = _catchall.run({ value: input[key], issues: [] }, ctx);\n if (r instanceof Promise) {\n proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, optin, optout)));\n }\n else {\n handlePropertyResult(r, payload, key, input, optin, optout);\n }\n }\n if (unrecognized.length) {\n payload.issues.push({\n code: \"unrecognized_keys\",\n keys: unrecognized,\n input,\n inst,\n // Describes the shape of the input, not the validity of the parsed value, so it never aborts. The parse still fails; the schema's own checks just get to run first, and an enclosing intersection can reconcile the key against a sibling operand.\n continue: true,\n });\n }\n if (!proms.length)\n return payload;\n return Promise.all(proms).then(() => {\n return payload;\n });\n}\nexport const $ZodObject = /*@__PURE__*/ core.$constructor(\"$ZodObject\", (inst, def) => {\n // requires cast because technically $ZodObject doesn't extend\n $ZodType.init(inst, def);\n const desc = Object.getOwnPropertyDescriptor(def, \"shape\");\n // a cloned def carries its source's accessor, which knows the shape it answers from; adopting that keeps the clone's keys readable without running it\n const sh = desc?.get ? desc.get.raw : (def.shape ?? {});\n if (sh) {\n // Freezes the shape on first read, so its getters resolve once and every later read sees the same schemas.\n const get = () => {\n const newSh = { ...sh };\n Object.defineProperty(def, \"shape\", { value: newSh });\n get.raw = newSh;\n return newSh;\n };\n get.raw = sh;\n Object.defineProperty(def, \"shape\", { get });\n }\n const _normalized = util.cached(() => normalizeDef(def));\n util.defineLazyInternal(inst, \"propValues\", (zod) => {\n const shape = zod.def.shape;\n const propValues = {};\n for (const key in shape) {\n const field = shape[key]._zod;\n if (field.values) {\n if (!Object.prototype.hasOwnProperty.call(propValues, key)) {\n util.assignProp(propValues, key, new Set());\n }\n for (const v of field.values)\n propValues[key].add(v);\n // An omittable slot reads back as undefined at a discriminator lookup, so it has to claim undefined: two options that can both omit the key are not discriminable on it.\n if (field.optin !== undefined)\n propValues[key].add(undefined);\n }\n }\n return propValues;\n });\n const isObject = util.isObject;\n const catchall = def.catchall;\n let value;\n const memo = core.globalConfig.memoizer;\n memo?.attach(inst);\n inst._zod.parse = (payload, ctx) => {\n value ?? (value = _normalized.value);\n const input = payload.value;\n if (!isObject(input)) {\n payload.issues.push({\n expected: \"object\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {};\n const proms = [];\n const shape = value.shape;\n const abortEarly = ctx?.abortEarly;\n let seen = payload.issues.length;\n for (const key of value.allKeys) {\n if (abortEarly && payload.issues.length !== seen) {\n if (util.aborted(payload, seen))\n break;\n seen = payload.issues.length;\n }\n if (key === \"__proto__\")\n continue;\n const el = shape[key];\n const optin = el._zod.optin;\n const optout = el._zod.optout;\n const r = el._zod.run({ value: input[key], issues: [] }, ctx);\n if (r instanceof Promise) {\n proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, optin, optout)));\n }\n else {\n handlePropertyResult(r, payload, key, input, optin, optout);\n }\n }\n if (!catchall) {\n return proms.length ? Promise.all(proms).then(() => payload) : payload;\n }\n return handleCatchall(proms, input, payload, ctx, _normalized.value, inst, abortEarly === true);\n };\n});\nexport const $ZodObjectJIT = /*@__PURE__*/ core.$constructor(\"$ZodObjectJIT\", (inst, def) => {\n // requires cast because technically $ZodObject doesn't extend\n $ZodObject.init(inst, def);\n const superParse = inst._zod.parse;\n const _normalized = util.cached(() => normalizeDef(def));\n const memo = core.globalConfig.memoizer;\n const generateFastpass = (shape) => {\n const normalized = _normalized.value;\n const syms = normalized.symbolKeys;\n // a symbol has no source literal, so it is read as `syms[i]` off the closed-over scope\n const doc = new Doc([\"payload\", \"ctx\"], { shape, inst, memo, syms });\n const parseStr = (k) => `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`;\n // prefixes in place, like util.prefixIssues. newResult must land before the early return: a catchall runs after this and would otherwise write onto the caller's input\n const prefixStr = (id, k) => `\n let ${id}_ab = false;\n for (let i = 0; i < ${id}.issues.length; i++) {\n const iss = ${id}.issues[i];\n iss.path = iss.path ? [${k}, ...iss.path] : [${k}];\n payload.issues.push(iss);\n if (iss.continue !== true) ${id}_ab = true;\n }\n if (${id}_ab && ctx && ctx.abortEarly) {\n payload.value = newResult;\n return payload;\n }`;\n doc.write(`const input = payload.value;`);\n const ids = Object.create(null);\n let counter = 0;\n for (const key of normalized.allKeys) {\n ids[key] = `key_${counter++}`;\n }\n // A: preserve key order {\n doc.write(memo ? `const newResult = memo.alloc(inst, payload, {}, ctx);` : `const newResult = {};`);\n for (const key of normalized.allKeys) {\n if (key === \"__proto__\")\n continue;\n const id = ids[key];\n const k = typeof key === \"symbol\" ? `syms[${syms.indexOf(key)}]` : util.esc(key);\n const isPresent = `${k} in input`;\n const schema = shape[key];\n const optin = schema?._zod?.optin;\n const isOptionalIn = optin !== undefined;\n const isOptionalOut = schema?._zod?.optout === \"optional\";\n doc.write(`const ${id} = ${parseStr(k)};`);\n if (isOptionalIn && isOptionalOut) {\n // For optional-in/out schemas, ignore errors on absent keys — and, like the interpreted path, drop the value produced alongside them. The middle rung goes further: it permits absence without supplying anything in its place, so an absent key contributes nothing at all.\n const assign = optin === \"optional\" ? `${id}_present` : `${id}.value !== undefined || ${id}_present`;\n doc.write(`\n const ${id}_present = ${isPresent};\n if (!${id}.issues.length || ${id}_present) {\n if (${id}.issues.length) {${prefixStr(id, k)}\n }\n\n if (${assign}) {\n newResult[${k}] = ${id}.value;\n }\n }\n\n `);\n }\n else if (!isOptionalIn) {\n doc.write(`\n const ${id}_present = ${isPresent};\n if (${id}.issues.length) {${prefixStr(id, k)}\n }\n if (!${id}_present && !${id}.issues.length) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"nonoptional\",\n input: undefined,\n path: [${k}]\n });\n if (ctx && ctx.abortEarly) {\n payload.value = newResult;\n return payload;\n }\n }\n\n if (${id}_present) {\n newResult[${k}] = ${id}.value;\n }\n\n `);\n }\n else {\n doc.write(`\n if (${id}.issues.length) {${prefixStr(id, k)}\n }\n `);\n if (optin === \"defaulted\") {\n doc.write(`newResult[${k}] = ${id}.value;`);\n }\n else {\n doc.write(`\n if (${id}.value !== undefined || ${isPresent}) {\n newResult[${k}] = ${id}.value;\n }\n `);\n }\n }\n }\n doc.write(`payload.value = newResult;`);\n doc.write(`return payload;`);\n // closing `shape` in is what pays: turbofan specializes the parser against that one shape object, so every `shape[k]._zod.run` folds to a known callee. as a parameter it stays a generic load and measures 13% slower even with the forwarding frame gone\n return doc.compile();\n };\n let fastpass;\n const isObject = util.isObject;\n const jit = !core.globalConfig.jitless;\n const allowsEval = util.allowsEval;\n const fastEnabled = jit && allowsEval.value; // && !def.catchall;\n const catchall = def.catchall;\n let value;\n inst._zod.parse = (payload, ctx) => {\n value ?? (value = _normalized.value);\n const input = payload.value;\n if (!isObject(input)) {\n payload.issues.push({\n expected: \"object\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) {\n // always synchronous\n if (!fastpass)\n fastpass = generateFastpass(def.shape);\n payload = fastpass(payload, ctx);\n if (!catchall)\n return payload;\n return handleCatchall([], input, payload, ctx, value, inst, ctx?.abortEarly === true);\n }\n return superParse(payload, ctx);\n };\n});\nfunction handleUnionResults(results, final, inst, ctx) {\n for (const result of results) {\n if (result.issues.length === 0) {\n final.value = result.value;\n return final;\n }\n }\n const nonaborted = results.filter((r) => !util.aborted(r));\n if (nonaborted.length === 1) {\n final.value = nonaborted[0].value;\n return nonaborted[0];\n }\n final.issues.push({\n code: \"invalid_union\",\n input: final.value,\n inst,\n errors: results.map((result) => result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n });\n return final;\n}\nexport const $ZodUnion = /*@__PURE__*/ core.$constructor(\"$ZodUnion\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.options.some((o) => o._zod.optin === \"defaulted\")\n ? \"defaulted\"\n : zod.def.options.some((o) => o._zod.optin !== undefined)\n ? \"optional\"\n : undefined);\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.options.some((o) => o._zod.optout === \"optional\") ? \"optional\" : undefined);\n util.defineLazyInternal(inst, \"values\", (zod) => {\n if (zod.def.options.every((o) => o._zod.values)) {\n return new Set(zod.def.options.flatMap((option) => Array.from(option._zod.values)));\n }\n return undefined;\n });\n util.defineLazyInternal(inst, \"pattern\", (zod) => {\n if (zod.def.options.every((o) => o._zod.pattern)) {\n const patterns = zod.def.options.map((o) => o._zod.pattern);\n return new RegExp(`^(${patterns.map((p) => util.cleanRegex(p.source)).join(\"|\")})$`);\n }\n return undefined;\n });\n const first = def.options.length === 1 ? def.options[0]._zod.run : null;\n inst._zod.parse = (payload, ctx) => {\n if (first) {\n return first(payload, ctx);\n }\n let async = false;\n const results = [];\n for (const option of def.options) {\n const result = option._zod.run({\n value: payload.value,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n results.push(result);\n async = true;\n }\n else {\n if (result.issues.length === 0)\n return result;\n results.push(result);\n }\n }\n if (!async)\n return handleUnionResults(results, payload, inst, ctx);\n return Promise.all(results).then((results) => {\n return handleUnionResults(results, payload, inst, ctx);\n });\n };\n});\nfunction handleExclusiveUnionResults(results, final, inst, ctx) {\n const matches = [];\n for (let i = 0; i < results.length; i++) {\n if (results[i].issues.length === 0)\n matches.push(i);\n }\n if (matches.length === 1) {\n final.value = results[matches[0]].value;\n return final;\n }\n if (matches.length === 0) {\n // No matches - same as regular union\n final.issues.push({\n code: \"invalid_union\",\n input: final.value,\n inst,\n errors: results.map((result) => result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n });\n }\n else {\n // Multiple matches - exclusive union failure\n final.issues.push({\n code: \"invalid_union\",\n input: final.value,\n inst,\n errors: [],\n inclusive: false,\n matches,\n });\n }\n return final;\n}\nexport const $ZodXor = /*@__PURE__*/ core.$constructor(\"$ZodXor\", (inst, def) => {\n $ZodUnion.init(inst, def);\n def.inclusive = false;\n const first = def.options.length === 1 ? def.options[0]._zod.run : null;\n inst._zod.parse = (payload, ctx) => {\n if (first) {\n return first(payload, ctx);\n }\n let async = false;\n const results = [];\n for (const option of def.options) {\n const result = option._zod.run({\n value: payload.value,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n results.push(result);\n async = true;\n }\n else {\n results.push(result);\n }\n }\n if (!async)\n return handleExclusiveUnionResults(results, payload, inst, ctx);\n return Promise.all(results).then((results) => {\n return handleExclusiveUnionResults(results, payload, inst, ctx);\n });\n };\n});\n/** Returns the option whose discriminator claims `value`, or throws if ambiguous. */\nexport function getDiscriminatedOption(union, value) {\n const internals = union._zod;\n let map = internals.bag.optionsMap;\n if (!map) {\n map = discriminatorMap(internals.def);\n internals.bag.optionsMap = map;\n }\n const option = map.get(value);\n if (option === null)\n throw new Error(`Ambiguous discriminator value \"${String(value)}\"`);\n return option;\n}\nfunction discriminatorMap(def) {\n const map = new Map();\n for (const option of def.options) {\n const values = option._zod.propValues?.[def.discriminator];\n if (!values || values.size === 0)\n throw new Error(`Invalid discriminated union option at index \"${def.options.indexOf(option)}\"`);\n for (const value of values) {\n if (map.has(value)) {\n if (value !== undefined)\n throw new Error(`Duplicate discriminator value \"${String(value)}\"`);\n // keep the collision marked so a later member cannot reclaim it\n map.set(value, null);\n }\n else {\n map.set(value, option);\n }\n }\n }\n return map;\n}\nexport const $ZodDiscriminatedUnion = \n/*@__PURE__*/\ncore.$constructor(\"$ZodDiscriminatedUnion\", (inst, def) => {\n def.inclusive = false;\n $ZodUnion.init(inst, def);\n const _super = inst._zod.parse;\n util.defineLazyInternal(inst, \"propValues\", (zod) => {\n const propValues = {};\n let undefinedCount = 0;\n for (const option of zod.def.options) {\n const pv = option._zod.propValues;\n if (!pv || Object.keys(pv).length === 0)\n throw new Error(`Invalid discriminated union option at index \"${zod.def.options.indexOf(option)}\"`);\n if (pv[zod.def.discriminator]?.has(undefined))\n undefinedCount++;\n for (const [k, v] of Object.entries(pv)) {\n if (!Object.prototype.hasOwnProperty.call(propValues, k)) {\n util.assignProp(propValues, k, new Set());\n }\n for (const val of v) {\n propValues[k].add(val);\n }\n }\n }\n if (!zod.def.unionFallback && undefinedCount > 1)\n propValues[zod.def.discriminator]?.delete(undefined);\n return propValues;\n });\n // Checked now rather than in the lookup map below, so an option that lacks the discriminator fails at the `discriminatedUnion` call instead of on the first object parsed. Options whose shape cannot be enumerated without resolving it — pipes and lazies — are left to the map.\n def.options.forEach((option, i) => {\n const propShape = util.rawShape(option._zod.def);\n if (propShape && !Object.prototype.hasOwnProperty.call(propShape, def.discriminator)) {\n throw new Error(`Invalid discriminated union option at index \"${i}\"`);\n }\n });\n const disc = util.cached(() => discriminatorMap(def));\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!util.isObject(input)) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"object\",\n input,\n inst,\n });\n return payload;\n }\n const value = input?.[def.discriminator];\n const opt = disc.value.get(value);\n // forward metadata cannot choose an encoder for an absent tag\n if (opt && (value !== undefined || ctx.direction !== \"backward\")) {\n return opt._zod.run(payload, ctx);\n }\n // Fall back to union matching when the fast discriminator path fails:\n // - explicitly enabled via unionFallback, or\n // - during backward direction (encode), since codec-based discriminators have different values in forward vs backward directions\n if (def.unionFallback || ctx.direction === \"backward\") {\n return _super(payload, ctx);\n }\n // no matching discriminator\n payload.issues.push({\n code: \"invalid_union\",\n errors: [],\n note: \"No matching discriminator\",\n discriminator: def.discriminator,\n options: Array.from(disc.value.keys()).filter((value) => disc.value.get(value) !== null),\n input,\n path: [def.discriminator],\n inst,\n });\n return payload;\n };\n});\nexport const $ZodIntersection = /*@__PURE__*/ core.$constructor(\"$ZodIntersection\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n const left = def.left._zod.run({ value: input, issues: [] }, ctx);\n const right = def.right._zod.run({ value: input, issues: [] }, ctx);\n const async = left instanceof Promise || right instanceof Promise;\n if (async) {\n return Promise.all([left, right]).then(([left, right]) => {\n return handleIntersectionResults(payload, left, right);\n });\n }\n return handleIntersectionResults(payload, left, right);\n };\n});\nexport function mergeValues(a, b) {\n // const aType = parse.t(a);\n // const bType = parse.t(b);\n if (a === b) {\n return { valid: true, data: a };\n }\n if (a instanceof Date && b instanceof Date && +a === +b) {\n return { valid: true, data: a };\n }\n if (util.isPlainObject(a) && util.isPlainObject(b)) {\n const bKeys = Object.keys(b);\n const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1);\n const newObj = { ...a, ...b };\n if (Object.prototype.hasOwnProperty.call(newObj, \"__proto__\"))\n delete newObj.__proto__;\n for (const key of sharedKeys) {\n if (key === \"__proto__\")\n continue;\n const sharedValue = mergeValues(a[key], b[key]);\n if (!sharedValue.valid) {\n return {\n valid: false,\n mergeErrorPath: [key, ...sharedValue.mergeErrorPath],\n };\n }\n newObj[key] = sharedValue.data;\n }\n return { valid: true, data: newObj };\n }\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length !== b.length) {\n return { valid: false, mergeErrorPath: [] };\n }\n const newArray = [];\n for (let index = 0; index < a.length; index++) {\n const itemA = a[index];\n const itemB = b[index];\n const sharedValue = mergeValues(itemA, itemB);\n if (!sharedValue.valid) {\n return {\n valid: false,\n mergeErrorPath: [index, ...sharedValue.mergeErrorPath],\n };\n }\n newArray.push(sharedValue.data);\n }\n return { valid: true, data: newArray };\n }\n return { valid: false, mergeErrorPath: [] };\n}\nfunction handleIntersectionResults(result, left, right) {\n // Track which side(s) reject each key. A key rejection is reported only when BOTH sides reject it, so a key owned by one branch survives the other's key schema. strictObject reports these as unrecognized_keys; a record with an open key schema reports one invalid_key per key.\n const unrecKeys = new Map();\n let unrecIssue;\n const keyIssues = new Map();\n const collect = (iss, side) => {\n let keys;\n if (iss.code === \"unrecognized_keys\" && !iss.path?.length) {\n unrecIssue ?? (unrecIssue = iss);\n keys = iss.keys;\n }\n else if (iss.code === \"invalid_key\" && iss.origin === \"record\" && iss.path?.length === 1) {\n const k = String(iss.path[0]);\n if (!keyIssues.has(k))\n keyIssues.set(k, iss);\n keys = [k];\n }\n else {\n return false;\n }\n for (const k of keys) {\n if (!unrecKeys.has(k))\n unrecKeys.set(k, {});\n unrecKeys.get(k)[side] = true;\n }\n return true;\n };\n for (const iss of left.issues) {\n if (!collect(iss, \"l\"))\n result.issues.push(iss);\n }\n for (const iss of right.issues) {\n if (!collect(iss, \"r\"))\n result.issues.push(iss);\n }\n // Report only keys rejected by BOTH sides\n const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k);\n if (bothKeys.length) {\n const aggregated = unrecIssue ? bothKeys.filter((k) => unrecIssue.keys.includes(k)) : [];\n if (aggregated.length)\n result.issues.push({ ...unrecIssue, keys: aggregated });\n for (const k of bothKeys) {\n if (!aggregated.includes(k) && keyIssues.has(k))\n result.issues.push(keyIssues.get(k));\n }\n }\n const merged = mergeValues(left.value, right.value);\n if (!merged.valid) {\n if (util.aborted(result))\n return result;\n throw new Error(`Unmergable intersection. Error path: ` + `${JSON.stringify(merged.mergeErrorPath)}`);\n }\n result.value = merged.data;\n return result;\n}\nexport const $ZodTuple = /*@__PURE__*/ core.$constructor(\"$ZodTuple\", (inst, def) => {\n $ZodType.init(inst, def);\n const items = def.items;\n const memo = core.globalConfig.memoizer;\n memo?.attach(inst);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!Array.isArray(input)) {\n payload.issues.push({\n input,\n inst,\n expected: \"tuple\",\n code: \"invalid_type\",\n });\n return payload;\n }\n payload.value = memo ? memo.alloc(inst, payload, [], ctx) : [];\n const proms = [];\n const optinStart = getTupleOptStart(items, \"optin\");\n const optoutStart = getTupleOptStart(items, \"optout\");\n if (!def.rest) {\n if (input.length < optinStart) {\n payload.issues.push({\n code: \"too_small\",\n minimum: optinStart,\n inclusive: true,\n input,\n inst,\n origin: \"array\",\n });\n return payload;\n }\n if (input.length > items.length) {\n payload.issues.push({\n code: \"too_big\",\n maximum: items.length,\n inclusive: true,\n input,\n inst,\n origin: \"array\",\n });\n }\n }\n // Run every item in parallel, collecting results into an indexed array. The post-processing in `handleTupleResults` walks them in order so it can decide whether an absent optional-output error can truncate the tail or must be reported to preserve required output.\n const itemResults = new Array(items.length);\n // only tracked when there is a rest loop to skip\n const abortEarly = def.rest ? ctx?.abortEarly : undefined;\n let itemAborted = false;\n for (let i = 0; i < items.length; i++) {\n const r = items[i]._zod.run({ value: input[i], issues: [] }, ctx);\n if (r instanceof Promise) {\n proms.push(r.then((rr) => {\n itemResults[i] = rr;\n }));\n }\n else {\n itemResults[i] = r;\n if (abortEarly && !itemAborted && r.issues.length)\n itemAborted = util.aborted(r);\n }\n }\n // sound because rest is non-empty exactly when every fixed index is present, the one case handleTupleResults cannot discard an item's issues\n if (def.rest && !itemAborted) {\n let i = items.length - 1;\n const rest = input.slice(items.length);\n let seen = payload.issues.length;\n for (const el of rest) {\n if (abortEarly && payload.issues.length !== seen) {\n if (util.aborted(payload, seen))\n break;\n seen = payload.issues.length;\n }\n i++;\n const result = def.rest._zod.run({ value: el, issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((r) => handleTupleResult(r, payload, i)));\n }\n else {\n handleTupleResult(result, payload, i);\n }\n }\n }\n if (proms.length) {\n return Promise.all(proms).then(() => handleTupleResults(itemResults, payload, items, input, optoutStart));\n }\n return handleTupleResults(itemResults, payload, items, input, optoutStart);\n };\n});\nfunction getTupleOptStart(items, key) {\n for (let i = items.length - 1; i >= 0; i--) {\n // optin is a three-rung ladder so any rung above `undefined` permits an absent slot; optout stays two-valued.\n const omittable = key === \"optin\" ? items[i]._zod.optin !== undefined : items[i]._zod.optout === \"optional\";\n if (!omittable)\n return i + 1;\n }\n return 0;\n}\nfunction handleTupleResult(result, final, index) {\n if (result.issues.length) {\n final.issues.push(...util.prefixIssues(index, result.issues));\n }\n final.value[index] = result.value;\n}\nfunction handleTupleResults(itemResults, final, items, input, optoutStart) {\n // Walk results in order. Mirror $ZodObject's swallow-on-absent-optional rule, but only after `optoutStart`: the first index where the output tuple tail can be absent.\n for (let i = 0; i < items.length; i++) {\n const r = itemResults[i];\n const isPresent = i < input.length;\n // The array analog of `handlePropertyResult`'s absent-key early return: the middle rung permits absence without supplying anything in its place, so the tail truncates here instead of materializing whatever the item made of `undefined`.\n if (!isPresent && i >= optoutStart && items[i]._zod.optin === \"optional\") {\n final.value.length = i;\n break;\n }\n if (r.issues.length) {\n if (!isPresent && i >= optoutStart) {\n final.value.length = i;\n break;\n }\n final.issues.push(...util.prefixIssues(i, r.issues));\n }\n final.value[i] = r.value;\n }\n // Drop trailing slots that produced `undefined` for absent input\n // (the array analog of an absent optional key on an object). The\n // `i >= input.length` floor is critical: an explicit `undefined`\n // *inside* the input must be preserved even when the schema is\n // optional-out (e.g. `z.string().or(z.undefined())` accepting an\n // explicit undefined value).\n for (let i = final.value.length - 1; i >= input.length; i--) {\n if (items[i]._zod.optout === \"optional\" && final.value[i] === undefined) {\n final.value.length = i;\n }\n else {\n break;\n }\n }\n return final;\n}\nexport const $ZodRecord = /*@__PURE__*/ core.$constructor(\"$ZodRecord\", (inst, def) => {\n $ZodType.init(inst, def);\n const memo = core.globalConfig.memoizer;\n memo?.attach(inst);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!util.isPlainObject(input)) {\n payload.issues.push({\n expected: \"record\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n // no guard in either loop below: a record's invalid_key aborts but an enclosing intersection can reconcile it, so a stopped loop hides keys the sibling does not own and the intersection then rejects nothing\n const proms = [];\n const values = def.keyType._zod.values;\n if (values && !def.partial) {\n payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {};\n const recordKeys = new Set();\n for (const key of values) {\n if (typeof key === \"string\" || typeof key === \"number\" || typeof key === \"symbol\") {\n recordKeys.add(typeof key === \"number\" ? key.toString() : key);\n // A declared __proto__ is stripped but is not an unrecognized key.\n if (key === \"__proto__\")\n continue;\n const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n if (keyResult instanceof Promise) {\n throw new Error(\"Async schemas not supported in object keys currently\");\n }\n if (keyResult.issues.length) {\n payload.issues.push({\n code: \"invalid_key\",\n origin: \"record\",\n issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n input: key,\n path: [key],\n inst,\n });\n continue;\n }\n const outKey = keyResult.value;\n if (outKey === \"__proto__\")\n continue;\n const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[outKey] = result.value;\n }));\n }\n else {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[outKey] = result.value;\n }\n }\n }\n let unrecognized;\n for (const key in input) {\n if (!recordKeys.has(key)) {\n if (def.mode === \"loose\") {\n // skip __proto__ so it can't replace the result prototype via the assignment setter on the plain {} we build into\n if (key === \"__proto__\")\n continue;\n payload.value[key] = input[key];\n }\n else {\n unrecognized = unrecognized ?? [];\n unrecognized.push(key);\n }\n }\n }\n if (unrecognized && unrecognized.length > 0) {\n payload.issues.push({\n code: \"unrecognized_keys\",\n input,\n inst,\n keys: unrecognized,\n continue: true,\n });\n }\n }\n else {\n payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {};\n // An enumerable key schema declares which keys the record owns, so a key outside the set is unrecognized. A non-enumerable one (regex, refine) is a constraint every key must satisfy, so a failing key is invalid. Only the former is reconcilable against the other side of an intersection.\n let unrecognized;\n // Reflect.ownKeys for Symbol-key support; filter non-enumerable to match z.object()\n for (const key of Reflect.ownKeys(input)) {\n if (key === \"__proto__\")\n continue;\n if (!Object.prototype.propertyIsEnumerable.call(input, key))\n continue;\n let keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n if (keyResult instanceof Promise) {\n throw new Error(\"Async schemas not supported in object keys currently\");\n }\n // Numeric string fallback: if key is a numeric string and failed, retry with Number(key). This handles z.number(), z.literal([1, 2, 3]), and unions containing numeric literals\n const checkNumericKey = typeof key === \"string\" && regexes.number.test(key) && keyResult.issues.length;\n if (checkNumericKey) {\n const retryResult = def.keyType._zod.run({ value: Number(key), issues: [] }, ctx);\n if (retryResult instanceof Promise) {\n throw new Error(\"Async schemas not supported in object keys currently\");\n }\n if (retryResult.issues.length === 0) {\n keyResult = retryResult;\n }\n }\n if (keyResult.issues.length) {\n if (def.mode === \"loose\") {\n // Pass through unchanged\n payload.value[key] = input[key];\n }\n else if (values) {\n unrecognized = unrecognized ?? [];\n unrecognized.push(key);\n }\n else {\n // Default \"strict\" behavior: error on invalid key\n payload.issues.push({\n code: \"invalid_key\",\n origin: \"record\",\n issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n input: key,\n path: [key],\n inst,\n });\n }\n continue;\n }\n // the guard above tests the raw input key, but the key schema can normalize an ordinary key into __proto__; re-check the key we actually write under\n const outKey = keyResult.value;\n if (outKey === \"__proto__\")\n continue;\n const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[outKey] = result.value;\n }));\n }\n else {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[outKey] = result.value;\n }\n }\n if (unrecognized && unrecognized.length > 0) {\n payload.issues.push({\n code: \"unrecognized_keys\",\n input,\n inst,\n keys: unrecognized,\n continue: true,\n });\n }\n }\n if (proms.length) {\n return Promise.all(proms).then(() => payload);\n }\n return payload;\n };\n});\nexport const $ZodMap = /*@__PURE__*/ core.$constructor(\"$ZodMap\", (inst, def) => {\n $ZodType.init(inst, def);\n const memo = core.globalConfig.memoizer;\n memo?.attach(inst);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!(input instanceof Map)) {\n payload.issues.push({\n expected: \"map\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n const proms = [];\n payload.value = memo ? memo.alloc(inst, payload, new Map(), ctx) : new Map();\n const abortEarly = ctx?.abortEarly;\n let seen = payload.issues.length;\n for (const [key, value] of input) {\n if (abortEarly && payload.issues.length !== seen) {\n if (util.aborted(payload, seen))\n break;\n seen = payload.issues.length;\n }\n const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n const valueResult = def.valueType._zod.run({ value: value, issues: [] }, ctx);\n if (keyResult instanceof Promise || valueResult instanceof Promise) {\n proms.push(Promise.all([keyResult, valueResult]).then(([keyResult, valueResult]) => {\n handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx);\n }));\n }\n else {\n handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx);\n }\n }\n if (proms.length)\n return Promise.all(proms).then(() => payload);\n return payload;\n };\n});\nfunction handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) {\n if (keyResult.issues.length) {\n if (util.propertyKeyTypes.has(typeof key)) {\n final.issues.push(...util.prefixIssues(key, keyResult.issues));\n }\n else {\n final.issues.push({\n code: \"invalid_key\",\n origin: \"map\",\n input,\n inst,\n issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n });\n }\n }\n if (valueResult.issues.length) {\n if (util.propertyKeyTypes.has(typeof key)) {\n final.issues.push(...util.prefixIssues(key, valueResult.issues));\n }\n else {\n final.issues.push({\n origin: \"map\",\n code: \"invalid_element\",\n input,\n inst,\n key: key,\n issues: valueResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n });\n }\n }\n final.value.set(keyResult.value, valueResult.value);\n}\nexport const $ZodSet = /*@__PURE__*/ core.$constructor(\"$ZodSet\", (inst, def) => {\n $ZodType.init(inst, def);\n const memo = core.globalConfig.memoizer;\n memo?.attach(inst);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!(input instanceof Set)) {\n payload.issues.push({\n input,\n inst,\n expected: \"set\",\n code: \"invalid_type\",\n });\n return payload;\n }\n const proms = [];\n payload.value = memo ? memo.alloc(inst, payload, new Set(), ctx) : new Set();\n const abortEarly = ctx?.abortEarly;\n let seen = payload.issues.length;\n for (const item of input) {\n if (abortEarly && payload.issues.length !== seen) {\n if (util.aborted(payload, seen))\n break;\n seen = payload.issues.length;\n }\n const result = def.valueType._zod.run({ value: item, issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => handleSetResult(result, payload)));\n }\n else\n handleSetResult(result, payload);\n }\n if (proms.length)\n return Promise.all(proms).then(() => payload);\n return payload;\n };\n});\nfunction handleSetResult(result, final) {\n if (result.issues.length) {\n final.issues.push(...result.issues);\n }\n final.value.add(result.value);\n}\nexport const $ZodEnum = /*@__PURE__*/ core.$constructor(\"$ZodEnum\", (inst, def) => {\n $ZodType.init(inst, def);\n const values = util.getEnumValues(def.entries);\n const valuesSet = new Set(values);\n inst._zod.values = valuesSet;\n util.defineLazyInternal(inst, \"pattern\", (zod) => {\n const patternValues = util.getEnumValues(zod.def.entries).filter((k) => util.propertyKeyTypes.has(typeof k));\n // unmatchable fallback, RE2-safe: an empty alternation would compile to /^()$/, which matches \"\"\n return new RegExp(patternValues.length ? `^(${patternValues.map((o) => util.escapeRegex(o.toString())).join(\"|\")})$` : \"^[^\\\\s\\\\S]$\");\n });\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (valuesSet.has(input)) {\n return payload;\n }\n payload.issues.push({\n code: \"invalid_value\",\n values,\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodLiteral = /*@__PURE__*/ core.$constructor(\"$ZodLiteral\", (inst, def) => {\n $ZodType.init(inst, def);\n const values = new Set(def.values);\n inst._zod.values = values;\n util.defineLazyInternal(inst, \"pattern\", (zod) => {\n const vals = zod.def.values;\n // unmatchable fallback, RE2-safe: an empty alternation would compile to /^()$/, which matches \"\"\n return new RegExp(vals.length\n ? `^(${vals\n .map((o) => typeof o === \"string\" ? util.escapeRegex(o) : o ? util.escapeRegex(o.toString()) : String(o))\n .join(\"|\")})$`\n : \"^[^\\\\s\\\\S]$\");\n });\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (values.has(input)) {\n return payload;\n }\n payload.issues.push({\n code: \"invalid_value\",\n values: def.values,\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodFile = /*@__PURE__*/ core.$constructor(\"$ZodFile\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n // @ts-ignore\n if (input instanceof File)\n return payload;\n payload.issues.push({\n expected: \"file\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodTransform = /*@__PURE__*/ core.$constructor(\"$ZodTransform\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.optin = \"optional\";\n core.globalConfig.memoizer?.guard(inst);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n throw new core.$ZodEncodeError(inst.constructor.name);\n }\n const _out = def.transform(payload.value, payload);\n if (ctx.async) {\n const output = _out instanceof Promise ? _out : Promise.resolve(_out);\n return output.then((output) => {\n payload.value = output;\n return payload;\n });\n }\n if (_out instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n payload.value = _out;\n return payload;\n };\n});\nfunction handleOptionalResult(payload, result) {\n // A substituting schema that still failed has no usable answer; yield undefined. Its issues are simply dropped: it ran on a payload of its own, so there is no shared array to truncate and nothing of the caller's to lose with it.\n payload.value = result.issues.length ? undefined : result.value;\n return payload;\n}\nexport const $ZodOptional = /*@__PURE__*/ core.$constructor(\"$ZodOptional\", (inst, def) => {\n $ZodType.init(inst, def);\n // .optional() propagates absence rather than substituting for it, so a defaulted inner keeps its rung.\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.innerType._zod.optin === \"defaulted\" ? \"defaulted\" : \"optional\");\n inst._zod.optout = \"optional\";\n util.defineLazyInternal(inst, \"values\", (zod) => {\n const values = zod.def.innerType._zod.values;\n return values ? new Set([...values, undefined]) : undefined;\n });\n util.defineLazyInternal(inst, \"pattern\", (zod) => {\n const pattern = zod.def.innerType._zod.pattern;\n return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)})?$`) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n if (payload.value === undefined) {\n // Only the top rung substitutes a value for absence; everything else leaves it intact, which is what .optional() means.\n if (def.innerType._zod.optin !== \"defaulted\")\n return payload;\n // Its own payload, for the same reason $ZodCatch gets one: a pipe forwards an unrecognized key through the caller's issues array, and this must not read that as the substituting schema failing and drop it.\n const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx);\n if (result instanceof Promise)\n return result.then((result) => handleOptionalResult(payload, result));\n return handleOptionalResult(payload, result);\n }\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodExactOptional = /*@__PURE__*/ core.$constructor(\"$ZodExactOptional\", (inst, def) => {\n // Call parent init - inherits optin/optout = \"optional\"\n $ZodOptional.init(inst, def);\n // Override values/pattern to NOT add undefined\n util.defineLazyInternal(inst, \"values\", (zod) => zod.def.innerType._zod.values);\n util.defineLazyInternal(inst, \"pattern\", (zod) => zod.def.innerType._zod.pattern);\n // Override parse to just delegate (no undefined handling)\n inst._zod.parse = (payload, ctx) => {\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodNullable = /*@__PURE__*/ core.$constructor(\"$ZodNullable\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.innerType._zod.optin);\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.innerType._zod.optout);\n util.defineLazyInternal(inst, \"pattern\", (zod) => {\n const pattern = zod.def.innerType._zod.pattern;\n return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)}|null)$`) : undefined;\n });\n util.defineLazyInternal(inst, \"values\", (zod) => {\n return zod.def.innerType._zod.values ? new Set([...zod.def.innerType._zod.values, null]) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n // Forward direction (decode): allow null to pass through\n if (payload.value === null)\n return payload;\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodDefault = /*@__PURE__*/ core.$constructor(\"$ZodDefault\", (inst, def) => {\n $ZodType.init(inst, def);\n // inst._zod.qin = \"true\";\n inst._zod.optin = \"defaulted\";\n util.defineLazyInternal(inst, \"values\", (zod) => zod.def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n // Forward direction (decode): apply defaults for undefined input\n if (payload.value === undefined) {\n payload.value = def.defaultValue;\n /**\n * $ZodDefault returns the default value immediately in forward direction.\n * It doesn't pass the default value into the validator (\"prefault\"). There's no reason to pass the default value through validation. The validity of the default is enforced by TypeScript statically. Otherwise, it's the responsibility of the user to ensure the default is valid. In the case of pipes with divergent in/out types, you can specify the default on the `in` schema of your ZodPipe to set a \"prefault\" for the pipe. */\n return payload;\n }\n // Forward direction: continue with default handling\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => handleDefaultResult(result, def));\n }\n return handleDefaultResult(result, def);\n };\n});\nfunction handleDefaultResult(payload, def) {\n if (payload.value === undefined) {\n payload.value = def.defaultValue;\n }\n return payload;\n}\nexport const $ZodPrefault = /*@__PURE__*/ core.$constructor(\"$ZodPrefault\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.optin = \"defaulted\";\n util.defineLazyInternal(inst, \"values\", (zod) => zod.def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n // Forward direction (decode): apply prefault for undefined input\n if (payload.value === undefined) {\n payload.value = def.defaultValue;\n }\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodNonOptional = /*@__PURE__*/ core.$constructor(\"$ZodNonOptional\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazyInternal(inst, \"values\", (zod) => {\n const v = zod.def.innerType._zod.values;\n return v ? new Set([...v].filter((x) => x !== undefined)) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => handleNonOptionalResult(result, inst));\n }\n return handleNonOptionalResult(result, inst);\n };\n});\nfunction handleNonOptionalResult(payload, inst) {\n if (!payload.issues.length && payload.value === undefined) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"nonoptional\",\n input: payload.value,\n inst,\n });\n }\n return payload;\n}\nexport const $ZodSuccess = /*@__PURE__*/ core.$constructor(\"$ZodSuccess\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n throw new core.$ZodEncodeError(\"ZodSuccess\");\n }\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => {\n payload.value = result.issues.length === 0;\n return payload;\n });\n }\n payload.value = result.issues.length === 0;\n return payload;\n };\n});\nfunction handleCatchResult(payload, result, def, ctx) {\n if (!result.issues.length) {\n payload.value = result.value;\n // The value carries up, so the flag describing it has to carry with it: a back-edge into a node still being parsed must not be frozen by an enclosing readonly, and its checks belong to the node itself. Guarded so the ordinary case adds no own property.\n if (result.memo)\n payload.memo = true;\n return payload;\n }\n // Spread the inner's own payload, not ours: `value` has to stay the input the catch was handed, and the inner ran on a payload of its own so its issues are already private to this call.\n payload.value = def.catchValue({\n ...result,\n value: payload.value,\n error: {\n issues: result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n },\n input: payload.value,\n });\n return payload;\n}\nexport const $ZodCatch = /*@__PURE__*/ core.$constructor(\"$ZodCatch\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.innerType._zod.optin === \"defaulted\" ? \"defaulted\" : \"optional\");\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.innerType._zod.optout);\n util.defineLazyInternal(inst, \"values\", (zod) => zod.def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n // Forward direction (decode): apply catch logic\n const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx);\n if (result instanceof Promise) {\n return result.then((result) => handleCatchResult(payload, result, def, ctx));\n }\n return handleCatchResult(payload, result, def, ctx);\n };\n});\nexport const $ZodNaN = /*@__PURE__*/ core.$constructor(\"$ZodNaN\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n if (typeof payload.value !== \"number\" || !Number.isNaN(payload.value)) {\n payload.issues.push({\n input: payload.value,\n inst,\n expected: \"nan\",\n code: \"invalid_type\",\n });\n return payload;\n }\n return payload;\n };\n});\nexport const $ZodPipe = /*@__PURE__*/ core.$constructor(\"$ZodPipe\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazyInternal(inst, \"values\", (zod) => zod.def.in._zod.values);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.in._zod.optin);\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.out._zod.optout);\n util.defineLazyInternal(inst, \"propValues\", (zod) => zod.def.in._zod.propValues);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n const right = def.out._zod.run(payload, ctx);\n if (right instanceof Promise) {\n return right.then((right) => handlePipeResult(right, def.in, ctx));\n }\n return handlePipeResult(right, def.in, ctx);\n }\n const left = def.in._zod.run(payload, ctx);\n if (left instanceof Promise) {\n return left.then((left) => handlePipeResult(left, def.out, ctx));\n }\n return handlePipeResult(left, def.out, ctx);\n };\n});\nfunction handlePipeResult(left, next, ctx) {\n // Any issue stops the pipe, so a failing refinement never feeds its transform. An unrecognized key is the exception: it describes the input's extra properties, not the value being piped, and an enclosing intersection may yet reconcile it.\n if (left.issues.some((iss) => iss.code !== \"unrecognized_keys\")) {\n // prevent further checks\n left.aborted = true;\n return left;\n }\n return next._zod.run({ value: left.value, issues: left.issues }, ctx);\n}\nexport const $ZodCodec = /*@__PURE__*/ core.$constructor(\"$ZodCodec\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazyInternal(inst, \"values\", (zod) => zod.def.in._zod.values);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.in._zod.optin);\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.out._zod.optout);\n util.defineLazyInternal(inst, \"propValues\", (zod) => zod.def.in._zod.propValues);\n inst._zod.parse = (payload, ctx) => {\n const direction = ctx.direction || \"forward\";\n if (direction === \"forward\") {\n const left = def.in._zod.run(payload, ctx);\n if (left instanceof Promise) {\n return left.then((left) => handleCodecAResult(left, def, ctx));\n }\n return handleCodecAResult(left, def, ctx);\n }\n else {\n const right = def.out._zod.run(payload, ctx);\n if (right instanceof Promise) {\n return right.then((right) => handleCodecAResult(right, def, ctx));\n }\n return handleCodecAResult(right, def, ctx);\n }\n };\n});\nfunction handleCodecAResult(result, def, ctx) {\n if (result.issues.length) {\n // prevent further checks\n result.aborted = true;\n return result;\n }\n const direction = ctx.direction || \"forward\";\n if (direction === \"forward\") {\n const transformed = def.transform(result.value, result);\n if (transformed instanceof Promise) {\n return transformed.then((value) => handleCodecTxResult(result, value, def.out, ctx));\n }\n return handleCodecTxResult(result, transformed, def.out, ctx);\n }\n else {\n const transformed = def.reverseTransform(result.value, result);\n if (transformed instanceof Promise) {\n return transformed.then((value) => handleCodecTxResult(result, value, def.in, ctx));\n }\n return handleCodecTxResult(result, transformed, def.in, ctx);\n }\n}\nfunction handleCodecTxResult(left, value, nextSchema, ctx) {\n // Check if transform added any issues\n if (left.issues.length) {\n left.aborted = true;\n return left;\n }\n return nextSchema._zod.run({ value, issues: left.issues }, ctx);\n}\nexport const $ZodPreprocess = /*@__PURE__*/ core.$constructor(\"$ZodPreprocess\", (inst, def) => {\n $ZodPipe.init(inst, def);\n});\nexport const $ZodReadonly = /*@__PURE__*/ core.$constructor(\"$ZodReadonly\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazyInternal(inst, \"propValues\", (zod) => zod.def.innerType._zod.propValues);\n util.defineLazyInternal(inst, \"values\", (zod) => zod.def.innerType._zod.values);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.innerType?._zod?.optin);\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.innerType?._zod?.optout);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then(handleReadonlyResult);\n }\n return handleReadonlyResult(result);\n };\n});\nfunction handleReadonlyResult(payload) {\n // A repeat visit hands back a node that is still being built; freezing it here would make the rest of its keys fail to assign.\n if (!payload.memo)\n payload.value = Object.freeze(payload.value);\n return payload;\n}\n// a leaf's pattern source with its own checks folded in: the last pattern-carrying check wins, else length bounds narrow the catch-all, else an integer format narrows the number form. the fold lives here instead of on `_zod.pattern` so a bundle without template literals never pays for it\nfunction leafPattern(schema) {\n const def = schema._zod.def;\n let pattern = def.pattern;\n let isInt = !!def.format?.includes(\"int\");\n let minimum;\n let maximum;\n for (const ch of def.checks ?? []) {\n const d = ch._zod.def;\n if (d.pattern)\n pattern = d.pattern;\n isInt || (isInt = !!d.format?.includes(\"int\"));\n const lo = d.minimum ?? d.length;\n const hi = d.maximum ?? d.length;\n if (lo !== undefined && (minimum === undefined || lo > minimum))\n minimum = lo;\n if (hi !== undefined && (maximum === undefined || hi < maximum))\n maximum = hi;\n }\n if (pattern)\n return pattern.source;\n // an empty range matches nothing at runtime, and `{8,5}` is not a legal quantifier\n if (minimum !== undefined && maximum !== undefined && minimum > maximum)\n return \"(?!)\";\n if (minimum !== undefined || maximum !== undefined)\n return regexes.string({ minimum, maximum }).source;\n const own = schema._zod.pattern;\n return (isInt && own === regexes.number ? regexes.integer : own)?.source;\n}\n// a part's pattern source. a wrapper's pattern embeds its inner pattern's source verbatim, so the folded form is substituted in place without knowing the wrapper's own composition; a union's options are joined the way the union builds its own pattern\nfunction partPattern(schema) {\n const def = schema._zod.def;\n const own = schema._zod.pattern?.source;\n // lazy resolves its inner on the internals, not the def\n const inner = def.innerType ?? schema._zod.innerType;\n if (inner) {\n const before = inner._zod.pattern?.source;\n const after = partPattern(inner);\n if (own && before && after && after !== before) {\n return own.replace(util.cleanRegex(before), () => util.cleanRegex(after));\n }\n return own;\n }\n if (def.options) {\n const sources = def.options.map(partPattern);\n if (sources.every(Boolean))\n return `^(${sources.map((s) => util.cleanRegex(s)).join(\"|\")})$`;\n }\n return leafPattern(schema);\n}\nexport const $ZodTemplateLiteral = /*@__PURE__*/ core.$constructor(\"$ZodTemplateLiteral\", (inst, def) => {\n $ZodType.init(inst, def);\n const regexParts = [];\n for (const part of def.parts) {\n if (typeof part === \"object\" && part !== null) {\n // is Zod schema\n const source = partPattern(part);\n if (!source) {\n throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`);\n }\n regexParts.push(util.cleanRegex(source));\n }\n else if (part === null || util.primitiveTypes.has(typeof part)) {\n regexParts.push(util.escapeRegex(`${part}`));\n }\n else {\n throw new Error(`Invalid template literal part: ${part}`);\n }\n }\n inst._zod.pattern = new RegExp(`^${regexParts.join(\"\")}$`);\n inst._zod.parse = (payload, _ctx) => {\n if (typeof payload.value !== \"string\") {\n payload.issues.push({\n input: payload.value,\n inst,\n expected: \"string\",\n code: \"invalid_type\",\n });\n return payload;\n }\n inst._zod.pattern.lastIndex = 0;\n if (!inst._zod.pattern.test(payload.value)) {\n payload.issues.push({\n input: payload.value,\n inst,\n code: \"invalid_format\",\n format: def.format ?? \"template_literal\",\n pattern: inst._zod.pattern.source,\n });\n return payload;\n }\n return payload;\n };\n});\nexport const $ZodFunction = /*@__PURE__*/ core.$constructor(\"$ZodFunction\", (inst, def) => {\n $ZodType.init(inst, def);\n // Defined, not assigned: the classic prototype exposes `_def` as a getter with no setter.\n Object.defineProperty(inst, \"_def\", { value: def });\n inst._zod.def = def;\n inst.implement = (func) => {\n if (typeof func !== \"function\") {\n throw new Error(\"implement() must be called with a function\");\n }\n // Defined inline so the closure stays anonymous: binding it to a `const` first names it, which costs 256 bytes per implemented function.\n return Object.defineProperty(function (...args) {\n const parsedArgs = inst._def.input ? parse(inst._def.input, args) : args;\n const result = Reflect.apply(func, this, parsedArgs);\n if (inst._def.output) {\n return parse(inst._def.output, result);\n }\n return result;\n }, \"_zod\", { value: inst._zod, enumerable: false });\n };\n inst.implementAsync = (func) => {\n if (typeof func !== \"function\") {\n throw new Error(\"implementAsync() must be called with a function\");\n }\n return Object.defineProperty(async function (...args) {\n const parsedArgs = inst._def.input ? await parseAsync(inst._def.input, args) : args;\n const result = await Reflect.apply(func, this, parsedArgs);\n if (inst._def.output) {\n return await parseAsync(inst._def.output, result);\n }\n return result;\n }, \"_zod\", { value: inst._zod, enumerable: false });\n };\n inst._zod.parse = (payload, _ctx) => {\n if (typeof payload.value !== \"function\") {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"function\",\n input: payload.value,\n inst,\n });\n return payload;\n }\n // Check if output is a promise type to determine if we should use async implementation\n const hasPromiseOutput = inst._def.output && inst._def.output._zod.def.type === \"promise\";\n if (hasPromiseOutput) {\n payload.value = inst.implementAsync(payload.value);\n }\n else {\n payload.value = inst.implement(payload.value);\n }\n return payload;\n };\n inst.input = (...args) => {\n const F = inst.constructor;\n if (Array.isArray(args[0])) {\n return new F({\n type: \"function\",\n input: new $ZodTuple({\n type: \"tuple\",\n items: args[0],\n rest: args[1],\n }),\n output: inst._def.output,\n });\n }\n return new F({\n type: \"function\",\n input: args[0],\n output: inst._def.output,\n });\n };\n inst.output = (output) => {\n const F = inst.constructor;\n return new F({\n type: \"function\",\n input: inst._def.input,\n output,\n });\n };\n return inst;\n});\nexport const $ZodPromise = /*@__PURE__*/ core.$constructor(\"$ZodPromise\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n return Promise.resolve(payload.value).then((inner) => def.innerType._zod.run({ value: inner, issues: [] }, ctx));\n };\n});\nexport const $ZodLazy = /*@__PURE__*/ core.$constructor(\"$ZodLazy\", (inst, def) => {\n $ZodType.init(inst, def);\n // Cache the resolved inner type on the shared `def` so all clones of this lazy (e.g. via `.describe()`/`.meta()`) share the same inner instance, preserving identity for cycle detection on recursive schemas.\n util.defineLazy(inst._zod, \"innerType\", () => {\n const d = def;\n if (!d._cachedInner)\n d._cachedInner = def.getter();\n return d._cachedInner;\n });\n util.defineLazyInternal(inst, \"pattern\", (zod) => zod.innerType?._zod?.pattern);\n util.defineLazyInternal(inst, \"propValues\", (zod) => zod.innerType?._zod?.propValues);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.innerType?._zod?.optin ?? undefined);\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.innerType?._zod?.optout ?? undefined);\n inst._zod.parse = (payload, ctx) => {\n const inner = inst._zod.innerType;\n return inner._zod.run(payload, ctx);\n };\n});\nexport const $ZodCustom = /*@__PURE__*/ core.$constructor(\"$ZodCustom\", (inst, def) => {\n checks.$ZodCheck.init(inst, def);\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _) => {\n return payload;\n };\n inst._zod.check = (payload) => {\n const input = payload.value;\n const r = def.fn(input);\n if (r instanceof Promise) {\n return r.then((r) => handleRefineResult(r, payload, input, inst));\n }\n handleRefineResult(r, payload, input, inst);\n return;\n };\n});\nfunction handleRefineResult(result, payload, input, inst) {\n if (!result) {\n const _iss = {\n code: \"custom\",\n input,\n inst, // incorporates params.error into issue reporting\n path: [...(inst._zod.def.path ?? [])], // incorporates params.error into issue reporting\n continue: !inst._zod.def.abort,\n // params: inst._zod.def.params,\n };\n if (inst._zod.def.params)\n _iss.params = inst._zod.def.params;\n payload.issues.push(util.issue(_iss));\n }\n}\n","import * as util from \"./util.js\";\nexport class $ZodCyclicError extends Error {\n constructor() {\n super(`Cannot parse a reference cycle that closes through a transform`);\n this.name = \"ZodCyclicError\";\n }\n}\n/** Keyed off the context object every schema in one parse call already shares. */\nconst STATE = \"~memo\";\nconst NO_ISSUES = [];\n// a value a cycle can close through\nfunction isRef(value) {\n return value !== null && typeof value === \"object\";\n}\n// Receivers prefix paths in place, so the cache and every hand-out need their own copies.\nfunction cloneIssues(issues) {\n return issues.map((iss) => (iss.path ? { ...iss, path: iss.path.slice() } : { ...iss }));\n}\nconst recursive = /*@__PURE__*/ new WeakMap();\n/** What the walk established, in order of certainty: ordered so the strongest answer among children wins. */\nconst NONE = 0;\nconst ASSUMED = 1;\nconst PROVEN = 2;\n/** Whether this schema's subtree contains a cycle, so one parse can re-enter it. */\nfunction isRecursive(inst, stack, resolve) {\n const cached = recursive.get(inst);\n if (cached !== undefined)\n return cached ? PROVEN : NONE;\n // Relative to the walk in progress, so not cached.\n if (stack.has(inst))\n return PROVEN;\n stack.add(inst);\n let result = NONE;\n const check = (child) => {\n if (result !== PROVEN && child?._zod) {\n const answer = isRecursive(child, stack, resolve);\n if (answer > result)\n result = answer;\n }\n };\n // `Reflect.ownKeys` rather than `Object.keys`, so a cycle through a declared symbol key is still seen\n const shape = (sh, spread) => {\n let answer = NONE;\n for (const key of Reflect.ownKeys(sh)) {\n const desc = Object.getOwnPropertyDescriptor(sh, key);\n // an object resolves its shape by spread, so a key it does not enumerate is never parsed; `z.properties` reads every own key and so keeps them all\n if (spread && !desc.enumerable)\n continue;\n // resolving runs user code, and a factory mints a fresh subtree per read, so an edge the walk can't follow counts as a cycle\n const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve) : NONE;\n if (child > answer)\n answer = child;\n }\n return answer;\n };\n const merge = (answer) => {\n if (answer > result)\n result = answer;\n };\n const def = inst._zod.def;\n const kind = def.type;\n switch (kind) {\n case \"object\": {\n const raw = util.rawShape(def);\n // a def with no raw shape answers `shape` from an accessor of its own, and running that can mint a whole fresh subtree\n merge(raw ? shape(raw, true) : ASSUMED);\n check(def.catchall);\n break;\n }\n case \"array\":\n check(def.element);\n break;\n case \"tuple\":\n for (const el of def.items)\n check(el);\n check(def.rest);\n break;\n case \"record\":\n case \"map\":\n check(def.keyType);\n check(def.valueType);\n break;\n case \"set\":\n check(def.valueType);\n break;\n case \"union\":\n for (const el of def.options)\n check(el);\n break;\n case \"intersection\":\n check(def.left);\n check(def.right);\n break;\n case \"optional\":\n case \"nullable\":\n case \"default\":\n case \"prefault\":\n case \"catch\":\n case \"readonly\":\n case \"nonoptional\":\n case \"promise\":\n case \"success\":\n check(def.innerType);\n break;\n case \"pipe\":\n check(def.in);\n check(def.out);\n break;\n case \"function\":\n check(def.input);\n check(def.output);\n break;\n // `$ZodLazy` caches its inner on the def, so a resolved edge is followed exactly\n case \"lazy\": {\n const inner = def._cachedInner ?? (resolve ? inst._zod.innerType : undefined);\n // walked with resolution off: one hop sees past the deferral, and a lazy that yields only another unresolved lazy is generative, so it stops there\n merge(inner ? isRecursive(inner, stack, false) : ASSUMED);\n break;\n }\n // a leaf by choice: `parts` are regex fragments, not data positions\n case \"template_literal\":\n // leaves\n case \"string\":\n case \"number\":\n case \"int\":\n case \"boolean\":\n case \"bigint\":\n case \"symbol\":\n case \"undefined\":\n case \"null\":\n case \"void\":\n case \"never\":\n case \"any\":\n case \"unknown\":\n case \"date\":\n case \"nan\":\n case \"enum\":\n case \"literal\":\n case \"file\":\n case \"transform\":\n case \"custom\":\n break;\n default: {\n // a new built-in kind becomes a compile error here\n kind;\n // a user-defined kind can still hold children, and only its author knows where, so fall back to scanning the def — skipping accessors, since reading one can run user code\n for (const key in def) {\n const desc = Object.getOwnPropertyDescriptor(def, key);\n if (!desc || desc.get)\n continue;\n const value = desc.value;\n if (!value || typeof value !== \"object\")\n continue;\n if (value._zod)\n check(value);\n else if (Array.isArray(value))\n for (const el of value)\n check(el);\n }\n }\n }\n stack.delete(inst);\n return settle(inst, result);\n}\n/** An assumed answer must not outlive the resolution that settles it, so only a certain one is cached. */\nfunction settle(inst, answer) {\n if (answer !== ASSUMED)\n recursive.set(inst, answer === PROVEN);\n return answer;\n}\n/**\n * Whether one parse can re-enter this schema, i.e. its subtree contains a cycle.\n * Exported for `z.compile`, which refuses to compile such a schema: cycle\n * breaking is driven from here off state keyed on the parse context, and a\n * generated fast path has no context to key on.\n */\nexport function isRecursiveSchema(inst) {\n // z.compile never parses, so nothing would ever resolve a lazy for it; it runs once and already treats a throw here as recursive\n return isRecursive(inst, new Set(), true) !== NONE;\n}\nfunction bucketFor(state, inst) {\n let bucket = state.buckets.get(inst);\n if (!bucket) {\n bucket = new WeakMap();\n state.buckets.set(inst, bucket);\n }\n return bucket;\n}\n// Set immediately before delegating to core and cleared immediately after, so `alloc` registers only for a visit this module is driving.\nlet handoff;\n// Allocated but unfinished entries. `alloc` and the matching pop both happen in the synchronous part of a parse, so they nest even when children are async, and one stack serves every schema.\nconst open = [];\nconst memo = {\n alloc(_inst, payload, empty) {\n const bucket = handoff;\n if (!bucket)\n return empty;\n handoff = undefined;\n const entry = { value: empty, issues: null };\n bucket.set(payload.value, entry);\n open.push(entry);\n return empty;\n },\n guard(inst) {\n var _a;\n (_a = inst._zod).deferred ?? (_a.deferred = []);\n inst._zod.deferred.push(() => {\n const base = inst._zod.parse;\n const wrapped = (payload, ctx) => {\n // The value is a placeholder a back-edge is still waiting on, so the cycle closes through this transform. Its output can't exist in time to bind.\n if (ctx.direction !== \"backward\" && isBackEdge(ctx, payload.value))\n throw new $ZodCyclicError();\n return base(payload, ctx);\n };\n inst._zod.parse = wrapped;\n if (inst._zod.run === base)\n inst._zod.run = wrapped;\n });\n },\n attach(inst) {\n var _a;\n let isRecursiveInst;\n let rechecked = false;\n // a recursive schema is re-entered many times per parse and its bucket never changes\n let lastCtx;\n let lastBucket;\n // Wraps `parse` in a deferred so it sees the container's final parse. Core's own deferred copies `parse` into `run` when there are no checks, and it ran first, so `run` is patched to match; with checks, `run` reads `parse` dynamically.\n (_a = inst._zod).deferred ?? (_a.deferred = []);\n inst._zod.deferred.push(() => {\n const base = inst._zod.parse;\n const wrapped = (payload, ctx) => {\n if (isRecursiveInst === undefined) {\n const walked = isRecursive(inst, new Set(), false);\n if (walked === NONE) {\n // Nothing here can ever fire, so take it back out.\n inst._zod.parse = base;\n if (inst._zod.run === wrapped)\n inst._zod.run = base;\n return base(payload, ctx);\n }\n // this parse resolves the deferred edges on its own path, so ask once more before latching\n if (walked === PROVEN || rechecked)\n isRecursiveInst = true;\n else\n rechecked = true;\n }\n const input = payload.value;\n if (!isRef(input))\n return base(payload, ctx);\n let state = ctx[STATE];\n if (!state) {\n state = { buckets: new WeakMap(), backEdges: undefined };\n ctx[STATE] = state;\n }\n let bucket;\n if (lastCtx === ctx) {\n bucket = lastBucket;\n }\n else {\n bucket = bucketFor(state, inst);\n lastCtx = ctx;\n lastBucket = bucket;\n }\n const hit = bucket.get(input);\n if (hit) {\n payload.value = hit.value;\n if (hit.issues) {\n if (hit.issues.length)\n payload.issues.push(...cloneIssues(hit.issues));\n }\n else {\n // Still being parsed: its own checks cover it, so skip them here.\n payload.memo = true;\n state.backEdges ?? (state.backEdges = new WeakSet());\n state.backEdges.add(hit.value);\n }\n return payload;\n }\n handoff = bucket;\n const depth = open.length;\n const result = base(payload, ctx);\n handoff = undefined;\n // A container that rejected its input outright allocated nothing.\n const entry = open.length > depth ? open.pop() : undefined;\n // Both paths written out so the sync one allocates no closure. It runs once per node, and capturing here cost more than everything else combined.\n if (result instanceof Promise) {\n return result.then((r) => {\n if (entry)\n entry.issues = r.issues.length ? cloneIssues(r.issues) : NO_ISSUES;\n return r;\n });\n }\n if (entry)\n entry.issues = result.issues.length ? cloneIssues(result.issues) : NO_ISSUES;\n return result;\n };\n inst._zod.parse = wrapped;\n if (inst._zod.run === base)\n inst._zod.run = wrapped;\n });\n },\n};\n/** The memoizer that gives containers cycle support. `zod` installs it by default; `zod/mini` opts in with `config({ memoizer: memoizer() })`. */\nexport function memoizer() {\n return memo;\n}\n/** Whether this value is a node a back-edge resolved to before it finished. */\nexport function isBackEdge(ctx, value) {\n const backEdges = ctx[STATE]?.backEdges;\n return backEdges !== undefined && isRef(value) && backEdges.has(value);\n}\n","import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"characters\", verb: \"to have\" },\n file: { unit: \"bytes\", verb: \"to have\" },\n array: { unit: \"items\", verb: \"to have\" },\n set: { unit: \"items\", verb: \"to have\" },\n map: { unit: \"entries\", verb: \"to have\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"input\",\n email: \"email address\",\n url: \"URL\",\n emoji: \"emoji\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"ISO datetime\",\n date: \"ISO date\",\n time: \"ISO time\",\n duration: \"ISO duration\",\n ipv4: \"IPv4 address\",\n ipv6: \"IPv6 address\",\n mac: \"MAC address\",\n cidrv4: \"IPv4 range\",\n cidrv6: \"IPv6 range\",\n base64: \"base64-encoded string\",\n base64url: \"base64url-encoded string\",\n json_string: \"JSON string\",\n e164: \"E.164 number\",\n currency_code: \"currency code\",\n credit_card: \"credit card number\",\n iban: \"IBAN\",\n jwt: \"JWT\",\n template_literal: \"input\",\n };\n // type names: missing keys = do not translate (use raw value via ?? fallback)\n const TypeDictionary = {\n // Compatibility: \"nan\" -> \"NaN\" for display\n nan: \"NaN\",\n // All other type names omitted - they fall back to raw values via ?? operator\n };\n function getTypeName(type, input) {\n if (type === \"number\" && typeof input === \"number\" && !Number.isFinite(input)) {\n return String(input);\n }\n return TypeDictionary[type] ?? type;\n }\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = getTypeName(issue.expected);\n const receivedType = util.parsedType(issue.input);\n const received = getTypeName(receivedType, issue.input);\n return `Invalid input: expected ${expected}, received ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `Invalid input: expected ${util.stringifyPrimitive(issue.values[0])}`;\n return `Invalid option: expected one of ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.exact ? \"exactly \" : issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return `Too big: expected ${issue.origin ?? \"value\"} to have ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"elements\"}`;\n return `Too big: expected ${issue.origin ?? \"value\"} to be ${adj}${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.exact ? \"exactly \" : issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `Too small: expected ${issue.origin} to have ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n }\n return `Too small: expected ${issue.origin} to be ${adj}${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\") {\n return `Invalid string: must start with \"${_issue.prefix}\"`;\n }\n if (_issue.format === \"ends_with\")\n return `Invalid string: must end with \"${_issue.suffix}\"`;\n if (_issue.format === \"includes\")\n return `Invalid string: must include \"${_issue.includes}\"`;\n if (_issue.format === \"regex\")\n return `Invalid string: must match pattern ${_issue.pattern}`;\n return `Invalid ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `Invalid number: must be a multiple of ${issue.divisor}`;\n case \"unrecognized_keys\":\n return `Unrecognized key${issue.keys.length > 1 ? \"s\" : \"\"}: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `Invalid key in ${issue.origin}`;\n case \"invalid_union\":\n if (issue.options && Array.isArray(issue.options) && issue.options.length > 0) {\n const opts = issue.options.map((o) => `'${o}'`).join(\" | \");\n return `Invalid discriminator value. Expected ${opts}`;\n }\n if (issue.inclusive === false) {\n return \"Invalid input: more than one option matched\";\n }\n return \"Invalid input\";\n case \"invalid_element\":\n return `Invalid value in ${issue.origin}`;\n default:\n return `Invalid input`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n","var _a;\nexport const $output = /*@__PURE__*/ Symbol(\"ZodOutput\");\nexport const $input = /*@__PURE__*/ Symbol(\"ZodInput\");\nexport class $ZodRegistry {\n constructor() {\n this._map = new WeakMap();\n this._idmap = new Map();\n }\n add(schema, ..._meta) {\n const meta = _meta[0];\n this._map.set(schema, meta);\n if (meta && typeof meta === \"object\" && \"id\" in meta) {\n this._idmap.set(meta.id, schema);\n }\n return this;\n }\n clear() {\n this._map = new WeakMap();\n this._idmap = new Map();\n return this;\n }\n remove(schema) {\n const meta = this._map.get(schema);\n if (meta && typeof meta === \"object\" && \"id\" in meta) {\n this._idmap.delete(meta.id);\n }\n this._map.delete(schema);\n return this;\n }\n get(schema) {\n // return this._map.get(schema) as any;\n // inherit metadata\n const p = schema._zod.parent;\n if (p) {\n const pm = { ...(this.get(p) ?? {}) };\n delete pm.id; // do not inherit id\n const f = { ...pm, ...this._map.get(schema) };\n return Object.keys(f).length ? f : undefined;\n }\n return this._map.get(schema);\n }\n has(schema) {\n return this._map.has(schema);\n }\n}\n// registries\nexport function registry() {\n return new $ZodRegistry();\n}\n(_a = globalThis).__zod_globalRegistry ?? (_a.__zod_globalRegistry = registry());\nexport const globalRegistry = globalThis.__zod_globalRegistry;\n","import * as checks from \"./checks.js\";\nimport * as registries from \"./registries.js\";\nimport * as schemas from \"./schemas.js\";\nimport * as util from \"./util.js\";\nfunction snapshotChecks(def) {\n if (def.checks)\n def.checks = [...def.checks];\n return def;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _string(Class, params) {\n return new Class(snapshotChecks({ type: \"string\", ...util.normalizeParams(params) }));\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedString(Class, params) {\n return new Class(snapshotChecks({ type: \"string\", coerce: true, ...util.normalizeParams(params) }));\n}\n// @__NO_SIDE_EFFECTS__\nexport function _email(Class, params) {\n return new Class({\n type: \"string\",\n format: \"email\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _guid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"guid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv4(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n version: \"v4\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv6(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n version: \"v6\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv7(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n version: \"v7\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _url(Class, params) {\n return new Class({\n type: \"string\",\n format: \"url\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _emoji(Class, params) {\n return new Class({\n type: \"string\",\n format: \"emoji\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nanoid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"nanoid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link _cuid2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\n// @__NO_SIDE_EFFECTS__\nexport function _cuid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cuid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cuid2(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cuid2\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ulid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ulid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _xid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"xid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ksuid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ksuid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ipv4(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ipv4\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ipv6(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ipv6\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _mac(Class, params) {\n return new Class({\n type: \"string\",\n format: \"mac\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cidrv4(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cidrv4\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cidrv6(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cidrv6\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _base64(Class, params) {\n return new Class({\n type: \"string\",\n format: \"base64\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _base64url(Class, params) {\n return new Class({\n type: \"string\",\n format: \"base64url\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _e164(Class, params) {\n return new Class({\n type: \"string\",\n format: \"e164\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _creditCard(Class, params) {\n return new Class({\n type: \"string\",\n format: \"credit_card\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _iban(Class, params) {\n return new Class({\n type: \"string\",\n format: \"iban\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _jwt(Class, params) {\n return new Class({\n type: \"string\",\n format: \"jwt\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\nexport const TimePrecision = {\n Any: null,\n Minute: -1,\n Second: 0,\n Millisecond: 3,\n Microsecond: 6,\n};\n// @__NO_SIDE_EFFECTS__\nexport function _isoDateTime(Class, params) {\n return new Class({\n type: \"string\",\n format: \"datetime\",\n check: \"string_format\",\n offset: false,\n local: false,\n precision: null,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoDate(Class, params) {\n return new Class({\n type: \"string\",\n format: \"date\",\n check: \"string_format\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoTime(Class, params) {\n return new Class({\n type: \"string\",\n format: \"time\",\n check: \"string_format\",\n precision: null,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoDuration(Class, params) {\n return new Class({\n type: \"string\",\n format: \"duration\",\n check: \"string_format\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _number(Class, params) {\n return new Class(snapshotChecks({ type: \"number\", checks: [], ...util.normalizeParams(params) }));\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedNumber(Class, params) {\n return new Class(snapshotChecks({ type: \"number\", coerce: true, checks: [], ...util.normalizeParams(params) }));\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"safeint\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _float32(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"float32\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _float64(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"float64\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int32(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"int32\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uint32(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"uint32\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _boolean(Class, params) {\n return new Class({\n type: \"boolean\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedBoolean(Class, params) {\n return new Class({\n type: \"boolean\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _bigint(Class, params) {\n return new Class({\n type: \"bigint\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedBigint(Class, params) {\n return new Class({\n type: \"bigint\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int64(Class, params) {\n return new Class({\n type: \"bigint\",\n check: \"bigint_format\",\n abort: false,\n format: \"int64\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uint64(Class, params) {\n return new Class({\n type: \"bigint\",\n check: \"bigint_format\",\n abort: false,\n format: \"uint64\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _symbol(Class, params) {\n return new Class({\n type: \"symbol\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _undefined(Class, params) {\n return new Class({\n type: \"undefined\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _null(Class, params) {\n return new Class({\n type: \"null\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _any(Class) {\n return new Class({\n type: \"any\",\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _unknown(Class) {\n return new Class({\n type: \"unknown\",\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _never(Class, params) {\n return new Class({\n type: \"never\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _void(Class, params) {\n return new Class({\n type: \"void\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _date(Class, params) {\n return new Class({\n type: \"date\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedDate(Class, params) {\n return new Class({\n type: \"date\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nan(Class, params) {\n return new Class({\n type: \"nan\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lt(value, params) {\n return new checks.$ZodCheckLessThan({\n check: \"less_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: false,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lte(value, params) {\n return new checks.$ZodCheckLessThan({\n check: \"less_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: true,\n });\n}\nexport { \n/** @deprecated Use `z.lte()` instead. */\n_lte as _max, };\n// @__NO_SIDE_EFFECTS__\nexport function _gt(value, params) {\n return new checks.$ZodCheckGreaterThan({\n check: \"greater_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: false,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _gte(value, params) {\n return new checks.$ZodCheckGreaterThan({\n check: \"greater_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: true,\n });\n}\nexport { \n/** @deprecated Use `z.gte()` instead. */\n_gte as _min, };\n// @__NO_SIDE_EFFECTS__\nexport function _positive(params) {\n return _gt(0, params);\n}\n// negative\n// @__NO_SIDE_EFFECTS__\nexport function _negative(params) {\n return _lt(0, params);\n}\n// nonpositive\n// @__NO_SIDE_EFFECTS__\nexport function _nonpositive(params) {\n return _lte(0, params);\n}\n// nonnegative\n// @__NO_SIDE_EFFECTS__\nexport function _nonnegative(params) {\n return _gte(0, params);\n}\n// @__NO_SIDE_EFFECTS__\nexport function _multipleOf(value, params) {\n return new checks.$ZodCheckMultipleOf({\n check: \"multiple_of\",\n ...util.normalizeParams(params),\n value,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _maxSize(maximum, params) {\n return new checks.$ZodCheckMaxSize({\n check: \"max_size\",\n ...util.normalizeParams(params),\n maximum,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _minSize(minimum, params) {\n return new checks.$ZodCheckMinSize({\n check: \"min_size\",\n ...util.normalizeParams(params),\n minimum,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _size(size, params) {\n return new checks.$ZodCheckSizeEquals({\n check: \"size_equals\",\n ...util.normalizeParams(params),\n size,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _maxLength(maximum, params) {\n const ch = new checks.$ZodCheckMaxLength({\n check: \"max_length\",\n ...util.normalizeParams(params),\n maximum,\n });\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _minLength(minimum, params) {\n return new checks.$ZodCheckMinLength({\n check: \"min_length\",\n ...util.normalizeParams(params),\n minimum,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _length(length, params) {\n return new checks.$ZodCheckLengthEquals({\n check: \"length_equals\",\n ...util.normalizeParams(params),\n length,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _regex(pattern, params) {\n return new checks.$ZodCheckRegex({\n check: \"string_format\",\n format: \"regex\",\n ...util.normalizeParams(params),\n pattern,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lowercase(params) {\n return new checks.$ZodCheckLowerCase({\n check: \"string_format\",\n format: \"lowercase\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uppercase(params) {\n return new checks.$ZodCheckUpperCase({\n check: \"string_format\",\n format: \"uppercase\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _includes(includes, params) {\n return new checks.$ZodCheckIncludes({\n check: \"string_format\",\n format: \"includes\",\n ...util.normalizeParams(params),\n includes,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _startsWith(prefix, params) {\n return new checks.$ZodCheckStartsWith({\n check: \"string_format\",\n format: \"starts_with\",\n ...util.normalizeParams(params),\n prefix,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _endsWith(suffix, params) {\n return new checks.$ZodCheckEndsWith({\n check: \"string_format\",\n format: \"ends_with\",\n ...util.normalizeParams(params),\n suffix,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _property(property, schema, params) {\n return new checks.$ZodCheckProperty({\n check: \"property\",\n property,\n schema,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _properties(shape, params) {\n return new checks.$ZodCheckProperties({\n check: \"properties\",\n shape,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _mime(types, params) {\n return new checks.$ZodCheckMimeType({\n check: \"mime_type\",\n mime: types,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _overwrite(tx) {\n return new checks.$ZodCheckOverwrite({\n check: \"overwrite\",\n tx,\n });\n}\n// normalize\n// @__NO_SIDE_EFFECTS__\nexport function _normalize(form) {\n return _overwrite((input) => input.normalize(form));\n}\n// trim\n// @__NO_SIDE_EFFECTS__\nexport function _trim() {\n return _overwrite((input) => input.trim());\n}\n// toLowerCase\n// @__NO_SIDE_EFFECTS__\nexport function _toLowerCase() {\n return _overwrite((input) => input.toLowerCase());\n}\n// toUpperCase\n// @__NO_SIDE_EFFECTS__\nexport function _toUpperCase() {\n return _overwrite((input) => input.toUpperCase());\n}\n// slugify\n// @__NO_SIDE_EFFECTS__\nexport function _slugify() {\n return _overwrite((input) => util.slugify(input));\n}\n// @__NO_SIDE_EFFECTS__\nexport function _array(Class, element, params) {\n return new Class({\n type: \"array\",\n element,\n // get element() {\n // return element;\n // },\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _union(Class, options, params) {\n return new Class({\n type: \"union\",\n options,\n ...util.normalizeParams(params),\n });\n}\nexport function _xor(Class, options, params) {\n return new Class({\n type: \"union\",\n options,\n inclusive: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _discriminatedUnion(Class, discriminator, options, params) {\n return new Class({\n type: \"union\",\n options: options,\n discriminator,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _intersection(Class, left, right) {\n return new Class({\n type: \"intersection\",\n left,\n right,\n });\n}\n// export function _tuple(\n// Class: util.SchemaClass<schemas.$ZodTuple>,\n// items: [],\n// params?: string | $ZodTupleParams\n// ): schemas.$ZodTuple<[], null>;\n// @__NO_SIDE_EFFECTS__\nexport function _tuple(Class, items, _paramsOrRest, _params) {\n const hasRest = _paramsOrRest instanceof schemas.$ZodType;\n const params = hasRest ? _params : _paramsOrRest;\n const rest = hasRest ? _paramsOrRest : null;\n return new Class({\n type: \"tuple\",\n items,\n rest,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _record(Class, keyType, valueType, params) {\n return new Class({\n type: \"record\",\n keyType,\n valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _map(Class, keyType, valueType, params) {\n return new Class({\n type: \"map\",\n keyType,\n valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _set(Class, valueType, params) {\n return new Class({\n type: \"set\",\n valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _enum(Class, values, params) {\n const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;\n // if (Array.isArray(values)) {\n // for (const value of values) {\n // entries[value] = value;\n // }\n // } else {\n // Object.assign(entries, values);\n // }\n // const entries: util.EnumLike = {};\n // for (const val of values) {\n // entries[val] = val;\n // }\n return new Class({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\n/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead.\n *\n * ```ts\n * enum Colors { red, green, blue }\n * z.enum(Colors);\n * ```\n */\nexport function _nativeEnum(Class, entries, params) {\n return new Class({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _literal(Class, value, params) {\n return new Class({\n type: \"literal\",\n values: Array.isArray(value) ? value : [value],\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _file(Class, params) {\n return new Class({\n type: \"file\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _transform(Class, fn) {\n return new Class({\n type: \"transform\",\n transform: fn,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _optional(Class, innerType) {\n return new Class({\n type: \"optional\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nullable(Class, innerType) {\n return new Class({\n type: \"nullable\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _default(Class, innerType, defaultValue) {\n return new Class({\n type: \"default\",\n innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nonoptional(Class, innerType, params) {\n return new Class({\n type: \"nonoptional\",\n innerType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _success(Class, innerType) {\n return new Class({\n type: \"success\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _catch(Class, innerType, catchValue) {\n return new Class({\n type: \"catch\",\n innerType,\n catchValue: (typeof catchValue === \"function\" ? catchValue : util.constantCatch(catchValue)),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _pipe(Class, in_, out) {\n return new Class({\n type: \"pipe\",\n in: in_,\n out,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _readonly(Class, innerType) {\n return new Class({\n type: \"readonly\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _templateLiteral(Class, parts, params) {\n return new Class({\n type: \"template_literal\",\n parts,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lazy(Class, getter) {\n return new Class({\n type: \"lazy\",\n getter,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _promise(Class, innerType) {\n return new Class({\n type: \"promise\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _custom(Class, fn, _params) {\n const norm = util.normalizeParams(_params);\n norm.abort ?? (norm.abort = true); // default to abort:false\n const schema = new Class({\n type: \"custom\",\n check: \"custom\",\n fn: fn,\n ...norm,\n });\n return schema;\n}\n// same as _custom but defaults to abort:false\n// @__NO_SIDE_EFFECTS__\nexport function _refine(Class, fn, _params) {\n const schema = new Class({\n type: \"custom\",\n check: \"custom\",\n fn: fn,\n ...util.normalizeParams(_params),\n });\n return schema;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _superRefine(fn, params) {\n const ch = _check((payload) => {\n payload.addIssue = (issue) => {\n if (typeof issue === \"string\") {\n payload.issues.push(util.issue(issue, payload.value, ch._zod.def));\n }\n else {\n // for Zod 3 backwards compatibility\n const _issue = issue;\n if (_issue.fatal)\n _issue.continue = false;\n _issue.code ?? (_issue.code = \"custom\");\n if (!(\"input\" in _issue))\n _issue.input = payload.value;\n _issue.inst ?? (_issue.inst = ch);\n _issue.continue ?? (_issue.continue = !ch._zod.def.abort); // abort is always undefined, so this is always true...\n payload.issues.push(util.issue(_issue));\n }\n };\n return fn(payload.value, payload);\n }, params);\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _check(fn, params) {\n const ch = new checks.$ZodCheck({\n check: \"custom\",\n ...util.normalizeParams(params),\n });\n ch._zod.check = fn;\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function describe(description) {\n const ch = new checks.$ZodCheck({ check: \"describe\" });\n ch._zod.onattach = [\n (inst) => {\n const existing = registries.globalRegistry.get(inst) ?? {};\n registries.globalRegistry.add(inst, { ...existing, description });\n },\n ];\n ch._zod.check = () => { }; // no-op check\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function meta(metadata) {\n const ch = new checks.$ZodCheck({ check: \"meta\" });\n ch._zod.onattach = [\n (inst) => {\n const existing = registries.globalRegistry.get(inst) ?? {};\n registries.globalRegistry.add(inst, { ...existing, ...metadata });\n },\n ];\n ch._zod.check = () => { }; // no-op check\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _stringbool(Classes, _params) {\n const params = util.normalizeParams(_params);\n let truthyArray = params.truthy ?? [\"true\", \"1\", \"yes\", \"on\", \"y\", \"enabled\"];\n let falsyArray = params.falsy ?? [\"false\", \"0\", \"no\", \"off\", \"n\", \"disabled\"];\n if (params.case !== \"sensitive\") {\n truthyArray = truthyArray.map((v) => (typeof v === \"string\" ? v.toLowerCase() : v));\n falsyArray = falsyArray.map((v) => (typeof v === \"string\" ? v.toLowerCase() : v));\n }\n const truthySet = new Set(truthyArray);\n const falsySet = new Set(falsyArray);\n const _Codec = Classes.Codec ?? schemas.$ZodCodec;\n const _Boolean = Classes.Boolean ?? schemas.$ZodBoolean;\n const _String = Classes.String ?? schemas.$ZodString;\n const stringSchema = new _String({ type: \"string\", error: params.error });\n const booleanSchema = new _Boolean({ type: \"boolean\", error: params.error });\n const codec = new _Codec({\n type: \"pipe\",\n in: stringSchema,\n out: booleanSchema,\n transform: ((input, payload) => {\n let data = input;\n if (params.case !== \"sensitive\")\n data = data.toLowerCase();\n if (truthySet.has(data)) {\n return true;\n }\n else if (falsySet.has(data)) {\n return false;\n }\n else {\n payload.issues.push({\n code: \"invalid_value\",\n expected: \"stringbool\",\n values: [...truthySet, ...falsySet],\n input: payload.value,\n inst: codec,\n continue: false,\n });\n return {};\n }\n }),\n reverseTransform: ((input, _payload) => {\n if (input === true) {\n return truthyArray[0] || \"true\";\n }\n else {\n return falsyArray[0] || \"false\";\n }\n }),\n error: params.error,\n });\n codec._zod.bag.truthy = truthyArray;\n codec._zod.bag.falsy = falsyArray;\n codec._zod.bag.case = params.case ?? \"insensitive\";\n return codec;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _stringFormat(Class, format, fnOrRegex, _params = {}) {\n const params = util.normalizeParams(_params);\n const def = {\n check: \"string_format\",\n type: \"string\",\n format,\n fn: typeof fnOrRegex === \"function\" ? fnOrRegex : (val) => fnOrRegex.test(val),\n ...params,\n };\n if (fnOrRegex instanceof RegExp) {\n def.pattern = fnOrRegex;\n }\n const inst = new Class(def);\n return inst;\n}\n","import { globalRegistry } from \"./registries.js\";\nimport { assignProp } from \"./util.js\";\nfunction assignProps(target, ...sources) {\n for (const source of sources) {\n for (const key of Reflect.ownKeys(source)) {\n if (Object.prototype.propertyIsEnumerable.call(source, key)) {\n assignProp(target, key, source[key]);\n }\n }\n }\n return target;\n}\n// function initializeContext<T extends schemas.$ZodType>(inputs: JSONSchemaGeneratorParams<T>): ToJSONSchemaContext<T> {\n// return {\n// processor: inputs.processor,\n// metadataRegistry: inputs.metadata ?? globalRegistry,\n// target: inputs.target ?? \"draft-2020-12\",\n// unrepresentable: inputs.unrepresentable ?? \"throw\",\n// };\n// }\nexport function initializeContext(params) {\n // Normalize target: convert old non-hyphenated versions to hyphenated versions\n let target = params?.target ?? \"draft-2020-12\";\n if (target === \"draft-4\")\n target = \"draft-04\";\n if (target === \"draft-7\")\n target = \"draft-07\";\n return {\n processors: params.processors ?? {},\n metadataRegistry: params?.metadata ?? globalRegistry,\n target,\n unrepresentable: params?.unrepresentable ?? \"throw\",\n override: params?.override ?? (() => { }),\n io: params?.io ?? \"output\",\n counter: 0,\n seen: new Map(),\n sharedDefsExtractedFor: undefined,\n sharedEmitDoneFor: undefined,\n cycles: params?.cycles ?? \"ref\",\n reused: params?.reused ?? \"inline\",\n intersections: [],\n deferred: [],\n external: params?.external ?? undefined,\n };\n}\n/**\n * Applies the `unrepresentable` setting at a site that has no JSON Schema equivalent. Throws\n * `message` unless the setting (or the handler's return value) says otherwise. Returns `true` if a\n * custom JSON Schema was written into `json`, in which case the caller must not write its own.\n */\nexport function handleUnrepresentable(schema, ctx, json, params, message) {\n const result = typeof ctx.unrepresentable === \"function\"\n ? ctx.unrepresentable({ zodSchema: schema, path: params.path, message })\n : ctx.unrepresentable;\n if (result === \"any\")\n return false;\n if (result === undefined || result === \"throw\")\n throw new Error(message);\n Object.assign(json, result);\n return true;\n}\n// never rename this back to `process`: bundler polyfills inject a top-level `const process` that a lexical declaration of the same name collides with (#6397)\nexport function processSchema(schema, ctx, _params = { path: [], schemaPath: [] }) {\n var _a;\n const def = schema._zod.def;\n // check for schema in seens\n const seen = ctx.seen.get(schema);\n if (seen) {\n seen.count++;\n // check if cycle\n const isCycle = _params.schemaPath.includes(schema);\n if (isCycle) {\n seen.cycle = _params.path;\n }\n return seen.schema;\n }\n // initialize\n const result = { schema: {}, count: 1, cycle: undefined, path: _params.path };\n ctx.seen.set(schema, result);\n ctx.sharedDefsExtractedFor = undefined;\n ctx.sharedEmitDoneFor = undefined;\n // custom method overrides default behavior\n const overrideSchema = schema._zod.toJSONSchema?.();\n if (overrideSchema) {\n result.schema = overrideSchema;\n }\n else {\n const params = {\n ..._params,\n schemaPath: [..._params.schemaPath, schema],\n path: _params.path,\n };\n if (schema._zod.processJSONSchema) {\n schema._zod.processJSONSchema(ctx, result.schema, params);\n }\n else {\n const _json = result.schema;\n const processor = ctx.processors[def.type];\n if (!processor) {\n throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`);\n }\n processor(schema, ctx, _json, params);\n }\n const parent = schema._zod.parent;\n if (parent) {\n // Also set ref if processor didn't (for inheritance)\n if (!result.ref)\n result.ref = parent;\n processSchema(parent, ctx, params);\n ctx.seen.get(parent).isParent = true;\n }\n }\n // metadata\n const meta = ctx.metadataRegistry.get(schema);\n if (meta)\n assignProps(result.schema, meta);\n if (ctx.io === \"input\" && isTransforming(schema)) {\n // examples/defaults only apply to output type of pipe\n delete result.schema.examples;\n delete result.schema.default;\n }\n // set prefault as default\n if (ctx.io === \"input\" && \"_prefault\" in result.schema)\n (_a = result.schema).default ?? (_a.default = result.schema._prefault);\n delete result.schema._prefault;\n // pulling fresh from ctx.seen in case it was overwritten\n const _result = ctx.seen.get(schema);\n return _result.schema;\n}\n/** @deprecated Renamed to `processSchema`. An export alias declares no binding, so it is safe to keep. */\nexport { processSchema as process };\n// Escape a reference token for use in a JSON Pointer fragment (RFC 6901): `~` becomes `~0` and `/` becomes `~1`. The `~` replacement must run first.\nfunction encodeJSONPointerSegment(segment) {\n return segment.replace(/~/g, \"~0\").replace(/\\//g, \"~1\");\n}\nexport function extractDefs(ctx, schema\n// params: EmitParams\n) {\n // iterate over seen map;\n const root = ctx.seen.get(schema);\n if (!root)\n throw new Error(\"Unprocessed schema. This is a bug in Zod.\");\n // With `external` set, every registered schema resolves through the external branch of `makeURI`, so the root branch below produces the same ref the external branch would — this pass is identical whichever schema it is called with, and only needs to run once.\n if (ctx.external && ctx.sharedDefsExtractedFor === ctx.external)\n return;\n // Track ids to detect duplicates across different schemas\n const idToSchema = new Map();\n for (const entry of ctx.seen.entries()) {\n const id = ctx.metadataRegistry.get(entry[0])?.id;\n if (id) {\n const existing = idToSchema.get(id);\n if (existing && existing !== entry[0]) {\n throw new Error(`Duplicate schema id \"${id}\" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);\n }\n idToSchema.set(id, entry[0]);\n }\n }\n // returns a ref to the schema defId will be empty if the ref points to an external schema (or #)\n const makeURI = (entry) => {\n // comparing the seen objects because sometimes multiple schemas map to the same seen object. e.g. lazy\n // external is configured\n const defsSegment = ctx.target === \"draft-2020-12\" ? \"$defs\" : \"definitions\";\n if (ctx.external) {\n const externalId = ctx.external.registry.get(entry[0])?.id; // ?? \"__shared\";// `__schema${ctx.counter++}`;\n // check if schema is in the external registry\n const uriGenerator = ctx.external.uri ?? ((id) => id);\n if (externalId) {\n return { ref: uriGenerator(externalId) };\n }\n // otherwise, add to __shared\n const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`;\n entry[1].defId = id; // set defId so it will be reused if needed\n return { defId: id, ref: `${uriGenerator(\"__shared\")}#/${defsSegment}/${encodeJSONPointerSegment(id)}` };\n }\n const uriPrefix = `#`;\n const defUriPrefix = `${uriPrefix}/${defsSegment}/`;\n // an id-less root has nowhere to be extracted to, so it stays inline and self-references as `#`\n if (entry[1] === root && !entry[1].schema.id) {\n return { ref: uriPrefix };\n }\n // self-contained schema\n const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`;\n return { defId, ref: defUriPrefix + encodeJSONPointerSegment(defId) };\n };\n // stored cached version in `def` property remove all properties, set $ref\n const extractToDef = (entry) => {\n // if the schema is already a reference, do not extract it\n if (entry[1].schema.$ref) {\n return;\n }\n const seen = entry[1];\n const { ref, defId } = makeURI(entry);\n seen.def = { ...seen.schema };\n // defId won't be set if the schema is a reference to an external schema or if the schema is the root schema\n if (defId)\n seen.defId = defId;\n // wipe away all properties except $ref\n const schema = seen.schema;\n for (const key in schema) {\n delete schema[key];\n }\n schema.$ref = ref;\n };\n // throw on cycles\n // break cycles\n if (ctx.cycles === \"throw\") {\n for (const entry of ctx.seen.entries()) {\n const seen = entry[1];\n if (seen.cycle) {\n throw new Error(\"Cycle detected: \" +\n `#/${seen.cycle?.join(\"/\")}/<root>` +\n '\\n\\nSet the `cycles` parameter to `\"ref\"` to resolve cyclical schemas with defs.');\n }\n }\n }\n // extract schemas into $defs\n for (const entry of ctx.seen.entries()) {\n const seen = entry[1];\n // convert root schema to # $ref\n if (schema === entry[0]) {\n extractToDef(entry); // this has special handling for the root schema\n continue;\n }\n // extract schemas that are in the external registry\n if (ctx.external) {\n const ext = ctx.external.registry.get(entry[0])?.id;\n if (schema !== entry[0] && ext) {\n extractToDef(entry);\n continue;\n }\n }\n // extract schemas with `id` meta\n const id = ctx.metadataRegistry.get(entry[0])?.id;\n if (id) {\n extractToDef(entry);\n continue;\n }\n // break cycles\n if (seen.cycle) {\n // any\n extractToDef(entry);\n continue;\n }\n // extract reused schemas\n if (seen.count > 1) {\n if (ctx.reused === \"ref\") {\n extractToDef(entry);\n }\n }\n }\n if (ctx.external)\n ctx.sharedDefsExtractedFor = ctx.external;\n}\n/** Rewrites `anyOf: [{type: \"a\"}, {type: \"b\"}]` to `type: [\"a\", \"b\"]`, which every JSON Schema draft treats as equivalent and most consumers render far better for the nullable case. Only branches that are a bare type assertion qualify — anything carrying a constraint, `$ref`, `const` or metadata is left alone. Runs after `flattenRef`, so a branch an override decorated or `$defs` extraction turned into a `$ref` is no longer bare and correctly stays in `anyOf`. `oneOf` is excluded: `integer` and `number` overlap, so \"exactly one\" and \"at least one\" are not the same there. OpenAPI 3.0 is excluded: its `type` must be a single string. */\nfunction compactTypeUnion(schema) {\n const options = schema.anyOf;\n if (!Array.isArray(options) || options.length === 0 || schema.type !== undefined)\n return;\n const types = [];\n for (const option of options) {\n if (!option || typeof option !== \"object\")\n return;\n // A branch that is itself a compactible union folds into this one — nested `anyOf` and a flat `type` array say the same thing. Compacting it first also makes the result independent of the order this pass walks the seen map in.\n compactTypeUnion(option);\n const keys = Object.keys(option);\n if (keys.length !== 1 || keys[0] !== \"type\")\n return;\n const type = option.type;\n for (const member of Array.isArray(type) ? type : [type]) {\n if (typeof member !== \"string\")\n return;\n if (!types.includes(member))\n types.push(member);\n }\n }\n delete schema.anyOf;\n // A `type` array must be non-empty and unique (metaschema); a single member is spelled as a bare string.\n schema.type = types.length === 1 ? types[0] : types;\n}\n/** Keywords `foldIntersection` knows how to combine. Anything else — `$ref`, `patternProperties`,\n * an annotation like `description` — makes a member unfoldable, so a constraint this does not\n * understand leaves the `allOf` alone instead of being silently dropped or misattributed. */\nconst FOLDABLE_KEYS = new Set([\"type\", \"properties\", \"required\", \"additionalProperties\"]);\nconst UNION_KEYS = [\"oneOf\", \"anyOf\"];\n/** A member's constraint on a key it does not declare itself. A `catchall` states one; `false`, an absent `additionalProperties`, and the empty schema a loose object emits state nothing. */\nfunction undeclaredConstraint(member) {\n const extra = member.additionalProperties;\n if (extra === undefined || extra === false || typeof extra !== \"object\" || extra === null)\n return null;\n return Object.keys(extra).length ? extra : null;\n}\n/** Combines object members into the single object they describe together, or returns `null` if any of them carries a keyword outside {@link FOLDABLE_KEYS}. */\nfunction foldObjects(members) {\n const objects = [];\n for (const member of members) {\n // A boolean subschema is legal JSON Schema and carries no keywords to fold.\n if (typeof member !== \"object\" || member.type !== \"object\")\n return null;\n for (const key in member) {\n if (!FOLDABLE_KEYS.has(key))\n return null;\n }\n objects.push(member);\n }\n const properties = {};\n const required = new Set();\n for (const object of objects) {\n for (const key in object.properties) {\n // `in` would report a `__proto__` key as already present via the prototype chain and skip it.\n if (Object.prototype.hasOwnProperty.call(properties, key))\n continue;\n // Every member constrains this key: the ones that declare it say how, and a `catchall` member constrains it too even though it does not name it. The key has to satisfy all of them, which is the same intersection one level down.\n const parts = [];\n for (const other of objects) {\n const part = other.properties?.[key] ?? undeclaredConstraint(other);\n if (part === null || part === undefined)\n continue;\n if (!parts.some((seen) => JSON.stringify(seen) === JSON.stringify(part)))\n parts.push(part);\n }\n const merged = parts.length === 1\n ? parts[0]\n : (foldObjects(parts) ?? { allOf: parts });\n assignProp(properties, key, merged);\n }\n for (const key of object.required ?? [])\n required.add(key);\n }\n const folded = { type: \"object\", properties };\n if (required.size)\n folded.required = [...required];\n // A key no member declares is rejected only when every member rejects it, so the fold is closed only when every member is. Otherwise it carries whatever the `catchall` members demand of such a key.\n if (objects.every((object) => object.additionalProperties === false)) {\n folded.additionalProperties = false;\n }\n else {\n const constraints = [];\n for (const object of objects) {\n const constraint = undeclaredConstraint(object);\n if (constraint && !constraints.some((seen) => JSON.stringify(seen) === JSON.stringify(constraint)))\n constraints.push(constraint);\n }\n if (constraints.length === 1)\n folded.additionalProperties = constraints[0];\n else if (constraints.length > 1)\n folded.additionalProperties = { allOf: constraints };\n }\n return folded;\n}\n/** `additionalProperties` in an `allOf` member sees only that member's own `properties`, so two\n * closed object members reject each other's keys and the schema validates nothing. Zod's parser\n * pools the key sets instead — `handleIntersectionResults` reports a key as unrecognized only when\n * *every* side rejects it — so the emitted schema has to pool them too, and folding the members\n * into one object is the encoding that says so on every target.\n *\n * This runs from `finalize`, after `extractDefs`, which is what keeps it clear of the `$ref`\n * machinery: a member extracted into `$defs` is already a `$ref` by now and declines to fold, so it\n * keeps its reference and its own closedness rather than being inlined as a stale copy. */\nfunction foldIntersection(json) {\n const allOf = json.allOf;\n if (!Array.isArray(allOf) || allOf.length < 2)\n return;\n // An `override` runs before this pass and may have written object keywords onto the intersection itself. Those are deliberate, so decline rather than overwrite them.\n for (const key of FOLDABLE_KEYS)\n if (key in json)\n return;\n // An intersection distributes over a union: `A & (X | Y)` is `(A & X) | (A & Y)`. Only the first union is distributed over; a second one stays among the members every branch folds against, where it fails the object check and declines the whole intersection rather than multiplying out.\n const unions = allOf.filter((m) => UNION_KEYS.some((k) => Array.isArray(m[k])));\n let folded = null;\n if (!unions.length) {\n folded = foldObjects(allOf);\n }\n else {\n const union = unions[0];\n const keyword = UNION_KEYS.find((k) => Array.isArray(union[k]));\n if (Object.keys(union).length !== 1)\n return;\n const rest = allOf.filter((m) => m !== union);\n const branches = union[keyword].map((branch) => foldObjects([...rest, branch]));\n if (branches.some((b) => !b))\n return;\n folded = { [keyword]: branches };\n }\n if (!folded)\n return;\n delete json.allOf;\n assignProps(json, folded);\n}\nexport function finalize(ctx, schema) {\n const root = ctx.seen.get(schema);\n if (!root)\n throw new Error(\"Unprocessed schema. This is a bug in Zod.\");\n // flatten refs - inherit properties from parent schemas\n const flattenRef = (zodSchema) => {\n const seen = ctx.seen.get(zodSchema);\n // already processed\n if (seen.ref === null)\n return;\n const schema = seen.def ?? seen.schema;\n const _cached = { ...schema };\n const ref = seen.ref;\n seen.ref = null; // prevent infinite recursion\n if (ref) {\n flattenRef(ref);\n const refSeen = ctx.seen.get(ref);\n const refSchema = refSeen.schema;\n // merge referenced schema into current\n if (refSchema.$ref && (ctx.target === \"draft-07\" || ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\")) {\n // older drafts can't combine $ref with other properties\n schema.allOf = schema.allOf ?? [];\n schema.allOf.push(refSchema);\n }\n else {\n assignProps(schema, refSchema);\n }\n // restore child's own properties (child wins)\n assignProps(schema, _cached);\n const isParentRef = zodSchema._zod.parent === ref;\n // For parent chain, child is a refinement - remove parent-only properties\n if (isParentRef) {\n for (const key in schema) {\n if (key === \"$ref\" || key === \"allOf\")\n continue;\n if (!(key in _cached)) {\n delete schema[key];\n }\n }\n }\n // When ref was extracted to $defs, remove properties that match the definition\n if (refSchema.$ref && refSeen.def) {\n for (const key in schema) {\n if (key === \"$ref\" || key === \"allOf\")\n continue;\n if (key in refSeen.def && JSON.stringify(schema[key]) === JSON.stringify(refSeen.def[key])) {\n delete schema[key];\n }\n }\n }\n }\n // If parent was extracted (has $ref), propagate $ref to this schema. This handles cases like: readonly().meta({id}).describe() where processor sets ref to innerType but parent should be referenced\n const parent = zodSchema._zod.parent;\n if (parent && parent !== ref) {\n // Ensure parent is processed first so its def has inherited properties\n flattenRef(parent);\n const parentSeen = ctx.seen.get(parent);\n if (parentSeen?.schema.$ref) {\n schema.$ref = parentSeen.schema.$ref;\n // De-duplicate with parent's definition\n if (parentSeen.def) {\n for (const key in schema) {\n if (key === \"$ref\" || key === \"allOf\")\n continue;\n if (key in parentSeen.def && JSON.stringify(schema[key]) === JSON.stringify(parentSeen.def[key])) {\n delete schema[key];\n }\n }\n }\n }\n }\n // execute overrides\n ctx.override({\n zodSchema: zodSchema,\n jsonSchema: schema,\n path: seen.path ?? [],\n });\n };\n // Flattening walks the whole map and clears each `ref` as it goes, so a second call over the same map is a no-op scan. Skip it outright once it has run for a registry conversion.\n if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) {\n for (const entry of [...ctx.seen.entries()].reverse()) {\n flattenRef(entry[0]);\n }\n if (ctx.target !== \"openapi-3.0\") {\n for (const entry of ctx.seen.entries()) {\n compactTypeUnion(entry[1].def ?? entry[1].schema);\n }\n }\n for (const rewrite of ctx.deferred)\n rewrite();\n // After flattening, every member that was extracted is a `$ref`, so the fold sees the final shape. A schema that inherits an intersection — through `z.lazy`, or any `ref` chain — holds the same `allOf` array, so fold by array identity to catch every copy.\n if (ctx.intersections.length) {\n const carriers = new Map();\n for (const seen of ctx.seen.values()) {\n for (const json of [seen.schema, seen.def]) {\n const allOf = json?.allOf;\n if (!Array.isArray(allOf))\n continue;\n const existing = carriers.get(allOf);\n if (existing)\n existing.push(json);\n else\n carriers.set(allOf, [json]);\n }\n }\n for (const allOf of ctx.intersections) {\n for (const json of carriers.get(allOf) ?? [])\n foldIntersection(json);\n }\n }\n }\n const result = {};\n if (ctx.target === \"draft-2020-12\") {\n result.$schema = \"https://json-schema.org/draft/2020-12/schema\";\n }\n else if (ctx.target === \"draft-07\") {\n result.$schema = \"http://json-schema.org/draft-07/schema#\";\n }\n else if (ctx.target === \"draft-04\") {\n result.$schema = \"http://json-schema.org/draft-04/schema#\";\n }\n else if (ctx.target === \"openapi-3.0\") {\n // OpenAPI 3.0 schema objects should not include a $schema property\n }\n else {\n // Arbitrary string values are allowed but won't have a $schema property set\n }\n if (ctx.external?.uri) {\n const id = ctx.external.registry.get(schema)?.id;\n if (!id)\n throw new Error(\"Schema is missing an `id` property\");\n result.$id = ctx.external.uri(id);\n }\n // when the root was extracted into $defs, `root.schema` is the `$ref` wrapper and `root.def` is the body that now lives under $defs\n assignProps(result, root.defId ? root.schema : (root.def ?? root.schema));\n // The `id` in `.meta()` is a Zod-specific registration tag used to extract schemas into $defs — it is not user-facing JSON Schema metadata. Strip it from the output body where it would otherwise leak. The id is preserved implicitly via the $defs key (and via $ref paths).\n const rootMetaId = ctx.metadataRegistry.get(schema)?.id;\n if (rootMetaId !== undefined && result.id === rootMetaId)\n delete result.id;\n // build defs object. With `external`, `defs` is the shared object every schema writes into, so the same entries are reassigned on every call. Without it, `defs` is fresh per call and must be rebuilt.\n const defs = ctx.external?.defs ?? {};\n if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) {\n for (const entry of ctx.seen.entries()) {\n const seen = entry[1];\n if (seen.def && seen.defId) {\n if (seen.def.id === seen.defId)\n delete seen.def.id;\n assignProp(defs, seen.defId, seen.def);\n }\n }\n }\n if (ctx.external)\n ctx.sharedEmitDoneFor = ctx.external;\n // set definitions in result\n if (ctx.external) {\n }\n else {\n if (Object.keys(defs).length > 0) {\n if (ctx.target === \"draft-2020-12\") {\n result.$defs = defs;\n }\n else {\n result.definitions = defs;\n }\n }\n }\n try {\n // this \"finalizes\" this schema and ensures all cycles are removed each call to finalize() is functionally independent though the seen map is shared\n const finalized = JSON.parse(JSON.stringify(result));\n Object.defineProperty(finalized, \"~standard\", {\n value: {\n ...schema[\"~standard\"],\n jsonSchema: {\n input: createStandardJSONSchemaMethod(schema, \"input\", ctx.processors),\n output: createStandardJSONSchemaMethod(schema, \"output\", ctx.processors),\n },\n },\n enumerable: false,\n writable: false,\n });\n return finalized;\n }\n catch (_err) {\n throw new Error(\"Error converting schema to JSON.\");\n }\n}\nfunction isTransforming(_schema, _ctx) {\n const ctx = _ctx ?? { seen: new Set() };\n if (ctx.seen.has(_schema))\n return false;\n ctx.seen.add(_schema);\n const def = _schema._zod.def;\n if (def.type === \"transform\")\n return true;\n if (def.type === \"array\")\n return isTransforming(def.element, ctx);\n if (def.type === \"set\")\n return isTransforming(def.valueType, ctx);\n if (def.type === \"lazy\")\n return isTransforming(def.getter(), ctx);\n if (def.type === \"promise\" ||\n def.type === \"optional\" ||\n def.type === \"nonoptional\" ||\n def.type === \"nullable\" ||\n def.type === \"readonly\" ||\n def.type === \"default\" ||\n def.type === \"prefault\" ||\n def.type === \"catch\") {\n return isTransforming(def.innerType, ctx);\n }\n if (def.type === \"intersection\") {\n return isTransforming(def.left, ctx) || isTransforming(def.right, ctx);\n }\n if (def.type === \"record\" || def.type === \"map\") {\n return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx);\n }\n if (def.type === \"pipe\") {\n if (_schema._zod.traits.has(\"$ZodCodec\"))\n return true;\n return isTransforming(def.in, ctx) || isTransforming(def.out, ctx);\n }\n if (def.type === \"object\") {\n for (const key in def.shape) {\n if (isTransforming(def.shape[key], ctx))\n return true;\n }\n return false;\n }\n if (def.type === \"union\") {\n for (const option of def.options) {\n if (isTransforming(option, ctx))\n return true;\n }\n return false;\n }\n if (def.type === \"tuple\") {\n for (const item of def.items) {\n if (isTransforming(item, ctx))\n return true;\n }\n if (def.rest && isTransforming(def.rest, ctx))\n return true;\n return false;\n }\n return false;\n}\n/**\n * Creates a toJSONSchema method for a schema instance.\n * This encapsulates the logic of initializing context, processing, extracting defs, and finalizing.\n */\nexport const createToJSONSchemaMethod = (schema, processors = {}) => (params) => {\n const ctx = initializeContext({ ...params, processors });\n processSchema(schema, ctx);\n extractDefs(ctx, schema);\n return finalize(ctx, schema);\n};\nexport const createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => {\n const { libraryOptions, target } = params ?? {};\n const ctx = initializeContext({ ...(libraryOptions ?? {}), target, io, processors });\n processSchema(schema, ctx);\n extractDefs(ctx, schema);\n return finalize(ctx, schema);\n};\n","import * as regexes from \"./regexes.js\";\nimport { base64Charset, base64urlCharset } from \"./schemas.js\";\nimport { extractDefs, finalize, handleUnrepresentable, initializeContext, processSchema, } from \"./to-json-schema.js\";\nimport { BIGINT_FORMAT_RANGES, NUMBER_FORMAT_RANGES, assignProp, getEnumValues } from \"./util.js\";\nconst narrowMin = (agg, key, value) => {\n if (agg[key] === undefined || value > agg[key])\n agg[key] = value;\n};\nconst narrowMax = (agg, key, value) => {\n if (agg[key] === undefined || value < agg[key])\n agg[key] = value;\n};\nconst narrowBoth = (agg, value) => {\n narrowMin(agg, \"minimum\", value);\n narrowMax(agg, \"maximum\", value);\n};\nconst addDivisor = (agg, value) => {\n agg.multipleOf ?? (agg.multipleOf = []);\n if (!agg.multipleOf.includes(value))\n agg.multipleOf.push(value);\n};\nconst addPattern = (agg, pattern) => {\n agg.patterns ?? (agg.patterns = new Set());\n agg.patterns.add(pattern);\n};\nconst intersectMime = (agg, mime) => {\n agg.mime = agg.mime ? agg.mime.filter((m) => mime.includes(m)) : [...mime];\n};\n// last-wins, matching the bag's historical write order; the flag keeps an integer format from being lost to a later float one\nconst setFormat = (agg, format) => {\n agg.format = format;\n if (format.includes(\"int\"))\n agg.isInt = true;\n};\nconst minContributor = (agg, def) => narrowMin(agg, \"minimum\", def.minimum);\nconst maxContributor = (agg, def) => narrowMax(agg, \"maximum\", def.maximum);\nconst formatContributor = (ranges) => (agg, def) => {\n setFormat(agg, def.format);\n const [minimum, maximum] = ranges[def.format];\n narrowMin(agg, \"minimum\", minimum);\n narrowMax(agg, \"maximum\", maximum);\n};\nconst contributors = {\n greater_than: (agg, def) => narrowMin(agg, def.inclusive ? \"minimum\" : \"exclusiveMinimum\", def.value),\n less_than: (agg, def) => narrowMax(agg, def.inclusive ? \"maximum\" : \"exclusiveMaximum\", def.value),\n multiple_of: (agg, def) => addDivisor(agg, def.value),\n number_format: formatContributor(NUMBER_FORMAT_RANGES),\n bigint_format: formatContributor(BIGINT_FORMAT_RANGES),\n min_length: minContributor,\n max_length: maxContributor,\n length_equals: (agg, def) => narrowBoth(agg, def.length),\n min_size: minContributor,\n max_size: maxContributor,\n size_equals: (agg, def) => narrowBoth(agg, def.size),\n string_format: (agg, def) => {\n setFormat(agg, def.format);\n if (def.pattern)\n addPattern(agg, def.pattern);\n if (def.format === \"base64\" || def.format === \"base64url\")\n agg.contentEncoding = def.format;\n if (def.local || def.precision === -1)\n agg.laxFormat = true;\n },\n mime_type: (agg, def) => intersectMime(agg, def.mime),\n};\nexport function aggregateChecks(schema) {\n const agg = {};\n const def = schema._zod.def;\n // a format schema is its own first check, same rule as $ZodType init\n const list = schema._zod.traits.has(\"$ZodCheck\")\n ? [schema, ...(def.checks ?? [])]\n : (def.checks ?? []);\n for (const ch of list)\n contributors[ch._zod.def.check]?.(agg, ch._zod.def);\n // reconcile with the bag so third-party onattach contributions still land; first-party residue is never tighter than the fold, so merging it back is idempotent for one and additive for the other\n const bag = schema._zod.bag;\n if (bag.minimum !== undefined)\n narrowMin(agg, \"minimum\", bag.minimum);\n if (bag.exclusiveMinimum !== undefined)\n narrowMin(agg, \"exclusiveMinimum\", bag.exclusiveMinimum);\n if (bag.maximum !== undefined)\n narrowMax(agg, \"maximum\", bag.maximum);\n if (bag.exclusiveMaximum !== undefined)\n narrowMax(agg, \"exclusiveMaximum\", bag.exclusiveMaximum);\n if (bag.multipleOf !== undefined)\n addDivisor(agg, bag.multipleOf);\n if (bag.format !== undefined) {\n agg.format ?? (agg.format = bag.format);\n if (bag.format.includes(\"int\"))\n agg.isInt = true;\n }\n if (bag.mime)\n intersectMime(agg, bag.mime);\n for (const pattern of bag.patterns ?? [])\n addPattern(agg, pattern);\n return agg;\n}\nconst formatMap = {\n guid: \"uuid\",\n url: \"uri\",\n datetime: \"date-time\",\n json_string: \"json-string\",\n regex: \"\", // do not set\n};\n// ==================== SIMPLE TYPE PROCESSORS ====================\n// the runtime patterns are lax so parse paths never overflow the regex stack; the emitted schema swaps in the exact block forms, which zod itself never executes\nconst exactPatterns = new Map([\n [base64Charset, regexes.base64],\n [base64urlCharset, regexes.base64url],\n]);\nconst exactPattern = (p) => exactPatterns.get(p) ?? p;\nexport const stringProcessor = (schema, ctx, _json, _params) => {\n const json = _json;\n json.type = \"string\";\n const { minimum, maximum, format, patterns, contentEncoding, laxFormat } = aggregateChecks(schema);\n if (typeof minimum === \"number\")\n json.minLength = minimum;\n if (typeof maximum === \"number\")\n json.maxLength = maximum;\n // custom pattern overrides format\n if (format) {\n json.format = formatMap[format] ?? format;\n if (json.format === \"\")\n delete json.format; // empty format is not valid\n // `z.iso.time()` is never full-time, and `laxFormat` carries the datetime shapes that also accept what their keyword forbids\n if (format === \"time\" || laxFormat) {\n delete json.format;\n }\n }\n if (contentEncoding)\n json.contentEncoding = contentEncoding;\n if (patterns && patterns.size > 0) {\n const patternList = [...patterns].map(exactPattern);\n if (patternList.length === 1)\n json.pattern = patternList[0].source;\n else if (patternList.length > 1) {\n json.allOf = [\n ...patternList.map((regex) => ({\n ...(ctx.target === \"draft-07\" || ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\"\n ? { type: \"string\" }\n : {}),\n pattern: regex.source,\n })),\n ];\n }\n }\n};\nexport const numberProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const { minimum, maximum, multipleOf, exclusiveMaximum, exclusiveMinimum, isInt } = aggregateChecks(schema);\n json.type = isInt ? \"integer\" : \"number\";\n // when both minimum and exclusiveMinimum exist, pick the more restrictive one\n const exMin = typeof exclusiveMinimum === \"number\" && exclusiveMinimum >= (minimum ?? Number.NEGATIVE_INFINITY);\n const exMax = typeof exclusiveMaximum === \"number\" && exclusiveMaximum <= (maximum ?? Number.POSITIVE_INFINITY);\n const legacy = ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\";\n if (exMin) {\n if (legacy) {\n json.minimum = exclusiveMinimum;\n json.exclusiveMinimum = true;\n }\n else {\n json.exclusiveMinimum = exclusiveMinimum;\n }\n }\n else if (typeof minimum === \"number\") {\n json.minimum = minimum;\n }\n if (exMax) {\n if (legacy) {\n json.maximum = exclusiveMaximum;\n json.exclusiveMaximum = true;\n }\n else {\n json.exclusiveMaximum = exclusiveMaximum;\n }\n }\n else if (typeof maximum === \"number\") {\n json.maximum = maximum;\n }\n if (multipleOf) {\n // JSON Schema requires a divisor strictly greater than zero, and a non-finite one does not survive JSON at all. A negative divisor accepts exactly what its absolute value accepts, so it still maps; zero, NaN and Infinity have no keyword form.\n const divisors = new Set();\n for (const divisor of multipleOf) {\n if (Number.isFinite(divisor) && divisor !== 0)\n divisors.add(Math.abs(divisor));\n else\n handleUnrepresentable(schema, ctx, json, params, `A multipleOf divisor of ${divisor} cannot be represented in JSON Schema`);\n }\n // chained divisors are a conjunction the keyword cannot carry alone, so extras ride an allOf, same as stacked patterns\n const [first, ...rest] = divisors;\n if (first !== undefined)\n json.multipleOf = first;\n if (rest.length)\n json.allOf = [...(json.allOf ?? []), ...rest.map((m) => ({ multipleOf: m }))];\n }\n};\nexport const booleanProcessor = (_schema, _ctx, json, _params) => {\n json.type = \"boolean\";\n};\nexport const bigintProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"BigInt cannot be represented in JSON Schema\");\n};\nexport const symbolProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Symbols cannot be represented in JSON Schema\");\n};\nexport const nullProcessor = (_schema, ctx, json, _params) => {\n if (ctx.target === \"openapi-3.0\") {\n json.type = \"string\";\n json.nullable = true;\n json.enum = [null];\n }\n else {\n json.type = \"null\";\n }\n};\nexport const undefinedProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Undefined cannot be represented in JSON Schema\");\n};\nexport const voidProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Void cannot be represented in JSON Schema\");\n};\nexport const neverProcessor = (_schema, _ctx, json, _params) => {\n json.not = {};\n};\nexport const anyProcessor = (_schema, _ctx, _json, _params) => {\n // empty schema accepts anything\n};\nexport const unknownProcessor = (_schema, _ctx, _json, _params) => {\n // empty schema accepts anything\n};\nexport const dateProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Date cannot be represented in JSON Schema\");\n};\nexport const enumProcessor = (schema, _ctx, json, _params) => {\n const def = schema._zod.def;\n const values = getEnumValues(def.entries);\n // an empty enum accepts nothing, same as z.never()\n if (values.length === 0) {\n json.not = {};\n return;\n }\n // Number enums can have both string and number values\n if (values.every((v) => typeof v === \"number\"))\n json.type = \"number\";\n if (values.every((v) => typeof v === \"string\"))\n json.type = \"string\";\n json.enum = values;\n};\nexport const literalProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n // a literal with no values accepts nothing, same as z.never()\n if (def.values.length === 0) {\n json.not = {};\n return;\n }\n const vals = [];\n for (const val of def.values) {\n if (val === undefined) {\n // a custom schema replaces the whole literal, so there is nothing left to accumulate\n if (handleUnrepresentable(schema, ctx, json, params, \"Literal `undefined` cannot be represented in JSON Schema\"))\n return;\n // otherwise do not add to vals\n }\n else if (typeof val === \"bigint\") {\n if (handleUnrepresentable(schema, ctx, json, params, \"BigInt literals cannot be represented in JSON Schema\"))\n return;\n vals.push(Number(val));\n }\n else {\n vals.push(val);\n }\n }\n if (vals.length === 0) {\n // do nothing (an undefined literal was stripped)\n }\n else if (vals.length === 1) {\n const val = vals[0];\n json.type = val === null ? \"null\" : typeof val;\n if (ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\") {\n json.enum = [val];\n }\n else {\n json.const = val;\n }\n }\n else {\n if (vals.every((v) => typeof v === \"number\"))\n json.type = \"number\";\n if (vals.every((v) => typeof v === \"string\"))\n json.type = \"string\";\n if (vals.every((v) => typeof v === \"boolean\"))\n json.type = \"boolean\";\n if (vals.every((v) => v === null))\n json.type = \"null\";\n json.enum = vals;\n }\n};\nexport const nanProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"NaN cannot be represented in JSON Schema\");\n};\nexport const templateLiteralProcessor = (schema, _ctx, json, _params) => {\n const _json = json;\n const pattern = schema._zod.pattern;\n if (!pattern)\n throw new Error(\"Pattern not found in template literal\");\n _json.type = \"string\";\n _json.pattern = pattern.source;\n};\nexport const fileProcessor = (schema, _ctx, json, _params) => {\n const _json = json;\n _json.type = \"string\";\n _json.format = \"binary\";\n _json.contentEncoding = \"binary\";\n const { minimum, maximum, mime } = aggregateChecks(schema);\n if (minimum !== undefined)\n _json.minLength = minimum;\n if (maximum !== undefined)\n _json.maxLength = maximum;\n if (!mime)\n return;\n // an empty intersection means the mime checks share no value, so nothing passes at runtime; `anyOf` must be non-empty, so the false schema is `not: {}`\n if (mime.length === 0)\n _json.not = {};\n else if (mime.length === 1)\n _json.contentMediaType = mime[0];\n // only contentMediaType differs, so the shared props stay at the root\n else\n _json.anyOf = mime.map((m) => ({ contentMediaType: m }));\n};\nexport const successProcessor = (_schema, _ctx, json, _params) => {\n json.type = \"boolean\";\n};\nexport const customProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Custom types cannot be represented in JSON Schema\");\n};\nexport const functionProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Function types cannot be represented in JSON Schema\");\n};\nexport const transformProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Transforms cannot be represented in JSON Schema\");\n};\nexport const mapProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Map cannot be represented in JSON Schema\");\n};\nexport const setProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Set cannot be represented in JSON Schema\");\n};\n// ==================== COMPOSITE TYPE PROCESSORS ====================\nexport const arrayProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n const { minimum, maximum } = aggregateChecks(schema);\n if (typeof minimum === \"number\")\n json.minItems = minimum;\n if (typeof maximum === \"number\")\n json.maxItems = maximum;\n json.type = \"array\";\n json.items = processSchema(def.element, ctx, {\n ...params,\n path: [...params.path, \"items\"],\n });\n};\n// Transform and catch set `optin = \"optional\"` at runtime so the parser lets them observe an\n// absent key, but their declared input type stays required. An input JSON Schema describes the\n// declared type, so resolve past them to the schema that actually carries the optionality.\n// Used by both `objectProcessor` (for `required`) and `tupleProcessor` (for `minItems`); see\n// wiki/optionality.md, \"The JSON Schema emitter reads the *static* value\".\nfunction inputOptin(schema) {\n const def = schema._zod.def;\n if (def.type === \"pipe\" && def.in._zod.traits.has(\"$ZodTransform\")) {\n return inputOptin(def.out);\n }\n if (def.type === \"catch\") {\n return inputOptin(def.innerType);\n }\n return schema._zod.optin;\n}\nexport const objectProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n const shape = def.shape;\n // dropping it while still emitting `additionalProperties: false` would emit a schema that rejects data this one requires\n const symbolKeys = Object.getOwnPropertySymbols(shape);\n if (symbolKeys.length &&\n handleUnrepresentable(schema, ctx, json, params, \"Symbol keys cannot be represented in JSON Schema\")) {\n return;\n }\n json.type = \"object\";\n json.properties = {};\n for (const key in shape) {\n // assignProp so a __proto__ key becomes an own property instead of hitting the inherited setter on the plain {} we build into\n assignProp(json.properties, key, processSchema(shape[key], ctx, {\n ...params,\n path: [...params.path, \"properties\", key],\n }));\n }\n // required keys\n const requiredKeys = [];\n for (const key of Object.keys(shape)) {\n const field = def.shape[key];\n if (ctx.io === \"input\" ? inputOptin(field) === undefined : field._zod.optout === undefined) {\n requiredKeys.push(key);\n }\n }\n if (requiredKeys.length > 0) {\n json.required = requiredKeys;\n }\n // catchall\n if (def.catchall?._zod.def.type === \"never\") {\n // strict\n json.additionalProperties = false;\n }\n else if (!def.catchall) {\n // regular\n if (ctx.io === \"output\")\n json.additionalProperties = false;\n }\n else if (def.catchall) {\n json.additionalProperties = processSchema(def.catchall, ctx, {\n ...params,\n path: [...params.path, \"additionalProperties\"],\n });\n }\n};\nexport const unionProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n // Exclusive unions (inclusive === false) use oneOf (exactly one match) instead of anyOf (one or more matches). This includes both z.xor() and discriminated unions\n const isExclusive = def.inclusive === false;\n const options = def.options.map((x, i) => processSchema(x, ctx, {\n ...params,\n path: [...params.path, isExclusive ? \"oneOf\" : \"anyOf\", i],\n }));\n if (isExclusive) {\n json.oneOf = options;\n }\n else {\n json.anyOf = options;\n }\n};\nexport const intersectionProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n const a = processSchema(def.left, ctx, {\n ...params,\n path: [...params.path, \"allOf\", 0],\n });\n const b = processSchema(def.right, ctx, {\n ...params,\n path: [...params.path, \"allOf\", 1],\n });\n const isSimpleIntersection = (val) => \"allOf\" in val && Object.keys(val).length === 1;\n const allOf = [\n ...(isSimpleIntersection(a) ? a.allOf : [a]),\n ...(isSimpleIntersection(b) ? b.allOf : [b]),\n ];\n json.allOf = allOf;\n // Recorded innermost first, so a nested intersection has already folded by the time this one is considered. The array is the handle rather than the schema, because a wrapper that inherits this schema shares the same array; `finalize` folds every object holding it. See `foldIntersection`.\n ctx.intersections.push(allOf);\n};\nexport const tupleProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n json.type = \"array\";\n const prefixPath = ctx.target === \"draft-2020-12\" ? \"prefixItems\" : \"items\";\n const restPath = ctx.target === \"draft-2020-12\" ? \"items\" : ctx.target === \"openapi-3.0\" ? \"items\" : \"additionalItems\";\n const prefixItems = def.items.map((x, i) => processSchema(x, ctx, {\n ...params,\n path: [...params.path, prefixPath, i],\n }));\n const rest = def.rest\n ? processSchema(def.rest, ctx, {\n ...params,\n path: [...params.path, restPath, ...(ctx.target === \"openapi-3.0\" ? [def.items.length] : [])],\n })\n : null;\n let minItems = def.items.length;\n while (minItems > 0) {\n const item = def.items[minItems - 1];\n const optional = ctx.io === \"input\" ? inputOptin(item) !== undefined : item._zod.optout === \"optional\";\n if (!optional)\n break;\n minItems--;\n }\n const maxItems = def.items.length;\n const isClosed = !def.rest;\n if (ctx.target === \"draft-2020-12\") {\n json.prefixItems = prefixItems;\n if (isClosed) {\n json.items = false;\n }\n else if (rest) {\n json.items = rest;\n }\n if (minItems > 0)\n json.minItems = minItems;\n if (isClosed)\n json.maxItems = maxItems;\n }\n else if (ctx.target === \"openapi-3.0\") {\n json.items = {\n anyOf: prefixItems,\n };\n if (rest) {\n json.items.anyOf.push(rest);\n }\n if (minItems > 0)\n json.minItems = minItems;\n if (isClosed)\n json.maxItems = maxItems;\n }\n else {\n json.items = prefixItems;\n if (isClosed) {\n json.additionalItems = false;\n }\n else if (rest) {\n json.additionalItems = rest;\n }\n if (minItems > 0)\n json.minItems = minItems;\n if (isClosed)\n json.maxItems = maxItems;\n }\n // explicit user-defined length checks take precedence\n const { minimum, maximum } = aggregateChecks(schema);\n if (typeof minimum === \"number\")\n json.minItems = minimum;\n if (typeof maximum === \"number\")\n json.maxItems = maximum;\n};\n/** JSON object keys are always strings, so a numeric record key schema is re-expressed over the\n * numeric-string form the record parser matches. Deferred to `finalize`, after the flatten: a key\n * behind a wrapper only carries its own `type` before then, and a union key only has its branches.\n *\n * A numeric bound cannot apply to a property name, so `minimum` and its siblings are dropped rather\n * than carried over: keeping them beside `type: \"string\"` reproduces the match-nothing schema this\n * exists to fix. A key that carries one therefore emits wider than the record parses — `z.record(z.number().min(5), V)`\n * accepts `\"3\"` — which is the deliberate trade, since throwing on it would reject an ordinary schema\n * outright. */\nfunction stringifyKeyNames(bySchema, json, visited) {\n // an extracted key that rewrites cannot go on sharing its definition — the string form a key position needs is not the number form every other reference wants — so it inlines. One that does not rewrite keeps the `$ref`.\n if (json.$ref) {\n // a recursive key holds its own reference inside its definition, so a node already on the path is left alone rather than resolved again\n if (visited.has(json))\n return json;\n visited.add(json);\n const def = bySchema.get(json)?.def;\n if (!def)\n return json;\n const inlined = stringifyKeyNames(bySchema, def, visited);\n return inlined === def ? json : inlined;\n }\n for (const keyword of [\"anyOf\", \"oneOf\"]) {\n const branches = json[keyword];\n if (!Array.isArray(branches))\n continue;\n const mapped = branches.map((branch) => stringifyKeyNames(bySchema, branch, visited));\n // rebuilding regardless would detach a key that had nothing to re-express, dropping its `$ref` and leaking the internal `id`\n if (mapped.some((branch, i) => branch !== branches[i]))\n json = { ...json, [keyword]: mapped };\n }\n // a member that already admits a string leaves the key unconstrained, so the node's own type re-expresses only when every member is numeric\n const types = Array.isArray(json.type) ? json.type : [json.type];\n const numericType = !types.includes(\"string\") && types.some((t) => t === \"number\" || t === \"integer\");\n // a heterogeneous key carries no type at all, so its numeric members are caught here instead\n const values = json.enum ?? (json.const !== undefined ? [json.const] : undefined);\n if (!numericType && !values?.some((v) => typeof v === \"number\"))\n return json;\n const { minimum, maximum, exclusiveMinimum, exclusiveMaximum, multipleOf, format, id, ...rest } = json;\n if (rest.enum)\n rest.enum = rest.enum.map((v) => (typeof v === \"number\" ? String(v) : v));\n else if (typeof rest.const === \"number\")\n rest.const = String(rest.const);\n // a heterogeneous key keeps its absent type: the stringified members already say what a key may be\n if (!numericType)\n return rest;\n rest.type = \"string\";\n if (!values)\n rest.pattern = (types.includes(\"number\") ? regexes.number : regexes.integer).source;\n return rest;\n}\n/** Every record of one conversion, so the carriers are found in a single pass rather than once per record. */\nconst pendingRecords = new WeakMap();\nfunction rewriteKeyNames(ctx) {\n // an extracted key is resolved by the object `extractToDef` left in its place, so the map is built once rather than searched per reference. `_zod.toJSONSchema` can hand the same object to two schemas, so the first entry carrying a body wins, as a search would have found it.\n const bySchema = new Map();\n for (const entry of ctx.seen.values()) {\n if (entry.def && !bySchema.has(entry.schema))\n bySchema.set(entry.schema, entry);\n }\n const rewrites = new Map();\n for (const record of pendingRecords.get(ctx) ?? []) {\n const seen = ctx.seen.get(record);\n const names = (seen?.def ?? seen?.schema)?.propertyNames;\n if (!names || names === true || rewrites.has(names))\n continue;\n const rewritten = stringifyKeyNames(bySchema, names, new Set());\n if (rewritten !== names)\n rewrites.set(names, rewritten);\n }\n if (!rewrites.size)\n return;\n // the flatten has already copied each record's own properties onto every wrapper by reference, and an extracted body is another such copy, so every carrier holding a rewritten key is updated together\n for (const entry of ctx.seen.values()) {\n for (const carrier of [entry.schema, entry.def]) {\n const rewritten = carrier && rewrites.get(carrier.propertyNames);\n if (rewritten)\n carrier.propertyNames = rewritten;\n }\n }\n}\nexport const recordProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n json.type = \"object\";\n // For looseRecord with regex patterns, use patternProperties. This correctly represents \"only validate keys matching the pattern\" semantics and composes well with allOf (intersections)\n const keyType = def.keyType;\n const patterns = aggregateChecks(keyType).patterns;\n if (def.mode === \"loose\" && patterns && patterns.size > 0) {\n // Use patternProperties for looseRecord with regex patterns\n const valueSchema = processSchema(def.valueType, ctx, {\n ...params,\n path: [...params.path, \"patternProperties\", \"*\"],\n });\n json.patternProperties = {};\n for (const pattern of patterns) {\n assignProp(json.patternProperties, exactPattern(pattern).source, valueSchema);\n }\n }\n else {\n // Default behavior: use propertyNames + additionalProperties\n if (ctx.target === \"draft-07\" || ctx.target === \"draft-2020-12\") {\n json.propertyNames = processSchema(def.keyType, ctx, {\n ...params,\n path: [...params.path, \"propertyNames\"],\n });\n let pending = pendingRecords.get(ctx);\n if (!pending) {\n pending = [];\n pendingRecords.set(ctx, pending);\n ctx.deferred.push(() => rewriteKeyNames(ctx));\n }\n pending.push(schema);\n }\n json.additionalProperties = processSchema(def.valueType, ctx, {\n ...params,\n path: [...params.path, \"additionalProperties\"],\n });\n }\n // Add required for keys with discrete values (enum, literal, etc.)\n const keyValues = keyType._zod.values;\n // Every key shares one value schema, so an optional-in value makes the whole key set omittable on input. Output keeps them: the exhaustive branch assigns every key, even one whose value came back undefined.\n const omittableOnInput = ctx.io === \"input\" && inputOptin(def.valueType) !== undefined;\n if (keyValues && !def.partial && !omittableOnInput) {\n const validKeyValues = [...keyValues].filter((v) => typeof v === \"string\" || typeof v === \"number\");\n if (validKeyValues.length > 0) {\n json.required = validKeyValues.map(String);\n }\n }\n};\nexport const nullableProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n const inner = processSchema(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n if (ctx.target === \"openapi-3.0\") {\n seen.ref = def.innerType;\n json.nullable = true;\n }\n else {\n json.anyOf = [inner, { type: \"null\" }];\n }\n};\nexport const nonoptionalProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n processSchema(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n};\n/** Round-trips a default value through JSON so the emitted schema is guaranteed to be valid JSON.\n * A BigInt has no reliable encoding, so it goes through `unrepresentable` like any other\n * unrepresentable value. Returns a sentinel when the caller must not write a default of its own. */\nconst UNREPRESENTABLE_DEFAULT = Symbol();\nfunction serializeDefaultValue(value, schema, ctx, json, params) {\n let unrepresentable = false;\n const serialized = JSON.stringify(value, (_, val) => {\n if (typeof val !== \"bigint\")\n return val;\n unrepresentable = true;\n return null;\n });\n if (!unrepresentable)\n return JSON.parse(serialized);\n handleUnrepresentable(schema, ctx, json, params, \"BigInt defaults cannot be represented in JSON Schema\");\n return UNREPRESENTABLE_DEFAULT;\n}\nexport const defaultProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n processSchema(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n const value = serializeDefaultValue(def.defaultValue, schema, ctx, json, params);\n if (value !== UNREPRESENTABLE_DEFAULT)\n json.default = value;\n};\nexport const prefaultProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n processSchema(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n if (ctx.io !== \"input\")\n return;\n const value = serializeDefaultValue(def.defaultValue, schema, ctx, json, params);\n if (value !== UNREPRESENTABLE_DEFAULT)\n json._prefault = value;\n};\nexport const catchProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n processSchema(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n let catchValue;\n try {\n catchValue = def.catchValue(undefined);\n }\n catch {\n handleUnrepresentable(schema, ctx, json, params, \"Dynamic catch values are not supported in JSON Schema\");\n return;\n }\n json.default = catchValue;\n};\nexport const pipeProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n const inIsTransform = def.in._zod.traits.has(\"$ZodTransform\");\n const innerType = ctx.io === \"input\" ? (inIsTransform ? def.out : def.in) : def.out;\n processSchema(innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = innerType;\n};\nexport const readonlyProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n processSchema(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n json.readOnly = true;\n};\nexport const promiseProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n processSchema(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n};\nexport const optionalProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n processSchema(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n};\nexport const lazyProcessor = (schema, ctx, _json, params) => {\n const innerType = schema._zod.innerType;\n processSchema(innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = innerType;\n};\n// ==================== ALL PROCESSORS ====================\nexport const allProcessors = {\n string: stringProcessor,\n number: numberProcessor,\n boolean: booleanProcessor,\n bigint: bigintProcessor,\n symbol: symbolProcessor,\n null: nullProcessor,\n undefined: undefinedProcessor,\n void: voidProcessor,\n never: neverProcessor,\n any: anyProcessor,\n unknown: unknownProcessor,\n date: dateProcessor,\n enum: enumProcessor,\n literal: literalProcessor,\n nan: nanProcessor,\n template_literal: templateLiteralProcessor,\n file: fileProcessor,\n success: successProcessor,\n custom: customProcessor,\n function: functionProcessor,\n transform: transformProcessor,\n map: mapProcessor,\n set: setProcessor,\n array: arrayProcessor,\n object: objectProcessor,\n union: unionProcessor,\n intersection: intersectionProcessor,\n tuple: tupleProcessor,\n record: recordProcessor,\n nullable: nullableProcessor,\n nonoptional: nonoptionalProcessor,\n default: defaultProcessor,\n prefault: prefaultProcessor,\n catch: catchProcessor,\n pipe: pipeProcessor,\n readonly: readonlyProcessor,\n promise: promiseProcessor,\n optional: optionalProcessor,\n lazy: lazyProcessor,\n};\nexport function toJSONSchema(input, params) {\n if (\"_idmap\" in input) {\n // Registry case\n const registry = input;\n const ctx = initializeContext({ ...params, processors: allProcessors });\n const defs = {};\n // First pass: process all schemas to build the seen map\n for (const entry of registry._idmap.entries()) {\n const [_, schema] = entry;\n processSchema(schema, ctx);\n }\n const schemas = {};\n const external = {\n registry,\n uri: params?.uri,\n defs,\n };\n // Update the context with external configuration\n ctx.external = external;\n // Second pass: emit each schema\n for (const entry of registry._idmap.entries()) {\n const [key, schema] = entry;\n extractDefs(ctx, schema);\n assignProp(schemas, key, finalize(ctx, schema));\n }\n if (Object.keys(defs).length > 0) {\n const defsSegment = ctx.target === \"draft-2020-12\" ? \"$defs\" : \"definitions\";\n schemas.__shared = {\n [defsSegment]: defs,\n };\n }\n return { schemas };\n }\n // Single schema case\n const ctx = initializeContext({ ...params, processors: allProcessors });\n processSchema(input, ctx);\n extractDefs(ctx, input);\n return finalize(ctx, input);\n}\n","import * as core from \"../core/index.js\";\nimport { $ZodError } from \"../core/index.js\";\nimport * as util from \"../core/util.js\";\n/* Prototypes that already carry the lazy helper methods. Seeded with the\n * intrinsics so that `init` on a foreign object — it accepts any object —\n * can never install an accessor onto a prototype we do not own. */\nconst _installedErrorProtos = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]);\n/* Helper methods live as non-enumerable lazy getters on the shared\n * prototype instead of own properties on every instance. On first\n * access the getter allocates the per-instance closure and caches it\n * as a non-enumerable own property, so detached usage still works and\n * the allocation only happens for methods actually touched. */\nfunction _lazyMethod(proto, key, make) {\n Object.defineProperty(proto, key, {\n configurable: true,\n enumerable: false,\n get() {\n const value = make(this);\n Object.defineProperty(this, key, { value, configurable: true, writable: true });\n return value;\n },\n set(value) {\n Object.defineProperty(this, key, { value, configurable: true, writable: true });\n },\n });\n}\nconst initializer = (inst, issues) => {\n $ZodError.init(inst, issues);\n inst.name = \"ZodError\";\n const proto = Object.getPrototypeOf(inst);\n if (_installedErrorProtos.has(proto))\n return;\n _installedErrorProtos.add(proto);\n _lazyMethod(proto, \"format\", (self) => (mapper) => core.formatError(self, mapper));\n _lazyMethod(proto, \"flatten\", (self) => (mapper) => core.flattenError(self, mapper));\n _lazyMethod(proto, \"addIssue\", (self) => (issue) => {\n self.issues.push(issue);\n self.message = JSON.stringify(self.issues, util.jsonStringifyReplacer, 2);\n });\n _lazyMethod(proto, \"addIssues\", (self) => (issues) => {\n self.issues.push(...issues);\n self.message = JSON.stringify(self.issues, util.jsonStringifyReplacer, 2);\n });\n Object.defineProperty(proto, \"isEmpty\", {\n configurable: true,\n enumerable: false,\n get() {\n return this.issues.length === 0;\n },\n });\n};\nexport const ZodError = /*@__PURE__*/ core.$constructor(\"ZodError\", initializer);\nexport const ZodRealError = /*@__PURE__*/ core.$constructor(\"ZodError\", initializer, undefined, {\n Parent: Error,\n});\n// /** @deprecated Use `z.core.$ZodErrorMapCtx` instead. */\n// export type ErrorMapCtx = core.$ZodErrorMapCtx;\n","import * as core from \"../core/index.js\";\nimport { ZodRealError } from \"./errors.js\";\nexport const parse = /* @__PURE__ */ core._parse(ZodRealError);\nexport const parseAsync = /* @__PURE__ */ core._parseAsync(ZodRealError);\nexport const safeParse = /* @__PURE__ */ core._safeParse(ZodRealError);\nexport const safeParseAsync = /* @__PURE__ */ core._safeParseAsync(ZodRealError);\nexport { validate, validateAsync } from \"../core/index.js\";\n// Codec functions\nexport const encode = /* @__PURE__ */ core._encode(ZodRealError);\nexport const decode = /* @__PURE__ */ core._decode(ZodRealError);\nexport const encodeAsync = /* @__PURE__ */ core._encodeAsync(ZodRealError);\nexport const decodeAsync = /* @__PURE__ */ core._decodeAsync(ZodRealError);\nexport const safeEncode = /* @__PURE__ */ core._safeEncode(ZodRealError);\nexport const safeDecode = /* @__PURE__ */ core._safeDecode(ZodRealError);\nexport const safeEncodeAsync = /* @__PURE__ */ core._safeEncodeAsync(ZodRealError);\nexport const safeDecodeAsync = /* @__PURE__ */ core._safeDecodeAsync(ZodRealError);\n","import * as core from \"../core/index.js\";\nimport { util } from \"../core/index.js\";\nimport * as processors from \"../core/json-schema-processors.js\";\nimport * as regexes from \"../core/regexes.js\";\nimport { createStandardJSONSchemaMethod, createToJSONSchemaMethod } from \"../core/to-json-schema.js\";\nimport en from \"../locales/en.js\";\nimport * as checks from \"./checks.js\";\nimport * as parse from \"./parse.js\";\n// Register English as the default locale on first ZodType construction. Hooked into the `ZodType` `$constructor` (rather than a top-level `config(en())` in `external.ts`) so bundlers honoring `sideEffects: false` can't tree-shake it out — see #5953, #5725. An explicit `z.config(z.locales.xx())` call wins regardless of order, since this only sets the default when none is present.\nfunction _ensureDefaultLocale() {\n if (!core.globalConfig.localeError)\n core.config(en());\n}\n// the default memoizer is read by the core container init, which runs before `ZodType.init`, so each container calls this first\nfunction _ensureDefaultMemoizer() {\n if (!core.globalConfig.memoizer)\n core.config({ memoizer: core.memoizer() });\n}\nexport const ZodType = /*@__PURE__*/ core.$constructor(\"ZodType\", (inst, def) => {\n _ensureDefaultLocale();\n core.$ZodType.init(inst, def);\n inst.def = def;\n inst.type = def.type;\n return inst;\n}, {\n check(...chks) {\n const def = this.def;\n return this.clone(util.mergeDefs(def, {\n checks: [\n ...(def.checks ?? []),\n ...chks.map((ch) => typeof ch === \"function\" ? { _zod: { check: ch, def: { check: \"custom\" }, onattach: [] } } : ch),\n ],\n }), { parent: true });\n },\n with(...chks) {\n return this.check(...chks);\n },\n clone(def, params) {\n return core.clone(this, def, params);\n },\n brand() {\n return this;\n },\n register(reg, meta) {\n reg.add(this, meta);\n return this;\n },\n refine(check, params) {\n return this.check(refine(check, params));\n },\n superRefine(refinement, params) {\n return this.check(superRefine(refinement, params));\n },\n overwrite(fn) {\n return this.check(checks.overwrite(fn));\n },\n optional() {\n return optional(this);\n },\n exactOptional() {\n return exactOptional(this);\n },\n nullable() {\n return nullable(this);\n },\n nullish() {\n return optional(nullable(this));\n },\n nonoptional(params) {\n return nonoptional(this, params);\n },\n array() {\n return array(this);\n },\n or(arg) {\n return union([this, arg]);\n },\n and(arg) {\n return intersection(this, arg);\n },\n transform(tx) {\n return pipe(this, transform(tx));\n },\n default(d) {\n return _default(this, d);\n },\n prefault(d) {\n return prefault(this, d);\n },\n catch(params) {\n return _catch(this, params);\n },\n pipe(target) {\n return pipe(this, target);\n },\n readonly() {\n return readonly(this);\n },\n describe(description) {\n const cl = this.clone();\n core.globalRegistry.add(cl, { description });\n return cl;\n },\n meta(...args) {\n // overloaded: meta() returns the registered metadata, meta(data) returns a clone with `data` registered. The mapped type picks up the second overload, so we accept variadic any-args and return `any` to satisfy both at runtime.\n if (args.length === 0)\n return core.globalRegistry.get(this);\n const cl = this.clone();\n core.globalRegistry.add(cl, args[0]);\n return cl;\n },\n isOptional() {\n return this.safeParse(undefined).success;\n },\n isNullable() {\n return this.safeParse(null).success;\n },\n apply(fn, ...args) {\n return args.length === 0 ? fn(this) : fn(this, ...args);\n },\n // Overrides core's `~standard` to add `jsonSchema`. Must stay a prototype entry: redefining it per instance demotes instances to dictionary mode.\n get \"~standard\"() {\n return util.hide(this, \"~standard\", {\n ...core.standardProps(this),\n jsonSchema: {\n input: createStandardJSONSchemaMethod(this, \"input\"),\n output: createStandardJSONSchemaMethod(this, \"output\"),\n },\n });\n },\n set \"~standard\"(value) {\n util.own(this, \"~standard\", value);\n },\n parse: function _parse(data, params) {\n return parse.parse(this, data, params, { callee: _parse });\n },\n parseAsync: async function _parseAsync(data, params) {\n return await parse.parseAsync(this, data, params, { callee: _parseAsync });\n },\n safeParse(data, params) {\n return parse.safeParse(this, data, params);\n },\n async safeParseAsync(data, params) {\n return parse.safeParseAsync(this, data, params);\n },\n // `spa` is an alias: same function object as `safeParseAsync`, as before.\n get spa() {\n return this?.safeParseAsync;\n },\n set spa(value) {\n util.own(this, \"spa\", value);\n },\n validate(data, params) {\n return parse.validate(this, data, params);\n },\n validateAsync(data, params) {\n return parse.validateAsync(this, data, params);\n },\n encode: function _encode(data, params) {\n return parse.encode(this, data, params, { callee: _encode });\n },\n decode: function _decode(data, params) {\n return parse.decode(this, data, params, { callee: _decode });\n },\n encodeAsync: async function _encodeAsync(data, params) {\n return await parse.encodeAsync(this, data, params, { callee: _encodeAsync });\n },\n decodeAsync: async function _decodeAsync(data, params) {\n return await parse.decodeAsync(this, data, params, { callee: _decodeAsync });\n },\n safeEncode(data, params) {\n return parse.safeEncode(this, data, params);\n },\n safeDecode(data, params) {\n return parse.safeDecode(this, data, params);\n },\n async safeEncodeAsync(data, params) {\n return parse.safeEncodeAsync(this, data, params);\n },\n async safeDecodeAsync(data, params) {\n return parse.safeDecodeAsync(this, data, params);\n },\n toJSONSchema(params) {\n return createToJSONSchemaMethod(this, {})(params);\n },\n // Reads through to the registry on every access, so it must not cache.\n get description() {\n return core.globalRegistry.get(this)?.description;\n },\n // No setter: `schema._def = x` throws, as it did when `_def` was a non-writable own property.\n get _def() {\n return this._zod.def;\n },\n});\n/** @internal */\nexport const _ZodString = /*@__PURE__*/ core.$constructor(\"_ZodString\", (inst, def) => {\n core.$ZodString.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.stringProcessor(inst, ctx, json, params);\n}, \n/*@__PURE__*/ util.derived({\n format: (inst) => processors.aggregateChecks(inst).format ?? null,\n minLength: (inst) => processors.aggregateChecks(inst).minimum ?? null,\n maxLength: (inst) => processors.aggregateChecks(inst).maximum ?? null,\n}, {\n regex(...args) {\n return this.check(checks.regex(...args));\n },\n includes(...args) {\n return this.check(checks.includes(...args));\n },\n startsWith(...args) {\n return this.check(checks.startsWith(...args));\n },\n endsWith(...args) {\n return this.check(checks.endsWith(...args));\n },\n min(...args) {\n return this.check(checks.minLength(...args));\n },\n max(...args) {\n return this.check(checks.maxLength(...args));\n },\n length(...args) {\n return this.check(checks.length(...args));\n },\n nonempty(...args) {\n return this.check(checks.minLength(1, ...args));\n },\n lowercase(params) {\n return this.check(checks.lowercase(params));\n },\n uppercase(params) {\n return this.check(checks.uppercase(params));\n },\n trim() {\n return this.check(checks.trim());\n },\n normalize(...args) {\n return this.check(checks.normalize(...args));\n },\n toLowerCase() {\n return this.check(checks.toLowerCase());\n },\n toUpperCase() {\n return this.check(checks.toUpperCase());\n },\n slugify() {\n return this.check(checks.slugify());\n },\n}));\nexport const ZodString = /*@__PURE__*/ core.$constructor(\"ZodString\", (inst, def) => {\n core.$ZodString.init(inst, def);\n _ZodString.init(inst, def);\n}, {\n email(params) {\n return this.check(core._email(ZodEmail, params));\n },\n url(params) {\n return this.check(core._url(ZodURL, params));\n },\n jwt(params) {\n return this.check(core._jwt(ZodJWT, params));\n },\n emoji(params) {\n return this.check(core._emoji(ZodEmoji, params));\n },\n guid(params) {\n return this.check(core._guid(ZodGUID, params));\n },\n uuid(params) {\n return this.check(core._uuid(ZodUUID, params));\n },\n uuidv4(params) {\n return this.check(core._uuidv4(ZodUUID, params));\n },\n uuidv6(params) {\n return this.check(core._uuidv6(ZodUUID, params));\n },\n uuidv7(params) {\n return this.check(core._uuidv7(ZodUUID, params));\n },\n nanoid(params) {\n return this.check(core._nanoid(ZodNanoID, params));\n },\n cuid(params) {\n return this.check(core._cuid(ZodCUID, params));\n },\n cuid2(params) {\n return this.check(core._cuid2(ZodCUID2, params));\n },\n ulid(params) {\n return this.check(core._ulid(ZodULID, params));\n },\n base64(params) {\n return this.check(core._base64(ZodBase64, params));\n },\n base64url(params) {\n return this.check(core._base64url(ZodBase64URL, params));\n },\n xid(params) {\n return this.check(core._xid(ZodXID, params));\n },\n ksuid(params) {\n return this.check(core._ksuid(ZodKSUID, params));\n },\n ipv4(params) {\n return this.check(core._ipv4(ZodIPv4, params));\n },\n ipv6(params) {\n return this.check(core._ipv6(ZodIPv6, params));\n },\n cidrv4(params) {\n return this.check(core._cidrv4(ZodCIDRv4, params));\n },\n cidrv6(params) {\n return this.check(core._cidrv6(ZodCIDRv6, params));\n },\n e164(params) {\n return this.check(core._e164(ZodE164, params));\n },\n datetime(params) {\n return this.check(core._isoDateTime(ZodISODateTime, params));\n },\n date(params) {\n return this.check(core._isoDate(ZodISODate, params));\n },\n time(params) {\n return this.check(core._isoTime(ZodISOTime, params));\n },\n duration(params) {\n return this.check(core._isoDuration(ZodISODuration, params));\n },\n});\nexport function string(params) {\n return core._string(ZodString, params);\n}\nexport const ZodStringFormat = /*@__PURE__*/ core.$constructor(\"ZodStringFormat\", (inst, def) => {\n core.$ZodStringFormat.init(inst, def);\n _ZodString.init(inst, def);\n});\nexport const ZodISODateTime = /*@__PURE__*/ core.$constructor(\"ZodISODateTime\", (inst, def) => {\n core.$ZodISODateTime.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport const ZodISODate = /*@__PURE__*/ core.$constructor(\"ZodISODate\", (inst, def) => {\n core.$ZodISODate.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport const ZodISOTime = /*@__PURE__*/ core.$constructor(\"ZodISOTime\", (inst, def) => {\n core.$ZodISOTime.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport const ZodISODuration = /*@__PURE__*/ core.$constructor(\"ZodISODuration\", (inst, def) => {\n core.$ZodISODuration.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport const ZodEmail = /*@__PURE__*/ core.$constructor(\"ZodEmail\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodEmail.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function email(params) {\n return core._email(ZodEmail, params);\n}\nexport const ZodGUID = /*@__PURE__*/ core.$constructor(\"ZodGUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodGUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function guid(params) {\n return core._guid(ZodGUID, params);\n}\nexport const ZodUUID = /*@__PURE__*/ core.$constructor(\"ZodUUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodUUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function uuid(params) {\n return core._uuid(ZodUUID, params);\n}\nexport function uuidv4(params) {\n return core._uuidv4(ZodUUID, params);\n}\n// ZodUUIDv6\nexport function uuidv6(params) {\n return core._uuidv6(ZodUUID, params);\n}\n// ZodUUIDv7\nexport function uuidv7(params) {\n return core._uuidv7(ZodUUID, params);\n}\nexport const ZodURL = /*@__PURE__*/ core.$constructor(\"ZodURL\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodURL.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function url(params) {\n return core._url(ZodURL, params);\n}\nexport function httpUrl(params) {\n return core._url(ZodURL, {\n protocol: regexes.httpProtocol,\n hostname: regexes.domain,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodEmoji = /*@__PURE__*/ core.$constructor(\"ZodEmoji\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodEmoji.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function emoji(params) {\n return core._emoji(ZodEmoji, params);\n}\nexport const ZodNanoID = /*@__PURE__*/ core.$constructor(\"ZodNanoID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodNanoID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function nanoid(params) {\n return core._nanoid(ZodNanoID, params);\n}\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link ZodCUID2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport const ZodCUID = /*@__PURE__*/ core.$constructor(\"ZodCUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodCUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\n/**\n * Validates a CUID v1 string.\n *\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link cuid2 | `z.cuid2()`} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport function cuid(params) {\n return core._cuid(ZodCUID, params);\n}\nexport const ZodCUID2 = /*@__PURE__*/ core.$constructor(\"ZodCUID2\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodCUID2.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function cuid2(params) {\n return core._cuid2(ZodCUID2, params);\n}\nexport const ZodULID = /*@__PURE__*/ core.$constructor(\"ZodULID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodULID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ulid(params) {\n return core._ulid(ZodULID, params);\n}\nexport const ZodXID = /*@__PURE__*/ core.$constructor(\"ZodXID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodXID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function xid(params) {\n return core._xid(ZodXID, params);\n}\nexport const ZodKSUID = /*@__PURE__*/ core.$constructor(\"ZodKSUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodKSUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ksuid(params) {\n return core._ksuid(ZodKSUID, params);\n}\nexport const ZodIPv4 = /*@__PURE__*/ core.$constructor(\"ZodIPv4\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodIPv4.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ipv4(params) {\n return core._ipv4(ZodIPv4, params);\n}\nexport const ZodMAC = /*@__PURE__*/ core.$constructor(\"ZodMAC\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodMAC.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function mac(params) {\n return core._mac(ZodMAC, params);\n}\nexport const ZodIPv6 = /*@__PURE__*/ core.$constructor(\"ZodIPv6\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodIPv6.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ipv6(params) {\n return core._ipv6(ZodIPv6, params);\n}\nexport const ZodCIDRv4 = /*@__PURE__*/ core.$constructor(\"ZodCIDRv4\", (inst, def) => {\n core.$ZodCIDRv4.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function cidrv4(params) {\n return core._cidrv4(ZodCIDRv4, params);\n}\nexport const ZodCIDRv6 = /*@__PURE__*/ core.$constructor(\"ZodCIDRv6\", (inst, def) => {\n core.$ZodCIDRv6.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function cidrv6(params) {\n return core._cidrv6(ZodCIDRv6, params);\n}\nexport const ZodBase64 = /*@__PURE__*/ core.$constructor(\"ZodBase64\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodBase64.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function base64(params) {\n return core._base64(ZodBase64, params);\n}\nexport const ZodBase64URL = /*@__PURE__*/ core.$constructor(\"ZodBase64URL\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodBase64URL.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function base64url(params) {\n return core._base64url(ZodBase64URL, params);\n}\nexport const ZodE164 = /*@__PURE__*/ core.$constructor(\"ZodE164\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodE164.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function e164(params) {\n return core._e164(ZodE164, params);\n}\nexport const ZodCreditCard = /*@__PURE__*/ core.$constructor(\"ZodCreditCard\", (inst, def) => {\n core.$ZodCreditCard.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function creditCard(params) {\n return core._creditCard(ZodCreditCard, params);\n}\nexport const ZodIBAN = /*@__PURE__*/ core.$constructor(\"ZodIBAN\", (inst, def) => {\n core.$ZodIBAN.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function iban(params) {\n return core._iban(ZodIBAN, params);\n}\nexport const ZodJWT = /*@__PURE__*/ core.$constructor(\"ZodJWT\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodJWT.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function jwt(params) {\n return core._jwt(ZodJWT, params);\n}\nexport const ZodCustomStringFormat = /*@__PURE__*/ core.$constructor(\"ZodCustomStringFormat\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodCustomStringFormat.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function stringFormat(format, fnOrRegex, _params = {}) {\n return core._stringFormat(ZodCustomStringFormat, format, fnOrRegex, _params);\n}\nexport function hostname(_params) {\n return core._stringFormat(ZodCustomStringFormat, \"hostname\", regexes.hostname, _params);\n}\nexport function hex(_params) {\n return core._stringFormat(ZodCustomStringFormat, \"hex\", regexes.hex, _params);\n}\nexport function currencyCode(_params) {\n return core._stringFormat(ZodCustomStringFormat, \"currency_code\", regexes.currencyCode, _params);\n}\nexport function hash(alg, params) {\n const enc = params?.enc ?? \"hex\";\n const format = `${alg}_${enc}`;\n const regex = core.regexes[format];\n if (!regex)\n throw new Error(`Unrecognized hash format: ${format}`);\n return core._stringFormat(ZodCustomStringFormat, format, regex, params);\n}\nexport const ZodNumber = /*@__PURE__*/ core.$constructor(\"ZodNumber\", (inst, def) => {\n core.$ZodNumber.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.numberProcessor(inst, ctx, json, params);\n inst.isFinite = true;\n}, \n/*@__PURE__*/ util.derived({\n minValue: (inst) => {\n const { minimum, exclusiveMinimum } = processors.aggregateChecks(inst);\n return Math.max(minimum ?? Number.NEGATIVE_INFINITY, exclusiveMinimum ?? Number.NEGATIVE_INFINITY);\n },\n maxValue: (inst) => {\n const { maximum, exclusiveMaximum } = processors.aggregateChecks(inst);\n return Math.min(maximum ?? Number.POSITIVE_INFINITY, exclusiveMaximum ?? Number.POSITIVE_INFINITY);\n },\n isInt: (inst) => {\n const { isInt, multipleOf } = processors.aggregateChecks(inst);\n return !!isInt || !!multipleOf?.some(Number.isSafeInteger);\n },\n format: (inst) => processors.aggregateChecks(inst).format ?? null,\n}, {\n gt(value, params) {\n return this.check(checks.gt(value, params));\n },\n gte(value, params) {\n return this.check(checks.gte(value, params));\n },\n min(value, params) {\n return this.check(checks.gte(value, params));\n },\n lt(value, params) {\n return this.check(checks.lt(value, params));\n },\n lte(value, params) {\n return this.check(checks.lte(value, params));\n },\n max(value, params) {\n return this.check(checks.lte(value, params));\n },\n int(params) {\n return this.check(int(params));\n },\n safe(params) {\n return this.check(int(params));\n },\n positive(params) {\n return this.check(checks.gt(0, params));\n },\n nonnegative(params) {\n return this.check(checks.gte(0, params));\n },\n negative(params) {\n return this.check(checks.lt(0, params));\n },\n nonpositive(params) {\n return this.check(checks.lte(0, params));\n },\n multipleOf(value, params) {\n return this.check(checks.multipleOf(value, params));\n },\n step(value, params) {\n return this.check(checks.multipleOf(value, params));\n },\n finite() {\n return this;\n },\n}));\nexport function number(params) {\n return core._number(ZodNumber, params);\n}\nexport const ZodNumberFormat = /*@__PURE__*/ core.$constructor(\"ZodNumberFormat\", (inst, def) => {\n core.$ZodNumberFormat.init(inst, def);\n ZodNumber.init(inst, def);\n});\nexport function int(params) {\n return core._int(ZodNumberFormat, params);\n}\nexport function float32(params) {\n return core._float32(ZodNumberFormat, params);\n}\nexport function float64(params) {\n return core._float64(ZodNumberFormat, params);\n}\nexport function int32(params) {\n return core._int32(ZodNumberFormat, params);\n}\nexport function uint32(params) {\n return core._uint32(ZodNumberFormat, params);\n}\nexport const ZodBoolean = /*@__PURE__*/ core.$constructor(\"ZodBoolean\", (inst, def) => {\n core.$ZodBoolean.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.booleanProcessor(inst, ctx, json, params);\n});\nexport function boolean(params) {\n return core._boolean(ZodBoolean, params);\n}\nexport const ZodBigInt = /*@__PURE__*/ core.$constructor(\"ZodBigInt\", (inst, def) => {\n core.$ZodBigInt.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.bigintProcessor(inst, ctx, json, params);\n}, \n/*@__PURE__*/ util.derived({\n minValue: (inst) => processors.aggregateChecks(inst).minimum ?? null,\n maxValue: (inst) => processors.aggregateChecks(inst).maximum ?? null,\n format: (inst) => processors.aggregateChecks(inst).format ?? null,\n}, {\n gte(value, params) {\n return this.check(checks.gte(value, params));\n },\n min(value, params) {\n return this.check(checks.gte(value, params));\n },\n gt(value, params) {\n return this.check(checks.gt(value, params));\n },\n lt(value, params) {\n return this.check(checks.lt(value, params));\n },\n lte(value, params) {\n return this.check(checks.lte(value, params));\n },\n max(value, params) {\n return this.check(checks.lte(value, params));\n },\n positive(params) {\n return this.check(checks.gt(BigInt(0), params));\n },\n negative(params) {\n return this.check(checks.lt(BigInt(0), params));\n },\n nonpositive(params) {\n return this.check(checks.lte(BigInt(0), params));\n },\n nonnegative(params) {\n return this.check(checks.gte(BigInt(0), params));\n },\n multipleOf(value, params) {\n return this.check(checks.multipleOf(value, params));\n },\n}));\nexport function bigint(params) {\n return core._bigint(ZodBigInt, params);\n}\nexport const ZodBigIntFormat = /*@__PURE__*/ core.$constructor(\"ZodBigIntFormat\", (inst, def) => {\n core.$ZodBigIntFormat.init(inst, def);\n ZodBigInt.init(inst, def);\n});\nexport function int64(params) {\n return core._int64(ZodBigIntFormat, params);\n}\nexport function uint64(params) {\n return core._uint64(ZodBigIntFormat, params);\n}\nexport const ZodSymbol = /*@__PURE__*/ core.$constructor(\"ZodSymbol\", (inst, def) => {\n core.$ZodSymbol.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.symbolProcessor(inst, ctx, json, params);\n});\nexport function symbol(params) {\n return core._symbol(ZodSymbol, params);\n}\nexport const ZodUndefined = /*@__PURE__*/ core.$constructor(\"ZodUndefined\", (inst, def) => {\n core.$ZodUndefined.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.undefinedProcessor(inst, ctx, json, params);\n});\nfunction _undefined(params) {\n return core._undefined(ZodUndefined, params);\n}\nexport { _undefined as undefined };\nexport const ZodNull = /*@__PURE__*/ core.$constructor(\"ZodNull\", (inst, def) => {\n core.$ZodNull.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nullProcessor(inst, ctx, json, params);\n});\nfunction _null(params) {\n return core._null(ZodNull, params);\n}\nexport { _null as null };\nexport const ZodAny = /*@__PURE__*/ core.$constructor(\"ZodAny\", (inst, def) => {\n core.$ZodAny.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.anyProcessor(inst, ctx, json, params);\n});\nexport function any() {\n return core._any(ZodAny);\n}\nexport const ZodUnknown = /*@__PURE__*/ core.$constructor(\"ZodUnknown\", (inst, def) => {\n core.$ZodUnknown.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.unknownProcessor(inst, ctx, json, params);\n});\nexport function unknown() {\n return core._unknown(ZodUnknown);\n}\nexport const ZodNever = /*@__PURE__*/ core.$constructor(\"ZodNever\", (inst, def) => {\n core.$ZodNever.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.neverProcessor(inst, ctx, json, params);\n});\nexport function never(params) {\n return core._never(ZodNever, params);\n}\nexport const ZodVoid = /*@__PURE__*/ core.$constructor(\"ZodVoid\", (inst, def) => {\n core.$ZodVoid.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.voidProcessor(inst, ctx, json, params);\n});\nfunction _void(params) {\n return core._void(ZodVoid, params);\n}\nexport { _void as void };\nexport const ZodDate = /*@__PURE__*/ core.$constructor(\"ZodDate\", (inst, def) => {\n core.$ZodDate.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.dateProcessor(inst, ctx, json, params);\n inst.min = (value, params) => inst.check(checks.gte(value, params));\n inst.max = (value, params) => inst.check(checks.lte(value, params));\n}, \n/*@__PURE__*/ util.derived({\n minDate: (inst) => {\n const { minimum } = processors.aggregateChecks(inst);\n return minimum ? new Date(minimum) : null;\n },\n maxDate: (inst) => {\n const { maximum } = processors.aggregateChecks(inst);\n return maximum ? new Date(maximum) : null;\n },\n}, {}));\nexport function date(params) {\n return core._date(ZodDate, params);\n}\nexport const ZodArray = /*@__PURE__*/ core.$constructor(\"ZodArray\", (inst, def) => {\n _ensureDefaultMemoizer();\n core.$ZodArray.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.arrayProcessor(inst, ctx, json, params);\n inst.element = def.element;\n}, {\n min(n, params) {\n return this.check(checks.minLength(n, params));\n },\n nonempty(params) {\n return this.check(checks.minLength(1, params));\n },\n max(n, params) {\n return this.check(checks.maxLength(n, params));\n },\n length(n, params) {\n return this.check(checks.length(n, params));\n },\n unwrap() {\n return this.element;\n },\n});\nexport function array(element, params) {\n return core._array(ZodArray, element, params);\n}\n// .keyof\nexport function keyof(schema) {\n const shape = schema._zod.def.shape;\n return _enum(Object.keys(shape));\n}\nexport const ZodObject = /*@__PURE__*/ core.$constructor(\"ZodObject\", (inst, def) => {\n _ensureDefaultMemoizer();\n core.$ZodObjectJIT.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.objectProcessor(inst, ctx, json, params);\n util.installLazyProp(inst, \"shape\", (self) => self._zod.def.shape, false);\n}, {\n keyof() {\n return _enum(Object.keys(this._zod.def.shape));\n },\n catchall(catchall) {\n // `mergeDefs` rather than a spread: spreading reads `shape`, and resolving it can mint a whole fresh subtree\n return this.clone(util.mergeDefs(this._zod.def, { catchall: catchall }));\n },\n passthrough() {\n return this.clone(util.mergeDefs(this._zod.def, { catchall: unknown() }));\n },\n loose() {\n return this.clone(util.mergeDefs(this._zod.def, { catchall: unknown() }));\n },\n strict() {\n return this.clone(util.mergeDefs(this._zod.def, { catchall: never() }));\n },\n strip() {\n return this.clone(util.mergeDefs(this._zod.def, { catchall: undefined }));\n },\n extend(incoming) {\n return util.extend(this, incoming);\n },\n safeExtend(incoming) {\n return util.safeExtend(this, incoming);\n },\n merge(other) {\n return util.merge(this, other);\n },\n pick(mask) {\n return util.pick(this, mask);\n },\n omit(mask) {\n return util.omit(this, mask);\n },\n partial(...args) {\n return util.partial(ZodOptional, this, args[0]);\n },\n exactPartial(...args) {\n return util.partial(ZodExactOptional, this, args[0], \"exactPartial\");\n },\n required(...args) {\n return util.required(ZodNonOptional, this, args[0]);\n },\n});\nexport function object(shape, params) {\n const def = {\n type: \"object\",\n shape: shape ?? {},\n ...util.normalizeParams(params),\n };\n return new ZodObject(def);\n}\n// strictObject\nexport function strictObject(shape, params) {\n return new ZodObject({\n type: \"object\",\n shape,\n catchall: never(),\n ...util.normalizeParams(params),\n });\n}\n// looseObject\nexport function looseObject(shape, params) {\n return new ZodObject({\n type: \"object\",\n shape,\n catchall: unknown(),\n ...util.normalizeParams(params),\n });\n}\nexport const ZodUnion = /*@__PURE__*/ core.$constructor(\"ZodUnion\", (inst, def) => {\n core.$ZodUnion.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.unionProcessor(inst, ctx, json, params);\n inst.options = def.options;\n});\nexport function union(options, params) {\n return new ZodUnion({\n type: \"union\",\n options: options,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodXor = /*@__PURE__*/ core.$constructor(\"ZodXor\", (inst, def) => {\n ZodUnion.init(inst, def);\n core.$ZodXor.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.unionProcessor(inst, ctx, json, params);\n inst.options = def.options;\n});\n/** Creates an exclusive union (XOR) where exactly one option must match.\n * Unlike regular unions that succeed when any option matches, xor fails if\n * zero or more than one option matches the input. */\nexport function xor(options, params) {\n return new ZodXor({\n type: \"union\",\n options: options,\n inclusive: false,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodDiscriminatedUnion = /*@__PURE__*/ core.$constructor(\"ZodDiscriminatedUnion\", (inst, def) => {\n ZodUnion.init(inst, def);\n core.$ZodDiscriminatedUnion.init(inst, def);\n});\nexport function discriminatedUnion(discriminator, options, params) {\n // const [options, params] = args;\n return new ZodDiscriminatedUnion({\n type: \"union\",\n options: options,\n discriminator,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodIntersection = /*@__PURE__*/ core.$constructor(\"ZodIntersection\", (inst, def) => {\n core.$ZodIntersection.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.intersectionProcessor(inst, ctx, json, params);\n});\nexport function intersection(left, right) {\n return new ZodIntersection({\n type: \"intersection\",\n left: left,\n right: right,\n });\n}\nexport const ZodTuple = /*@__PURE__*/ core.$constructor(\"ZodTuple\", (inst, def) => {\n _ensureDefaultMemoizer();\n core.$ZodTuple.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.tupleProcessor(inst, ctx, json, params);\n}, {\n rest(rest) {\n return this.clone({\n ...this._zod.def,\n rest: rest,\n });\n },\n partial() {\n const def = this._zod.def;\n // a refinement was authored against the full arity; partialing would run it on a shorter array\n if (def.checks?.length)\n throw new Error(\".partial() cannot be used on tuple schemas containing refinements\");\n return this.clone({\n ...def,\n items: def.items.map((item) => new ZodOptional({ type: \"optional\", innerType: item })),\n });\n },\n});\nexport function tuple(items, _paramsOrRest, _params) {\n const hasRest = _paramsOrRest instanceof core.$ZodType;\n const params = hasRest ? _params : _paramsOrRest;\n const rest = hasRest ? _paramsOrRest : null;\n return new ZodTuple({\n type: \"tuple\",\n items: items,\n rest,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodRecord = /*@__PURE__*/ core.$constructor(\"ZodRecord\", (inst, def) => {\n _ensureDefaultMemoizer();\n core.$ZodRecord.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.recordProcessor(inst, ctx, json, params);\n inst.keyType = def.keyType;\n inst.valueType = def.valueType;\n});\nexport function record(keyType, valueType, params) {\n // v3-compat: z.record(valueType, params?) — defaults keyType to z.string()\n if (!valueType || !valueType._zod) {\n return new ZodRecord({\n type: \"record\",\n keyType: string(),\n valueType: keyType,\n ...util.normalizeParams(valueType),\n });\n }\n return new ZodRecord({\n type: \"record\",\n keyType,\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\n// type alksjf = core.output<core.$ZodRecordKey>;\nexport function partialRecord(keyType, valueType, params) {\n return new ZodRecord({\n type: \"record\",\n keyType,\n valueType: valueType,\n ...util.normalizeParams(params),\n partial: true,\n });\n}\nexport function looseRecord(keyType, valueType, params) {\n return new ZodRecord({\n type: \"record\",\n keyType,\n valueType: valueType,\n mode: \"loose\",\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMap = /*@__PURE__*/ core.$constructor(\"ZodMap\", (inst, def) => {\n _ensureDefaultMemoizer();\n core.$ZodMap.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.mapProcessor(inst, ctx, json, params);\n inst.keyType = def.keyType;\n inst.valueType = def.valueType;\n inst.min = (...args) => inst.check(core._minSize(...args));\n inst.nonempty = (params) => inst.check(core._minSize(1, params));\n inst.max = (...args) => inst.check(core._maxSize(...args));\n inst.size = (...args) => inst.check(core._size(...args));\n});\nexport function map(keyType, valueType, params) {\n return new ZodMap({\n type: \"map\",\n keyType: keyType,\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodSet = /*@__PURE__*/ core.$constructor(\"ZodSet\", (inst, def) => {\n _ensureDefaultMemoizer();\n core.$ZodSet.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.setProcessor(inst, ctx, json, params);\n inst.min = (...args) => inst.check(core._minSize(...args));\n inst.nonempty = (params) => inst.check(core._minSize(1, params));\n inst.max = (...args) => inst.check(core._maxSize(...args));\n inst.size = (...args) => inst.check(core._size(...args));\n});\nexport function set(valueType, params) {\n return new ZodSet({\n type: \"set\",\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodEnum = /*@__PURE__*/ core.$constructor(\"ZodEnum\", (inst, def) => {\n core.$ZodEnum.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.enumProcessor(inst, ctx, json, params);\n inst.enum = def.entries;\n // reuse the parsed value set so a numeric TS enum's reverse-mapping keys stay out\n inst.options = [...inst._zod.values];\n const keys = new Set(Object.keys(def.entries));\n inst.extract = (values, params) => {\n const newEntries = {};\n for (const value of values) {\n if (keys.has(value)) {\n newEntries[value] = def.entries[value];\n }\n else\n throw new Error(`Key ${value} not found in enum`);\n }\n return new ZodEnum({\n ...def,\n checks: [],\n ...util.normalizeParams(params),\n entries: newEntries,\n });\n };\n inst.exclude = (values, params) => {\n const newEntries = { ...def.entries };\n for (const value of values) {\n if (keys.has(value)) {\n delete newEntries[value];\n }\n else\n throw new Error(`Key ${value} not found in enum`);\n }\n return new ZodEnum({\n ...def,\n checks: [],\n ...util.normalizeParams(params),\n entries: newEntries,\n });\n };\n});\nfunction _enum(values, params) {\n const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;\n return new ZodEnum({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\nexport { _enum as enum };\n/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead.\n *\n * ```ts\n * enum Colors { red, green, blue }\n * z.enum(Colors);\n * ```\n */\nexport function nativeEnum(entries, params) {\n return new ZodEnum({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodLiteral = /*@__PURE__*/ core.$constructor(\"ZodLiteral\", (inst, def) => {\n core.$ZodLiteral.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.literalProcessor(inst, ctx, json, params);\n inst.values = new Set(def.values);\n Object.defineProperty(inst, \"value\", {\n get() {\n if (def.values.length > 1) {\n throw new Error(\"This schema contains multiple valid literal values. Use `.values` instead.\");\n }\n return def.values[0];\n },\n });\n});\nexport function literal(value, params) {\n return new ZodLiteral({\n type: \"literal\",\n values: Array.isArray(value) ? value : [value],\n ...util.normalizeParams(params),\n });\n}\nexport const ZodFile = /*@__PURE__*/ core.$constructor(\"ZodFile\", (inst, def) => {\n core.$ZodFile.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.fileProcessor(inst, ctx, json, params);\n inst.min = (size, params) => inst.check(core._minSize(size, params));\n inst.max = (size, params) => inst.check(core._maxSize(size, params));\n inst.mime = (types, params) => inst.check(core._mime(Array.isArray(types) ? types : [types], params));\n});\nexport function file(params) {\n return core._file(ZodFile, params);\n}\nexport const ZodTransform = /*@__PURE__*/ core.$constructor(\"ZodTransform\", (inst, def) => {\n _ensureDefaultMemoizer();\n core.$ZodTransform.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.transformProcessor(inst, ctx, json, params);\n inst._zod.parse = (payload, _ctx) => {\n if (_ctx.direction === \"backward\") {\n throw new core.$ZodEncodeError(inst.constructor.name);\n }\n payload.addIssue = (issue) => {\n if (typeof issue === \"string\") {\n payload.issues.push(util.issue(issue, payload.value, def));\n }\n else {\n // for Zod 3 backwards compatibility\n const _issue = issue;\n if (_issue.fatal)\n _issue.continue = false;\n _issue.code ?? (_issue.code = \"custom\");\n if (!(\"input\" in _issue))\n _issue.input = payload.value;\n _issue.inst ?? (_issue.inst = inst);\n // _issue.continue ??= true;\n payload.issues.push(util.issue(_issue));\n }\n };\n const output = def.transform(payload.value, payload);\n if (output instanceof Promise) {\n return output.then((output) => {\n payload.value = output;\n return payload;\n });\n }\n payload.value = output;\n return payload;\n };\n});\nexport function transform(fn) {\n return new ZodTransform({\n type: \"transform\",\n transform: fn,\n });\n}\nexport const ZodOptional = /*@__PURE__*/ core.$constructor(\"ZodOptional\", (inst, def) => {\n core.$ZodOptional.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.optionalProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function optional(innerType) {\n return new ZodOptional({\n type: \"optional\",\n innerType: innerType,\n });\n}\nexport const ZodExactOptional = /*@__PURE__*/ core.$constructor(\"ZodExactOptional\", (inst, def) => {\n core.$ZodExactOptional.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.optionalProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function exactOptional(innerType) {\n return new ZodExactOptional({\n type: \"optional\",\n innerType: innerType,\n });\n}\nexport const ZodNullable = /*@__PURE__*/ core.$constructor(\"ZodNullable\", (inst, def) => {\n core.$ZodNullable.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nullableProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function nullable(innerType) {\n return new ZodNullable({\n type: \"nullable\",\n innerType: innerType,\n });\n}\n// nullish\nexport function nullish(innerType) {\n return optional(nullable(innerType));\n}\nexport const ZodDefault = /*@__PURE__*/ core.$constructor(\"ZodDefault\", (inst, def) => {\n core.$ZodDefault.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.defaultProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n inst.removeDefault = inst.unwrap;\n});\nexport function _default(innerType, defaultValue) {\n return new ZodDefault({\n type: \"default\",\n innerType: innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\nexport const ZodPrefault = /*@__PURE__*/ core.$constructor(\"ZodPrefault\", (inst, def) => {\n core.$ZodPrefault.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.prefaultProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function prefault(innerType, defaultValue) {\n return new ZodPrefault({\n type: \"prefault\",\n innerType: innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\nexport const ZodNonOptional = /*@__PURE__*/ core.$constructor(\"ZodNonOptional\", (inst, def) => {\n core.$ZodNonOptional.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nonoptionalProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function nonoptional(innerType, params) {\n return new ZodNonOptional({\n type: \"nonoptional\",\n innerType: innerType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodSuccess = /*@__PURE__*/ core.$constructor(\"ZodSuccess\", (inst, def) => {\n core.$ZodSuccess.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.successProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function success(innerType) {\n return new ZodSuccess({\n type: \"success\",\n innerType: innerType,\n });\n}\nexport const ZodCatch = /*@__PURE__*/ core.$constructor(\"ZodCatch\", (inst, def) => {\n core.$ZodCatch.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.catchProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n inst.removeCatch = inst.unwrap;\n});\nfunction _catch(innerType, catchValue) {\n return new ZodCatch({\n type: \"catch\",\n innerType: innerType,\n catchValue: (typeof catchValue === \"function\" ? catchValue : core.util.constantCatch(catchValue)),\n });\n}\nexport { _catch as catch };\nexport const ZodNaN = /*@__PURE__*/ core.$constructor(\"ZodNaN\", (inst, def) => {\n core.$ZodNaN.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nanProcessor(inst, ctx, json, params);\n});\nexport function nan(params) {\n return core._nan(ZodNaN, params);\n}\nexport const ZodPipe = /*@__PURE__*/ core.$constructor(\"ZodPipe\", (inst, def) => {\n core.$ZodPipe.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.pipeProcessor(inst, ctx, json, params);\n inst.in = def.in;\n inst.out = def.out;\n});\nexport function pipe(in_, out) {\n return new ZodPipe({\n type: \"pipe\",\n in: in_,\n out: out,\n // ...util.normalizeParams(params),\n });\n}\nexport const ZodCodec = /*@__PURE__*/ core.$constructor(\"ZodCodec\", (inst, def) => {\n ZodPipe.init(inst, def);\n core.$ZodCodec.init(inst, def);\n});\nexport function codec(in_, out, params) {\n return new ZodCodec({\n type: \"pipe\",\n in: in_,\n out: out,\n transform: params.decode,\n reverseTransform: params.encode,\n });\n}\nexport function invertCodec(codec) {\n const def = codec._zod.def;\n return new ZodCodec({\n type: \"pipe\",\n in: def.out,\n out: def.in,\n transform: def.reverseTransform,\n reverseTransform: def.transform,\n });\n}\nexport const ZodPreprocess = /*@__PURE__*/ core.$constructor(\"ZodPreprocess\", (inst, def) => {\n ZodPipe.init(inst, def);\n core.$ZodPreprocess.init(inst, def);\n});\nexport const ZodReadonly = /*@__PURE__*/ core.$constructor(\"ZodReadonly\", (inst, def) => {\n core.$ZodReadonly.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.readonlyProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function readonly(innerType) {\n return new ZodReadonly({\n type: \"readonly\",\n innerType: innerType,\n });\n}\nexport const ZodTemplateLiteral = /*@__PURE__*/ core.$constructor(\"ZodTemplateLiteral\", (inst, def) => {\n core.$ZodTemplateLiteral.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.templateLiteralProcessor(inst, ctx, json, params);\n});\nexport function templateLiteral(parts, params) {\n return new ZodTemplateLiteral({\n type: \"template_literal\",\n parts,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodLazy = /*@__PURE__*/ core.$constructor(\"ZodLazy\", (inst, def) => {\n core.$ZodLazy.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.lazyProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.getter();\n});\nexport function lazy(getter) {\n return new ZodLazy({\n type: \"lazy\",\n getter: getter,\n });\n}\nexport const ZodPromise = /*@__PURE__*/ core.$constructor(\"ZodPromise\", (inst, def) => {\n core.$ZodPromise.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.promiseProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function promise(innerType) {\n return new ZodPromise({\n type: \"promise\",\n innerType: innerType,\n });\n}\nexport const ZodFunction = /*@__PURE__*/ core.$constructor(\"ZodFunction\", (inst, def) => {\n core.$ZodFunction.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.functionProcessor(inst, ctx, json, params);\n});\nexport function _function(params) {\n return new ZodFunction({\n type: \"function\",\n input: Array.isArray(params?.input) ? tuple(params?.input) : (params?.input ?? array(unknown())),\n output: params?.output ?? unknown(),\n });\n}\nexport { _function as function };\nexport const ZodCustom = /*@__PURE__*/ core.$constructor(\"ZodCustom\", (inst, def) => {\n core.$ZodCustom.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.customProcessor(inst, ctx, json, params);\n});\n// custom checks\nexport function check(fn) {\n const ch = new core.$ZodCheck({\n check: \"custom\",\n // ...util.normalizeParams(params),\n });\n ch._zod.check = fn;\n return ch;\n}\nexport function custom(fn, _params) {\n return core._custom(ZodCustom, fn ?? (() => true), _params);\n}\nexport function refine(fn, _params = {}) {\n return core._refine(ZodCustom, fn, _params);\n}\n// superRefine\nexport function superRefine(fn, params) {\n return core._superRefine(fn, params);\n}\n// Re-export describe and meta from core\nexport const describe = core.describe;\nexport const meta = core.meta;\nexport const ZodInstanceOf = /*@__PURE__*/ core.$constructor(\"ZodInstanceOf\", (inst, def) => {\n ZodCustom.init(inst, def);\n}, {\n properties(shape, params) {\n // asserts in place, so the narrowed output type is truthful without a wrapper\n return this.check(core._properties(shape, params));\n },\n});\nfunction _instanceof(cls, params = {}) {\n const inst = new ZodInstanceOf({\n type: \"custom\",\n check: \"custom\",\n fn: (data) => data instanceof cls,\n abort: true,\n ...util.normalizeParams(params),\n });\n inst._zod.bag.Class = cls;\n // Override check to emit invalid_type instead of custom\n inst._zod.check = (payload) => {\n if (!(payload.value instanceof cls)) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: cls.name,\n input: payload.value,\n inst,\n path: [...(inst._zod.def.path ?? [])],\n });\n }\n };\n return inst;\n}\nexport { _instanceof as instanceof };\n// stringbool\nexport const stringbool = (...args) => core._stringbool({\n Codec: ZodCodec,\n Boolean: ZodBoolean,\n String: ZodString,\n}, ...args);\nexport function json(params) {\n const jsonSchema = lazy(() => {\n return union([string(params), number(), boolean(), _null(), array(jsonSchema), record(string(), jsonSchema)]);\n });\n return jsonSchema;\n}\n// preprocess\nexport function preprocess(fn, schema) {\n return new ZodPreprocess({\n type: \"pipe\",\n in: transform(fn),\n out: schema,\n });\n}\n","import { z } from 'zod';\nimport type { HiAgentTool, McpToolResult } from './mcp-tool-types';\n\n// The path of an issue as the MCP SDK writes it: groupId, roots[0].articleId.\nconst dotPath = (path: PropertyKey[]): string =>\n path.reduce<string>(\n (text, segment, index) =>\n index === 0\n ? String(segment)\n : typeof segment === 'number'\n ? `${text}[${segment}]`\n : `${text}.${String(segment)}`,\n '',\n );\n\nexport const errorResult = (text: string): McpToolResult => ({\n content: [{ type: 'text', text }],\n isError: true,\n});\n\n/**\n * A tool as an MCP server registers it: the JSON Schema the MCP SDK serves;\n * the input validated here, an invalid input and a thrown error answered as\n * MCP error results, which the model reads like any other result.\n */\nexport const mcpTool = (\n name: string,\n description: string,\n shape: z.ZodRawShape,\n handler: (args: any) => Promise<McpToolResult>,\n): HiAgentTool => {\n const schema = z.object(shape);\n return {\n description,\n inputSchema: z.toJSONSchema(schema, {\n target: 'draft-7',\n io: 'input',\n }) as Record<string, unknown>,\n execute: async (input) => {\n const parsed = await schema.safeParseAsync(input);\n if (!parsed.success) {\n const issues = parsed.error.issues\n .map((issue) =>\n issue.path.length > 0\n ? `${issue.message} at ${dotPath(issue.path)}`\n : issue.message,\n )\n .join('\\n');\n return errorResult(\n `MCP error -32602: Input validation error: Invalid arguments for tool ${name}: ${issues}`,\n );\n }\n try {\n return await handler(parsed.data);\n } catch (error) {\n return errorResult(\n error instanceof Error ? error.message : String(error),\n );\n }\n },\n };\n};\n","/** A tool call that changed the plan, as the undo tool reverts it. */\nexport interface ToolCallRecord {\n tool: string;\n /** The planner steps the call put on the planner's undo history. */\n steps: number;\n /** The plan's groups before and after the call, as comparison keys. */\n groupsBefore: string;\n groupsAfter: string;\n}\n\n// The tool set's view of the planner's undo history: the planner's history\n// events and the tool calls that changed the plan, with the planner steps\n// each made. An event while no tool call runs is a change the user made\n// in the planner - the tool calls below it can no longer be undone safely, so\n// they are forgotten.\nexport class PlanHistory {\n private _events = 0;\n private _inFlight = false;\n private _done: ToolCallRecord[] = [];\n private _undone: ToolCallRecord[] = [];\n private _changedInPlanner = false;\n private _waiters = new Set<() => void>();\n\n public get events(): number {\n return this._events;\n }\n\n public get changedInPlanner(): boolean {\n return this._changedInPlanner;\n }\n\n public historyChanged(): void {\n this._events += 1;\n if (!this._inFlight) {\n this.forget();\n this._changedInPlanner = true;\n }\n for (const wake of this._waiters) {\n wake();\n }\n }\n\n /** Resolves true once `count` events have arrived, false after the timeout. */\n public waitForEvents(count: number, timeoutMs: number): Promise<boolean> {\n if (this._events >= count) {\n return Promise.resolve(true);\n }\n return new Promise((resolve) => {\n const finish = (reached: boolean) => {\n clearTimeout(timer);\n this._waiters.delete(wake);\n resolve(reached);\n };\n const wake = () => {\n if (this._events >= count) {\n finish(true);\n }\n };\n const timer = setTimeout(() => finish(false), timeoutMs);\n this._waiters.add(wake);\n });\n }\n\n public begin(): void {\n this._inFlight = true;\n }\n\n public end(): void {\n this._inFlight = false;\n }\n\n /** A new change on top of the history ends redo, as in the planner. */\n public record(call: ToolCallRecord): void {\n this._done.push(call);\n this._undone = [];\n this._changedInPlanner = false;\n }\n\n public lastDone(): ToolCallRecord | undefined {\n return this._done.at(-1);\n }\n\n public lastUndone(): ToolCallRecord | undefined {\n return this._undone.at(-1);\n }\n\n public markUndone(): void {\n const call = this._done.pop();\n if (call) {\n this._undone.push(call);\n }\n }\n\n public markRedone(): void {\n const call = this._undone.pop();\n if (call) {\n this._done.push(call);\n }\n }\n\n public forget(): void {\n this._done = [];\n this._undone = [];\n }\n\n /** A change in the planner was found: no record can be trusted any more. */\n public markChangedInPlanner(): void {\n this.forget();\n this._changedInPlanner = true;\n }\n}\n","export const DEFAULT_CALL_TIMEOUT_MS = 30_000;\nexport const SNAPSHOT_CALL_TIMEOUT_MS = 120_000;\n\n// The planner methods the tools call.\nexport interface PlannerApi {\n extended: {\n getExternalObjectPlanContext(\n include: string[],\n options?: {\n interiorDesign: {\n groupId: string;\n rootId?: string;\n containerModuleId?: string;\n articleId?: string;\n };\n },\n ): Promise<any>;\n getExternalObjectLibraryContext(\n include: string[],\n options?: { articleIds?: string[] },\n ): Promise<any>;\n externalObjectGroupOperation(\n command: string,\n payload: Record<string, unknown>,\n ): Promise<any>;\n fetchPrice(): Promise<any>;\n getExternalObjectSnapshot(options: Record<string, boolean>): Promise<any>;\n undo(): Promise<void>;\n redo(): Promise<void>;\n };\n}\n\n/**\n * The planner the HI MCP tools run in: the seven planner methods the tools\n * call, and the planner's callbacks, whose `onHistoryChange` the tools chain\n * to tell their own planner steps from the user's changes.\n */\nexport type HiMcpPlannerApi = PlannerApi & {\n extended: {\n callbacks: {\n onHistoryChange?: (undo: boolean, redo: boolean) => void;\n };\n };\n};\n\n// The seven planner methods as the tools call them: each call with a timeout -\n// a planner call has none of its own - and a log line.\nexport const createPlannerApi = ({ extended }: PlannerApi): PlannerApi => {\n let nextCallId = 1;\n const call = (\n method: keyof PlannerApi['extended'],\n args: unknown[],\n timeoutMs: number,\n ): Promise<any> => {\n const id = nextCallId++;\n console.log(\n `[hi-mcp] call ${id}: ${method} ${JSON.stringify(args).slice(0, 400)}`,\n );\n let timeout: ReturnType<typeof setTimeout> | undefined;\n const timedOut = new Promise<never>((_resolve, reject) => {\n timeout = setTimeout(\n () =>\n reject(\n new Error(\n `Planner call '${method}' timed out after ${timeoutMs}ms`,\n ),\n ),\n timeoutMs,\n );\n });\n return Promise.race([\n (extended[method] as (...callArgs: unknown[]) => Promise<unknown>).apply(\n extended,\n args,\n ),\n timedOut,\n ]).finally(() => clearTimeout(timeout));\n };\n return {\n extended: {\n getExternalObjectPlanContext: (include, options) =>\n call(\n 'getExternalObjectPlanContext',\n options === undefined ? [include] : [include, options],\n DEFAULT_CALL_TIMEOUT_MS,\n ),\n getExternalObjectLibraryContext: (include, options) =>\n call(\n 'getExternalObjectLibraryContext',\n options === undefined ? [include] : [include, options],\n DEFAULT_CALL_TIMEOUT_MS,\n ),\n externalObjectGroupOperation: (command, payload) =>\n call(\n 'externalObjectGroupOperation',\n [command, payload],\n SNAPSHOT_CALL_TIMEOUT_MS,\n ),\n fetchPrice: () => call('fetchPrice', [], DEFAULT_CALL_TIMEOUT_MS),\n getExternalObjectSnapshot: (options) =>\n call('getExternalObjectSnapshot', [options], SNAPSHOT_CALL_TIMEOUT_MS),\n undo: async () => {\n await call('undo', [], DEFAULT_CALL_TIMEOUT_MS);\n },\n redo: async () => {\n await call('redo', [], DEFAULT_CALL_TIMEOUT_MS);\n },\n },\n };\n};\n","export default \"---\\nname: image-planning\\ndescription: 'Plan furniture from an image or photo the user sends, with or without text: identify the pieces of furniture, read their layout, counts and sizes, map them onto the room of the plan and the article catalog, and report what was substituted and adapted. Use whenever a user message carries an image of furniture or of a room.'\\n---\\n\\n# Planning from an Image\\n\\n## Purpose\\n\\nThe image is the brief. Plan the furniture it shows as close to it as possible, with the articles of the catalog, in the room of the plan. The text of the message, when there is one, comes first: it names the wall, the corner, the changes or the part of the image to plan; the image supplies everything the text leaves open.\\n\\nA photo is enough for a concept. Do not ask for a measured plan, a site survey or the services first: plan with stated assumptions and name them in the answer.\\n\\n## 1. Identify the furniture\\n\\n- Name every piece of furniture in the image and its kind — a kitchen, a wardrobe, a media unit, a sideboard, shelves, a utility room, a row of tall cabinets — before choosing articles. Plan what the image shows: tall cabinets in a kitchen-like room are tall cabinets, not a kitchen.\\n- Plan each piece as one group. Cabinets beside, above or behind each other belong to the same group.\\n- Leave out what is no furniture of the catalog — walls, floors, decoration, loose items — and name the pieces the catalog has nothing for.\\n\\n## 2. Read the layout\\n\\n- The shape: one row, an L around a corner, a U, two facing rows (a galley), a row with an island, a free-standing piece.\\n- The levels: floor cabinets, tall cabinets, wall cabinets above the floor cabinets, cabinets on top; which wall cabinets hang above which floor cabinets, and where a tall cabinet interrupts the rows.\\n- The order along each row, from left to right as seen from the front: what stands next to what — sink, dishwasher, hob, oven, fridge, drawers, open shelves, a corner. Keep this sequence; it makes the planning look like the image.\\n\\n## 3. Read the counts and the sizes\\n\\n- Count the cabinets per row and per level. A pair of doors is usually one cabinet, one wide drawer front one cabinet.\\n- Judge the widths relative to each other and to a reference of known size — a door, an appliance, the height of the floor cabinets or of the room. Then take for each cabinet the catalog article whose width comes closest: the catalog's widths are the truth, the estimate is not.\\n- A photo distorts: cabinets far from the camera look narrower, cabinets at the edge of the image wider. Prefer the count and the proportions over the width in pixels.\\n\\n## 4. Map it onto the plan\\n\\n- The room of the plan is not the room in the image. Read its walls, doors, windows and obstacles from the plan context.\\n- When the text names a wall or a corner, plan there. Otherwise choose the wall or corner whose length and openings fit the shape: an L into a room corner with two free walls, a long row onto the longest free wall, a galley onto two facing walls.\\n- Fit the length to the wall. Keep the sequence and the proportions; when the wall is shorter than the furniture in the image, leave out or narrow the cabinets of least weight — a filler, an open shelf, a second drawer cabinet. When it is longer, add nothing the image does not show.\\n- Keep doors and windows clear, and name in the answer what moved for them.\\n\\n## 5. Articles and attributes\\n\\n- Choose each article by what the cabinet does in the image — a sink cabinet, a drawer cabinet, an appliance housing, a corner cabinet — from the desc, the category and the dimensions of the catalog.\\n- Read the fronts, the handles, the worktop and the carcase from the image and set them as attributes of the group, with the values the attribute vocabulary of the plan context offers. Take the closest value and say which one you took.\\n\\n## 6. The room skills\\n\\nWhen the furniture is of a kind another planning skill covers — a kitchen, a living room — fetch that skill too, for its checks. The image keeps precedence:\\n\\n- Apply its hard constraints: clearances, openings, what an appliance needs to work and to be installed.\\n- Report its recommendations — a better sequence, more worktop, another position of an appliance — in the answer as notes. Do not change what the image shows for them, unless the user asks for an improved planning.\\n- Fetch its planning reference only for a dimension this skill does not settle.\\n\\n## 7. The answer\\n\\nSay in a few sentences:\\n\\n- what you identified in the image and planned, group by group;\\n- what you substituted — the closest article or attribute value for what the catalog lacks;\\n- what you adapted to the room — the wall, the length, the cabinets left out, the openings kept clear;\\n- the assumptions, and the open checks of the room skill.\\n\"","export default \"---\\nname: kitchen-planning\\ndescription: 'Plan or review a residential kitchen: room survey, kitchen layout, sink and hob spacing, dishwasher placement, cabinet ordering, drawer organization, storage zones, short walking routes, ergonomics, accessibility, appliance clearances, and installation readiness. Use for kitchen planning, kitchen design, Kuechenplanung, arranging cabinets, or improving cooking and dishwasher-unloading workflows. Defaults to Germany/EU and millimetres; adapt rules to the actual jurisdiction.'\\n---\\n\\n# Kitchen Planning\\n\\n## Purpose and Scope\\n\\nProduce practical, dimensioned residential kitchen proposals with short daily routes, usable storage, and explicit feasibility checks. Plan from activities and contents before choosing cabinet fronts. Here, cabinet \\\"ordering\\\" means arranging cabinets; procurement requires a separate approval gate.\\n\\nDefault to Germany/EU, dimensions in mm, and costs in EUR. Confirm country and, in Germany, Bundesland before applying regulatory requirements. There is no single EU kitchen-clearance code. Commercial kitchens require a separate specialist workflow.\\n\\nRead [the planning constraints reference](./references/planning-reference.md) before applying numerical guidance or reviewing installation risks. It includes rule classifications, qualifications, and short source IDs for traceability. Recheck current local requirements and exact product manuals for each real project.\\n\\nThe [source catalog](./references/source-catalog.md) is optional. Load it only to verify a source-backed claim, answer a provenance/citation question, or update the guidance. Do not load it during routine planning merely to resolve source IDs; the operational guidance and its limitations are in this skill and the planning reference. This does not waive project-specific verification of regulations or product instructions.\\n\\n## Non-Negotiable Planning Discipline\\n\\n- Treat law, applicable technical requirements, product instructions, and verified site constraints as simultaneous constraints. If they conflict, stop and resolve the conflict; a manufacturer cannot waive the law.\\n- Do not turn a recommendation into a regulation. In particular, do not claim that a sink beside a hob is universally illegal. Usually the problem is missing preparation/landing space; actual installation restrictions are product- and site-specific.\\n- Unknown is not pass. Missing dimensions, manuals, or service information remain unresolved. Photographs and generated images cannot establish installation readiness.\\n- Use a planner's authoritative geometry, catalog, and prices where available. Never invent a catalog item, price, service point, clearance, or successful validation result.\\n- Optimize only after hard constraints pass. A short walking route cannot compensate for a blocked exit, unsafe installation, or inaccessible appliance.\\n- Offer concepts with explicit assumptions when facts are incomplete. Do not call them order-ready or installation-ready.\\n- Do not move services, alter structures, purchase items, or overwrite an accepted design without explicit authorization. Draft alternatives should remain reversible.\\n\\n## 1. Collect the Brief and Survey\\n\\nAsk only for missing information that changes the next decision. Start with room dimensions/openings, fixed services, users, appliances, and budget. Collect remaining details progressively.\\n\\n| Input | Required information |\\n| --- | --- |\\n| Location and scope | Country, region, dwelling type, new build/remodel, ownership/landlord restrictions, required accessibility standard, retained items. |\\n| Room | Each wall length, ceiling/soffit heights, angles/diagonals, niches, columns, slopes, and finished floor levels. Measure irregular walls at relevant heights. |\\n| Openings | Door/window position, clear opening, frame/trim, sill height, opening direction and swept volume; curtains/blinds and window handles. |\\n| Services | Measured water/drain positions and heights, shutoffs, electrical points/circuits, gas, ventilation/exhaust routes, heating, meters, and service access. Mark relocation permission separately. |\\n| Structure | Wall construction/fixing capacity, floor/ceiling constraints, existing ventilation, room-air-dependent fireplace or combustion appliance, underfloor services. |\\n| People | Household size, number of simultaneous cooks, heights/elbow heights, handedness, reach/lifting ability, mobility aids, children, and future needs. |\\n| Activities | Shopping frequency, everyday meals, batch cooking, baking, coffee, entertaining, table setting, cleaning, waste sorting, and current annoyances. |\\n| Inventory | Counts and dimensions of dishes, pans, trays, containers, food, appliances, and waste bins; frequency and typical weight of use. |\\n| Products | Exact models or provisional envelopes, installation manuals, cabinet system, appliance niches, front/hinge system, handle projections, and worktop material. |\\n| Commercial | Total installed budget, service relocation allowance, delivery/access constraints, timing, and priorities ranked by the user. |\\n\\nFor each critical fact record `value`, `unit`, `source`, `verification_state`, and measurement uncertainty where known. Use `unknown`, `inferred`, `user_verified`, or `professionally_verified`. Preserve raw measurements and identify the finished reference surfaces.\\n\\nIf only a photo is supplied, request a measured plan or verified reference dimensions. Hidden pipe routes, wall strength, electrical capacity, and regulatory compliance cannot be inferred from appearance.\\n\\n## 2. Build the Constraint Register\\n\\nGive each rule a stable ID and classify it:\\n\\n| Class | Meaning | Handling |\\n| --- | --- | --- |\\n| `regulatory` | Verified applicable legal/code requirement, with jurisdiction and edition. | Hard; no user override. |\\n| `manufacturer` | Exact installation/compatibility requirement for the selected product. | Hard; change the product or design if necessary. |\\n| `site` | Verified room, structural, service, or geometric limitation. | Hard unless an approved change creates a new verified condition. |\\n| `user_must` | Explicit user requirement, including a fixed budget if stated. | Hard for this brief; ask before relaxing. |\\n| `recommendation` | Sourced ergonomic/design recommendation or labeled planning heuristic. | Soft; document the consequence of departures. |\\n| `preference` | Style, symmetry, convenience, or other discretionary choice. | Soft; trade off transparently. |\\n\\nEach record needs `id`, `class`, `applicability`, `requirement`, `measurement_definition`, `source`, `status`, `affected_items`, and `remedy_or_next_action`. Status is `pass`, `fail`, `unknown`, or `not_applicable`; explain exclusions. Preserve recommendation deviations rather than silently deleting them.\\n\\nComplete every category in the reference's installation checklist. Record applicability separately from compliance: an unconfirmed rule is not automatically irrelevant.\\n\\n## 3. Arrange Functional Zones\\n\\nUse five zones as an adjacency model, not a compulsory left-to-right sequence [S1, S2]:\\n\\n1. Food storage: refrigerator/freezer and dry provisions.\\n2. Preparation: the principal clear work surface and preparation tools.\\n3. Cooking: hob, oven, heat-safe landing surfaces, and cookware.\\n4. Cleaning: sink, dishwasher, waste sorting, and cleaning supplies.\\n5. Clean storage/serving: dishes, dining cutlery, glasses, and serving items.\\n\\nTrace these distinct workflows:\\n\\n- Shopping arrival -> grocery landing -> refrigerator/pantry.\\n- Food storage -> sink when needed -> preparation -> cooking -> serving.\\n- Table return -> scrape/sort -> sink as needed -> dishwasher. Do not prescribe routine pre-rinsing; follow appliance guidance.\\n- Dishwasher -> clean storage -> table/serving.\\n- Hob -> sink for draining hot cookware, without avoidable traffic crossings.\\n- Coffee/breakfast and snack access without walking through active cooking.\\n\\nKeep through-traffic outside the principal work area. The refrigerator-sink-hob triangle is a diagnostic, not a mandatory geometry or a substitute for these workflows. A one-wall kitchen can work without a triangle. Mixed-handed or multi-cook households need task trials, not automatic mirroring.\\n\\n### Placing the Kitchen in the Room\\n\\nWhen the user does not name a place for the kitchen, plan it so that the sink stands near a water connection of the plan, if the room has one. The installation elements of the plan context list the water connections with their positions.\\n\\n### Sink, Preparation Surface, and Hob\\n\\nPrefer `sink -> continuous preparation surface -> hob`, or the mirror image. Blum recommends approximately 900 mm of preparation width, with 800 mm as its lower ergonomic recommendation [S3]. These are not German legal minimums. More space may be needed for two cooks or extensive baking.\\n\\nMeasure usable clear surface between fixture edges, excluding an occupied drainer, permanent appliances, or other obstructions. Record actual usable depth too. Separately verify cut-out-to-cut-out webs, edge distances, and supports from the worktop fabricator; a visible surface gap does not prove structural suitability.\\n\\nAvoid placing a tall cabinet across this continuous workflow. Keep the preparation surface genuinely available after locating the kettle, coffee machine, knife storage, and drying area. Where the room cannot accommodate the recommendation, disclose the compromise and test an adjacent alternative preparation surface.\\n\\n### Dishwasher and Clean Storage\\n\\n- Start with the dishwasher beside the sink, subject to plumbing, appliance instructions, and usable access. Prefer a side outside the main preparation stance when feasible.\\n- Compare both sides of the sink. Do not prescribe left/right solely from handedness.\\n- Locate everyday dining cutlery, plates, and bowls in an adjacent or nearby accessible drawer bank. Locate daily glasses and cups within comfortable reach nearby [S4].\\n- Aim for a comfortable turn or short step during unloading. This is a qualitative target, not a universal distance limit.\\n- Check dishwasher fully open, racks extended, destination drawer open, and a person standing in the unloading position. Neither nominal adjacency nor cabinet-centre distance establishes usability.\\n- Across an aisle can work only if the actual door/drawer projections, standing space, reach, and circulation work together. Never require stepping over a dishwasher door.\\n- At an inside corner, check perpendicular drawer collisions and access to the sink/waste. Move the dishwasher or storage bank if fillers alone cannot solve the conflict.\\n- Keep dining/table access convenient without routing other people through the hot zone. Do not put every item beside the dishwasher: cooking tools still belong at their principal point of use.\\n- Consider a raised dishwasher for users who benefit, but validate approved support, niche, front mechanism, rack heights, and adjacent unloading space.\\n\\n## 4. Assign Contents Before Cabinet Sizes\\n\\nCreate the storage schedule first. Then fit catalog modules around the fixed zones.\\n\\n| Contents | Preferred home | Checks |\\n| --- | --- | --- |\\n| Dining cutlery | Shallow upper drawer near dishwasher and dish storage. | Organizer fits internally; accessible with dishwasher open. |\\n| Everyday plates/bowls | Full-extension drawer in the same or nearby bank. | Plate diameter, stack height, restraint, loaded runner capacity, comfortable lifting height. |\\n| Glasses/cups | Reachable nearby shelf, lift-front cabinet, or suitable drawer. | Safe reach, glass height, retention, opening clearance; not forced overhead. |\\n| Preparation knives/tools | Upper drawer at principal preparation surface. | Blade protection, child security, separation from dining cutlery. |\\n| Boards/trays | Vertical divider storage near preparation/oven. | Actual tray dimensions and removal path. |\\n| Pans/pots/lids | Full-extension storage beside or below hob where permitted. | Heat separation, hob underside, ventilation and extractor/oven volume. |\\n| Spices/oils | Near preparation/cooking, protected from heat/light/moisture. | Not directly exposed to hob heat or steam. |\\n| Mixing bowls, scales, baking tools | Preparation/baking zone. | Nesting, appliance weight, lifting distance, and usable drawer height. |\\n| Dry food | Pantry/pull-outs near grocery landing and preparation. | Stock volume, visibility, shelf adjustment, runner loads. |\\n| Waste/recycling | Accessible from preparation and sink. | Local sorting streams, bin removal, odours, and access while dishwasher is open. |\\n| Cleaning chemicals | Separate secure storage, often near sink. | No food/clean-utensil mixing; child access, plumbing and leak clearance. |\\n| Food containers/lids | Near preparation, leftovers packing, and dishwasher. | Paired or divided organization; capacity for actual inventory. |\\n| Small appliances | At use location or reachable storage. | Operating footprint, lid opening, steam, power, ventilation, weight. |\\n| Rarely used items | Less accessible but safe locations. | Do not put heavy objects overhead simply because they are infrequent. |\\n\\nPrefer full-extension drawers for frequently used base storage [S4, S5]. Upper shallow drawers suit small tools; deeper drawers suit bulky items, but choose heights from actual contents, not a fixed three-drawer formula. Prioritize heavy frequently used items at a comfortable lifting height rather than automatically on the lowest level.\\n\\nCompare wide drawer banks with multiple narrow cabinets using usable capacity, load, cost, and multi-user access. A wide open drawer can block another cook. Compare corner mechanisms with a deliberately unused corner plus accessible straight drawers; maximum gross volume is not necessarily best value.\\n\\nFor each cabinet record: `id`, `zone`, `catalog_id_or_provisional`, external dimensions, usable internal dimensions, contents, load, opening direction/extension, fittings, and reason for location. Include fillers, end panels, scribes, plinths, supports, and tolerances in each run. Never assume nominal width equals usable storage or appliance niche width.\\n\\n## 5. Generate and Check Alternatives\\n\\nDevelop two or three genuinely different feasible options when geometry permits, for example retained services versus improved workflow. Do not force an island or a U-layout into a room that cannot support it.\\n\\nFor each option:\\n\\n1. Place immovable constraints and reserve circulation/accessibility envelopes.\\n2. Locate sink, principal preparation area, hob/extraction, and refrigerator landing.\\n3. Fit dishwasher, waste, and nearby clean storage as a working group.\\n4. Allocate remaining storage and secondary tasks from the inventory.\\n5. Fit actual modules, fillers, worktops, panels, and service voids.\\n6. Check 3D fit, closed projections, full swept openings, service access, ventilation, and installation tolerances.\\n7. Run the task trials below. Repair hard failures before comparing soft preferences.\\n\\nRequired trials: unload a full dishwasher; prepare/cook a typical meal; drain a heavy pot; set/clear the table; put away groceries; remove waste; and let a second person reach drinks while cooking continues. Include the actual accessibility/child-use scenarios in the brief.\\n\\nCheck necessary simultaneous openings, especially dishwasher plus receiving drawer, refrigerator door plus internal drawer, sink/waste plus dishwasher, and perpendicular corner units. Not every door must open simultaneously, but the normal task combinations must work. Record remaining conflicts and their consequences.\\n\\nMeasure travel along collision-free walkable paths between usable standing positions, with task-specific openings represented. Do not measure straight through an island or across an open door. Without a geometry/path tool, use a clearly labeled manual estimate or `unknown`; do not fabricate precision.\\n\\n### Compare Everyday Effort\\n\\nUse lexicographic priorities: hard feasibility first, essential usability/storage second, daily effort third, then cost/style trade-offs within the agreed brief.\\n\\nFor a transparent optional distance estimate, calculate:\\n\\n`daily_travel_m = sum(task_cycles_per_day * sum(trip_count_per_leg * walkable_leg_length_m))`\\n\\nDefine each leg as a one-way movement. Include return legs explicitly where they occur. For unloading, use realistic batches carried per trip, not one trip per plate and not an implausibly heavy stack. Use the same inventory, carry capacity, and task frequencies for every option. Label assumed frequencies and distances.\\n\\nReport bending/high reaching, awkward lifts, door conflicts, and traffic crossings separately; do not add metres, counts, and money without explicit normalization and user-agreed weights. Never label a heuristic score a certified optimum or claim percentage savings without a baseline calculation.\\n\\n## 6. Deliver the Plan\\n\\nReturn a concise recommendation followed by:\\n\\n1. Brief, assumptions, missing measurements, and readiness status.\\n2. Dimensioned layout, orientation, appliance locations, and clear work surfaces. If no drawing tool exists, supply wall-by-wall cabinet sequences with dimensions, not an invented rendered plan.\\n3. Cabinet/drawer schedule specifying exactly what goes where.\\n4. Dishwasher-unloading explanation: standing position, receiving drawers/cup storage, openings, paths, and compromises.\\n5. Alternatives table: hard failures/unknowns, preparation space, usable storage, travel estimate, ergonomics, installed cost confidence, and trade-offs.\\n6. Constraint report with rule IDs, measurement definitions, evidence, pass/fail/unknown, and remedies.\\n7. Action list assigning survey, electrical, plumbing, ventilation, structural, accessibility, and installation checks to the appropriate reviewer.\\n\\nUse the status `concept`, `dimensionally_checked`, or `ready_for_professional_order_review`. The last status requires verified survey, exact product compatibility, complete parts/cost scope, and no unresolved hard constraint. It is not professional installation approval. When required reviewers approve, record who approved what and against which plan/manual revisions before any separate order authorization.\\n\\nIf no feasible layout exists, identify the conflicting constraints and smallest changes to consider, such as reducing an island, changing an appliance, or obtaining approval to relocate services. Never silently shrink a required clearance or alter a user must-have.\\n\\n## Quality Checks for This Skill\\n\\nBefore delivering a plan, verify these counterexamples are handled correctly:\\n\\n- Sink beside hob: report preparation-space and installation checks, not an invented EU prohibition.\\n- Dish drawer close to dishwasher but behind its open door: reject the unloading arrangement despite the short nominal distance.\\n- Short route through an island: replace it with a walkable route or mark distance unknown.\\n- Attractive layout with unknown hood clearance: keep installation readiness blocked.\\n- Single-wall or mixed-handed kitchen: use task-based zoning without forcing a triangle or handedness rule.\\n- Wheelchair brief: invoke applicable accessibility checks and user trials; a generic aisle recommendation is insufficient.\\n- Best geometric score but insufficient plate storage or overloaded drawers: do not recommend until capacity/load are resolved.\\n\"","export default \"# Kitchen Planning Evidence and Constraints\\n\\nResearch checked: 2026-10-09. Scope: residential kitchens, Germany/EU default. This is an original synthesis of public guidance, not a reproduction of a standard, a legal opinion, or an installation specification.\\n\\n## Evidence Boundaries\\n\\nAMK, Blum, and IKEA offer useful planning guidance; their editorial advice is not law. Product marketing is not proof of compatibility or universal ergonomic superiority. A named standard is mandatory only where applicable through law, contract, or the project brief; establish that applicability with qualified reviewers.\\n\\nShort source IDs refer to the optional [source catalog](./source-catalog.md), which holds URLs, publication details, and research notes. Do not load it for routine planning; consult it only for source verification, provenance/citation questions, or guidance updates. Rule classifications and operational qualifications remain in this reference.\\n\\nThe full DIN standard and project-specific appliance installation manuals were not examined. Numerical clearance requirements for a real product therefore remain to be supplied. Verify current applicable requirements and exact product instructions for each project; the research date does not establish a document's technical currency.\\n\\nSome general advice is too absolute to reuse literally. For example, induction surfaces can remain hot from cookware, lift-up doors still need head/ceiling/reach checks, and handedness does not determine a whole household's best layout. Apply task and product checks rather than repeating marketing assurances.\\n\\n## Dimensions and How to Use Them\\n\\nAll dimensions below are in mm. Label the rule class and source whenever presenting them to a customer.\\n\\n| Topic | Starting guidance | Status and measurement |\\n| --- | --- | --- |\\n| Main preparation width | Approximately 900; Blum advises at least 800 for comfortable preparation. | Published ergonomic recommendation [S3], not a statutory minimum. Clear usable work surface, preferably between sink and hob; not centre-to-centre distance. |\\n| Single-cook working aisle | Explore roughly 1000-1200 initially. | This skill's concept-sizing heuristic, not a sourced legal minimum. Measure the narrowest gap between finished closed projections, then test open appliances and the user. |\\n| Shared working aisle | Explore roughly 1200-1500 initially. | Concept-sizing heuristic only. Simultaneous work, carry tasks, and passage can need more; extra width also lengthens transfers. |\\n| Standing preparation height | Start near measured elbow height minus 150. | AMK recommendation [S1]; test in usual footwear with a mock-up. Sink depth and cookware change effective task height. No universal 900-high worktop. |\\n| Accessible kitchen movement space | The DIN 18040-2 secondary summary describes 1200 x 1200, and 1500 x 1500 for wheelchair use; front clearance depths of 1200 and 1500 respectively. | [S7] is a secondary explanation, not the standard itself. Confirm current applicable provisions, including the wheelchair-specific category, and all other access requirements. These are not universal minimum kitchen dimensions. |\\n| Dishwasher to dish storage | Comfortable turn or short step where feasible. | Adjacency principle [S4]; no universal maximum distance established by this research. Open-state usability determines success. |\\n| Hob/oven/fridge landing | Reserve usable nearby surface sized for the actual pan, tray, or grocery load. | Functional planning recommendation. Do not invent a universal legal landing width. The hot-tray route must be safe with the appliance door open. |\\n| Hood, hob, combustible surfaces | Use exact product and applicable local requirements. | No generic numeric default. Check all applicable instructions; resolving a conflict may require changing products. |\\n| Cut-out webs, overhangs, supports | Use material/fabricator specifications. | No generic numeric default; material, thickness, cut-outs, support and installation details matter. |\\n| Drawers, fronts, fillers, service voids | Use selected cabinet/appliance system drawings. | Catalog-specific; never insert an arbitrary filler and assume collision/installation issues are resolved. |\\n\\nA concept aisle width is not the free width remaining during use. For an illustrative opposing arrangement only, a 1200 aisle minus a 600 dishwasher-door projection minus a 500 drawer projection leaves just 100 between the open fronts. That is not adequate standing space between them. Real doors, racks, handles, body envelopes, and sideways access require actual drawings and task simulation. The numbers here are hypothetical, not product specifications.\\n\\n## Installation and Usability Checklist\\n\\nUse the IDs below in the project's constraint register. These are check categories: obtain evidence to establish the exact hard requirement or recommendation for each project. Mark unknowns explicitly.\\n\\n| ID | Check | Evidence or required outcome |\\n| --- | --- | --- |\\n| GEO-01 | Verified geometry | Finished dimensions, out-of-square walls, slopes, trims, levels, and measurement tolerance are represented. No fit claim based only on photos. |\\n| GEO-02 | Circulation and exit | Doors, clear passages, room access and applicable escape requirements remain usable. Assess appliance-open task states and occupants. |\\n| GEO-03 | Collision volumes | Check full door/drawer travel, handles, lift fronts, internal pull-outs, adjacent fronts, and head clearance. Closed-box collision tests are insufficient. |\\n| GEO-04 | Windows and heat | Tap does not prevent required window operation. Window/blind/curtain position, hob heat, drafts, splash exposure and required access are reviewed. |\\n| GEO-05 | Seating and island | Account for occupied seats, pulled-out chairs, knee space, passage and hot/splash zones. Do not double-count the same area for incompatible simultaneous uses. |\\n| FIT-01 | Cabinet run and niches | Include end panels, corner solutions, fillers, scribes, wall tolerances and actual appliance niches, not just nominal cabinet widths. |\\n| FIT-02 | Front and plinth systems | Integrated dishwasher front weight/height, fixed or sliding hinge, plinth sweep, mounting and countertop protection match the exact model. |\\n| FIT-03 | Refrigerator operation | Required opening angle permits internal drawers/shelves to operate and be removed; wall stand-off, hinges and ventilation are correct. |\\n| FIT-04 | Hob underside and extraction | Body, induction cooling, required separation, cables, downdraft motor/duct/filter and drawers do not compete for the same volume. |\\n| FIT-05 | Oven and microwave | Approved niche, ventilation, door travel and shelf reach; hot vessels can be removed safely to a landing surface. A high oven must not require lifting hot trays above the user's safe reach. |\\n| FIT-06 | Raised appliances | Support structure, fixing, manufacturer approval and reachable controls/racks are verified. Do not put a floor-supported appliance on an improvised shelf. |\\n| WAT-01 | Sink assembly | Bowl, drainer, clips, tap, waste, trap, hoses, drawers and bins fit together; servicing remains possible. |\\n| WAT-02 | Water and drainage | Qualified installer verifies supplies, pressure, hot-water compatibility, drainage route/levels, appliance hose limits and required backflow protection. Proximity alone proves none of these. |\\n| WAT-03 | Shutoff and leak access | Isolation, connections and leak-protection equipment remain accessible as required; no pinched hoses or inaccessible maintenance points. |\\n| WAT-04 | Special water equipment | Boiling/chilled/carbonated/filter systems have approved taps, tank/filter/cylinder space, ventilation, power, maintenance and child protection. |\\n| ELE-01 | Electrical design | Qualified electrician verifies available supply, connected loads, circuits, protective devices, earthing, isolation and socket installation under applicable rules. |\\n| ELE-02 | Socket and cable placement | Plan for all fixed and small appliances, lighting and powered fittings. Keep cords out of wet/hot areas and across no circulation route; verify plugs do not consume a prohibited niche/service volume. |\\n| ELE-03 | No invented wet-area rule | Do not transpose bathroom electrical zones into a kitchen or assert a blanket socket-to-sink distance without an applicable source. Obtain the electrician's project-specific layout. |\\n| GAS-01 | Gas equipment | Approved professional checks supply, isolation, installation, ventilation and appliance-specific combustible clearances. No DIY connection instructions. |\\n| VEN-01 | Extraction choice | Establish exhaust or recirculation early. Check hood capture at the actual hob, installed airflow, noise, filter access, duct dimensions, bends, outlet and replacement-air strategy. |\\n| VEN-02 | Recirculation limits | Recirculation normally does not remove cooking moisture outdoors and is not a substitute for necessary room ventilation. Check system-specific requirements. |\\n| VEN-03 | Combustion interaction | Exhaust plus a room-air-dependent fireplace/heater triggers professional pressure/backdraft review with the responsible chimney sweep and ventilation specialist. Do not assume a window switch alone makes the system safe. |\\n| VEN-04 | Building permissions | Check landlord/owners' association approvals, facade penetrations, fire separations, communal shafts and whole-dwelling ventilation interactions. |\\n| TOP-01 | Worktop structure | Fabricator verifies cut-out spacing, edge webs, joint locations, supports, spans, overhangs, thermal limits and installation method. |\\n| TOP-02 | Water and steam protection | Seal/protect cut-outs, joints, sink area and dishwasher edges as specified; account for automatic-opening dishwasher steam. |\\n| STR-01 | Fixings and stability | Suitable wall fixings, rails, suspended loads, tall-unit restraint, island support and loaded drawers. Check floor/underfloor services before drilling. |\\n| STR-02 | Structural alterations | No wall removal or structural drilling assumption without qualified assessment and required permissions. |\\n| USE-01 | Preparation and landings | Real unobstructed preparation and grocery/hot-vessel landing space remains after permanent countertop items are placed. |\\n| USE-02 | Unloading | Dishwasher, rack, receiving storage and user can occupy needed positions together; no stepping over the door or excessive reaching. |\\n| USE-03 | Waste and hygiene | Scrape/sort/load route works; bins can be removed and cleaned. Separate chemicals from food/clean items; provide cleanable food-contact surfaces and drying space. |\\n| USE-04 | Storage capacity and loads | Actual inventory fits internally with chosen organizers and runner ratings. Record spare capacity if requested; do not invent a mandatory percentage. |\\n| USE-05 | Multi-user tasks | Test concurrent cooking, dish handling, drinks access and table setting; identify crossings and bottlenecks. |\\n| ACC-01 | Accessibility | Confirm required standard/category; check turning and approach spaces, knee/toe clearance, seated reach, controls, grip/force, task height and protected hot pipes. Test with the actual user/mobility aid. |\\n| SAFE-01 | Children and burns | Secure knives/chemicals, review reachable controls and hot-water dispensing, prevent pot-handle exposure to traffic/seating. Induction still has residual heat; child locks do not replace supervision. |\\n| SAFE-02 | Flooring and edges | Review slip/trip risk, thresholds, protrusions, sharp corners and cleanability. Do not let loose mats create an access hazard. |\\n| LGT-01 | Lighting | Illuminate preparation, sink and hob without the user casting a working shadow. Check glare, contrast, controls and usable light beneath cabinets; lighting drivers remain serviceable. |\\n| ENV-01 | Comfort and maintenance | Compare actual appliance noise, energy/water data, extractor filter costs, cleanability, material heat/moisture resistance and repairability. Verify current product labels. |\\n| SRV-01 | Replacement access | Appliances can be isolated, removed and replaced after flooring/worktops are installed; filters, traps, drivers and fixings can be serviced. |\\n| ORD-01 | Complete order scope | Include appliances, cabinets, fronts, hinges, runners, handles, fillers, panels, plinths, feet, rails, supports, worktops, cut-outs, lighting, extraction, fittings, delivery, installation and service work. |\\n| ORD-02 | Release gate | Final survey, product/manual revisions, costs, permissions and responsible professional checks match the exact proposed order. Obtain explicit order authorization. |\\n\\n## Worked Arrangement: Pattern, Not Template\\n\\nAn illustrative working run can be:\\n\\n`[dish/cutlery drawers] [dishwasher] [sink] [prep drawers + clear worktop] [hob/cookware]`\\n\\nDaily cups/glasses can occupy comfortably reachable storage above the dish bank or another nearby accessible location. Waste can be under the sink or in a separate nearby pull-out if loading, preparation and bin removal all work. Do not consume the only preparation drawer space without a replacement.\\n\\nThis pattern places clean storage on one side of cleanup and preparation on the other. It is neither a complete kitchen nor a mandatory sequence: refrigerator/pantry, oven, landing surfaces, end conditions and services must still be located. Mirror or split the run when the room and users benefit. A hob at the run's exposed end still needs its verified clearances and usable landing arrangement.\\n\\nFor an L-layout, a drawer around the corner from the dishwasher may be physically close but impossible to open during unloading. For a galley, opposing dish drawers may work or may block the user's standing position. The decisive check is the open-state task, not the diagram's apparent neatness.\\n\\n### Transparent Travel Example\\n\\nSuppose two otherwise feasible options each need four storage transfers per dishwasher cycle. Assume three return legs to the dishwasher before the final transfer, one cycle daily, and equal one-way path lengths in either direction:\\n\\n- Option A: 1.0 m per leg -> `(4 + 3) * 1.0 = 7.0 m` per cycle.\\n- Option B: 2.5 m per leg -> `(4 + 3) * 2.5 = 17.5 m` per cycle.\\n- Difference: 10.5 m per cycle under these assumptions, excluding any final return and other kitchen tasks.\\n\\nThese are illustrative distances and batch counts, not research results. Do not extrapolate time or lifetime savings without measurements. A comfortable turn may produce almost no walking but still involve awkward reaching; report that separately. An option with an obstructed unloading path is infeasible regardless of its calculated distance.\\n\\n## Maintenance and Unverified Requirements\\n\\nThe checklist is deliberately broad but not exhaustive. Actual regulatory requirements, permitted clearances, and compatibility depend on the site, products and users. Obtain the current applicable primary sources, exact installation manuals and qualified reviews before converting any unresolved checklist item into a pass.\\n\\nRevisit this reference when products, material systems, regulations or source guidance change. Keep the general workflow vendor-neutral; replace examples with the project's authorized catalog without losing the open-door, capacity, accessibility and safety checks.\\n\"","export default \"# Kitchen Planning Source Catalog\\n\\nOptional research reference. Load only to verify a source-backed claim, answer a provenance/citation question, or update the guidance. Routine planning does not require this file; the rules, classifications, and operational qualifications are in the skill and [planning reference](./planning-reference.md).\\n\\nResearch checked: 2026-10-09. Scope: residential kitchens, Germany/EU default. The sources below were retrieved for the stated topics. The full DIN standard, paid NKBA handbook, and project-specific appliance installation manuals were not examined. The retrieval date does not establish technical currency; verify current applicable requirements and exact product instructions for each real project.\\n\\n## Sources\\n\\n### S1. AMK: Planen und gestalten\\n\\nhttps://www.amk-ratgeber-kueche.de/kueche/planen-gestalten\\n\\nGerman kitchen-industry association guidance. Supports functional zones, point-of-use storage, approximately 150 mm elbow-to-worktop difference, individualized working heights, full-extension drawers, early service planning, lighting and accessibility considerations. This is consumer guidance, not a regulation or a complete technical standard. Do not adopt every safety/marketing statement literally; see the evidence boundaries in the planning reference.\\n\\n### S2. IKEA Germany: Gestaltungsideen fuer reibungslose Ablaeufe\\n\\nhttps://www.ikea.com/de/de/rooms/kitchen/how-to/kueche-effizient-planen-pub6d21e890/\\n\\nSupports generous preparation space between sink and hob, proximity of waste and dishwasher, and placing cookware/tools at their point of use. Uses the work triangle as a general planning aid. Does not establish a statutory sink-to-hob distance.\\n\\n### S3. Blum: Speisenvorbereitung leicht gemacht\\n\\nhttps://www.blum-inspirations.com/de-eu/wissen/speisenvorbereitung-leicht-gemacht-der-passende-schrank-unterstuetzt-sie-dabei\\n\\nManufacturer ergonomic guidance, article dated March 2022. Recommends a preparation area between sink and hob, approximately 900 mm wide, and advises at least 800 mm; preparation tools and bowls belong nearby in organized drawers. These dimensions are ergonomic recommendations, not proof of product clearance or German code compliance.\\n\\n### S4. Blum: Geschirr perfekt organisiert\\n\\nhttps://www.blum-inspirations.com/de-eu/wissen/geschirr-perfekt-organisiert-im-unterschrank-mit-auszuegen\\n\\nManufacturer guidance, article dated June 2022. Supports dining cutlery and dishes together in full-extension base storage, nearby cups/glasses, and proximity to the dishwasher to reduce unloading travel. It does not supply a universal maximum distance or guarantee collision-free access.\\n\\n### S5. Blum: Die ergonomische Kueche\\n\\nhttps://www.blum-inspirations.com/de-eu/wissen/die-ergonomische-kueche-das-muss-man-beachten\\n\\nManufacturer guidance, article dated July 2021. Explains access benefits of full-extension base drawers and overhead lift fronts versus projecting doors. Benefits still depend on actual reach, opening height, operating force and room geometry; powered fittings are optional, not necessary for every accessible kitchen.\\n\\n### S6. AMK: Geraetetechnik\\n\\nhttps://www.amk-ratgeber-kueche.de/kueche/geraetetechnik\\n\\nSupports early extraction planning, the importance of capture efficiency, storage consumed by downdraft equipment, and appliance feature/energy/noise considerations. Room-volume airflow rules of thumb alone do not constitute a ventilation design. The combustion-safety checklist in the planning reference is a professional-review trigger, not a quoted clearance rule from this page.\\n\\n### S7. nullbarriere.de: DIN 18040-2 Kuechen, Essplatz\\n\\nhttps://nullbarriere.de/din18040-2-kuechen.htm\\n\\nSpecialist secondary summary of German dwelling accessibility guidance. Describes 1200/1500 movement-space dimensions and wheelchair considerations. It is not the official DIN text. Verify the current standard, project category, legal/contractual applicability and complete requirements before claiming conformity.\\n\\n### S8. IKEA Germany: Kuechenplanung\\n\\nhttps://www.ikea.com/de/de/rooms/kitchen/kuechenplanung-pub6003162f/\\n\\nSupports surveying in mm, marking openings/services, and staged planning, checking, ordering and installation. Links to current system-specific planning and installation documents. Those documents and the chosen product manuals must be obtained for a real order.\\n\\n### S9. IKEA Germany: Schubladen organisieren\\n\\nhttps://www.ikea.com/de/de/rooms/kitchen/how-to/kuechenschraenke-und-schubladen-organisieren-8-ideen-die-zeit-und-platz-sparen-pube8ed7a50/\\n\\nSupports full-extension storage, functional grouping, protected knives, organizers and reachable everyday contents. Named fittings are examples, not a recommendation to adopt one vendor.\\n\\n### S10. NKBA Planning Guidelines: Regional Boundary\\n\\nhttps://nkba.org/planning-guidelines/\\n\\nThe public overview describes guidance intended for US/Canadian design practice and its code context. Only the overview was consulted, not the paid handbook. Do not label NKBA dimensions as German/EU requirements or cite handbook clauses not actually verified.\\n\"","export default \"---\\nname: kitchen-planning-fr\\ndescription: \\\"Plan or review a residential kitchen in France, from the measured brief to a proposal for professional order review. Use for French kitchen layouts, cuisine amenagee or equipee, NF C 15-100 planning checks, VMC and hood coordination, copropriete renovation constraints, furnished-rental equipment, sink/preparation/hob placement, dishwasher unloading, and cabinet or drawer allocation. France-first, metric guidance that distinguishes applicable requirements from ergonomic recommendations and household preferences. Not installation certification or a commercial-kitchen design standard.\\\"\\n---\\n\\n# Kitchen Planning for France\\n\\n## Purpose and scope\\n\\nProduce a usable, measurable residential kitchen proposal for a project in France. Default to millimetres and EUR; confirm territory, budget basis, building type, tenure, and work scope before applying requirements. Respond in the user's language; keep French trade terms when they improve coordination.\\n\\nThis is a self-contained specialization of the workspace kitchen-planning approach. It does not require loading the Germany/EU skill. Use [the planning reference](references/planning-reference.md) for detailed checks, evidence qualifications, and worked examples.\\n\\nThe [source catalog](references/source-catalog.md) is optional. Load it only to verify a claim, provide citations, or update guidance. Do not load the bibliography merely to resolve source IDs: operational qualifications are already in this skill and the planning reference.\\n\\n## What is specifically French?\\n\\nThere is no single \\\"normal European kitchen\\\" or uniform French kitchen style. French-market layout guidance uses the same preparation, cleaning, cooking, and point-of-use storage principles as other European guidance (FR-S5).\\n\\n| Planning topic | France-specific adaptation |\\n| --- | --- |\\n| Electrical installation | Establish the applicable NF C 15-100 edition and work scope; distinguish ordinary kitchen sockets from specialized appliance circuits. |\\n| Ventilation | Identify the actual natural ventilation or VMC system, collective or individual, before choosing a hood or moving a cooking zone. |\\n| Renovation authority | Ask about copropriete, landlord consent, common services, structure, and exterior alterations; do not treat a kitchen seller's drawing as permission. |\\n| Rental brief | Distinguish owner occupation, location nue, furnished principal-residence lease, and tourist accommodation; their equipment and legal scopes are not interchangeable. |\\n| Accessibility | Determine applicable French housing provisions and user needs. Do not relabel German DIN dimensions as French compliance. |\\n| Procurement | Resolve cuisine amenagee/equipee labels into an itemized equipment and works schedule, a devis, and an installed TTC budget. |\\n| Lifestyle | Ask about actual cooking, meals, pantry and serving needs. Gas, wine storage, an island, rustic fronts, and elaborate cooking are not national requirements. |\\n\\nThese topics are not all unique to France; their governing documents, terminology, and project decisions are localized here.\\n\\n## Authority and evidence\\n\\n- Classify constraints as `regulatory`, `manufacturer`, `site`, `user_must`, `recommendation`, or `preference`.\\n- The first four are hard constraints when applicable. Recommendations and preferences are soft and may be traded off explicitly.\\n- A published standard is not automatically a universal retroactive legal obligation. Establish the applicable regulation, standard edition, contract, project dates, and scope with the responsible professional.\\n- A manufacturer summary is not the full standard. A product-specific installation requirement is different from that manufacturer's general planning advice.\\n- Never convert an unknown to a pass. If requirements conflict, stop the affected decision and obtain clarification; do not select the convenient rule.\\n- Photographs, scans, inferred dimensions, catalog nominal widths, and AI drawings do not replace a site survey or exact product documentation.\\n- The planner's geometry, catalog, prices, and accepted design remain authoritative. Propose reversible edits and obtain acceptance before changing the design.\\n- Do not claim electrical, gas, structural, ventilation, accessibility, rental, or installation certification. Do not authorize purchases or works.\\n\\n## Workflow\\n\\n### 1. Establish the French project brief\\n\\nCollect only the missing facts needed for the next decision; allow assumptions for concepts, clearly marked.\\n\\n- Commune and territory: metropolitan France or the relevant overseas territory; do not silently apply metropolitan rules overseas.\\n- Apartment or house, approximate construction date, new build or existing dwelling, occupied or vacant during works.\\n- Owner or tenant; copropriete and syndic contact where relevant; private versus shared walls, ducts and service risers.\\n- Cosmetic replacement, partial technical renovation, complete electrical renovation, kitchen relocation, or structural alteration; project and permit/contract dates if relevant.\\n- Owner occupation, location nue, location meublee as a principal residence, bail mobilite, or tourist/secondary-residence use.\\n- Household size, simultaneous cooks, children, reach and mobility needs, wheelchair or seated work, and any applicable accessibility brief.\\n- Cooking frequency, appliance inventory, shopping/storage quantities, dining location, entertaining, and cleaning habits.\\n- Total installed budget in EUR TTC, retained items, time constraints, and responsibility for each trade.\\n\\nAsk whether the household needs a table/coin repas, separate dining area, cellier, baking area, coffee station, large serving dishes, or bottle storage. Derive dimensions from their inventory and routines, not nationality.\\n\\n### 2. Survey the room and services\\n\\nRecord wall lengths at relevant heights, diagonals, finished floor levels, ceiling height, wall build-ups, out-of-square corners, windows and opening arcs, doors, radiators, obstructions, and structural uncertainty.\\n\\nLocate water, waste, isolation valves, electrical outlets and known circuit identities, gas if present, ventilation terminals, air inlets, ducts, and service access. Record delivery access, stairs, lift restrictions, and worktop handling constraints.\\n\\nFor each fact capture `value`, `unit`, `source`, `verification_state`, and measurement uncertainty. Use `unknown`, `inferred`, `user_verified`, or `professionally_verified`. Measure service positions from a declared datum and finished floor; do not infer concealed routes from visible endpoints.\\n\\n### 3. Build the constraint register\\n\\nEach record needs:\\n\\n```text\\nid\\nclass\\napplicability\\nrequirement\\nmeasurement_definition\\nsource\\nstatus: pass | fail | unknown | not_applicable\\naffected_items\\nremedy_or_next_action\\n```\\n\\nRun the French context checks in the reference before freezing a layout. Identify the person responsible for resolving each technical unknown.\\n\\n- Electrical: confirm applicable edition and renovation scope with an electrician; reserve ordinary outlets separately from appliance connections. Socket count alone cannot establish compliance.\\n- Ventilation: a hood does not replace general dwelling ventilation (FR-S3). Preserve air inlets, transfer paths and extraction terminals. A visible communal shaft is not an approved powered-hood connection.\\n- Permissions: flag changes affecting shared services, structure, exterior outlets, or rented premises for the relevant professional, landlord, syndic, and authority checks before works.\\n- Rental: for a furnished principal-residence lease, check the scoped equipment list in the reference (FR-S4). Do not apply it to every kitchen or treat it as a complete rental-compliance assessment.\\n- Accessibility: establish applicable French requirements separately from ergonomic targets; unresolved legal applicability blocks a compliance claim, not an explicitly provisional concept.\\n\\n### 4. Arrange five functional zones\\n\\nMap food storage, preparation, cooking, cleaning, and clean storage/serving to real tasks. Prefer sink -> clear preparation surface -> hob, or its mirror, where the room allows it.\\n\\nProvide a continuous useful preparation area, not a nominal length occupied by a drainer, appliance, corner, or landing zone. As an ergonomic starting point, aim for about 900 mm clear width; around 800 mm is a lower recommendation from manufacturer planning guidance, not a French statutory minimum (FR-S6). Check actual tasks and product cutout/edge requirements separately.\\n\\nDo not invent a universal French 600 mm sink-to-hob prohibition. Assess splashing, heat, pan handles, worktop bridges, adjacent materials, and exact product requirements. A compact compliant layout can still have poor preparation space.\\n\\nKeep grocery-to-fridge, washing-to-preparation, cooking-to-serving, and dirty-dish routes short and unobstructed. A triangle is an optional analytical aid, not a rule; a linear kitchen can work well. Separate through-traffic from hot work where feasible.\\n\\nWhen the user does not name a place for the kitchen, plan it so that the sink stands near a water connection of the plan, if the room has one. The installation elements of the plan context list the water connections with their positions.\\n\\n### 5. Design dishwasher unloading and storage together\\n\\nStart with the dishwasher near the sink, subject to verified connection limits and usable access. Decide which side by actual unloading and loading tests, not handedness alone.\\n\\nTest all of these together: dishwasher door open, racks extended, receiving drawer or cupboard open, and a person standing and turning. Do not make the user step over the door or balance dishes while opening storage.\\n\\nPut everyday plates, bowls and dining cutlery close to a safe unloading position and the serving route. Put cooking utensils, pans and preparation tools near their use. Check that the shortest storage route remains accessible with doors open. A slightly longer unobstructed route can be better than blocked adjacent storage.\\n\\n### 6. Allocate cabinets and drawers by contents\\n\\nCreate a schedule with cabinet ID, location, contents, quantities, largest item size, usable internal dimensions, load limit, opening mechanism, access frequency, and service conflicts.\\n\\n- Use accessible drawers or pull-outs for frequently handled base storage where appropriate; check heavy dish stacks and hardware loads (FR-S7).\\n- Separate dining cutlery from cooking utensils. Give pans, lids, boards and trays usable storage near preparation/cooking.\\n- Size pantry storage to shopping habits; a cellier supplements but does not automatically replace daily point-of-use storage.\\n- Provide safe storage for knives and cleaning products, and a waste-sorting arrangement matching local collection and the household's carrying route.\\n- Keep shutoffs, traps, filters and appliance removal paths accessible. Under-sink space is not an empty rectangular cabinet volume.\\n- Use exact cabinet/appliance combinations: nominal 600 mm widths do not prove integration, ventilation, hinge, front, plinth or worktop compatibility.\\n\\n### 7. Compare feasible alternatives\\n\\nNormally compare two plausible layouts, such as a service-preserving option and a user-priority option. Include an island only if occupied circulation, services, budget and work surfaces support it.\\n\\nTest grocery unloading, preparing a meal, draining a hot pan, dishwasher loading/unloading, serving, waste removal, and two people sharing the room. Include chairs pulled out, doors and drawers open, and a person at the oven. Test task lighting, glare, extraction noise and sightlines for an open kitchen.\\n\\nUse 1000-1200 mm single-cook and 1200-1500 mm shared working aisles only as concept heuristics between the nearest closed projections, not French legal or wheelchair clearances. Then test actual open-state and occupied clearances; apply verified project requirements instead where stricter.\\n\\nFor repeated tasks, estimate:\\n\\n```text\\ndaily_travel_m = sum(task_cycles_per_day *\\n sum(trip_count_per_leg * walkable_leg_length_m))\\n```\\n\\nCount return trips explicitly. State assumptions; compare bending, awkward reaches, handling and collision risks separately. Do not present this proxy as a validated human-performance score.\\n\\n### 8. Resolve the devis and installation boundaries\\n\\nTranslate cuisine amenagee/equipee into explicit inclusions, never assumed legal definitions. List meubles, facades, fileurs, joues, plinthes, plan de travail, credence, evier, robinetterie, electromenager, and fittings as applicable.\\n\\nSeparate supply, delivery, carrying, removal/disposal, preparation works, plumbing, electrical/gas work, ventilation, fitting, worktop templating/cutouts, finishing, testing and handover. Record exclusions, tax basis, quote validity, allowances and who owns final measurements. Do not promise a reduced VAT rate or a fixed total without a verified quote.\\n\\nAsk the cuisiniste and trades to resolve interfaces before final ordering: sockets behind drawers, sink/trap versus bin, dishwasher front versus plinth, duct versus wall unit, and opening clearances versus fileurs are common coordination risks.\\n\\n### 9. Deliver and gate readiness\\n\\nProvide the brief and assumptions, dimensioned plan with opening envelopes, zone/task rationale, cabinet contents schedule, appliance/service schedule, constraint register, alternatives and trade-offs, installed-cost scope, and professional questions/next actions.\\n\\nUse one readiness status:\\n\\n- `concept`: assumptions or unresolved geometry/services remain; no order-ready implication.\\n- `dimensionally_checked`: stated geometry and operating envelopes checked against identified measurements and product data; list unresolved regulatory/technical matters separately.\\n- `ready_for_professional_order_review`: required survey, exact product compatibility, service feasibility, applicable permissions, and hard constraints have supporting evidence with no unresolved failures or unknowns. This still requires professional order review and is not installation approval or purchasing authorization.\\n\\nNever call a proposal \\\"French-compliant\\\" solely because it follows this skill.\\n\"","export default \"# France Kitchen Planning Reference\\n\\nOperational reference for [kitchen-planning-fr](../SKILL.md). Source IDs support traceability without requiring bibliography loading. Open the [optional source catalog](source-catalog.md) only for verification, citations or maintenance.\\n\\n## Evidence boundaries\\n\\nResearch reviewed on 2026-10-09. These are planning checks, not a complete French legal or installation specification. Refresh time-sensitive claims for the actual project. Full NF C 15-100 text, current project-specific accessibility provisions, and product-specific manuals were not inspected in this research.\\n\\nFrench-market planning guidance supports familiar workflow principles, not a separate national geometry (FR-S5). Do not infer household habits, a required style, or a gas preference from the country. Imported appliances and retained furniture need exact compatibility checks, not assumptions based on EU marketing.\\n\\n## French technical and project gates\\n\\n### Electrical scope and layout reservation\\n\\nLegrand's professional guide describes the NF C 15-100 series for new or entirely renovated low-voltage installations in France. It reports the 2024 revision, publication on 2024-08-23, and a 12-month overlap with the previous edition ending 2025-08-23; project reference dates include the contract, permit application or prior declaration (FR-S1). Schneider independently confirms a 2024 revision (FR-S2). These summaries do not determine a particular project's legal or contractual obligations.\\n\\nAsk the electrician to identify the applicable edition, reference date, affected circuits, work scope, protection and testing requirements. Do not assert that replacing cabinets, selling a dwelling, or changing one appliance automatically requires complete rewiring. Conversely, do not use \\\"existing installation\\\" as an exemption from addressing identified hazards or new-work requirements.\\n\\nUse these source-qualified reservations, not automatic compliance tests:\\n\\n| Situation | Reservation and qualification |\\n| --- | --- |\\n| Kitchen clearly greater than 4 m2 | Legrand reports at least six ordinary sockets on a dedicated kitchen circuit, including four above the worktop. Identify appliance connections separately (FR-S1). |\\n| Kitchen clearly less than 4 m2 | Legrand reports at least three ordinary sockets. Confirm applicable exception and placement with the electrician; reduced count is not proof of functional adequacy (FR-S1). |\\n| Exactly 4 m2, uncertain measurement, or open kitchen | The inspected web summary uses less-than/greater-than wording without resolving equality or area definition. Reserve six provisionally and keep applicability unknown until the electrician verifies the full rule. Do not encode a legal threshold from this ambiguity. |\\n| Hood outlet | Legrand describes an optional additional hood outlet at least 1800 mm above finished floor. This is an outlet position, NOT the hood-to-hob installation clearance (FR-S1). Confirm exact permitted position and product instructions. |\\n| Hob, oven, dishwasher and other substantial appliances | Record each model, rated load, connection method, required specialized circuit and isolation access. Have the electrician size and verify the installation. Ordinary socket count is not an appliance-circuit allowance. |\\n| Appliance operation | Verify available supply and simultaneous loads, including retained appliances. Do not assume an existing socket or adapter makes an imported appliance suitable. |\\n\\nAs a conservative planning rule, keep ordinary sockets and trailing leads away from sink and cooking surfaces and do not propose ordinary sockets directly above them. Have the electrician verify exact restrictions and hood exceptions against the applicable standard; this research did not independently verify the full placement clause. Do not import bathroom electrical volumes around a kitchen sink or assert an unsupported universal 600 mm sink/hob separation.\\n\\nCoordinate outlet positions with credence joints, wall units, drawer backs, appliance depth and accessibility. Do not supply DIY conductor, breaker or wiring instructions as part of a furniture plan. Add task lighting without assuming that a ceiling point alone lights preparation adequately.\\n\\n### Ventilation, extraction and gas\\n\\nA hood treats cooking emissions intermittently; dwelling ventilation renews indoor air more generally. Sauter's FAQ explains why a hood cannot replace VMC (FR-S3). This distinction does not prove that every existing French dwelling must receive the same mechanical system.\\n\\nSurvey natural ventilation, individual VMC, collective VMC, air inlets, transfer paths, kitchen extraction terminal, and any combustion appliance. Obtain the relevant design and maintenance information. Do not obstruct vents with cabinets or close a required air path during replacement works.\\n\\n- Recirculation filters return air to the room; do not count them as outdoor exhaust or as a substitute for moisture removal by dwelling ventilation.\\n- Dedicated outdoor extraction requires a feasible, authorized duct route and coordinated air supply. Confirm flow, pressure loss, noise, discharge, fire/acoustic provisions and service access professionally.\\n- Do not connect a powered hood to an unidentified communal duct or VMC terminal. Treat compatibility and permission as unresolved until the responsible ventilation professional and building representative confirm the design. No universal connection prohibition is claimed from the inspected sources.\\n- Where gas or another combustion appliance is present, obtain professional review of air supply and depressurization risks before changing extraction. Do not infer safety from a closed cabinet drawing.\\n- Product manuals determine hood clearance, duct arrangement, filters, maintenance and compatibility; generic advice is not installation evidence.\\n\\n### Copropriete, rented premises and works\\n\\nThese are due-diligence gates, not a sourced statement of voting thresholds or permit law. Determine ownership and permissions before relocating services, cutting walls, changing collective ventilation, penetrating floors, or adding a facade/roof outlet.\\n\\nRecord the reglement de copropriete, syndic response, any required authorization, landlord agreement where relevant, structural assessment, and any mairie/planning-authority requirement. A verbal sales assurance does not resolve these dependencies. Identify who verifies the applicable rules and what evidence is still missing.\\n\\nFor an older building, ask the responsible professional whether surveys for hazardous materials or other pre-work investigations are required before invasive works. Do not diagnose materials from a photograph.\\n\\n### Rental equipment branch\\n\\nService Public's furnished-equipment page, verified 2026-03-06, covers a furnished dwelling used as the tenant's principal residence, including bail mobilite (FR-S4). Its kitchen/meal-related minimum equipment includes:\\n\\n- Cooking plates.\\n- An oven OR a microwave, not necessarily both.\\n- A refrigerator and a freezer, OR a refrigerator with a freezing compartment reaching a maximum temperature of -6 C.\\n- Dishes sufficient for occupants' meals and cooking utensils.\\n- A table and seats, storage shelves, and lighting.\\n\\nThe full furnished-dwelling list also covers bedding, bedroom shading and appropriate cleaning equipment. An inventory and detailed furniture condition record accompany the lease. Kitchen planning alone cannot certify the whole dwelling.\\n\\nDo not add a dishwasher to this minimum list. Do not require luxurious fitted cabinets or apply this list to an owner-occupied home, location nue, or tourist rental. For those branches, identify the applicable requirements separately. The decency overview reviewed during research distinguishes metropolitan and overseas contexts but its detailed equipment sections were not inspected; do not infer that unfurnished rental means \\\"no kitchen obligations.\\\"\\n\\nIn a relevant furnished-rental project, separate `regulatory` minimum equipment from `user_must` additions and `preference` upgrades. Verify the current applicable legal basis before final review.\\n\\n### Accessibility\\n\\nConfirm whether French housing accessibility provisions apply to the building category, new/existing context, project date, dwelling status and work scope. Ask the responsible professional to supply current requirements and their measurement definitions, including any accessible/evolutive provisions relevant to the project.\\n\\nThe official-partner accessibility portal distinguishes new housing, existing housing and building types, but the inspected page was last updated in 2021 and warns of CCH recodification (FR-S8). It is orientation only, not current numerical kitchen-compliance evidence.\\n\\nDo not substitute German DIN, US guidance or a generic 1500 mm aisle for the applicable French rule. Separately test the actual user's turning, approach, knee/toe space, reach, handles, controls, sink protection, seated preparation and transfer needs. A user trial supplements, not replaces, applicable requirements.\\n\\n## Working dimensions and measurement definitions\\n\\n| Item | Concept starting point | Definition and authority |\\n| --- | --- | --- |\\n| Main preparation width | About 900 mm; around 800 mm as a lower ergonomic recommendation | Clear usable worktop between interfering features; manufacturer planning guidance, not French law (FR-S6). |\\n| Single-cook working aisle | 1000-1200 mm | Nearest closed projections, including handles; inherited planning heuristic, then test occupied/open states. |\\n| Shared working aisle | 1200-1500 mm | Same measurement; concept heuristic, not an accessibility standard. |\\n| Worktop height | User/task-specific | Trial with actual users, sink depth and hob/pan height; do not impose a fixed \\\"French height.\\\" |\\n| Appliance bay and ventilation | Exact selected system | Installation drawings, required air paths, fronts, fixings and service voids; never nominal cabinet width alone. |\\n| Sink/hob separation and worktop bridges | Product and task-specific | Distinguish clear preparation width from cutout-edge distances and structural bridges. |\\n| Accessibility dimensions | Project-specific, professionally verified | State current source, applicability and exact geometry before marking pass. |\\n\\n## Constraint checklist\\n\\nCreate project records from these categories; do not automatically mark the checklist passed. Applicable regulatory, manufacturer, site and user-must requirements are hard constraints. Record unknowns and their owners.\\n\\n| ID | Check and evidence needed |\\n| --- | --- |\\n| FR-CTX-01 | Territory, building type, tenure, lease branch and project dates established. |\\n| FR-CTX-02 | Scope of works and applicable technical/regulatory documents identified by responsible professionals. |\\n| FR-PER-01 | Shared property, structure, facade and communal-service alterations identified; permissions resolved where required. |\\n| FR-PER-02 | Landlord and project-specific pre-work survey/authority dependencies resolved where applicable. |\\n| FR-GEO-01 | Survey datums, finished surfaces, diagonals, tolerances and uncertainty recorded. |\\n| FR-GEO-02 | Window/door arcs, radiators, ceiling and service obstructions represented. |\\n| FR-GEO-03 | Delivery, lift/stair access, worktop transport and assembly path verified. |\\n| FR-FIT-01 | Cabinet runs include fileurs, joues, fronts, handles, plinths and installation tolerances. |\\n| FR-FIT-02 | Exact appliance niches, hinges, ventilation, front weights and door/plinth compatibility checked. |\\n| FR-FIT-03 | Drawers, corner mechanisms, appliances and neighboring doors tested together. |\\n| FR-FIT-04 | Walls/floors, cabinet fixings, suspended loads and worktop support verified. |\\n| FR-WAT-01 | Water, drain route, levels and proposed relocation feasible; not inferred from endpoints. |\\n| FR-WAT-02 | Valves, trap, bins, sink bowl and drawer envelopes compatible and accessible. |\\n| FR-WAT-03 | Dishwasher hose routing, limits and connection access match selected product. |\\n| FR-ELE-01 | Electrician confirms edition, reference date, work scope and applicable requirements. |\\n| FR-ELE-02 | Ordinary socket count, area interpretation and usable placement verified separately from appliance circuits. |\\n| FR-ELE-03 | Appliance loads, circuit provisions, supply, protection and isolation access professionally checked. |\\n| FR-ELE-04 | Outlet/lead positions coordinated with wet/hot areas, furniture and credence; lighting supports tasks. |\\n| FR-VEN-01 | Existing ventilation type, inlets, transfer paths and extraction terminals documented and preserved. |\\n| FR-VEN-02 | Hood mode, duct feasibility, air supply, collective-system compatibility and permissions verified. |\\n| FR-VEN-03 | Hood/product clearances, noise, filters and maintenance access checked. |\\n| FR-GAS-01 | Gas/combustion installation and extraction interaction professionally assessed where applicable. |\\n| FR-TOP-01 | Worktop cutouts, bridges, edge distances, joints and supports meet supplier requirements. |\\n| FR-TOP-02 | Splash/heat exposure and adjacent surface/material compatibility resolved. |\\n| FR-USE-01 | Continuous preparation surface remains usable with everyday appliances in place. |\\n| FR-USE-02 | Dishwasher unloading tested with racks, receiving storage and user present. |\\n| FR-USE-03 | Cabinet allocation reflects real contents, usable dimensions, loads and frequency. |\\n| FR-USE-04 | Grocery, cooking, serving and waste routes tested without unsafe crossings. |\\n| FR-USE-05 | Occupied chairs, multiple cooks and open oven/drawer states preserve required passage. |\\n| FR-ACC-01 | Applicable French accessibility requirements and actual user needs both addressed. |\\n| FR-SAF-01 | Hot-pan landing, child safety, knife/chemical storage and stable furniture addressed. |\\n| FR-SRV-01 | Appliance removal, shutoffs, filters and repair access remain possible. |\\n| FR-REN-01 | Correct lease/territory branch selected; relevant equipment inventory verified without overextending its scope. |\\n| FR-ORD-01 | Itemized supply/work/exclusion schedule and installed EUR TTC budget agreed. |\\n| FR-ORD-02 | Final measurements, exact products, technical interfaces, evidence and professional-review responsibilities resolved. |\\n\\n## Worked checks\\n\\n### Open-state dishwasher conflict\\n\\nA 1200 mm closed-front aisle looks generous. A dishwasher projects 600 mm into it and an opposing receiving drawer projects 500 mm. The residual gap is:\\n\\n```text\\n1200 - 600 - 500 = 100 mm\\n```\\n\\nThat is not usable standing/unloading space. It fails this simultaneous-use scenario even if neither closed cabinet footprint overlaps. Move the receiving storage, change opening direction/type or redesign the arrangement; then rerun the test with actual products and the user envelope.\\n\\n### Unloading travel\\n\\nAssume four equal batches carried from dishwasher to storage, three return trips, and start at the dishwasher/end at storage. For illustrative measured walkable routes of 1.0 m and 2.5 m:\\n\\n```text\\nnear_storage_m = (4 + 3) * 1.0 = 7.0\\nfar_storage_m = (4 + 3) * 2.5 = 17.5\\ndifference_per_cycle_m = 17.5 - 7.0 = 10.5\\n```\\n\\nDo not use straight-line cabinet distances through open doors. The shorter route wins only if it remains safe and usable; bending and load handling need separate assessment.\\n\\n### French socket-count boundary\\n\\nA kitchen is measured at 4.0 m2 with uncertainty, and the seller proposes three ordinary sockets. The inspected manufacturer's less-than/greater-than summary does not settle the boundary. Reserve six provisionally, ask the electrician for the applicable area/count rule, and keep that requirement `unknown`. Even six visible sockets cannot prove circuit or placement compliance.\\n\\n### Furnished-rental distinction\\n\\nA principal-residence furnished letting has a hob, microwave and suitable refrigerator/freezing compartment but no conventional oven or dishwasher. The oven-or-microwave requirement is not failed merely because there is no conventional oven; the dishwasher is not on the inspected minimum list. Verify the rest of the equipment, lease scope and dwelling requirements before any compliance conclusion (FR-S4).\\n\\n### Shared-duct constraint beats preferred island\\n\\nA proposed island hood depends on an unidentified communal shaft. Do not draw a connection and mark ventilation passed. Keep feasibility/permission `unknown`; compare a service-preserving arrangement and a professionally assessed recirculation option that retains general ventilation. Neither becomes order-review-ready until all applicable hard constraints are resolved.\\n\\n## Final review questions\\n\\nCan a user prepare, cook, unload and serve with real occupied/open states? Are French project requirements evidenced rather than presumed? Can installers resolve every service/furniture interface from the documents? Are remaining assumptions visible and incompatible with any claimed readiness? If not, return the proposal to the appropriate earlier stage.\\n\"","export default \"# France Kitchen Planning Source Catalog\\n\\nOptional research/provenance file for [the skill](../SKILL.md) and [its operational reference](planning-reference.md). Do not load during routine planning unless a claim needs verification, the user requests citations, or guidance is being updated.\\n\\nReviewed on 2026-10-09. Source claims are paraphrased. A retrieval date is not a guarantee of current legal applicability. Commercial guidance is identified as such; general manufacturer advice is not a selected product's installation manual.\\n\\n## FR-S1: Legrand, NF C 15-100 professional guide\\n\\n- URL: https://www.legrand.fr/pro/normes-et-reglementations/norme-nf-c-15-100/norme-nf-c-15-100-suivez-le-guide\\n- Publisher/type: Legrand, manufacturer technical summary; page headed \\\"Norme NF C 15-100 en 2026 : on vous dit tout.\\\"\\n- Inspected: introduction, structure of the standard, circuits prises, and related scope text.\\n- Supports: 2024 revision and reported transition dates; new/entirely renovated installation context; ordinary kitchen socket reservations; separate specialized appliance connections; four worktop sockets within the six-socket case; optional additional hood outlet at 1800 mm minimum above finished floor.\\n- Limits: not the complete standard or an independent legal interpretation. The page uses `< 4 m2` and `> 4 m2` without explicitly resolving equality. Do not convert that gap into a legal rule. Its general appliance circuit examples are not a complete design for any particular supply or appliance inventory. Full placement clauses were not independently inspected.\\n- Use in skill: French electrical intake, reservations, electrician handoff, and boundary-case test. No DIY wiring instructions or automatic retrofit obligation.\\n\\n## FR-S2: Schneider Electric, NF C 15-100 overview\\n\\n- URL: https://www.se.com/fr/fr/work/support/local/reglementation/norme-nfc15-100/\\n- Publisher/type: Schneider Electric France, manufacturer standards overview.\\n- Supports: identification of the 2024 revision and availability of updated guidance; AFNOR standard versus explanatory guide distinction.\\n- Limits: detailed expandable answers and the downloadable guide were not inspected. Does not independently verify the numeric kitchen reservations used from FR-S1.\\n- Use in skill: cross-check of the revision context, not project compliance evidence.\\n\\n## FR-S3: Sauter, hood versus VMC\\n\\n- URL: https://www.confort-sauter.com/aide/vmc/installation/ma-hotte-de-cuisine-peut-elle-remplacer-une-vmc/\\n- Publisher/type: Sauter, manufacturer ventilation FAQ.\\n- Supports: continuous air renewal by VMC versus intermittent removal of cooking emissions by a hood; their complementary functions.\\n- Limits: blanket marketing statements about mandatory VMC are not used as universal retrofit law. This FAQ did not establish legal permission or a universal prohibition for powered-hood connection to a communal system.\\n- Use in skill: retain general ventilation, investigate the actual system, and require professional compatibility/permission evidence.\\n\\n## FR-S4: Service Public, furnished-dwelling equipment\\n\\n- URL: https://www.service-public.gouv.fr/particuliers/vosdroits/F34769\\n- Title: \\\"Bail d'habitation : qu'est-ce qu'un logement meuble ?\\\"\\n- Publisher/type: French public-service administrative guidance; page verification date 2026-03-06.\\n- Supports: minimum equipment for a furnished principal-residence lease, including bail mobilite; cooking plates, oven OR microwave, refrigerator/freezer alternative, dishes, utensils, table/seats, storage and lighting; inventory documentation.\\n- Limits: not a universal specification for owner occupation, location nue, holiday rentals or every overseas jurisdiction. The whole dwelling has additional requirements beyond the kitchen. Verify the current applicable legal basis and territorial scope for the project.\\n- Use in skill: scoped rental branch and equipment distinction, not a complete decency certificate.\\n\\n## FR-S5: IKEA France, practical kitchen layout\\n\\n- URL: https://www.ikea.com/fr/fr/rooms/kitchen/how-to/idees-dagencement-pratique-pour-la-cuisine-pub6d21e890/\\n- Title: \\\"Idees d'agencement pratique pour la cuisine.\\\"\\n- Publisher/type: French-market retailer planning advice.\\n- Supports: preparation between sink and cooking, nearby dishwasher/waste, storage at point of use, and several layout forms.\\n- Limits: activity-triangle and equal-distance language is advisory, not mandatory. One retailer cannot establish the prevalence of national household habits.\\n- Use in skill: evidence that familiar ergonomic principles also apply in France; no invented French triangle or style requirement.\\n\\n## FR-S6: Blum, preparation storage and worktop\\n\\n- URL: https://www.blum-inspirations.com/de-eu/wissen/speisenvorbereitung-leicht-gemacht-der-passende-schrank-unterstuetzt-sie-dabei\\n- Publisher/type: Blum, German-language European manufacturer ergonomics/planning advice, reused from the general kitchen research.\\n- Supports: preparation worktop and related storage; approximately 900 mm recommended working width and around 800 mm lower ergonomic recommendation.\\n- Limits: not French regulation and not a universal minimum. Usable clear surface, tasks, products and users matter more than a nominal run length.\\n- Use in skill: explicitly labeled transferable ergonomic recommendation, not country-specific compliance.\\n\\n## FR-S7: Blum, accessible dish storage\\n\\n- URL: https://www.blum-inspirations.com/de-eu/wissen/geschirr-perfekt-organisiert-im-unterschrank-mit-auszuegen\\n- Publisher/type: Blum, German-language European manufacturer storage guidance, reused from the general kitchen research.\\n- Supports: accessible base-unit pull-outs for dishes and handling-oriented storage allocation.\\n- Limits: commercial guidance; verify actual usable dimensions, loads and user reach. Does not prove that every drawer is suitable for every dish stack.\\n- Use in skill: contents-driven drawers and dishwasher-unloading evaluation.\\n\\n## FR-S8: Accessibility portal, housing applicability orientation\\n\\n- URL: https://www.accessibilite-batiment.fr/logements-neufs/generalites-et-definitions/code-de-la-construction-et-de-lhabitation.html\\n- Publisher/type: DHUP-CSTB-Cerema accessibility portal, regulatory orientation.\\n- Inspected: general distinctions for collective housing and individual houses; page update 2021-09-10 and warning concerning CCH recodification from 2021-07-01.\\n- Supports: the need to distinguish building categories, project context and applicable documents rather than treating every kitchen identically.\\n- Limits: old numbering and dated material; not relied on for a current legal determination or any French kitchen dimension. Current full applicable provisions must be obtained for the project.\\n- Use in skill: accessibility applicability gate; no imported DIN or unverified French numeric requirement.\\n\\n## Research exclusions and maintenance\\n\\n- Service Public's rental-decency overview at https://www.service-public.gouv.fr/particuliers/vosdroits/F2042 was only partially accessible. Its metropolitan/overseas distinction informed the intake; detailed kitchen-equipment provisions were not verified.\\n- IZI by EDF's kitchen-electrical article was inspected but not adopted as authority because its broad claims and comments contained ambiguities or conflicts. In particular, no universal 600 mm sink/hob rule, kitchen bathroom-like volumes, mandatory kitchen RJ45, or automatic whole-dwelling upgrade on sale is adopted.\\n- IKEA France's hood article was inspected but is not used for generic hood heights, filter lifetimes or claims that recirculation removes humidity outdoors.\\n- Primary ventilation legislation could not be retrieved from Legifrance during research. No numeric statutory ventilation rate or categorical communal-duct legal rule is asserted.\\n- Copropriete permissions, landlord agreement, quotations and trade coordination are practical due-diligence checks. Voting thresholds, permit procedures, statutory quote requirements and VAT rates were not established and are not prescribed.\\n- No primary text or current project-specific French accessibility clause was verified. Do not turn portal orientation into an accessibility certificate.\\n- Before updating a numeric requirement, check the full current source, territorial/project applicability, exceptions and measurement definition; update the operational guidance and source qualification together.\\n\"","export default \"---\\nname: living-room-planning\\ndescription: \\\"Plan or review a living room, lounge, sitting room, or Wohnzimmer using household activities, verified geometry, and practical furniture constraints. Use when arranging sofas, armchairs, recliners, sofa beds, coffee tables, TV/media units, bookshelves, or storage; comparing conversation and TV layouts; checking circulation, accessibility, lighting, glare, child safety, or open-plan living zones. Defaults to Germany/EU context and metric units; separates requirements from ergonomic recommendations and preferences. Includes operational checks and an optional research source catalog.\\\"\\n---\\n\\n# Living Room Planning\\n\\n## Purpose and loading policy\\n\\nCreate practical, explainable living-room proposals that work for the household's real activities. Optimize comfort, access, storage, and ease of changing activities before decorative composition or maximum furniture count.\\n\\nDefault to Germany/EU context, dimensions in millimetres, and costs in EUR unless the user specifies otherwise. Confirm the actual country and, where relevant, German federal state. There is no single set of EU living-room layout rules.\\n\\n- Read [the planning reference](./references/planning-reference.md) before applying numerical guidance, assessing accessibility or installation risks, or declaring a layout dimensionally checked.\\n- Read [the optional source catalog](./references/source-catalog.md) only to verify a source, answer provenance/citation questions, resolve disputed claims, or update guidance.\\n- Do not load the source catalog merely to resolve source IDs during routine planning. The operational reference contains the qualifications needed for normal use.\\n- This skill supports planning, not structural design, electrical installation, fire-safety approval, clinical assessment, or permission to purchase.\\n\\n## Non-negotiable discipline\\n\\n1. Distinguish measured facts, assumptions, user preferences, recommendations, and mandatory requirements.\\n2. Never infer exact room dimensions, wall construction, load capacity, or safe clearances from a photograph alone.\\n3. Preserve the existing planner's authoritative geometry, product catalog, and accepted design. Proposals are reversible drafts until explicitly accepted.\\n4. Check occupied, moving, and fully deployed furniture, not just closed footprints. A sofa bed's sleeping surface is not its overall deployed size.\\n5. Do not treat a reachable-looking gap, generic furniture dimension, or aesthetic rule as proof of accessibility or safety.\\n6. Keep required exits and escape openings usable in every relevant mode. A blocked exit is not acceptable because guest use is infrequent.\\n7. Unknown is not pass. Missing critical dimensions or installation evidence must remain visible.\\n8. Do not prescribe a TV, fireplace, large sectional sofa, rug, or symmetry unless it serves the brief.\\n\\n## 1. Establish the brief and survey\\n\\nAsk only questions that can change the next decision; group missing information instead of sending a long questionnaire. Start with daily occupants, activities, existing furniture to retain, room geometry, and budget. If measurements are missing, offer a labelled concept and a concise measurement list.\\n\\nCapture:\\n\\n| Subject | Required information |\\n| --- | --- |\\n| Household | Daily and visiting occupants; children; mobility aids; reach, vision, hearing, balance, transfer, and sensory needs; foreseeable changes |\\n| Activities | Conversation, TV/gaming, reading, music, play, exercise, hobbies, occasional work/dining/sleeping; priorities, frequency, duration, and simultaneous use |\\n| Geometry | Room outline, ceiling/slopes, columns, niches, skirtings, changes in level, actual door and window positions, sill heights, handles, opening arcs, thresholds |\\n| Connections | Entrance, adjacent rooms, kitchen/dining area, balcony/terrace, required exits and escape openings; routes used while carrying items |\\n| Services | Radiators, thermostats, ventilation openings, fireplace/stove and hearth, sockets, switches, data/TV points, ceiling outlets, fixed lighting |\\n| Daylight and sound | Window orientation, glare at typical viewing times, shading, street/neighbour noise, adjacent bedrooms, reflective surfaces |\\n| Products | Retained pieces and exact candidate models; external and usable internal dimensions, weight/load limits, open/deployed sizes, anchoring and ventilation instructions |\\n| Inventory | Books, games, toys, blankets, media devices, controllers, chargers, hobby/work items, guest bedding; quantities, sizes, weights, access frequency |\\n| Delivery and work | Building entrance, stairs, lift, door turns, package dimensions, assembly space, wall permissions, access for installers and later servicing |\\n| Preferences and cost | Must-keep items, comfort trials, style/materials, cleaning needs, budget including delivery/assembly, wiring, mounting, shading, lighting, and disposal |\\n\\nFor each critical fact record `value`, `unit`, `source`, `verification_state`, and uncertainty/tolerance. Use `unknown`, `inferred`, `user_verified`, or `professionally_verified`. A product's nominal width does not prove the available room width.\\n\\nCreate an activity table with `mode`, `users`, `frequency`, `simultaneous_activities`, `required_items`, `deployed_state`, and `reset_steps`. Distinguish daily seats from occasional guest seats. Do not count the same floor area twice for simultaneous activities.\\n\\n## 2. Build a constraint register\\n\\nUse these classes:\\n\\n- `regulatory`: verified, applicable local requirements; record jurisdiction and edition.\\n- `manufacturer`: exact product instructions, clearances, loads, mounting, and intended use.\\n- `site`: verified fixed geometry, services, structural limits, and permissions.\\n- `user_must`: explicit non-negotiable household requirements.\\n- `recommendation`: ergonomic or functional advice, including labelled planning heuristics.\\n- `preference`: negotiable visual or lifestyle choices.\\n\\nThe first four classes are hard constraints. The latter two are soft unless explicitly adopted as a project requirement. Identify safety hazards even when their legal classification is unverified; do not bury them in an aesthetic score. A user preference cannot waive a mandatory requirement.\\n\\nRecord `id`, `class`, `applicability`, `requirement`, `measurement_definition`, `source`, `status`, `affected_items`, and `remedy_or_next_action`. Status is `pass`, `fail`, `unknown`, or `not_applicable` with a reason. Include the room mode in each state-dependent check.\\n\\nResolve conflicting requirements explicitly. Reject hard failures from viable options; separate options needing missing evidence from checked options. Escalate wall loading, fixed electrics, combustion/hearth conditions, or accessibility compliance to the appropriate professional.\\n\\n## 3. Reserve routes and activity zones\\n\\n1. Mark fixed features, required access, opening arcs, and no-go areas before placing furniture.\\n2. Connect the entrance to used seats, storage, adjacent rooms, windows, and balcony along genuinely walkable paths.\\n3. Prefer through-routes outside the conversation group and TV sightline where geometry permits. Show the compromise when a through-room makes this impossible.\\n4. Size the main zone for daily activities; reserve secondary zones only where the brief requires them.\\n5. Test daylight and noisy/quiet activities together. A shelf or curtain can separate views without providing acoustic privacy.\\n6. Locate movable furniture's parking positions. A coffee table moved for a sofa bed must not be parked in a doorway or another required activity zone.\\n\\nPossible strategies include facing/angled seating for conversation, sofa plus movable chairs for mixed use, a media-oriented group, or distinct quiet/active zones. These are alternatives, not mandatory room types.\\n\\n## 4. Fit the seating to the users\\n\\n- Select usable seat width, seat depth, compressed seat height, support, armrests, and ease of standing through user trials, not a universal ideal sofa size.\\n- Count seats that people can actually use together. A chaise, corner junction, ottoman, or armless end is not automatically an equivalent full-time seat.\\n- For conversation, arrange faces so users can hear and see each other without sustained twisting. Try angled chairs or more than one small group before enlarging a distant perimeter arrangement.\\n- Check entry to each seat, knees/feet, standing, transfers, walking-aid parking, swivel arcs, recliner mechanisms, and access to controls.\\n- Position drinks, a book, glasses, and remotes within comfortable reach. A side table can serve a seat better than a large central table.\\n- Treat coffee-table reach space and through-circulation as different things. An easy-to-reach table gap is not a corridor.\\n- Verify sofa-bed deployment, bed-making, access to bedding, night-time routes, and the effort/strength needed to operate it. Do not assume an occasional sofa bed is suitable for regular sleep.\\n\\n## 5. Locate TV, media, and listening equipment\\n\\nOnly apply this step when relevant to the brief.\\n\\n1. Identify primary and secondary viewing seats and measure actual seated eye positions.\\n2. Start with the screen centre near seated eye level, then trial the real posture, screen size, subtitles, and viewing comfort. Do not choose a fixed mounting height from the floor alone (S3, S4).\\n3. Choose viewing distance with screen size, resolution, content, eyesight, and preference. There is no universal distance multiplier suitable for every user (S5).\\n4. Check horizontal viewing positions, head turning, and sightline obstruction from every claimed TV seat. The panel's specified viewing angle is not a comfort guarantee.\\n5. Check reflections from windows and luminaires at typical times. Side-on placement to windows is a candidate, not an automatic glare solution; verify with the actual room and shading.\\n6. Check exact TV foot spacing/depth, furniture load capacity, anti-tip measures, bracket compatibility, wall substrate, and cable strain through mount movement. A wider cabinet alone does not prevent tipping (S3, S8).\\n7. Allow actual device ventilation, connector depth, plug removal, service access, and remote/signal operation behind doors. An opening for cables does not establish adequate cooling.\\n8. Position speakers using product guidance, listening trials, and neighbour considerations. Do not promise acoustic isolation from rugs, curtains, or decorative panels.\\n\\nDo not default to a TV above a fireplace: both viewing posture and verified heat/installation limits must work. An unknown heat condition blocks mounting approval.\\n\\n## 6. Assign contents before choosing storage\\n\\n| Contents | Preferred relationship | Operational check |\\n| --- | --- | --- |\\n| Remotes, glasses, current book | At the relevant seat | Reach while seated; no risky leaning or trailing charger |\\n| Games and controllers | Near play/media area | Access and return without disconnecting equipment or clearing occupied seats |\\n| Toys | Near the agreed play area | Child access where appropriate; anchoring, lid/pinch risks, tidy-up route |\\n| Books and records | Near reading/listening area | Real shelf depth, load limits, adjustable spacing, safe retrieval |\\n| Throws and cushions | Near relaxation seats | Storage opens while people are seated; no need to empty the tabletop |\\n| Guest bedding | Near sofa bed | Retrieve before/during deployment; dry storage and manageable lifting |\\n| Work or hobby equipment | Near its use zone | Fast setup/reset, suitable work surface, secure storage where needed |\\n| Hazardous or fragile items | Controlled location | Access restrictions appropriate to household; height alone is not a lock |\\n\\nUse internal clear dimensions, hinges, drawer travel, shelf loads, and actual object sizes. Locate frequent items for easy retrieval; avoid heavy overhead storage. Compare closed storage for clutter control with open storage for access/display, without sacrificing equipment cooling.\\n\\nStorage should reduce repeated interruptions: getting up, asking someone to move, reaching across a screen, unloading a tabletop to lift a lid, or shifting furniture. Shorter walking distance is useful only when access remains safe and convenient.\\n\\n## 7. Integrate light, environment, and safety\\n\\n- Combine general, task, and ambient/accent lighting with independently usable controls (S2). Reading needs suitable light on the page, not just a bright room.\\n- Check source glare, reflected screen glare, contrast, shadows, and seated/standing sightlines. Place switches where users can reach them on entry and at key seats; retain usable non-app control.\\n- Plan cables and outlets before accepting floating furniture. Do not hide extension leads under rugs or use cable routing that creates trip, pinch, or heat hazards. Fixed electrical alterations require qualified work.\\n- Keep radiator heat flow, thermostat sensing, and ventilation unobstructed (S7). Check exact installation instructions and any cold/damp wall concern; do not invent a universal furniture-to-wall gap.\\n- Treat required furniture/TV anchoring as part of the layout. Verify suitable wall/floor construction and fixings; an unknown wall is not a passed mounting check (S8).\\n- Address climbing access to windows, accessible blind cords, unstable tall furniture, loose rugs, sharp/glass edges, hot surfaces, and moving mechanisms. Prefer cordless window coverings around young children; moving furniture alone does not eliminate cord hazards (S9).\\n- For echo, consider appropriate absorptive furnishings subject to cleaning, trip, and fire constraints. Speech privacy, bass transmission, and sound isolation require different assessment; do not invent decibel improvements.\\n- If sustained work or dining is required, check a suitable table/chair/task-light setup. A sofa with a laptop tray is not evidence of an ergonomic full-time workstation.\\n\\n## 8. Generate and test alternatives\\n\\nOffer two or three meaningfully different layouts when useful, not multiple cosmetic versions. Preserve existing furniture when it meets the brief. Explain when only one credible option fits.\\n\\nFor each option test the required states:\\n\\n- Normal day with the usual seats occupied.\\n- Conversation/guests with occasional seats placed and used.\\n- TV/gaming with sightlines, glare, and controller/device access.\\n- Reading/work/play occurring simultaneously where requested.\\n- Recliners, drawers, doors, swivel chairs, and sofa bed through their full motion and deployed states.\\n- Night-time access, window operation, cleaning, servicing, and eventual furniture removal.\\n\\nMeasure the narrowest clear route between actual obstacles, including occupied feet/knees and deployed parts. Check turning and approach geometry as well as width. Use tolerance-aware dimensions; marginal clearance with unverified geometry remains unknown.\\n\\nUse scaled geometry checks where available and full-size tape/cardboard mock-ups with user trials where practical. Describe exactly what was checked; a language-model review alone is not deterministic collision validation.\\n\\nCompare options by hard failures/unknowns first, then daily comfort, circulation, conversation/media suitability, storage access, reset effort, light/glare, maintenance, cost, and preferences. Let the user set priorities; do not invent authoritative scoring weights.\\n\\nCount furniture moves, lifting, setup time, interruptions, and actual walkable trips for repeated routines. State assumptions and frequency. Do not optimize walking distance at the expense of comfort, inclusion, or required access.\\n\\n## 9. Deliver the proposal\\n\\nProvide:\\n\\n1. Brief, priority activities, assumptions, and missing evidence.\\n2. Recommended layout and alternatives, using labelled walls or a defined coordinate origin; include external furniture dimensions and critical clearances.\\n3. Seating and storage assignments, TV/light relationships, services, and required anchors.\\n4. Mode-by-mode checks, worst pinch points, and the destination of every displaced item.\\n5. Constraint register with failures, unknowns, source type, and next action/owner.\\n6. Budget range, retained/new items, installation/delivery dependencies, and next measurements or trials.\\n7. An explicit readiness level.\\n\\nUse `concept` when dimensions or products are provisional. Use `dimensionally_checked` only for the listed modes and checks supported by verified geometry/product envelopes. Use `ready_for_professional_order_review` only when critical unknowns and hard failures are resolved and delivery/installation evidence is assembled. None of these labels authorizes purchase or certifies regulatory compliance; professional review and user acceptance remain separate.\\n\\n## Counterexample quality checks\\n\\nBefore concluding, reject these false passes:\\n\\n- The closed recliner leaves a wide route, but its footrest blocks the balcony when used.\\n- Six nominal sofa places exist, but two require twisting and one blocks access to another.\\n- A nearby storage ottoman is convenient only when nobody uses it and everything is removed from its lid.\\n- A sofa bed opens only after the coffee table is moved, with no safe parking place for that table.\\n- A low TV cabinet fits, but the television feet overhang or its anti-tip provision is unresolved.\\n- A 1500 mm square is shown somewhere in the room, but the wheelchair user cannot reach a seat, storage, or exit.\\n- A room divider hides a desk but does not make concurrent calls and television acoustically private.\\n- A layout photographs well but covers a radiator, blocks a window handle, or requires a cable across a walking route.\\n\"","export default \"# Living Room Planning Reference\\n\\nOperational guidance for the living-room-planning skill. Defaults: Germany/EU context, millimetres, EUR. Source IDs identify research without requiring bibliography loading.\\n\\nLoad [the optional source catalog](./source-catalog.md) only for source verification, citations/provenance, disputed claims, or maintenance. Do not load it just to resolve IDs in routine planning.\\n\\n## Evidence boundaries\\n\\n- S1-S3 are IKEA consumer guidance on activity zones, lighting, and TV furniture. They support design reasoning, not building-code compliance or endorsement of particular products.\\n- S4-S5 are Sony general support guidance on TV height and distance. They are not exact product installation manuals or universal health limits.\\n- S6 is a secondary summary of DIN 18040-2 living/sleeping-room accessibility. Its index identifies the 2011-09 edition. Verify the current edition, project applicability, state adoption, and any contractual requirements before treating a dimension as mandatory. The full standard was not reviewed.\\n- S7 is German consumer advice supporting unobstructed radiator heat flow and thermostat sensing, not a numerical clearance standard.\\n- S8-S9 are US CPSC safety guidance on tip-over and window-covering cords. The hazard principles are relevant; US legal provisions are not German/EU requirements.\\n- The workflow, check catalog, and examples below are planning synthesis. A source supports only the stated claim, not every adjacent check. Project-specific manuals, structural conditions, and local requirements still need verification.\\n\\n## Dimensions and measurement definitions\\n\\nThe heuristic rows below are deliberately provisional starting points for mock-ups. They are not sourced standards, minimum legal dimensions, accessibility specifications, or guarantees of comfort. Override them for actual users, geometry, products, and applicable requirements.\\n\\n| Topic | Starting guidance | Measurement and qualification |\\n| --- | --- | --- |\\n| Main walking route | Explore 900-1200 mm clear width | Skill heuristic for initial ordinary residential layouts; measure narrowest obstacle-to-obstacle gap in the relevant occupied mode. Passing, carrying, mobility aids, turns, or applicable rules may need more. This does not certify an escape route. |\\n| Seat to coffee table | Try 400-500 mm | Skill heuristic between seat front and table edge for reach and leg space; trial actual posture. Not a through-route or wheelchair-transfer clearance. Side tables or no central table may be better. |\\n| Conversation spacing | Trial roughly 1500-2500 mm between seated head positions | Skill heuristic for a small conversational group, not between sofa backs. Hearing, room noise, furniture angles, and personal space govern the result. |\\n| Turning/movement area | S6 reports 1200 x 1200 mm; 1500 x 1500 mm for unrestricted wheelchair use | Secondary DIN summary for relevant living/sleeping rooms. Distinguish general barrier-free from the R category; verify applicability and full provisions. A free square alone does not prove accessible use. |\\n| Space along/in front of furniture | S6 reports 900 mm depth; 1500 mm for unrestricted wheelchair use | Secondary summary; not a universal route-width substitute. Verify the actual approach, transfer, furniture function, and applicable category. |\\n| Seat dimensions | User- and product-specific | Measure usable width/depth and compressed seat height; trial support, feet placement, standing, and transfers. No fixed ideal dimensions specified here. |\\n| Screen centre height | Start near seated eye level (S3, S4) | Finished floor to centre of visible screen; use actual primary viewers and posture. Reclined viewing may require a different tested arrangement. |\\n| Viewing distance | No mandatory multiplier (S5) | Eye position to screen; note size, resolution, content, subtitles, and preference. Distinguish this from wall-to-sofa distance. |\\n| TV support/mount | Exact product dimensions and limits | Check TV feet, support depth, load rating, anchors, wall construction, bracket specification, and full movement envelope. Screen diagonal alone is insufficient. |\\n| Sofa bed/recliner | Exact fully deployed dimensions and motion | Include mechanisms, rear travel, user operation/standing, feet, bedding access, and displaced furniture. No generic clearance is approved. |\\n| Cabinet/device clearances | Exact manuals and usable internal space | Include plugs, cable bend space, drawer/door travel, ventilation, load capacity, and service removal. |\\n| Radiators, stove/hearth, cold walls | Site and product assessment | No universal gap. Keep heat flow and controls usable (S7); obtain verified combustion clearances and investigate moisture concerns. |\\n| Lighting | Activity-specific placement and controls (S2) | No mandatory domestic lux or colour-temperature target is established by this research. Agree needs; use photometric data/measurement for quantified claims. |\\n\\nOverlap of movement areas may be permissible in an applicable accessibility design, but do not overlap fixed obstacles or simultaneous occupied/deployed functions. Record exactly which states can share space and validate the applicable provisions.\\n\\n## Practical check catalog\\n\\nThese are check categories, not a claim that all checks apply or are legally required. Instantiate the relevant checks with the constraint class, measurement, mode, evidence, status, and next action. Preserve `unknown` where evidence is missing.\\n\\n| ID | Check | Failure or unresolved condition to expose |\\n| --- | --- | --- |\\n| GEO-01 | Survey and tolerances | Furniture accepted against estimated wall dimensions, unmeasured skirtings, slopes, or out-of-square corners |\\n| GEO-02 | Openings | Door/window arcs, handles, curtains, thresholds, or escape openings obstructed |\\n| GEO-03 | Route continuity | A nominal clear width exists locally but the full entrance-seat-storage-exit route fails |\\n| GEO-04 | Required access | Balcony, services, ventilation, cleaning, or emergency access sacrificed to furniture |\\n| USE-01 | Activity brief | Maximum seating or TV dominance chosen without household priorities |\\n| USE-02 | Simultaneous use | Work, play, conversation, or dining claim the same space at the same time |\\n| USE-03 | Real seating capacity | Corner/chaise/occasional places counted as equivalent comfortable daily seats |\\n| USE-04 | Seated comfort | Unsupported feet, excessive seat depth, difficult standing, or inaccessible controls |\\n| USE-05 | Conversation | Sustained twisting, blocked faces, distance/noise incompatible with hearing needs |\\n| USE-06 | Reach and standing | Table placement forces leaning or removes space for feet, standing, or transfers |\\n| FIT-01 | Actual external envelope | Product footprint excludes arms, legs, handles, overhang, or cables |\\n| FIT-02 | Motion and deployment | Recliner, swivel chair, drawer, or sofa-bed travel collides with people or objects |\\n| FIT-03 | Reset and parking | Displaced tables, cushions, bedding, or guest seats have no safe destination |\\n| FIT-04 | Delivery and assembly | Package or assembled piece cannot negotiate entry, stairs, lift, or room turns |\\n| STO-01 | Contents and loads | Object sizes/weights exceed usable shelf/drawer dimensions or ratings |\\n| STO-02 | Retrieval | Frequent items require moving occupants, unloading a lid, or crossing active viewing |\\n| STO-03 | Safe reach | Heavy overhead items, climbing, insecure hazardous contents, or inaccessible essentials |\\n| MED-01 | TV eye geometry | Screen height/distance/angle chosen without the primary viewers and actual screen |\\n| MED-02 | All claimed viewing seats | Obstructed picture, neck turning, subtitle difficulty, or unsuitable off-axis image |\\n| MED-03 | Glare | Window or luminaire reflections untested at relevant times |\\n| MED-04 | TV support and mounting | Feet overhang, inadequate loads, incompatible bracket, unknown substrate or fixing |\\n| MED-05 | Device operation | Cooling, cable/plug space, service removal, or remote/signal access missing |\\n| LGT-01 | General/task/ambient light | One source cannot serve agreed activities or leaves routes inadequately visible |\\n| LGT-02 | Control and glare | Unreachable controls, app-only dependency, glare or harsh contrast at a used seat |\\n| ENV-01 | Heating and ventilation | Sofa, cabinetry, or curtains obstruct radiator flow, thermostat sensing, or vents |\\n| ENV-02 | Moisture and finishes | Cold/damp wall concern ignored; finishes/rugs unsuitable for actual conditions |\\n| ENV-03 | Acoustic compatibility | Visual screen treated as sound isolation; no plan for concurrent noisy/quiet use |\\n| ACC-01 | Accessible movement | Applicable clear areas, approaches, turning, and route continuity not verified |\\n| ACC-02 | Inclusive use | Seat transfer, aid parking, reach, contrast, hearing, or control needs not met |\\n| SAFE-01 | Stability and anchoring | Furniture, TV, or room divider lacks required stability/anchors and verified substrate |\\n| SAFE-02 | Child/window safety | Climbing route, accessible blind cord, pinch/lid risk, or hazardous contents unresolved |\\n| SAFE-03 | Trips and impact | Loose rug edges, trailing leads, low unseen obstacles, sharp/glass edges on routes |\\n| SAFE-04 | Heat and combustion | Unverified stove/hearth/TV relationship, combustible furnishings, or obstructed provisions |\\n| SRV-01 | Power and data | Unsafe extension routing, pinched leads, insufficient outlets, or unapproved fixed work |\\n| ORD-01 | Ordering evidence | Product variants, prices, measurements, permissions, or installation checks unresolved |\\n| ORD-02 | Readiness claim | Concept labelled installation-ready, unverified checks passed, or approval implied |\\n\\n## Worked examples\\n\\nAll dimensions, timings, and counts in these examples are invented teaching inputs, not recommended product clearances or measured performance.\\n\\n### 1. Closed-state route that fails when used\\n\\nA straight passage between a closed recliner front and a cabinet front is 1250 mm. In the same cross-section, the footrest extends 550 mm into the passage and an opposing drawer extends 400 mm.\\n\\n```text\\nremaining_gap_mm = 1250 - 550 - 400 = 300\\n```\\n\\nThe positive gap does not imply a usable route. Feet, the person retrieving contents, and approach/turning space have not even been included. It fails an agreed 900 mm project route target. If this is the only access to an exit, rejecting the simultaneous state alone is not a sufficient remedy; relocate or resize furniture so required access remains usable in intended operation.\\n\\nThis subtraction is valid only for aligned projections at that cross-section. Offset furniture, curves, swing arcs, and room turns require actual geometry checks.\\n\\n### 2. Sofa-bed mode includes its displaced furniture\\n\\nA room has 3500 mm clear depth on the deployment axis. The bed's verified overall deployed depth is 2200 mm and the opposite cabinet is 400 mm deep.\\n\\n```text\\nnominal_foot_gap_mm = 3500 - 2200 - 400 = 900\\n```\\n\\nThis is not yet a pass: check doors, drawer access, operator standing, side approach, night-time route, and tolerances. A 600 mm deep coffee table parked in that gap leaves only 300 mm on the assumed aligned section. Find a separate safe parking position or change the furniture plan. Do not claim the mattress length is the deployed furniture depth.\\n\\n### 3. Viewing geometry, not a prescribed distance\\n\\nFor a centred, perpendicular viewer and a 16:9 screen:\\n\\n```text\\ndiagonal_mm = diagonal_inches * 25.4\\nscreen_width_mm = diagonal_mm * 16 / sqrt(16^2 + 9^2)\\nhorizontal_angle_degrees = 2 * atan(screen_width_mm / (2 * eye_distance_mm)) * 180 / pi\\n```\\n\\nA 65-inch screen is about 1439 mm wide. At a 2500 mm perpendicular eye-to-screen distance it spans about 32.1 degrees horizontally. This describes the geometry; it is not a recommended angle, a safety threshold, a panel off-axis specification, or a comfort guarantee. Trial content, subtitle readability, eyesight, and actual seated posture (S4, S5).\\n\\n### 4. Storage reduces reset effort, not just distance\\n\\nSuppose daily hobby setup/reset requires moving a table twice and clearing an ottoman lid twice, each assumed to take 20 seconds. A nearby accessible drawer avoids those four actions without creating another obstruction.\\n\\n```text\\navoided_actions_per_day = 2 + 2 = 4\\nillustrative_time_saved_seconds_per_day = 4 * 20 = 80\\n```\\n\\nThese are user-supplied or trial assumptions to verify, not a product claim. Also compare lifting effort, comfort, actual walkable trips, and whether anyone must move. Do not choose unsafe reachable storage to save time.\\n\\n## Maintenance and limits\\n\\nKeep numerical heuristics labelled whenever repeated in a proposal. If a source changes, update the affected operational claim as well as the optional catalog. Record exact manual editions and project evidence separately from this generic research.\\n\\nNo exact project product manuals, structural calculations, full accessibility standard, local fire/escape provisions, quantitative acoustic assessment, or photometric design were reviewed to produce this generic skill. Obtain them when the project requires them. A checklist review does not replace installation approval.\\n\"","export default \"# Living Room Planning Source Catalog\\n\\nOptional research/provenance file. Do not load for routine planning or solely to expand a source ID. Load when the user asks for citations, a claim needs verification, sources conflict, or the skill is being maintained.\\n\\nResearch reviewed: 2026-10-09. Scope: generic domestic living-room planning with Germany/EU defaults. Summaries are original planning notes, not reproduced articles. The operational rules and qualifications are in [the planning reference](./planning-reference.md); the workflow is in [the skill](../SKILL.md).\\n\\n## S1 - IKEA Germany: activity zones and reset storage\\n\\n- Source: [So gestaltest du drei Arbeitsbereiche in einem Raum](https://www.ikea.com/de/de/rooms/living-room/how-to/wohnzimmer-aufteilen-pubd020bb20/).\\n- Type: retailer guidance; German market.\\n- Retrieved support: separate work/relaxation areas, visual screening, movable storage, keeping work items together for easy reset.\\n- Applied: activity and simultaneous-use brief, nearby storage, explicit setup/reset actions.\\n- Limits: product inspiration, not dimensional or acoustic compliance evidence. Do not generalize the sofa/laptop examples into suitable full-time workstation ergonomics. Screens do not establish speech privacy or sound isolation.\\n\\n## S2 - IKEA Germany: living-room lighting\\n\\n- Source: [Bestmoegliche Nutzung deiner Wohnzimmerbeleuchtung](https://www.ikea.com/de/de/rooms/living-room/how-to/wohnzimmerbeleuchtung-ideen-pub75352e80/).\\n- Type: retailer guidance; German market.\\n- Retrieved support: combine general, task, and mood lighting; support concentrated tasks with appropriate surrounding light; cabinet lighting and adjustable controls.\\n- Applied: activity-specific lighting, contrast/glare review, multiple controllable sources.\\n- Limits: does not establish mandatory domestic illuminance, colour temperature, or a required number of lamps. Battery-powered lighting still needs energy and charging; the page's casual wording is not an electrical claim.\\n\\n## S3 - IKEA Germany: TV furniture\\n\\n- Source: [So waehlst du eine TV-Bank, die bestens in dein Zuhause passt](https://www.ikea.com/de/de/rooms/living-room/how-to/stilvolle-tv-baenke-pub8de44a60/).\\n- Type: retailer guidance; German market.\\n- Retrieved support: screen centre at seated eye height; open/closed storage choices; cable openings; suggests cabinet wider than screen.\\n- Applied: seated-eye planning, storage configuration, cable access.\\n- Limits: furniture wider than the screen does not establish stability. Check feet, depth, loads, anchors, and exact manuals independently. Product range dimensions/prices are not universal design rules and are not embedded in the skill.\\n\\n## S4 - Sony: wall-mounted TV height\\n\\n- Source: [What is the recommended height when mounting the TV on a wall?](https://www.sony.com/electronics/support/articles/00026357).\\n- Type: manufacturer general support; US site. Retrieved page displayed article ID 00026358 and modification date 2019-08-19 despite the requested URL.\\n- Retrieved support: height depends on preference and seating; generally centre the screen at viewers' eye level; model-specific off-axis image characteristics need checking.\\n- Applied: actual seated eye measurements, posture trials, per-seat sightline checks.\\n- Limits: not a fixed floor-height rule, comfort guarantee, bracket specification, or installation manual. Panel viewing-angle specifications differ from the visual angle a screen occupies.\\n\\n## S5 - Sony: viewing distance qualifications\\n\\n- Source: [Recommended viewing distance for watching TV](https://www.sony.com/electronics/support/articles/00008601).\\n- Type: manufacturer general support; US site. Retrieved page displayed article ID 00008602 and modification date 2025-01-17.\\n- Retrieved support: distance depends on screen size/resolution, content, surroundings, and the viewer; adapt reference distances to preference and room layout.\\n- Applied: avoid a universal screen-diagonal multiplier; trial the intended screen and content.\\n- Limits: the fetched text did not expose the numeric content inside the 4K/HD/SD sections. No numerical distance recommendation is attributed to this source. The reference's screen-angle example is elementary geometry, not a Sony recommendation.\\n\\n## S6 - nullbarriere: living/sleeping-room accessibility\\n\\n- Source: [DIN 18040-2 Wohnraum, Schlafraum](https://nullbarriere.de/din18040-2-wohnraum-schlafraum.htm).\\n- Context: [DIN 18040-2 index](https://nullbarriere.de/din18040-2.htm), identifying edition 2011-09 and distinguishing ordinary barrier-free use from unrestricted wheelchair use (R).\\n- Type: German specialist secondary standard summary, not the normative text.\\n- Retrieved support: turning/movement areas of 1200 x 1200 mm and 1500 x 1500 mm for wheelchair use; depths along/in front of furniture of 900 mm and 1500 mm respectively; flexibility and functional access matter.\\n- Applied: qualified accessibility prompts and provisional checks; do not import ordinary coffee-table gaps into accessible approaches.\\n- Limits: current edition, legal adoption by federal state, contractual applicability, exact measurement provisions, and exceptions need verification from authoritative project sources. Full standard text was not reviewed. Bedroom examples and unrelated dimensions are not generalized into living-room rules.\\n\\n## S7 - Verbraucherzentrale: keep radiator heat flow clear\\n\\n- Source: [Heizung optimieren und Heizkosten sparen](https://www.verbraucherzentrale.de/wissen/energie/heizen-und-warmwasser/heizung-optimieren-und-heizkosten-sparen-30096).\\n- Type: German consumer advice; retrieved article dated 2026-10-08.\\n- Retrieved support: long curtains, furniture, and covers in front of radiators can trap heat, impair room warming, and distort thermostat sensing; keep radiators unobstructed.\\n- Applied: furniture/shading layout must preserve heat flow and usable controls.\\n- Limits: no universal clearance is inferred. Heating-system modification, fireplace clearances, and cold-wall moisture assessment require their own evidence. Unrelated legislation and numerical savings on this page are not used.\\n\\n## S8 - US CPSC: furniture and TV tip-over prevention\\n\\n- Source: [Anchor It!](https://www.anchorit.gov/).\\n- Type: US government consumer-safety campaign.\\n- Retrieved support: anchor susceptible furniture and televisions using suitable anchoring equipment; follow installation instructions.\\n- Applied: include anchoring in layout/installation planning, account for wall construction, and do not assume a low or visually stable unit needs no assessment.\\n- Limits: US regulations and typical wall construction are not German/EU requirements. Exact product manuals, appropriate substrate/fixings, and professional review control project installation. This skill does not reproduce a generic DIY anchoring procedure.\\n\\n## S9 - US CPSC: window-covering cords\\n\\n- Source: [Window Covering Cords](https://www.cpsc.gov/Safety-Education/Safety-Education-Centers/Window-Covering) (retrieved canonical destination: [Go Cordless](https://www.cpsc.gov/gocordless)).\\n- Type: US government consumer-safety guidance.\\n- Retrieved support: cordless coverings are the safest choice around young children; keep furniture that enables access away from windows/cords; mitigation of existing cords does not eliminate the hazard.\\n- Applied: check climbing routes and reachable cords when positioning sofas, shelves, and play areas; prefer cordless coverings.\\n- Limits: not a claim about current German/EU product law or a complete child-safety audit. No US retrofit dimensions or regulatory requirements are transposed into the skill.\\n\\n## Research gaps and update policy\\n\\n- The initially attempted living-room accessibility URL was invalid; S6 records the valid page found through the index, not the failed address.\\n- An attempted licht.de living-room page yielded no meaningful extract and is not used as evidence.\\n- The ordinary route, coffee-table, and conversation spacing ranges are explicitly labelled skill heuristics, not research-backed minima.\\n- Acoustic cautions and delivery/open-state checks are planning synthesis, not validated acoustic performance or model-specific installation data.\\n- No exact project manuals, current full DIN standard, local fire/escape rules, engineering calculations, or quantitative lighting/acoustic study were inspected.\\n- For updates, recheck the relevant article and its scope, then update the operational claim and its qualifications. Never replace a missing source with an unqualified mandatory-sounding number.\\n\"","/** A frontmatter field as YAML reads it: a scalar, or a nested field (metadata) as an object of scalars. */\nexport type FrontmatterValue = string | Record<string, string>;\n\n/** A planning skill in the Agent Skills format: a directory with SKILL.md and supporting files. */\nexport interface Skill {\n name: string;\n description: string;\n frontmatter: Record<string, FrontmatterValue>;\n /** The text of every file of the skill by its path in the skill's directory. */\n texts: Record<string, string>;\n files: string[];\n}\n\nexport const SKILL_FILE = 'SKILL.md';\n\n// The files of the skills directory, bundled as text, by their path below it.\nconst SKILL_FILES = Object.fromEntries(\n Object.entries(\n import.meta.glob<string>('./skills/**/*', {\n query: '?raw',\n import: 'default',\n eager: true,\n }),\n ).map(([path, text]) => [path.replace(/^\\.\\/skills\\//, ''), text]),\n);\n\nconst FRONTMATTER = /^---\\r?\\n([\\s\\S]*?)\\r?\\n---\\r?\\n/;\nconst FIELD = /^([A-Za-z][\\w-]*):\\s*(.*)$/;\nconst NESTED_FIELD = /^\\s+([A-Za-z][\\w-]*):\\s*(.*)$/;\nconst BLOCK_SCALAR = /^([|>])([+-]?)$/;\n\ninterface Field {\n value: string;\n lines: string[];\n}\n\nconst unquoted = (value: string): string =>\n /^'.*'$|^\".*\"$/.test(value) ? value.slice(1, -1) : value;\n\nconst folded = (lines: string[]): string =>\n lines\n .join('\\n')\n .split(/\\n\\s*\\n/)\n .map((paragraph) => paragraph.split('\\n').join(' '))\n .join('\\n');\n\n// The YAML of Agent Skills frontmatter: a plain, quoted, multi-line or block\n// scalar per field, a block scalar with its chomping (clip, - strip, + keep),\n// and a nested field (metadata) as an object of scalars.\nconst valueOf = ({ value, lines }: Field): FrontmatterValue => {\n const content = lines.filter((line) => line.trim());\n const block = BLOCK_SCALAR.exec(value);\n if (block) {\n const [, style, chomping] = block;\n const indent = Math.min(\n ...content.map((line) => line.length - line.trimStart().length),\n );\n const body = lines.map((line) => line.slice(indent));\n let end = body.length;\n while (end > 0 && !body[end - 1].trim()) {\n end--;\n }\n const core = body.slice(0, end);\n const text = style === '|' ? core.join('\\n') : folded(core);\n if (chomping === '-') {\n return text;\n }\n return text + '\\n'.repeat(chomping === '+' ? body.length - end + 1 : 1);\n }\n const nested = content.map((line) => NESTED_FIELD.exec(line));\n if (\n !value &&\n nested.length > 0 &&\n nested.every((field): field is RegExpExecArray => field !== null)\n ) {\n return Object.fromEntries(\n nested.map(([, key, nestedValue]) => [key, unquoted(nestedValue.trim())]),\n );\n }\n return unquoted(\n [value, ...content.map((line) => line.trim())].join(' ').trim(),\n );\n};\n\nconst frontmatterOf = (\n text: string,\n file: string,\n): Record<string, FrontmatterValue> => {\n const block = FRONTMATTER.exec(text)?.[1];\n if (block === undefined) {\n throw new Error(`${file}: no frontmatter`);\n }\n const fields: Record<string, Field> = {};\n let current: Field | undefined;\n for (const line of block.split(/\\r?\\n/)) {\n const field = FIELD.exec(line);\n if (field) {\n current = { value: field[2].trim(), lines: [] };\n fields[field[1]] = current;\n } else if (current && /^(\\s|$)/.test(line)) {\n current.lines.push(line);\n } else if (!line.startsWith('#')) {\n throw new Error(`${file}: the frontmatter line \"${line}\" is not a field`);\n }\n }\n return Object.fromEntries(\n Object.entries(fields).map(([key, field]) => [key, valueOf(field)]),\n );\n};\n\n/**\n * Reads every skill of the skills directory, given as the text of each file by\n * its path below the directory; a broken skill fails the load and names its\n * file.\n */\nexport const loadSkills = (files: Record<string, string>): Skill[] => {\n const directories = new Map<string, Record<string, string>>();\n for (const [path, text] of Object.entries(files)) {\n const [directory, ...rest] = path.split('/');\n if (rest.length > 0) {\n directories.set(directory, {\n ...directories.get(directory),\n [rest.join('/')]: text,\n });\n }\n }\n return [...directories]\n .map(([directory, texts]) => {\n const file = `skills/${directory}/${SKILL_FILE}`;\n if (texts[SKILL_FILE] === undefined) {\n throw new Error(`${file}: no such file`);\n }\n const frontmatter = frontmatterOf(texts[SKILL_FILE], file);\n const { name, description } = frontmatter;\n if (name !== directory) {\n throw new Error(\n `${file}: the name \"${name}\" differs from its directory \"${directory}\"`,\n );\n }\n if (typeof description !== 'string' || !description.trim()) {\n throw new Error(`${file}: no description`);\n }\n const supporting = Object.keys(texts)\n .filter((path) => path !== SKILL_FILE)\n .sort();\n return {\n name,\n description: description.trim(),\n frontmatter,\n texts,\n files: [SKILL_FILE, ...supporting],\n };\n })\n .sort((a, b) => a.name.localeCompare(b.name));\n};\n\n/** One line per skill: its name and its description. */\nexport const skillIndex = (skills: Skill[]): string =>\n skills.map((skill) => `- ${skill.name}: ${skill.description}`).join('\\n');\n\nconst skillFileText = (skill: Skill, path: string): string =>\n skill.texts[path].replace(/\\r\\n/g, '\\n');\n\n/** A file of a skill by its path; only a file of the skill's list is read. */\nexport const readSkillFile = (\n skills: Skill[],\n name: string,\n file: string = SKILL_FILE,\n): string => {\n const skill = skills.find((candidate) => candidate.name === name);\n if (!skill) {\n throw new Error(\n `Unknown skill \"${name}\" - the skills are ${skills.map((candidate) => candidate.name).join(', ')}`,\n );\n }\n const path = file.replace(/^(\\.\\/)+/, '');\n if (!skill.files.includes(path)) {\n throw new Error(\n `Unknown file \"${file}\" of the skill ${name} - its files are ${skill.files.join(', ')}`,\n );\n }\n return skillFileText(skill, path);\n};\n\nexport const skills = loadSkills(SKILL_FILES);\n","// The plan context in the words of the agent: wall names, room corners, the\n// wall of a door or a window, and the catalog's short descriptions.\n\ntype WallSide = 'left' | 'right' | 'top' | 'bottom';\n\ninterface DerivedWall {\n index: number;\n side: WallSide;\n start: [number, number, number];\n end: [number, number, number];\n lengthMm: number;\n type?: string;\n thicknessMm?: number;\n facingRotationY: number;\n}\n\n// + 0 turns IEEE -0 into +0 so serialized values never show -0\nconst round2 = (value: number): number => Math.round(value * 100) / 100 + 0;\n\nconst POINT_EPSILON_MM = 1;\n\nconst samePoint = (a: [number, number], b: [number, number]): boolean =>\n Math.hypot(a[0] - b[0], a[1] - b[1]) < POINT_EPSILON_MM;\n\nconst unitDirection = (\n from: [number, number],\n to: [number, number],\n): [number, number] | undefined => {\n const length = Math.hypot(to[0] - from[0], to[1] - from[1]);\n return length < 1e-6\n ? undefined\n : [(to[0] - from[0]) / length, (to[1] - from[1]) / length];\n};\n\nconst projectOntoAxis = (\n polygon: Array<[number, number]>,\n [axisX, axisZ]: [number, number],\n): [number, number] => {\n let minimum = Number.POSITIVE_INFINITY;\n let maximum = Number.NEGATIVE_INFINITY;\n for (const [x, z] of polygon) {\n const projection = x * axisX + z * axisZ;\n minimum = Math.min(minimum, projection);\n maximum = Math.max(maximum, projection);\n }\n return [minimum, maximum];\n};\n\nconst wallFloorPoints = ({\n start,\n end,\n}: DerivedWall): [[number, number], [number, number]] => [\n [start[0], start[2]],\n [end[0], end[2]],\n];\n\nconst WALL_NAMES: Record<WallSide, string> = {\n top: 'back wall',\n bottom: 'front wall',\n left: 'left wall',\n right: 'right wall',\n};\n\n// The name of a wall in the words of the user: back and front for the top and\n// the bottom of the top-view image.\nexport const wallName = (side: WallSide): string =>\n WALL_NAMES[side] ?? `${side} wall`;\n\nexport interface RoomCorner {\n name: string;\n point: [number, number, number];\n posRotationY: number;\n}\n\n// The corners of a room: where a wall or an opening ends and the next starts\n// at an angle that turns into the room - towards the side the ending one\n// faces, as the room lies left of the contour (D61). A partition and the inner\n// corner of an L-shaped room turn away from it and give none. The name is\n// back/front plus left/right, and posRotationY is the facingRotationY of the\n// wall that ends in the corner - the rotation of a corner kitchen there, for\n// both hands of corner article (D13, D33, D83).\nexport const roomCorners = (walls: DerivedWall[]): RoomCorner[] => {\n const corners: RoomCorner[] = [];\n for (const ending of walls) {\n const [endingStart, endPoint] = wallFloorPoints(ending);\n const along = unitDirection(endingStart, endPoint);\n for (const starting of walls) {\n const [startPoint, startingEnd] = wallFloorPoints(starting);\n const next = unitDirection(startPoint, startingEnd);\n if (\n starting === ending ||\n !samePoint(endPoint, startPoint) ||\n !along ||\n !next ||\n Math.abs(along[0] * next[0] + along[1] * next[1]) > 0.999 ||\n along[1] * next[0] - along[0] * next[1] <= 0\n ) {\n continue;\n }\n const sides = [ending.side, starting.side];\n const depth = sides.find((side) => side === 'top' || side === 'bottom');\n const hand = sides.find((side) => side === 'left' || side === 'right');\n if (!depth || !hand) {\n continue;\n }\n corners.push({\n name: `${depth === 'top' ? 'back' : 'front'} ${hand}`,\n point: [endPoint[0], 0, endPoint[1]],\n posRotationY: ending.facingRotationY,\n });\n }\n }\n return corners;\n};\n\n// The extent of room points along a wall, measured from the wall's start.\nexport const spanAlongWall = (\n wall: DerivedWall,\n points: Array<[number, number]>,\n): [number, number] => {\n const [[startX, startZ], [endX, endZ]] = wallFloorPoints(wall);\n const length = Math.hypot(endX - startX, endZ - startZ);\n const along: [number, number] = [\n (endX - startX) / length,\n (endZ - startZ) / length,\n ];\n return projectOntoAxis(\n points.map(([x, z]) => [x - startX, z - startZ]),\n along,\n );\n};\n\nexport interface WallOfOpening {\n roomIndex: number;\n wall: number;\n fromEndMm: [number, number];\n}\n\n// The wall a door or a window lies in: the wall whose line its floor outline\n// touches - within the wall's thickness - over the longest stretch. The span\n// is measured from the wall's end, like the d of a placement.\nexport const wallOfOpening = (\n outline: Array<[number, number]>,\n rooms: Array<{ walls?: DerivedWall[] }>,\n): WallOfOpening | undefined => {\n let found: WallOfOpening | undefined;\n let longestOverlap = POINT_EPSILON_MM;\n rooms.forEach((room, roomIndex) => {\n for (const wall of room.walls ?? []) {\n const [[startX, startZ], [endX, endZ]] = wallFloorPoints(wall);\n const along = unitDirection([startX, startZ], [endX, endZ]);\n if (!along) {\n continue;\n }\n const distanceToLine = Math.min(\n ...outline.map(([x, z]) =>\n Math.abs((x - startX) * along[1] - (z - startZ) * along[0]),\n ),\n );\n if (distanceToLine > (wall.thicknessMm ?? 0) + POINT_EPSILON_MM) {\n continue;\n }\n const length = Math.hypot(endX - startX, endZ - startZ);\n const [from, to] = spanAlongWall(wall, outline);\n const overlap = Math.min(to, length) - Math.max(from, 0);\n if (overlap > longestOverlap) {\n longestOverlap = overlap;\n found = {\n roomIndex,\n wall: wall.index,\n fromEndMm: [\n round2(length - Math.min(to, length)),\n round2(length - Math.max(from, 0)),\n ],\n };\n }\n }\n });\n return found;\n};\n\n// A sectioned article description - FUNCTION:, PURPOSE:, …,\n// AI_SELECTION_HINT: - shortened to what the article is and when to pick it.\nconst SHORT_DESCRIPTION_SECTIONS = ['FUNCTION', 'AI_SELECTION_HINT'];\nconst shortDescription = (desc: unknown): unknown => {\n if (typeof desc !== 'string') {\n return desc;\n }\n const lines = SHORT_DESCRIPTION_SECTIONS.map((section) =>\n desc\n .match(new RegExp(`(?:^|\\\\n)${section}:[ \\\\t]*\\\\n([^\\\\n]+)`))?.[1]\n ?.trim(),\n ).filter((line) => line);\n return lines.length > 0 ? lines.join(' ') : desc;\n};\n\n// A value list several attributes share is listed once: the later attributes\n// name the attribute that lists it.\nexport const withSharedSelectionsOnce = (attributes: any[]): any[] => {\n const listedBy = new Map<string, string>();\n return attributes.map((attribute) => {\n if (\n !Array.isArray(attribute.selections) ||\n attribute.selections.length === 0\n ) {\n return attribute;\n }\n const key = `${attribute.libraryId}\\n${JSON.stringify(attribute.selections, (field, value) => (field === 'imageUrl' ? undefined : value))}`;\n const listing = listedBy.get(key);\n if (listing === undefined) {\n listedBy.set(key, attribute.id);\n return attribute;\n }\n const shared = { ...attribute, sameSelectionsAs: listing };\n delete shared.selections;\n return shared;\n });\n};\n\n// Whether the agent sees and sets an attribute. The element type is what the\n// article is - another type is another article. The library does not mark such\n// attributes yet, so the element type is named here.\nexport const isAgentFacingAttribute = (attributeId: unknown): boolean =>\n attributeId !== 'mod_TypeElement';\n\n// A list of attributes or of attribute ids without those the agent does not see.\nconst agentFacingEntries = (entries: unknown): unknown =>\n Array.isArray(entries)\n ? entries.filter((entry) =>\n isAgentFacingAttribute(typeof entry === 'string' ? entry : entry?.id),\n )\n : entries;\n\nconst withAgentFacingAttributes = <T extends { attributes?: unknown }>(\n item: T,\n): T =>\n Array.isArray(item?.attributes)\n ? { ...item, attributes: agentFacingEntries(item.attributes) }\n : item;\n\n// The interior fittings without the attributes the agent does not see.\nexport const agentFacingFittings = (fittings: unknown): unknown =>\n Array.isArray(fittings) ? fittings.map(withAgentFacingAttributes) : fittings;\n\n// The groups without the attributes the agent does not see: those of the\n// group, its roots, their sub modules and the interior fittings.\nexport const agentFacingGroups = (groups: any): any =>\n Array.isArray(groups)\n ? groups.map((group) => ({\n ...withAgentFacingAttributes(group),\n ...(Array.isArray(group?.roots) && {\n roots: group.roots.map((root: any) => ({\n ...withAgentFacingAttributes(root),\n ...(Array.isArray(root?.subModules) && {\n subModules: root.subModules.map(withAgentFacingAttributes),\n }),\n })),\n }),\n ...(Array.isArray(group?.interiorFittings) && {\n interiorFittings: agentFacingFittings(group.interiorFittings),\n }),\n }))\n : groups;\n\n// The compacted master data without the attributes the agent does not see:\n// the attributes, the ids the modules carry and the group settings.\nexport const agentFacingMasterData = (masterData: any): any =>\n masterData !== null && typeof masterData === 'object'\n ? Object.fromEntries(\n Object.entries(masterData as Record<string, any>).map(\n ([libraryId, library]) => [\n libraryId,\n {\n ...withAgentFacingAttributes(library),\n ...(Array.isArray(library?.modules) && {\n modules: library.modules.map(withAgentFacingAttributes),\n }),\n ...(Array.isArray(library?.subModules) && {\n subModules: library.subModules.map(withAgentFacingAttributes),\n }),\n ...(Array.isArray(library?.groupSettings) && {\n groupSettings: agentFacingEntries(library.groupSettings),\n }),\n },\n ],\n ),\n )\n : masterData;\n\n// The attribute vocabulary: per library every attribute of the compacted master\n// data with its values, a shared value list listed once. The modules and the\n// group settings stay in masterData.\nexport const agentFacingAttributes = (masterData: any) =>\n Object.fromEntries(\n Object.entries((masterData ?? {}) as Record<string, any>).map(\n ([libraryId, library]) => [\n libraryId,\n withSharedSelectionsOnce((library?.attributes ?? []) as any[]),\n ],\n ),\n );\n\n// The corner point is not the agent's. The description is short; the\n// articleDescriptions section has the full one.\nexport const agentFacingArticle = (article: any) => {\n const compact = {\n ...article,\n ...(article.desc !== undefined && { desc: shortDescription(article.desc) }),\n ...(Array.isArray(article.rootModules) && {\n rootModules: article.rootModules.map((rootModule: any) => ({\n ...rootModule,\n ...(Array.isArray(rootModule?.dimensions) && {\n dimensions: agentFacingEntries(rootModule.dimensions),\n }),\n ...(Array.isArray(rootModule?.mainAttributes) && {\n mainAttributes: agentFacingEntries(rootModule.mainAttributes),\n }),\n })),\n }),\n };\n delete compact.cornerPoint;\n return compact;\n};\n\n// The walls in the words of the user: a name per wall, an opening named as\n// such (the contour gives it no type), and the room corners with their point\n// and the rotation of a group that starts with a corner article there.\nexport const agentFacingRooms = (rooms: any) => {\n if (!Array.isArray(rooms?.rooms)) {\n return rooms;\n }\n return {\n ...rooms,\n rooms: rooms.rooms.map((room: any) => {\n const walls = ((room?.walls ?? []) as any[]).map((wall) => ({\n ...wall,\n ...(wall?.type === null || wall?.type === undefined\n ? { type: 'opening' }\n : {}),\n name: wallName(wall?.side),\n }));\n return { ...room, walls, corners: roomCorners(walls) };\n }),\n };\n};\n\n// A door or a window lies in a wall: the room, the wall and its span along the\n// wall, measured from the wall's end like the d of a placement.\nexport const agentFacingObstacles = (obstacles: any, rooms: any) => {\n if (!Array.isArray(obstacles?.objects)) {\n return obstacles;\n }\n return {\n ...obstacles,\n objects: obstacles.objects.map((object: any) => {\n if (object?.kind !== 'door' && object?.kind !== 'window') {\n return object;\n }\n const wall = wallOfOpening(\n ((object.outline ?? []) as number[][]).map(\n ([x, , z]): [number, number] => [x, z],\n ),\n rooms?.rooms ?? [],\n );\n return wall ? { ...object, ...wall } : object;\n }),\n };\n};\n","import {\n agentFacingArticle,\n agentFacingAttributes,\n agentFacingFittings,\n agentFacingGroups,\n agentFacingMasterData,\n agentFacingObstacles,\n agentFacingRooms,\n withSharedSelectionsOnce,\n} from './agent-facing';\nimport type { PlanHistory, ToolCallRecord } from './plan-history';\nimport type { PlannerApi } from './planner-api';\nimport { readSkillFile, skills } from './skills';\n\nexport type ToolExecutor = (\n roomDesignerApi: PlannerApi,\n args: Record<string, unknown>,\n) => Promise<unknown>;\n\ntype PlanContextSection =\n | 'masterData'\n | 'rooms'\n | 'articles'\n | 'groups'\n | 'obstacles'\n | 'installationElements';\n\nconst PLAN_CONTEXT_SECTIONS: unknown[] = [\n 'masterData',\n 'rooms',\n 'articles',\n 'groups',\n 'obstacles',\n 'installationElements',\n];\n\n// The sections of these the library context returns; the others are the plan\n// context's.\nconst LIBRARY_CONTEXT_SECTIONS: unknown[] = ['masterData', 'articles'];\n\n// The sections of the server: the full descriptions of the catalog's\n// articles, and the attribute vocabulary, both derived from the planner's\n// sections.\nconst ARTICLE_DESCRIPTIONS = 'articleDescriptions';\nconst ATTRIBUTES = 'attributes';\nconst SERVER_SECTIONS: unknown[] = [ARTICLE_DESCRIPTIONS, ATTRIBUTES];\n\nconst DEFAULT_SECTIONS: unknown[] = [\n 'rooms',\n 'articles',\n ATTRIBUTES,\n 'groups',\n 'obstacles',\n 'installationElements',\n];\n\nconst MAX_ATTRIBUTE_MATCHES = 20;\n\n// The library spells one way, the agent often the other: both read alike.\nconst SPELLINGS: Array<[RegExp, string]> = [\n [/colour/g, 'color'],\n [/grey/g, 'gray'],\n [/worktop/g, 'countertop'],\n];\n\nconst searchable = (text: string): string =>\n SPELLINGS.reduce(\n (normalized, [spelling, as]) => normalized.replace(spelling, as),\n text.toLowerCase(),\n );\n\nconst searchWords = (text: string): string[] =>\n searchable(text)\n .split(/[\\s,;()-]+/)\n .filter((word) => word.length > 0);\n\n// Every word is in one of the attribute's fields.\nconst attributeMatches = (attribute: any, words: string[]): boolean => {\n const fields = [\n attribute.id,\n attribute.name,\n attribute.desc,\n attribute.group,\n ...(attribute.selections ?? []).flatMap((selection: any) => [\n selection.name,\n selection.desc,\n selection.value,\n ]),\n ]\n .filter((value) => value !== undefined && value !== null)\n .map((value) => searchable(String(value)));\n return words.every((word) => fields.some((field) => field.includes(word)));\n};\n\nconst rootsOfGroups = (groups: any[]): any[] =>\n groups.flatMap((group) => (group?.roots ?? []) as any[]);\n\nconst planGroups = async (roomDesignerApi: PlannerApi): Promise<any[]> =>\n ((await roomDesignerApi.extended.getExternalObjectPlanContext(['groups']))\n .groups ?? []) as any[];\n\nconst isObject = (value: unknown): boolean =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\n// A planner undo or redo is confirmed by its history event.\nconst HISTORY_EVENT_WAIT_MS = 1000;\n\nconst roundedToTenthMm = (_key: string, value: unknown) =>\n typeof value === 'number' ? Math.round(value * 10) / 10 : value;\n\n// The plan's groups as a comparison key, sorted by id - an undo restores them\n// to the tenth of a millimetre.\nconst groupsKey = (groups: unknown): string =>\n JSON.stringify(\n [...((groups ?? []) as any[])].sort((a, b) =>\n String(a?.id).localeCompare(String(b?.id)),\n ),\n roundedToTenthMm,\n );\n\nconst readGroupsKey = async (roomDesignerApi: PlannerApi) =>\n groupsKey(await planGroups(roomDesignerApi));\n\n// The planner API of a tool call that changes the plan. The tool runs in the\n// planner page as one group command, which answers after its last reload and\n// reports the steps it put on the planner's undo history - one per load that\n// loaded something and one per group command. The API counts the steps and\n// reads the plan before the first one.\nconst countingPlannerApi = (roomDesignerApi: PlannerApi) => {\n const { extended } = roomDesignerApi;\n const count = {\n steps: 0,\n groupsBefore: undefined as string | undefined,\n };\n const api: PlannerApi = {\n extended: {\n ...extended,\n externalObjectGroupOperation: async (command, payload) => {\n count.groupsBefore ??= await readGroupsKey(roomDesignerApi);\n const result = await extended.externalObjectGroupOperation(\n command,\n payload,\n );\n count.steps += Number(result?.historySteps ?? 1);\n return result;\n },\n },\n };\n return { api, count };\n};\n\ntype HistoryDirection = 'undo' | 'redo';\n\nconst NOTHING_TO_UNDO =\n 'Nothing to undo: no tool call has changed the plan since the planner page connected.';\nconst NOTHING_TO_REDO =\n 'Nothing to redo: redo brings back a tool call that undo reverted, and a new change of the plan ends redo.';\nconst CHANGED_IN_PLANNER =\n \"The plan was changed in the planner after the last tool call, so no tool call was reverted - the planner's own undo button reverts the changes made there.\";\n\n// The groups a tool call changed, by the plan before and after it: those it\n// created, removed or changed.\nconst changedGroupIds = (call: ToolCallRecord): Set<string> => {\n const byId = (key: string) =>\n new Map(\n ((JSON.parse(key) ?? []) as any[]).map((group) => [\n String(group?.id),\n JSON.stringify(group),\n ]),\n );\n const before = byId(call.groupsBefore);\n const after = byId(call.groupsAfter);\n return new Set(\n [...before.keys(), ...after.keys()].filter(\n (id) => before.get(id) !== after.get(id),\n ),\n );\n};\n\n// A result that changed some groups of the plan: those groups in full, the\n// others by their id - the agent knows them already.\nconst changedGroupsOnly = (\n groups: any[],\n changed: (group: any) => boolean,\n): { groups: any[]; otherGroupIds?: string[] } => {\n const others = groups.filter((group) => !changed(group));\n return {\n groups: groups.filter(changed),\n ...(others.length > 0 && {\n otherGroupIds: others.map((group) => group.id),\n }),\n };\n};\n\n// An attribute change answers with what changed, not with the whole group:\n// get-plan-context shows the group.\nconst compactAttributeResult = (result: any) => ({\n command: result.command,\n groupIds: ((result.groups ?? []) as any[]).map((group) => group.id),\n ...(result.changedModuleIds?.length > 0 && {\n changedModuleIds: result.changedModuleIds,\n }),\n ...(result.corrections?.length > 0 && { corrections: result.corrections }),\n});\n\n// The executors of one tool set: its plan changes run one after another and\n// its tool calls that changed the plan are recorded in its plan history.\nexport const createToolExecutors = (\n planHistory: PlanHistory,\n): Record<string, ToolExecutor> => {\n // The tool calls that change the plan run one after another: the record of a\n // call for undo compares the plan before and after it, and the page runs every\n // planner call it receives at once, so a concurrent call would mix into the\n // record. get-plan-context, find-attributes, get-price and get-order-data\n // wait as well, so that they never read a plan halfway through a change.\n let planChanges: Promise<unknown> = Promise.resolve();\n\n const oneAtATime =\n (executor: ToolExecutor): ToolExecutor =>\n (roomDesignerApi, args) => {\n const run = planChanges.then(() => executor(roomDesignerApi, args));\n planChanges = run.catch(() => undefined);\n return run;\n };\n // A tool call that changed the plan is recorded with its planner steps and\n // the plan before and after it, so that undo can revert it; the history\n // events while it runs are its own. A plan that cannot be read afterwards\n // leaves no record the undo could trust.\n const recorded =\n (tool: string, executor: ToolExecutor): ToolExecutor =>\n async (roomDesignerApi, args) => {\n const { api, count } = countingPlannerApi(roomDesignerApi);\n planHistory.begin();\n try {\n return await executor(api, args);\n } finally {\n const recordable = count.steps > 0 && count.groupsBefore !== undefined;\n let groupsAfter: string | undefined;\n if (recordable) {\n try {\n groupsAfter = await readGroupsKey(roomDesignerApi);\n } catch {\n groupsAfter = undefined;\n }\n }\n if (recordable && groupsAfter === undefined) {\n planHistory.forget();\n } else if (recordable) {\n planHistory.record({\n tool,\n steps: count.steps,\n groupsBefore: count.groupsBefore!,\n groupsAfter: groupsAfter!,\n });\n }\n planHistory.end();\n }\n };\n\n const planChange = (tool: string, executor: ToolExecutor): ToolExecutor =>\n oneAtATime(recorded(tool, executor));\n\n // One planner undo or redo per step, each confirmed by its history event.\n // Returns the number of steps done: fewer when the planner's history ran out.\n const stepHistory = async (\n roomDesignerApi: PlannerApi,\n direction: HistoryDirection,\n steps: number,\n ): Promise<number> => {\n planHistory.begin();\n try {\n for (let step = 0; step < steps; step++) {\n const eventsBefore = planHistory.events;\n await roomDesignerApi.extended[direction]();\n const confirmed = await planHistory.waitForEvents(\n eventsBefore + 1,\n HISTORY_EVENT_WAIT_MS,\n );\n if (!confirmed) {\n return step;\n }\n }\n return steps;\n } finally {\n planHistory.end();\n }\n };\n\n // undo reverts the last tool call that changed the plan, redo brings back the\n // last one undo reverted - only while the plan is as that call left it. The\n // server cannot keep the user from changing the plan in the planner while a\n // tool call runs, and such a change sits among the call's steps: an undo or\n // redo that does not give back the plan before or after the call is taken\n // back, so it never leaves a wrong revert in place.\n const revertToolCall =\n (direction: HistoryDirection): ToolExecutor =>\n async (roomDesignerApi) => {\n const undo = direction === 'undo';\n const call = undo ? planHistory.lastDone() : planHistory.lastUndone();\n const answer = async (tool: string | null, hint?: string) => ({\n [undo ? 'undone' : 'redone']: tool,\n groups: agentFacingGroups(await planGroups(roomDesignerApi)),\n ...(hint && { hint }),\n });\n if (!call) {\n return answer(\n null,\n planHistory.changedInPlanner\n ? CHANGED_IN_PLANNER\n : undo\n ? NOTHING_TO_UNDO\n : NOTHING_TO_REDO,\n );\n }\n const [from, to] = undo\n ? [call.groupsAfter, call.groupsBefore]\n : [call.groupsBefore, call.groupsAfter];\n if ((await readGroupsKey(roomDesignerApi)) !== from) {\n planHistory.forget();\n return answer(null, CHANGED_IN_PLANNER);\n }\n const done = await stepHistory(roomDesignerApi, direction, call.steps);\n if (done < call.steps) {\n planHistory.forget();\n return answer(\n null,\n done === 0\n ? `The planner's undo history no longer holds ${call.tool} - the plan was loaded again, nothing was ${undo ? 'undone' : 'redone'}.`\n : `The planner's undo history ended after ${done} of ${call.steps} steps of ${call.tool} - check the plan with get-plan-context.`,\n );\n }\n if ((await readGroupsKey(roomDesignerApi)) !== to) {\n const back = await stepHistory(\n roomDesignerApi,\n undo ? 'redo' : 'undo',\n call.steps,\n );\n const restored =\n back === call.steps &&\n (await readGroupsKey(roomDesignerApi)) === from;\n planHistory.markChangedInPlanner();\n const missed = `${undo ? 'Undo' : 'Redo'} of ${call.tool} did not give back the plan ${undo ? 'before' : 'after'} it - the plan was changed in the planner while the tool call ran.`;\n return answer(\n null,\n restored\n ? `${missed} The ${direction} was taken back and the plan is as it was; the planner's undo button reverts the changes made there.`\n : `${missed} The ${direction} could not be taken back completely - check the plan with get-plan-context.`,\n );\n }\n if (undo) {\n planHistory.markUndone();\n } else {\n planHistory.markRedone();\n }\n const changed = changedGroupIds(call);\n const groups = await planGroups(roomDesignerApi);\n const removed = [...changed].filter(\n (id) => !groups.some((group) => group.id === id),\n );\n return {\n [undo ? 'undone' : 'redone']: call.tool,\n ...changedGroupsOnly(agentFacingGroups(groups), (group) =>\n changed.has(group.id),\n ),\n ...(removed.length > 0 && { removedGroupIds: removed }),\n };\n };\n\n // The tools that change the plan run in the planner page: roomle-ui performs\n // the tool with the agent's arguments and reports the planner steps it made,\n // which the server records for undo. A tool that failed after it changed the\n // plan answers with its error and its steps: the steps are recorded, so undo\n // reverts them, and the agent gets the error.\n const inPlanner = (\n tool: string,\n shape: (result: any) => any = (result) => result,\n ): ToolExecutor =>\n planChange(tool, async (roomDesignerApi, args) => {\n const result = {\n ...(await roomDesignerApi.extended.externalObjectGroupOperation(\n tool,\n args,\n )),\n };\n delete result.historySteps;\n delete result.historyFollowUps;\n if (typeof result.error === 'string') {\n throw new Error(result.error);\n }\n if (result.groups !== undefined) {\n result.groups = agentFacingGroups(result.groups);\n }\n if (result.fittings !== undefined) {\n result.fittings = agentFacingFittings(result.fittings);\n }\n return shape(result);\n });\n\n return {\n 'add-interior-fitting': inPlanner('add-interior-fitting'),\n 'move-interior-fitting': inPlanner('move-interior-fitting'),\n 'delete-interior-fittings': inPlanner('delete-interior-fittings'),\n 'replace-interior-fitting': inPlanner('replace-interior-fitting'),\n 'open-or-close-group': inPlanner('open-or-close-group'),\n 'open-or-close-article': inPlanner('open-or-close-article'),\n 'get-interior-design-options': oneAtATime(async (api, args) => {\n const { groupId, rootId, containerModuleId, articleId } = args;\n if (typeof groupId !== 'string' || !groupId.trim()) {\n throw new Error('groupId is required for interior discovery.');\n }\n const { interiorDesign } =\n await api.extended.getExternalObjectPlanContext(['interiorDesign'], {\n interiorDesign: {\n groupId,\n ...(typeof rootId === 'string' && { rootId }),\n ...(typeof containerModuleId === 'string' && { containerModuleId }),\n ...(typeof articleId === 'string' && { articleId }),\n },\n });\n return interiorDesign?.fittings === undefined\n ? interiorDesign\n : {\n ...interiorDesign,\n fittings: agentFacingFittings(interiorDesign.fittings),\n };\n }),\n // The plan and the library context arrive agent-ready from the planner API\n // (compacted sections, 3D room contours with derived walls, the groups in\n // the frame a placement names); the executor asks each for its sections,\n // names the walls and leaves out the articles' corner points.\n 'get-plan-context': oneAtATime(async (roomDesignerApi, args) => {\n // an unknown section is ignored\n const named = (Array.isArray(args.include) ? args.include : []).filter(\n (section) =>\n PLAN_CONTEXT_SECTIONS.includes(section) ||\n SERVER_SECTIONS.includes(section),\n );\n const include = named.length > 0 ? named : DEFAULT_SECTIONS;\n const withDescriptions = include.includes(ARTICLE_DESCRIPTIONS);\n const withAttributes = include.includes(ATTRIBUTES);\n const requested = include.filter(\n (section): section is PlanContextSection =>\n PLAN_CONTEXT_SECTIONS.includes(section),\n );\n // the descriptions come with the articles\n const withArticles = withDescriptions && !requested.includes('articles');\n // the walls name the doors and windows of the obstacles\n const withRooms =\n requested.includes('obstacles') && !requested.includes('rooms');\n // the vocabulary comes with the master data\n const withMasterData =\n withAttributes && !requested.includes('masterData');\n const sections = [\n ...requested,\n ...(withRooms ? ['rooms' as const] : []),\n ...(withArticles ? ['articles' as const] : []),\n ...(withMasterData ? ['masterData' as const] : []),\n ];\n const planSections = sections.filter(\n (section) => !LIBRARY_CONTEXT_SECTIONS.includes(section),\n );\n const librarySections = sections.filter((section) =>\n LIBRARY_CONTEXT_SECTIONS.includes(section),\n );\n const [planContext, libraryContext] = await Promise.all([\n planSections.length > 0\n ? roomDesignerApi.extended.getExternalObjectPlanContext(planSections)\n : {},\n librarySections.length > 0\n ? roomDesignerApi.extended.getExternalObjectLibraryContext(\n librarySections,\n )\n : {},\n ]);\n if (!isObject(planContext)) {\n return planContext;\n }\n if (!isObject(libraryContext)) {\n return libraryContext;\n }\n const result: Record<string, any> = {\n ...planContext,\n ...libraryContext,\n };\n if (result.rooms !== undefined) {\n result.rooms = agentFacingRooms(result.rooms);\n }\n if (result.obstacles !== undefined) {\n result.obstacles = agentFacingObstacles(result.obstacles, result.rooms);\n }\n if (result.groups !== undefined) {\n result.groups = agentFacingGroups(result.groups);\n }\n if (result.masterData !== undefined) {\n result.masterData = agentFacingMasterData(result.masterData);\n }\n if (withRooms) {\n delete result.rooms;\n }\n if (Array.isArray(result.articles)) {\n const articles = result.articles as any[];\n if (withDescriptions) {\n result[ARTICLE_DESCRIPTIONS] = articles.map(\n ({ articleId, desc }) => ({\n articleId,\n desc,\n }),\n );\n }\n result.articles = articles.map((article) =>\n agentFacingArticle(article),\n );\n }\n if (withArticles) {\n delete result.articles;\n }\n if (withAttributes && result.masterData !== undefined) {\n result[ATTRIBUTES] = agentFacingAttributes(result.masterData);\n }\n if (withMasterData) {\n delete result.masterData;\n }\n return result;\n }),\n\n 'find-attributes': oneAtATime(async (roomDesignerApi, args) => {\n const words = searchWords(String(args.text ?? ''));\n if (words.length === 0) {\n throw new Error('text must not be empty.');\n }\n const libraryId = args.libraryId as string | undefined;\n const [planContext, libraryContext] = await Promise.all([\n roomDesignerApi.extended.getExternalObjectPlanContext(['groups']),\n roomDesignerApi.extended.getExternalObjectLibraryContext([\n 'masterData',\n ]),\n ]);\n const context = {\n groups: planContext?.groups,\n masterData: agentFacingMasterData(libraryContext?.masterData),\n };\n // the attributes the root modules in the plan and their sub modules\n // carry - the worktop of a group, not a panel top it does not have\n const inPlan = new Set(\n rootsOfGroups((context.groups ?? []) as any[]).flatMap((root) =>\n [root, ...((root?.subModules ?? []) as any[])].flatMap((module) =>\n ((module?.attributes ?? []) as any[]).map(\n (attribute) => attribute?.id,\n ),\n ),\n ),\n );\n const matches: any[] = [];\n for (const [id, masterData] of Object.entries(\n (context.masterData ?? {}) as Record<string, any>,\n )) {\n if (libraryId && id !== libraryId) {\n continue;\n }\n // The master data arrives compacted: every attribute, the root modules\n // and the sub modules with the attributes they carry.\n const carriers = (modules: any[], attributeId: string) =>\n modules\n .filter((module: any) =>\n (module.attributes ?? []).includes(attributeId),\n )\n .map((module: any) => ({ id: module.id, name: module.name }));\n for (const attribute of masterData.attributes ?? []) {\n if (!attributeMatches(attribute, words)) {\n continue;\n }\n const subModules = carriers(\n masterData.subModules ?? [],\n attribute.id,\n );\n matches.push({\n libraryId: id,\n ...attribute,\n rootModules: carriers(masterData.modules ?? [], attribute.id),\n ...(subModules.length > 0 && { subModules }),\n });\n }\n }\n const ranked = [\n ...matches.filter((match) => inPlan.has(match.id)),\n ...matches.filter((match) => !inPlan.has(match.id)),\n ];\n return {\n matches: withSharedSelectionsOnce(\n ranked.slice(0, MAX_ATTRIBUTE_MATCHES),\n ),\n total: matches.length,\n ...(matches.length > MAX_ATTRIBUTE_MATCHES && {\n hint: `Only the first ${MAX_ATTRIBUTE_MATCHES} of ${matches.length} matches are listed - narrow the text.`,\n }),\n };\n }),\n\n 'create-or-replace-groups': inPlanner('create-or-replace-groups'),\n 'place-group': inPlanner('place-group'),\n 'change-module-attribute': inPlanner(\n 'change-module-attribute',\n compactAttributeResult,\n ),\n 'change-group-attribute': inPlanner(\n 'change-group-attribute',\n compactAttributeResult,\n ),\n 'delete-group': inPlanner('delete-group'),\n 'delete-article-in-place': inPlanner('delete-article-in-place'),\n 'delete-article-and-compact': inPlanner('delete-article-and-compact'),\n 'merge-article-into-group': inPlanner('merge-article-into-group'),\n 'exchange-root-module': inPlanner('exchange-root-module'),\n 'insert-article-into-group': inPlanner('insert-article-into-group'),\n 'swap-root-modules': inPlanner('swap-root-modules'),\n 'merge-groups': inPlanner('merge-groups'),\n\n undo: oneAtATime(revertToolCall('undo')),\n\n redo: oneAtATime(revertToolCall('redo')),\n\n 'get-skill': async (_roomDesignerApi, { name, file }) =>\n readSkillFile(\n skills,\n String(name),\n file === undefined ? undefined : String(file),\n ),\n\n 'get-price': oneAtATime(async (roomDesignerApi) => {\n return roomDesignerApi.extended.fetchPrice();\n }),\n\n 'get-order-data': oneAtATime(async (roomDesignerApi) => {\n const snapshot = await roomDesignerApi.extended.getExternalObjectSnapshot(\n {\n orderData: true,\n },\n );\n return snapshot?.orderData ?? null;\n }),\n\n // waits like get-plan-context, so the images show the plan and the doors\n // after the change or the opening sent before them\n 'get-plan-images': oneAtATime(async (roomDesignerApi) => {\n const snapshot = await roomDesignerApi.extended.getExternalObjectSnapshot(\n {\n perspectiveObjectImage: true,\n topImage: true,\n keepOpenGeometry: true,\n },\n );\n return {\n perspectiveObjectImage: snapshot?.perspectiveObjectImage,\n topImage: snapshot?.topImage,\n };\n }),\n };\n};\n","import { z } from 'zod';\nimport { mcpTool } from './mcp-tool';\nimport type { HiAgentTools, McpToolResult } from './mcp-tool-types';\nimport { PlanHistory } from './plan-history';\nimport { createPlannerApi } from './planner-api';\nimport type { HiMcpPlannerApi } from './planner-api';\nimport { SKILL_FILE, skillIndex, skills } from './skills';\nimport { createToolExecutors } from './tool-executors';\n\nconst MOUNTING_GUIDANCE =\n 'Choose articles and mounting settings from their descriptions and attributes; categories organize the catalog. ' +\n 'For an article used at wall level, above names the root module below it and gapMm sets the clearance; ' +\n 'rightOf or leftOf continues that wall row, including its finishing parts. ' +\n 'Fetch articleDescriptions when its mounting requirements are unclear.';\n\nconst AUTHORING_RULES = `Authoring rules for pos groups:\n- ${MOUNTING_GUIDANCE}\n- Words: the catalog offers articles - cabinets, wardrobes, appliances, panels. A group is one piece of furniture made of articles: a kitchen, a wardrobe, a sideboard, a utility room, a row of cabinets. An article placed in a group is a root module (root for short); the user may call it a cabinet, a unit or a module. The description says what an article is and dimensions give its size. The user decides which articles stand next to each other: a low cabinet between two high cabinets is an order like any other. When the user names a kind, not an article, take the article of that kind from the category of its neighbours where that category has one (a kitchen cabinet into a kitchen, a wardrobe into a wardrobe), else the closest kind of another category.\n- A group is { id?, libraryId?, placement?, roots: [...] }. A root module is an article pick and nothing else: { id, articleId, attributes? } plus one relation that names its neighbour (rightOf, leftOf, onTop, above or behind - see Relations below). The server ignores every other field - a position on a root or a group included - and drops roots marked isGenerated (worktop, toe kick - the library regenerates them). Every root position comes from its relation; the position of a new group comes from its placement. Groups returned by get-plan-context carry their docking as contextData instead - resubmit them as they are. Use a unique id of your choice for new roots (the planner regenerates it and remaps your docking references); keep the real ids of roots that already exist in a replaced group. Choose the articleId from the article catalog of get-plan-context: desc and category say what an article is and what it is for, dimensions give its size (per size attribute its id, its name - e.g. Width, Depth, Height - and its value in millimetres; a root in groups carries the same attribute ids among its attributes, and change-module-attribute with that attribute id, never its name, changes the size of a root module; an article of another size - \"a 900 mm cabinet\" - is the same article with that attribute set, which merge-article-into-group, insert-article-into-group and exchange-root-module take in their attributes), dockingVectors the names of its docking vectors, subModules its fronts and appliances, cornerArticle true marks an article made for a room corner. Sub-modules come with the article. For Interior Design, interior fittings or sub-articles use get-interior-design-options and the interior fitting tools; never author nested module trees. Ask for clarification when the requested interior change or installed instance is ambiguous. Identify an upper/lower fitting from its measured position in the same parent, never its array order. attributes is an optional list of { id, value } overrides of that root module - an attribute only its sub modules carry is set on those sub modules; a material for the whole group - the fronts, the worktop, the carcase - goes into the group's attributes ({ id, value } entries beside roots), and the server sets it on every root module and on the worktop; a root module that names its own value of it in its attributes keeps that value - an accent, e.g. dark wall units in a light group. Attribute ids and their values are in the attributes section of get-plan-context - every attribute of the library with its values; a value list several attributes share is listed once, sameSelectionsAs names the attribute that lists it; the desc of a colour value carries its code. find-attributes answers a question about one attribute. Everything else the calculation needs is completed automatically from the article template.\n- Every desc - of an article, a root, a module, an attribute and an attribute value - is authoritative: trust it for what that article, module or value is, and trust dimensions for how big an article is. A colour code in the desc of an attribute value - Cloudy blue (#506080) - is the colour of that value: take it as it is, and tell light from dark and one hue from another by it, not by the name. All of them are authoritative over the catalog images of the master data (imageUrl): never take the kind or the size of an article, or the colour of a value, from a catalog image. A desc says what an article is, not where the user may put it.\n- Fronts: the front program says how a front is built - by its desc: simple fronts, frame fronts with wooden filling, mitred frame fronts with glass filling, milled fronts. Choose it by its desc first, then the front colour. A program offers only some colours: a colour it does not offer switches the program to one that does, and the fronts are then built as that program says; a program resets a colour it does not offer. corrections name every such change. When the colour the user wants comes only with fronts built differently, keep the fronts the user wants: undo a switched program, take the closest colour their program offers, and tell the user which fronts the wanted colour comes with.\n- Doors: a door is hinged on one side and has its handle on the other. In a row, the door at the left end is hinged on the left and the door at the right end on the right, as seen from the front, so no handle is on the outside of the row; a pair of doors side by side is hinged at its two outer sides. Set it with the attribute whose values say on which side a door is hinged - the value for single doors or for a pair of doors, as the article has - in the attributes of the root modules at the two ends of the row (rowIndex 1 and the last), and again on the root module at an end after an edit that gives the row a new end: an article added, deleted, exchanged or swapped at an end. The other doors keep their side.\n- One piece of furniture is one group. Every article standing beside, above or back to back with another article is a root module of the SAME group, related to it; a new group carries one placement, and the planner derives every root position from the relations. Never create a second group to put articles next to existing ones - articles that belong together are related.\n- Never author a position: roots are positioned by their relation only, a new group with placement only; a position on a root or a group is ignored.\n- Relations: every root after the first names one neighbour of the same group by its id, with exactly one of these fields - the server builds the docking from it:\n rightOf: \"<id>\" - the article stands right of that root module; leftOf: \"<id>\" - left of it (right and left as seen from the front). A row is each root module rightOf the one before.\n onTop: \"<id>\" - the article stands on top of that root module (stacking on a tall unit or a wall unit, also several levels); align: \"left\" (default), \"right\" or \"back\" says which edges line up, gapMm lifts it.\n above: \"<id>\" - a wall unit hanging above that floor-standing root module, at the height of the wall units; gapMm sets the gap below the wall unit instead.\n behind: \"<id>\" - back to back with that root module, turned by 180 degrees (an island).\n A wall unit rightOf or leftOf a tall unit hangs beside it with the tops flush, on the side of the base units (leftOf a tall unit that ends the row on the right); further wall units and the range hood continue rightOf or leftOf each other. Without a tall unit, the first wall unit hangs above a floor unit and the next ones continue rightOf or leftOf it; a range hood without wall units hangs above the hob unit.\n A room corner (an L-shaped kitchen, \"in the corner\"): start the group with a corner article (cornerArticle true in the catalog), give the group a placement at one wall of that corner with the other wall as alignment (the back right corner: wall right, alignment back), and continue one row rightOf the corner article and the other row leftOf it - the complete payload is example 3. The wall units of each leg hang above the floor units of that leg: the first one above a floor unit of the leg, the next ones rightOf or leftOf it; never put a wall unit on or above the corner article. Prefer a corner article over butting two straight articles together in a corner; a U-shaped kitchen continues a row with a second corner article.\n A root without a relation continues the row of its kind: right of the previous floor-standing root module or wall unit in the list; corrections says so.\n- Docking vectors: groups from get-plan-context show their docking as contextData - per root its ownDockingVector and the dockingVector of each root it names. RightBottom -> LeftBottom puts that root to the right, LeftBottom -> RightBottom to the left, a Top vector -> a Bottom vector on top, BackBottom -> BackBottom back to back. Two root modules that name each other with RightBottom -> LeftBottom stand side by side. freeDockingVectors are the vectors a new root module can dock to; merge-article-into-group names them in dockTo.\n- placement positions a new group, in one of two forms. At a wall or in a room corner: { wall, alignment?, offsetMm?, roomIndex? } - wall a side label (left, right, back, front; back = top, front = bottom in the top-view image) or the index of a wall in the walls array; alignment center (the default), the side label of the adjoining wall to stand flush in the corner the two walls share (wall back with alignment right: the back right corner; with two corner articles the first one in roots goes into the corner), or end; offsetMm moves the group along the wall away from that corner or from the wall's end; roomIndex the room, 0 by default. The server computes the point and the rotation from the calculated group, as place-group does; a group that would overlap another group moves along the wall to the nearest free place, and corrections say so. Anywhere else - an island, the middle of the room - and for a group of wall units only: { posGroup: [x, y, z], posRotationY, rootId? } - posGroup the room point of the group's back left bottom corner in millimetres (y up, y = 0 on the floor; for a group of wall units only, their mounting height), posRotationY its rotation in degrees, counter-clockwise as seen from above (in the top-view image), required, 0 for no rotation; rootId optional: with two corner articles, the one that goes into the corner posGroup names. A placement is applied exactly once, when the group is created; a placement on a group that is already in the plan is not used (move it with place-group), and groups returned by get-plan-context never carry this field.\n- Walls: every room of get-plan-context carries a walls array - per wall its index, side, name (back wall, front wall, left wall, right wall), start and end (points [x, 0, z] on the floor, in the coordinates of posGroup), lengthMm, type and facingRotationY, the posRotationY of a group with its back against that wall (back 0, left 90, front 180, right 270 in a rectangular room); a door or a floor-to-ceiling window splits a wall into several entries of the same side and name - pieces of type wall and the openings between them; a side label names the whole wall, and the server puts the group on its longest piece of wall, or across the openings when no piece is wide enough. For a group anywhere else (an island, the middle of the room, next to a door): any point on the floor as posGroup, any posRotationY.\n- Room corners: every room of get-plan-context carries a corners list - per corner its name (back left, back right, front left, front right; back = top, front = bottom in the top-view image) and its point. A group in a room corner names one of the two walls as wall and the other as alignment; a corner article first in the group goes into the corner. Looking into the corner from the room, the root modules rightOf the corner article run along the wall on the right, the root modules leftOf it along the wall on the left (the back right corner: rightOf along the right wall, leftOf along the back wall). This holds for both hands of corner article.\n- Obstacles: the obstacles section of get-plan-context lists what stands in the room, in the coordinates of the walls - objects (doors, windows, other furniture) with kind, outline (floor points [x, 0, z]) and bottomMm to topMm, a door or a window also with roomIndex, wall (its index in the walls array) and fromEndMm, its span along that wall measured from the wall's end -, and per group its root modules with id, outline and bottomMm to topMm. Root outlines bound the calculated parts and can extend past the docking edges over a neighbour in the same group; that overlap alone is not a placement error. A group goes where the user puts it - the wall, the corner or the spot the user names, also when a door or a window is there: the result's hint names what it stands in front of, and your answer says so. Where the user leaves the place open, choose a stretch of wall or a spot that obstacles leaves free: fromEndMm is measured from the wall's end, so a placement with that wall, alignment end and offsetMm = the start of a free stretch puts the group on it; base units lower than a window's bottomMm fit below it. A group placed in a room corner reaches along the adjoining wall by its depth: a door or a window of the adjoining wall that begins within that depth of the corner is in its way - when the user leaves the corner open, choose the other corner, or an offsetMm of at least 600 mm from that corner, which keeps the group out of the 600 mm strip in front of the opening. The result's hint names every root module that overlaps an object or another group or stands in front of a door or a window, with the free stretches of its wall, and for a group placed at a wall in front of a door or a window of the adjoining wall the offsetMm that keeps it clear.\n- Extending a group: articles next to an existing group are root modules of that group, never a new group. Dock each new article to a free docking vector of the root module it continues (freeDockingVectors per root: a free LeftBottom takes the new root's RightBottom, a free RightBottom takes LeftBottom, a free Top vector takes the new root's Bottom vector) - one article with merge-article-into-group, several at once by adding the picks, each with its relation, to the group from get-plan-context and resubmitting it with its id; an article between two root modules with insert-article-into-group. A new root module inherits the attributes the library passes on between neighbours - fronts, handles, carcase - from the root module it is docked to (insert-article-into-group: the first of between), as in the planner; its attributes override them. Never position a new group against an existing one.\n- To move an existing group against a wall or into a room corner, call place-group with wall, alignment and offsetMm as in a placement. The group keeps its roots and docking.\n- To change an existing group, use the command tools: merge-article-into-group adds an article at a free end of a row, insert-article-into-group inserts an article between two root modules, delete-article-and-compact deletes an article and closes the gap, delete-article-in-place deletes an article and leaves the gap (root modules no longer docked together become separate groups where they stand), exchange-root-module replaces a root module - with attributes also by an article of another width -, swap-root-modules lets two root modules change places, delete-group deletes a group, change-module-attribute and change-group-attribute set attributes, merge-groups joins groups where they stand (nothing is moved, no docking is added). Delete and remove mean the same: delete-article-in-place, unless the user asks to close the gap - then delete-article-and-compact. In an insert, a delete that closes the gap, an exchange or a swap the root modules at a wall or in a corner keep their place and the others move; wall units and the range hood move with the root module they hang from. Every command returns the changed groups. To rebuild a group, take it from get-plan-context, change it, and resubmit it with its id and without placement via create-or-replace-groups - it keeps its position; keep the ids of the root modules you keep.\n- Verify results numerically: the returned groups carry position (pos, rotationY, footprint) and per root the dockingVectors, the input attributes, the docking and rowIndex; the hint names a root module that stands on an obstacle. Do not judge a position from a rendering alone.\n- A root module named by its place - the middle unit, the second from the left, the last one - is found by rowIndex: its place in its row, 1 at the left end as seen from the front, floor units and wall units counted apart. The roots are listed in the order they were added, not in row order.\n- Undo a wrong result: when a result is not what was asked - the wrong wall, a root module missing or replaced by mistake, a merge or a delete that went wrong - call undo and send the corrected call, instead of correcting the wrong plan piece by piece; one undo reverts one tool call. A group that only needs a change is edited with the command tools. undo and redo also serve the user who asks for them.\n- Read corrections, notLoaded and hint in a result: corrections lists what the server changed in your input and has already applied, and what the library changed beyond the attribute you set - a front program switched by a front colour; notLoaded lists the groups and the roots it could not build or fully calculate, with what to send instead; hint names something to check that stopped nothing - a root module on an obstacle, with the free stretches of its wall.\n\nExample 1 - \"a row of three tall units along the right wall, from the back right corner\" is ONE call, create-or-replace-groups, placed at the right wall, flush into its corner with the back wall:\n{ \"posGroups\": [{ \"libraryId\": \"<libraryId>\", \"placement\": { \"wall\": \"right\", \"alignment\": \"back\" }, \"roots\": [\n { \"id\": \"u1\", \"articleId\": \"<articleId from the catalog>\" },\n { \"id\": \"u2\", \"articleId\": \"<articleId>\", \"rightOf\": \"u1\" },\n { \"id\": \"u3\", \"articleId\": \"<articleId>\", \"rightOf\": \"u2\" }\n] }] }\n\nExample 2 - \"a tall unit and two base units with a wall unit above each\" is the same call with these roots - the wall units hang beside the tall unit with the tops flush:\n { \"id\": \"t1\", \"articleId\": \"<tall unit>\" },\n { \"id\": \"b1\", \"articleId\": \"<base unit>\", \"rightOf\": \"t1\" },\n { \"id\": \"b2\", \"articleId\": \"<base unit>\", \"rightOf\": \"b1\" },\n { \"id\": \"w1\", \"articleId\": \"<wall unit>\", \"rightOf\": \"t1\" },\n { \"id\": \"w2\", \"articleId\": \"<wall unit>\", \"rightOf\": \"w1\" }\nWithout the tall unit, the first wall unit hangs above a base unit: { \"id\": \"w1\", \"articleId\": \"<wall unit>\", \"above\": \"b1\" }.\n\nExample 3 - \"an L-shaped kitchen in the back right corner\" (back = top in the top view) is ONE group starting with the corner article c1, placed at the right wall with the back wall as alignment; looking into the corner from the room, the root modules rightOf c1 run along the right wall, the root modules leftOf it along the back wall (see the corner rules above), and the wall units hang above the floor units of their leg:\n{ \"posGroups\": [{ \"libraryId\": \"<libraryId>\", \"placement\": { \"wall\": \"right\", \"alignment\": \"back\" }, \"roots\": [\n { \"id\": \"c1\", \"articleId\": \"<corner article, cornerArticle true>\" },\n { \"id\": \"r1\", \"articleId\": \"<base unit>\", \"rightOf\": \"c1\" },\n { \"id\": \"r2\", \"articleId\": \"<base unit>\", \"rightOf\": \"r1\" },\n { \"id\": \"l1\", \"articleId\": \"<base unit>\", \"leftOf\": \"c1\" },\n { \"id\": \"l2\", \"articleId\": \"<base unit>\", \"leftOf\": \"l1\" },\n { \"id\": \"w1\", \"articleId\": \"<wall unit>\", \"above\": \"r1\" },\n { \"id\": \"w2\", \"articleId\": \"<wall unit>\", \"above\": \"l1\" }\n] }] }\n\nExample 4 - \"the row centred on the back wall\" is \"placement\": { \"wall\": \"back\" } - centred is the default.\n\nExample 5 - \"add a cabinet to the right of the existing cabinets\" extends that group, never a new group: take the group from get-plan-context, find the root module with a free RightBottom (freeDockingVectors) and call merge-article-into-group { \"groupId\": \"<group id>\", \"articleId\": \"<article>\", \"dockTo\": { \"rootId\": \"<that root module>\", \"ownDockingVector\": \"RightBottom\", \"dockingVector\": \"LeftBottom\" } } - the group keeps its position.\n\nExample 6 - \"insert a low cabinet between the high cabinets\" is insert-article-into-group { \"groupId\": \"<group id>\", \"articleId\": \"<a base cabinet from the catalog>\", \"between\": [\"<first root module>\", \"<second root module>\"] }: the high cabinets are the two root modules of the group that stand side by side - whatever the group is, a wardrobe too -, the low cabinet an article about 720 mm high; the root modules on the side away from the wall move by the article's width, the ones at the wall keep their place.`;\n\n// Put before every SKILL.md: how a planning skill meets this session.\nconst SKILL_IN_SESSION =\n 'In this planning session the survey is the plan context - the walls, the doors and windows, the obstacles, the ' +\n 'installation elements with the positions of the electric plugs and the water connections - and the products are the ' +\n 'article catalog. What the plan context does not carry - services beyond those connection positions, budget, ' +\n 'inventory, the household - ' +\n 'is unknown: plan a concept with stated assumptions and name them in your answer, instead of asking first, unless the ' +\n 'user asks to be interviewed. The layout is the groups you create, one group per piece of furniture: check them against ' +\n 'the returned positions and the obstacles, and name the alternatives and the open checks in your answer instead of ' +\n 'building them.';\n\n// The plan context carries a signed CDN image URL for every article, module\n// and attribute value - three quarters of its tokens, and no agent can open them.\nconst withoutImageUrls = (key: string, value: unknown) =>\n key === 'imageUrl' ? undefined : value;\n\nconst textResult = (result: unknown) => ({\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(result ?? null, withoutImageUrls),\n },\n ],\n});\n\nconst PLAN_CHANGING_TOOLS = [\n 'add-interior-fitting',\n 'move-interior-fitting',\n 'delete-interior-fittings',\n 'replace-interior-fitting',\n 'create-or-replace-groups',\n 'place-group',\n 'change-module-attribute',\n 'change-group-attribute',\n 'delete-group',\n 'delete-article-in-place',\n 'delete-article-and-compact',\n 'merge-article-into-group',\n 'insert-article-into-group',\n 'exchange-root-module',\n 'swap-root-modules',\n 'merge-groups',\n 'undo',\n 'redo',\n];\n\nconst ATTRIBUTE_OVERRIDES = z.array(\n z.object({\n id: z.string(),\n value: z.union([z.string(), z.number(), z.boolean()]),\n }),\n);\n\nconst stripDataUrlPrefix = (image: string): string =>\n image.replace(/^data:image\\/\\w+;base64,/, '');\n\nexport const createHiMcpTools = (\n roomDesignerApi: HiMcpPlannerApi,\n): HiAgentTools => {\n // The tools tell their own planner steps from the changes the user makes in\n // the planner by the planner's history events; the handler the planner's UI\n // and the host set keeps running.\n const planHistory = new PlanHistory();\n const { callbacks } = roomDesignerApi.extended;\n const previousHistoryChange = callbacks.onHistoryChange;\n callbacks.onHistoryChange = (undo: boolean, redo: boolean) => {\n planHistory.historyChanged();\n previousHistoryChange?.call(callbacks, undo, redo);\n };\n const plannerApi = createPlannerApi(roomDesignerApi);\n const toolExecutors = createToolExecutors(planHistory);\n\n const tools: HiAgentTools = {};\n const registerTool = (\n name: string,\n {\n description,\n inputSchema,\n }: { description: string; inputSchema: z.ZodRawShape },\n handler: (args: any) => Promise<McpToolResult>,\n ) => {\n tools[name] = mcpTool(name, description, inputSchema, handler);\n };\n\n // What the agent sent to a tool that changes the plan, and the feedback it\n // got, go to the log as one JSON line each, so a test run can tell what the\n // agent sent and which corrections and errors it saw. The arguments are\n // copied first, so the log shows them as sent. Every call of a\n // tool that changes the plan ends with one feedback or error line, empty\n // feedback included, so a test run can pair the lines in call order.\n const runTool = async (tool: string, args: Record<string, unknown>) => {\n console.log(`[hi-mcp] tool ${tool}`);\n const sent = structuredClone(args);\n if (PLAN_CHANGING_TOOLS.includes(tool)) {\n console.log(`[hi-mcp] tool ${tool} args ${JSON.stringify(sent)}`);\n }\n try {\n const result = (await toolExecutors[tool](plannerApi, args)) as any;\n const { corrections, notLoaded } = result ?? {};\n if (corrections || notLoaded || PLAN_CHANGING_TOOLS.includes(tool)) {\n console.log(\n `[hi-mcp] tool ${tool} feedback ${JSON.stringify({ corrections, notLoaded })}`,\n );\n }\n return result;\n } catch (error) {\n console.log(\n `[hi-mcp] tool ${tool} error ${JSON.stringify({\n message: (error as Error)?.message ?? String(error),\n args: sent,\n })}`,\n );\n throw error;\n }\n };\n\n const fittingId = z.string().min(1);\n const insertion = z\n .tuple([z.number().finite(), z.number().finite(), z.number().finite()])\n .optional()\n .describe(\n 'Millimetres x right, y up, z front, relative to parentModuleId - the frame of a fitting position from get-interior-design-options; to move a fitting by an offset, add it to that position. Omit for the library default on add, or retain actual placement on move/replace. Read calculated result for adjustments.',\n );\n const destination = z.object({\n rootId: fittingId,\n containerModuleId: fittingId,\n parentModuleId: fittingId,\n });\n registerTool(\n 'get-interior-design-options',\n {\n description:\n 'Inspect Interior Design / interior fittings / sub-articles of one loaded HI group without selecting it. Returns unique installed instance IDs, parent-local positions where each fitting starts, compatible additions with destination tuples and fittings[].replacementArticles for each occupied parent. Choose replacements from that installed fitting, even when no additions fit. articleId filters addition/replacement candidates. Discover before editing; clarify ambiguous instances or unspecified interior changes. Empty options differ from unsupported or failed discovery. To see the fittings in get-plan-images, open the cabinet with open-or-close-article first.',\n inputSchema: {\n groupId: fittingId,\n rootId: fittingId.optional(),\n containerModuleId: fittingId.optional(),\n articleId: fittingId.optional(),\n },\n },\n async (args) =>\n textResult(await runTool('get-interior-design-options', args)),\n );\n registerTool(\n 'add-interior-fitting',\n {\n description:\n 'Add a compatible Interior Design fitting inside a group, using an article and destination returned by get-interior-design-options. Waits for final calculation/load and returns actual instance IDs, placement and corrections. One undoable action when changed.',\n inputSchema: {\n groupId: fittingId,\n articleId: fittingId,\n destination,\n insertPosition: insertion,\n },\n },\n async (args) => textResult(await runTool('add-interior-fitting', args)),\n );\n registerTool(\n 'move-interior-fitting',\n {\n description:\n 'Reposition one installed interior fitting or transfer it to a compatible container/root within the SAME group. Use its unique instanceId from discovery. Omitted destination keeps the current parent. Supply a destination and/or insertion point. Recreation may change the instance ID; use returned IDs.',\n inputSchema: {\n groupId: fittingId,\n instanceId: fittingId,\n destination: destination.optional(),\n insertPosition: insertion,\n },\n },\n async (args) => textResult(await runTool('move-interior-fitting', args)),\n );\n registerTool(\n 'delete-interior-fittings',\n {\n description:\n 'Delete the explicitly identified installed interior fittings of one group, preserving the cabinet and unrelated contents. Validates the entire batch before changing anything, deduplicates IDs with a correction, and makes one undoable action.',\n inputSchema: {\n groupId: fittingId,\n instanceIds: z.array(fittingId).min(1),\n },\n },\n async (args) => textResult(await runTool('delete-interior-fittings', args)),\n );\n registerTool(\n 'replace-interior-fitting',\n {\n description:\n 'Atomically replace one installed interior fitting with an article from its replacementArticles in get-interior-design-options, in its current parent, retaining actual placement and compatible settings. An explicit insertion point overrides placement. Failure restores the original; lost settings and new IDs are returned. Never implement replacement as separate delete and add calls.',\n inputSchema: {\n groupId: fittingId,\n instanceId: fittingId,\n articleId: fittingId,\n insertPosition: insertion,\n },\n },\n async (args) => textResult(await runTool('replace-interior-fitting', args)),\n );\n const VIEW_ONLY =\n 'It is a view of the planner: it changes nothing in the plan, is not saved, is not part of undo and changes ' +\n 'neither the price nor the order.';\n registerTool(\n 'open-or-close-group',\n {\n description:\n 'Opens (open true) or closes (open false) every door and drawer of a group at once, so get-plan-images ' +\n 'shows the group as it is - open it to look inside its cabinets. ' +\n VIEW_ONLY +\n ' A group without doors or drawers is named in corrections.',\n inputSchema: {\n groupId: z\n .string()\n .describe('The id of the group, as get-plan-context shows it.'),\n open: z.boolean().describe('true opens, false closes.'),\n },\n },\n async (args) => textResult(await runTool('open-or-close-group', args)),\n );\n registerTool(\n 'open-or-close-article',\n {\n description:\n 'Opens (open true) or closes (open false) the doors and drawers of one root module at once, none of the ' +\n 'root modules next to it, so get-plan-images shows the cabinet as it is - open it to look inside, at its ' +\n 'interior fittings for example. ' +\n VIEW_ONLY +\n ' A root module without doors or drawers is named in corrections.',\n inputSchema: {\n rootModuleId: z\n .string()\n .describe('The id of the root module, as get-plan-context shows it.'),\n open: z.boolean().describe('true opens, false closes.'),\n },\n },\n async (args) => textResult(await runTool('open-or-close-article', args)),\n );\n\n registerTool(\n 'get-plan-context',\n {\n description:\n MOUNTING_GUIDANCE +\n ' Returns a snapshot of the HI planning session, agent-ready as the planner API provides it - one coordinate ' +\n 'system throughout: 3D, right-handed, Y up (group pos and room contours use pos: [x, level, -y]). Default ' +\n 'sections: rooms (every room carries its contour levels with 3D segments and a derived walls array - per ' +\n 'wall: a side label (left/right/top/bottom as seen in the top-view image), start/end [x, 0, z] in millimetres ' +\n '(the 3D contour points on the floor), lengthMm, type, heightMm, thicknessMm and facingRotationY - the ' +\n 'posRotationY of a group standing with its back against that wall), articles (compact catalog: articleId, ' +\n 'name, desc - what the article is and when to pick it -, category, and per root module its master-data module, dimensions (the size attributes - ' +\n 'e.g. Width, Depth, Height - with their values in millimetres), main attribute values, ' +\n 'docking vector names, insert levels and sub-modules, plus cornerArticle ' +\n 'for articles made for a room corner), attributes (the attribute vocabulary: per library every ' +\n 'attribute with id, name, desc, group, type and its values - value, name, desc -, the ids ' +\n \"the catalog's mainAttributes, the roots' attributes and their sub modules' attributes carry; a value list several attributes share is \" +\n 'listed once, sameSelectionsAs names the attribute that lists it), ' +\n \"groups (the groups currently in the plan: position with pos - the room point of the group's back left bottom corner, as a placement names it - rotationY, rootId (only with two corner articles: the one pos belongs to) and footprint, and \" +\n 'per root the article pick with input attributes, docking, docking vector names and the free docking vectors ' +\n 'a new root can dock to, plus its desc, its subModules with their input attributes and its rowIndex, its place in its row - 1 at the left end as seen from the ' +\n 'front; floor units and wall units form rows of their own, and the roots are listed in the order they were added - ' +\n 'no root positions, ' +\n 'no geometry; a returned group is a valid create-or-replace-groups payload) and obstacles (what stands in the ' +\n 'room, in the coordinates of the walls: objects - doors, windows, other furniture - with kind, outline ' +\n \"(floor points [x, 0, z]) and bottomMm/topMm, a door or a window also with roomIndex, wall and fromEndMm (its span along that wall from the wall's end); \" +\n 'and per group its root modules with id, outline and bottomMm/topMm), ' +\n 'and installationElements (the electric plugs and the water connections of the plan: per element its type - ' +\n 'ElectricPlug or WaterConnection - and its position [x, level, z] in the coordinates of the walls; a ' +\n 'position only, no size, and no obstacle: a group may stand on a supply). ' +\n 'When an edit gives a row a new end, hinge its end doors at the outer sides: left at the left end, ' +\n \"right at the right end, as seen from the front. Choose the attribute and value from the library's \" +\n 'descriptions for single or paired doors, and keep other door directions unchanged. ' +\n 'Root outlines bound the calculated parts and can extend past the docking edges over a neighbour in the same group; ' +\n 'that overlap alone is not a placement error. ' +\n 'When a door or window determines a placement, briefly name it and explain whether the final placement ' +\n 'keeps it clear, using the returned obstacle dimensions and final tool results. masterData (per library the root ' +\n 'modules with their attribute ids, the attributes and the group settings) is returned only when included ' +\n 'explicitly. desc - what an article is and when to pick it - is enough to choose an article; ' +\n 'articleDescriptions (per article its full description: purpose, placement, requirements, neighbours, ' +\n 'restrictions, style) is returned only when included explicitly and answers a question about one ' +\n 'article, not the planning. Every desc is ' +\n 'authoritative and dimensions give the size - trust them over the catalog images (imageUrl); a colour ' +\n 'code in the desc of an attribute value (#rrggbb) is the colour of that value. Use it before ' +\n 'authoring or modifying groups.',\n inputSchema: {\n include: z\n .array(z.string())\n .optional()\n .describe(\n 'The sections to include: rooms, articles, attributes, groups, obstacles, installationElements, masterData, articleDescriptions. Default: rooms, articles, attributes, groups, obstacles and installationElements. ' +\n 'Add masterData for the root modules of the master data, articleDescriptions for a question about ' +\n \"one article's requirements and neighbours - desc is enough to pick the articles of a planning.\",\n ),\n },\n },\n async ({ include }) =>\n textResult(await runTool('get-plan-context', { include })),\n );\n\n registerTool(\n 'find-attributes',\n {\n description:\n 'Answers a question about an attribute: searches the attribute vocabulary - the attributes section of ' +\n 'get-plan-context - by text (attribute id, name, description, ' +\n 'group or selection name) and returns the matching attributes with their values (each with ' +\n 'its desc) and the root modules and sub modules that carry them, with their names - the worktop colour is the colour of ' +\n 'the root module Countertop; the attributes the root modules in the plan and their sub modules carry come first. ' +\n 'Your answer names the attribute by its name and its id - several attributes can share a name - with the values it lists. ' +\n 'The attributes section already holds every attribute with its values, so a planning needs no search; ' +\n 'search for the modules that carry an attribute, or for a property - e.g. \"front color\" - whose ' +\n 'attribute the section does not make obvious. Every word of the text is matched on ' +\n 'its own, in any order, British and American spelling alike (colour and color, grey and gray, worktop ' +\n 'and countertop): one search for \"color\" returns every colour attribute - front, carcase, countertop, ' +\n 'toe kick and the others - with their values, and a value list several attributes share is listed once ' +\n '(sameSelectionsAs names the attribute that lists it). The desc of a value carries ' +\n 'its colour code where the library gives one - Cloudy blue (#506080) -, the colour of that value: ' +\n 'pick a dark, a light or a blue value by its code.',\n inputSchema: {\n text: z\n .string()\n .min(1)\n .describe('The words to search for, case-insensitive.'),\n libraryId: z\n .string()\n .optional()\n .describe('Restricts the search to one library.'),\n },\n },\n async ({ text, libraryId }) =>\n textResult(await runTool('find-attributes', { text, libraryId })),\n );\n\n registerTool(\n 'get-authoring-rules',\n {\n description:\n 'Returns the authoring rules for pos groups: the payload format of create-or-replace-groups, the root ' +\n 'module fields, how to position a new group with a placement and move an existing one with place-group, ' +\n 'the relations a unit names its neighbour with (rightOf, leftOf, onTop, above, behind), the docking vector ' +\n 'names of existing groups, and complete examples for a row against a wall, wall units beside a tall unit, ' +\n 'a group around a room corner and extending a group. Fetch this before authoring pos groups.',\n inputSchema: {},\n },\n async () => ({\n content: [{ type: 'text' as const, text: AUTHORING_RULES }],\n }),\n );\n\n registerTool(\n 'get-skill',\n {\n description:\n 'Returns a planning skill: how to plan a room of one kind, or from an image the user sends, well - the workflow, ' +\n 'the zones, the dimensions and the checks. Before planning a room of a kind listed here, or from an image, fetch ' +\n 'its skill and follow it; fetch the files it names with file. Skills:\\n' +\n skillIndex(skills),\n inputSchema: {\n name: z.string().describe('The name of the skill'),\n file: z\n .string()\n .optional()\n .describe(\n 'A file of the skill by its path, e.g. references/planning-reference.md; SKILL.md by default',\n ),\n },\n },\n async ({ name, file }) => {\n const text = (await runTool('get-skill', { name, file })) as string;\n const preamble =\n file === undefined || file.replace(/^(\\.\\/)+/, '') === SKILL_FILE\n ? `${SKILL_IN_SESSION}\\n\\n`\n : '';\n return {\n content: [{ type: 'text' as const, text: `${preamble}${text}` }],\n };\n },\n );\n\n registerTool(\n 'create-or-replace-groups',\n {\n description:\n MOUNTING_GUIDANCE +\n ' Creates or replaces HI object groups in the plan from an array of pos groups. Roots are article picks ' +\n '({ id, articleId, attributes? }) - the server completes them from the article template -, and every root ' +\n 'after the first names its neighbour with one relation: rightOf, leftOf, onTop, above or behind with the ' +\n 'id of the neighbour; the server builds the docking from it, and the planner arranges the root modules; never author root ' +\n 'positions. Author one piece of furniture as ONE group: articles beside, above or back to back with each other are ' +\n \"related root modules of the same group, never separately positioned groups; a material for the whole group goes into the group's attributes, and a root module's own value of it stays. \" +\n 'A group is created with all its articles in one call: roots holds every article of the group from the first call, each with its relation - a group is never created empty and filled later. ' +\n 'An article beside an existing group goes into that group: merge-article-into-group at the end of a row, insert-article-into-group between two root modules. ' +\n 'Position a new group in the same ' +\n 'call with placement. At a wall or in a room corner: { wall, alignment?, offsetMm?, roomIndex? } - wall a ' +\n 'side label (left, right, back, front) or a wall index; alignment center (the default), the side label ' +\n 'of the adjoining wall, which puts the group flush into that corner (wall back with alignment right: the ' +\n 'back right corner) and a group that starts with a corner article into the corner, or end; offsetMm moves ' +\n \"it along the wall away from that corner or from the wall's end - the fromEndMm of the obstacles is \" +\n 'measured from there; roomIndex the room, 0 by default. The server computes the point and the rotation. ' +\n 'Anywhere else, an island or ' +\n \"a free spot: { posGroup, posRotationY }, the room point of the group's back left corner and its \" +\n 'rotation. A group whose id matches an existing group completely ' +\n 'replaces that group and keeps its position (root modules keep their ids when they already exist in ' +\n 'the replaced group; a placement on it is not used; a root module the replace adds inherits ' +\n 'the attributes the library passes on between neighbours - fronts, handles, carcase - from the root module it is docked to, and its attributes override them); ' +\n 'all other groups are created with regenerated ids. Returns the loaded object ids, the groups of the call - ' +\n 'check their pos and footprint - and otherGroupIds, the other groups of the plan, unchanged; plus groupAttributes (per group the group attributes set on every unit, ' +\n 'notCarried: attributes no current module carries. For a requested part the library generates, use find-attributes to look for an enabling attribute on the units; ' +\n \"if available, enable it, then set the part's attributes after it is generated. Report only what is still missing. \" +\n 'rootValues: the root modules that keep their own value of one), corrections (what ' +\n 'the server changed in the input, and what the library ' +\n 'changed beyond the attributes sent - a front colour reset by a front program), notLoaded (the groups it ' +\n 'could not build or roots it could not fully calculate, with what to send instead) and hint (a root module on an obstacle, in another group or in front of ' +\n 'a door or a window, with the free stretches of its wall and the offsetMm that clears an opening of the adjoining wall). ' +\n 'The payload format is returned by get-authoring-rules.',\n inputSchema: {\n posGroups: z\n .array(z.record(z.string(), z.unknown()))\n .min(1)\n .describe(\n 'The pos groups to create or replace, following the rules returned by get-authoring-rules.',\n ),\n },\n },\n async ({ posGroups }) =>\n textResult(await runTool('create-or-replace-groups', { posGroups })),\n );\n\n registerTool(\n 'place-group',\n {\n description:\n 'Moves an existing group against a wall of a room or into a room corner and reloads it there: the ' +\n \"server computes the position from the wall, the alignment and the group's calculated footprint; a \" +\n 'group with a corner article goes into the corner when the alignment names the adjoining wall. A ' +\n 'target that overlaps another group moves along the wall to the nearest free position; corrections in ' +\n 'the result say so. Name the wall by its side ' +\n 'label (left/right/top/bottom as seen in the top-view image) or its index in the walls array of ' +\n 'get-plan-context. Use it to move a group that is already in the plan; a new group takes the same ' +\n 'wall, alignment and offsetMm in its placement in create-or-replace-groups. Returns placedIn (corner or ' +\n 'wall), the wall, the resulting group and a hint when a root module stands on an object or in front of ' +\n 'a door or a window.',\n inputSchema: {\n groupId: z\n .string()\n .describe(\n 'The id of the group to move. A unique id prefix is accepted.',\n ),\n wall: z\n .union([\n z.enum(['left', 'right', 'top', 'bottom', 'back', 'front']),\n z.number().int().min(0),\n ])\n .describe(\n \"The target wall: a side label as seen in the top view ('right' is the whole right wall, its \" +\n \"doors and floor-to-ceiling windows included; 'back' is 'top', 'front' is 'bottom') or a \" +\n 'wall index from the walls array of get-plan-context, which names one piece of a wall.',\n ),\n roomIndex: z\n .number()\n .int()\n .min(0)\n .optional()\n .describe('The index of the room in the rooms array. Defaults to 0.'),\n alignment: z\n .enum([\n 'start',\n 'center',\n 'end',\n 'left',\n 'right',\n 'top',\n 'bottom',\n 'back',\n 'front',\n ])\n .optional()\n .describe(\n \"Where the group sits along the wall: 'center' (default), 'start'/'end' (the wall's endpoints), \" +\n 'or the side label of an adjoining wall to sit flush in that corner (e.g. wall \"right\" + ' +\n 'alignment \"top\" is the back right corner in the top view).',\n ),\n offsetMm: z\n .number()\n .optional()\n .describe(\n 'Extra distance in millimetres along the wall from the chosen alignment. Defaults to 0.',\n ),\n },\n },\n async ({ groupId, wall, roomIndex, alignment, offsetMm }) =>\n textResult(\n await runTool('place-group', {\n groupId,\n wall,\n roomIndex,\n alignment,\n offsetMm,\n }),\n ),\n );\n\n registerTool(\n 'change-module-attribute',\n {\n description:\n 'Sets one attribute of one or more root modules in the plan and of their sub modules that carry it - ' +\n 'the front colour of a root module reaches its fronts -, or with moduleId of that one sub module of ' +\n 'each root module only, and recalculates their groups: name every root module that gets the value in ' +\n 'one call, e.g. the accent fronts of a row. The root modules may belong to one group or to several. ' +\n 'The ids are the ones get-plan-context shows (a sub module by its id in ' +\n 'subModules); attribute ids and values are in the attributes section of get-plan-context. ' +\n 'The library may change a related attribute with it - a front colour the front program does not offer ' +\n 'switches the program, and the fronts are built differently; corrections name every attribute the ' +\n 'library changed besides the one set. ' +\n 'Returns the ids of the changed groups and modules and the corrections; get-plan-context shows the groups.',\n inputSchema: {\n rootModuleIds: z\n .array(z.string())\n .optional()\n .describe('The ids of the root modules that get the value.'),\n rootModuleId: z\n .string()\n .optional()\n .describe('The id of a single root module, as one of rootModuleIds.'),\n moduleId: z\n .string()\n .optional()\n .describe(\n 'The id of the sub module. Omit to change the root modules and their sub modules that carry the attribute.',\n ),\n attributeId: z.string().describe('The id of the attribute.'),\n value: z\n .union([z.string(), z.number(), z.boolean()])\n .describe('The new value: a string, a number or a boolean.'),\n },\n },\n async (args) => textResult(await runTool('change-module-attribute', args)),\n );\n\n registerTool(\n 'change-group-attribute',\n {\n description:\n 'Sets attributes on every module of a group that has them - the root modules and their sub ' +\n 'modules, e.g. the front colour of a whole group - in one recalculation: one attribute with attributeId ' +\n 'and value, several at once with attributes - all the materials of a group in one call, the programs set ' +\n 'before the colours. ' +\n 'The library may change a related attribute with it - a front colour the front program does not offer ' +\n 'switches the program, and the fronts are built differently; corrections name every attribute the ' +\n 'library changed besides the ones set, and an attribute no module of the group has. ' +\n 'Returns the id of the group, the ids of the changed modules and the corrections; get-plan-context shows the group.',\n inputSchema: {\n groupId: z\n .string()\n .describe('The id of the group. A unique id prefix is accepted.'),\n attributeId: z\n .string()\n .optional()\n .describe('The id of the attribute, with value.'),\n value: z\n .union([z.string(), z.number(), z.boolean()])\n .optional()\n .describe('The new value: a string, a number or a boolean.'),\n attributes: z\n .array(\n z.object({\n attributeId: z.string(),\n value: z.union([z.string(), z.number(), z.boolean()]),\n }),\n )\n .min(1)\n .optional()\n .describe(\n 'Several attributes set in one recalculation: [{ attributeId, value }].',\n ),\n },\n },\n async (args) => textResult(await runTool('change-group-attribute', args)),\n );\n\n registerTool(\n 'delete-group',\n {\n description:\n 'Deletes a group with all its root modules from the plan. Returns the id of the deleted group.',\n inputSchema: {\n groupId: z\n .string()\n .describe('The id of the group. A unique id prefix is accepted.'),\n },\n },\n async (args) => textResult(await runTool('delete-group', args)),\n );\n\n registerTool(\n 'delete-article-in-place',\n {\n description:\n 'Deletes an article from its group and leaves the gap - the tool for \"delete\" or \"remove\" when the user does ' +\n 'not ask to close the gap: every other root module keeps its place; root modules that are no longer ' +\n 'docked together afterwards become separate groups where they stand, and deleting the only root module deletes ' +\n 'the group. To close the gap, use delete-article-and-compact. Generated roots (worktop, toe kick) ' +\n 'cannot be deleted - the library regenerates them. Returns the remaining groups.',\n inputSchema: {\n rootModuleId: z.string().describe('The id of the root module.'),\n },\n },\n async (args) => textResult(await runTool('delete-article-in-place', args)),\n );\n\n registerTool(\n 'delete-article-and-compact',\n {\n description:\n 'Deletes an article from its group and closes the gap - the tool when the user asks to close the gap (move ' +\n 'the others up, keep the row together): the root modules beside it are docked together, and the ' +\n 'root modules at a wall or in a corner keep their place. A wall unit or a range hood that hung from the ' +\n 'deleted root module hangs from the one that moves into the gap. A root module with a neighbour on one side only is deleted and ' +\n 'nothing else moves. Deleting a corner article between two legs closes the gap as well: one leg turns by 90 ' +\n 'degrees, with the units above it, and is docked to the other, so the legs form one straight row - the result ' +\n 'names the leg that turned. Deleting the only root module deletes the group. To leave the gap, ' +\n 'use delete-article-in-place. Generated roots ' +\n '(worktop, toe kick) cannot be deleted - the library regenerates them. Returns the changed group.',\n inputSchema: {\n groupId: z\n .string()\n .optional()\n .describe(\n 'The id of the group, optional - left out, the server takes the group of the root module. ' +\n 'A unique id prefix is accepted.',\n ),\n rootModuleId: z.string().describe('The id of the root module.'),\n },\n },\n async (args) =>\n textResult(await runTool('delete-article-and-compact', args)),\n );\n\n registerTool(\n 'merge-article-into-group',\n {\n description:\n 'Adds one article to an existing group as a new root module: docks it to a ' +\n 'free docking vector of a root module of the group, the way the authoring rules describe docking. dockTo ' +\n \"names the root module the article continues, that root module's free vector (one of its freeDockingVectors in \" +\n \"get-plan-context) and the new root module's vector: RightBottom -> LeftBottom puts it to the right, \" +\n 'LeftBottom -> RightBottom to the left, LeftTop -> LeftBottom hangs a wall unit or a range hood above ' +\n 'a floor-standing root module at the height of the wall units. For an article mounted above a floor unit, ' +\n 'the server sets the gap when offset has no y value; a supplied y value is the clearance, and an explicit zero stays zero. The new root module inherits ' +\n 'the attributes the library passes on between neighbours - fronts, handles, carcase - from the root module of dockTo, as in the planner; attributes override them. ' +\n 'To put an article between two root modules, use insert-article-into-group. The group keeps its position. Returns the changed group.',\n inputSchema: {\n groupId: z\n .string()\n .describe('The id of the group. A unique id prefix is accepted.'),\n articleId: z.string().describe('The article id from the catalog.'),\n attributes: ATTRIBUTE_OVERRIDES.optional().describe(\n 'Attribute overrides of the new root module: [{ id, value }].',\n ),\n dockTo: z\n .object({\n rootId: z\n .string()\n .describe(\n 'The id of the root module of the group the new article docks to.',\n ),\n ownDockingVector: z\n .string()\n .describe(\n \"That root module's free docking vector, e.g. RightBottom.\",\n ),\n dockingVector: z\n .string()\n .describe(\n \"The new root module's docking vector that meets it, e.g. LeftBottom.\",\n ),\n mode: z\n .enum(['StartStart', 'EndEnd', 'StartEnd', 'EndStart'])\n .optional()\n .describe(\n 'Which endpoints of the two vectors coincide. Default StartStart.',\n ),\n offset: z\n .tuple([z.number(), z.number(), z.number()])\n .optional()\n .describe(\n '[x, y, z] in millimetres added after docking. For an article mounted above a floor-standing root module, omit offset to let the server set the hang gap; a supplied y value sets the clearance, including zero. Otherwise the default is [0, 0, 0].',\n ),\n })\n .describe('Where the new root module docks.'),\n },\n },\n async (args) => textResult(await runTool('merge-article-into-group', args)),\n );\n\n registerTool(\n 'insert-article-into-group',\n {\n description:\n 'Inserts one article from the catalog between two root modules of an existing group that stand side by side - ' +\n 'whatever the group is and whatever the article is: a low cabinet between two high cabinets or wardrobes too; the user ' +\n 'decides what stands between what. between names the two root modules, in either order; a group of two root modules ' +\n 'has one place to insert: between them. No gap is needed - the tool makes room. The new root module is docked to both; the root modules at a wall or in a ' +\n \"corner keep their place, the others move by the article's width. Wall units and the range hood move with the \" +\n 'root module they hang from. The new root module inherits the attributes the library passes on between neighbours - fronts, handles, carcase - from the first root module of between, ' +\n 'as in the planner; attributes override them. To add an article beside the last root module of a row, use merge-article-into-group. ' +\n 'Returns the changed group.',\n inputSchema: {\n groupId: z\n .string()\n .describe('The id of the group. A unique id prefix is accepted.'),\n articleId: z.string().describe('The article id from the catalog.'),\n attributes: ATTRIBUTE_OVERRIDES.optional().describe(\n 'Attribute overrides of the new root module: [{ id, value }].',\n ),\n between: z\n .tuple([z.string(), z.string()])\n .describe(\n 'The ids of the two root modules that stand side by side and take the new article between them, in either order.',\n ),\n },\n },\n async (args) =>\n textResult(await runTool('insert-article-into-group', args)),\n );\n\n registerTool(\n 'exchange-root-module',\n {\n description:\n 'Replaces one root module of a group with an article from the catalog that has one root ' +\n 'module, e.g. a base cabinet with a drawer cabinet; the new root module takes over the position, the docking and ' +\n 'the attributes the library passes on between neighbours - fronts, handles, carcase - of the replaced one, as in the planner; attributes override them, e.g. mod_Width 900 for an article of ' +\n 'another width: the other root modules move by the difference, and the ones at a wall keep their ' +\n 'place. A docking the new article cannot take is named in corrections. Returns the changed group.',\n inputSchema: {\n groupId: z\n .string()\n .describe('The id of the group. A unique id prefix is accepted.'),\n rootModuleId: z\n .string()\n .describe('The id of the root module to replace.'),\n articleId: z.string().describe('The article id from the catalog.'),\n attributes: ATTRIBUTE_OVERRIDES.optional().describe(\n 'Attribute overrides of the new root module: [{ id, value }].',\n ),\n },\n },\n async (args) => textResult(await runTool('exchange-root-module', args)),\n );\n\n registerTool(\n 'swap-root-modules',\n {\n description:\n 'Lets two root modules of a group change places, neighbours or not. Each keeps its attributes, and the ' +\n 'wall units and the range hood hanging from a root module move with it. The group keeps its length, and the root modules ' +\n 'at a wall keep their place. Returns the changed group.',\n inputSchema: {\n groupId: z\n .string()\n .describe('The id of the group. A unique id prefix is accepted.'),\n rootModuleIds: z\n .tuple([z.string(), z.string()])\n .describe('The ids of the two root modules that change places.'),\n },\n },\n async (args) => textResult(await runTool('swap-root-modules', args)),\n );\n\n registerTool(\n 'merge-groups',\n {\n description:\n 'Joins groups into one: the groups in groupIds are merged into the target group where they stand, ' +\n 'like the merge action of the planner - nothing is moved and no docking is added, so merge groups ' +\n 'that already stand next to each other. Groups of different libraries cannot be merged. To add an article ' +\n 'next to a group, use merge-article-into-group instead. Returns the merged group and the ids of the ' +\n 'groups merged into it.',\n inputSchema: {\n targetGroupId: z\n .string()\n .describe(\n 'The id of the group the others are merged into. A unique id prefix is accepted.',\n ),\n groupIds: z\n .array(z.string())\n .min(1)\n .describe('The ids of the groups to merge into the target group.'),\n },\n },\n async (args) => textResult(await runTool('merge-groups', args)),\n );\n\n registerTool(\n 'undo',\n {\n description:\n \"Reverts the plan change of the last tool call that changed the plan, as the planner's undo does. \" +\n 'Use it when that result is not what was asked - the user says it was the wrong article, wall or group, or a ' +\n 'merge or delete went wrong - and then send the corrected call; call it again to revert the call before. ' +\n 'To bring back what an undo reverted, call redo, not undo. ' +\n 'Returns the reverted tool, the groups it changed back as they are now, removedGroupIds - the groups it took out ' +\n 'of the plan - and otherGroupIds, the groups it left as they were; when there is nothing to undo, the result says so.',\n inputSchema: {},\n },\n async () => textResult(await runTool('undo', {})),\n );\n\n registerTool(\n 'redo',\n {\n description:\n 'Brings back the tool call the last undo reverted - the tool when the user asks to redo or to bring back ' +\n 'what was undone (\"redo it\", \"bring it back\"); undo would revert one more call instead. ' +\n 'A new change of the plan ends redo. Returns the ' +\n 'restored tool, the groups it changed as they are now, removedGroupIds - the groups it took out of the plan - ' +\n 'and otherGroupIds, the groups it left as they were; when there is nothing to redo, the result says so.',\n inputSchema: {},\n },\n async () => textResult(await runTool('redo', {})),\n );\n\n registerTool(\n 'get-price',\n {\n description:\n 'Calculates and returns the price/order data of the current planning situation.',\n inputSchema: {},\n },\n async () => textResult(await runTool('get-price', {})),\n );\n\n registerTool(\n 'get-order-data',\n {\n description:\n 'Returns the order data of the current planning situation without placing an order.',\n inputSchema: {},\n },\n async () => textResult(await runTool('get-order-data', {})),\n );\n\n registerTool(\n 'get-plan-images',\n {\n description:\n 'Renders two images of the current plan, so the plan can be inspected visually. First the groups ' +\n 'alone, seen from their front without the room or other objects - one camera for all groups, so where ' +\n 'fronts face opposite directions one side is seen from behind, and root modules can hide one another: a ' +\n 'root module not seen is not missing, get-plan-context lists the root modules. Second a top view of the ' +\n 'whole plan that shows where the groups stand; its orientation matches the wall side labels of ' +\n \"get-plan-context: a wall with side 'right' is at the right edge of the top image, 'top' at the upper \" +\n 'edge. A text before the images names them; without groups in the plan only the top view is returned. ' +\n 'Doors and drawers are shown as they are: to look inside a cabinet, open it with open-or-close-article ' +\n '(a whole group with open-or-close-group) right before this tool.',\n inputSchema: {},\n },\n async () => {\n const images = (await runTool('get-plan-images', {})) as {\n perspectiveObjectImage?: string;\n topImage?: string;\n };\n const views = [\n {\n image: images.perspectiveObjectImage,\n name: 'the HI groups alone, seen from their front, without the room',\n },\n { image: images.topImage, name: 'the top view of the whole plan' },\n ].filter((view) => view.image);\n if (views.length === 0) {\n return textResult({ error: 'No images available' });\n }\n const names = views\n .map((view, index) => `Image ${index + 1}: ${view.name}.`)\n .join(' ');\n return {\n content: [\n {\n type: 'text' as const,\n text: images.perspectiveObjectImage\n ? names\n : `The plan has no groups, so there is no group view. ${names}`,\n },\n ...views.map((view) => ({\n type: 'image' as const,\n data: stripDataUrlPrefix(view.image as string),\n mimeType: 'image/png',\n })),\n ],\n };\n },\n );\n\n return tools;\n};\n"],"x_google_ignoreList":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17],"mappings":";AAgBA,SAAgB,EAAc,GAAS;CACnC,IAAM,IAAgB,OAAO,OAAO,EAAQ,CAAC,QAAQ,MAAM,OAAO,KAAM,SAAS;AAIjF,QAHe,OAAO,QAAQ,EAAQ,CACjC,QAAQ,CAAC,GAAG,OAAO,EAAc,QAAQ,CAAC,EAAE,KAAK,GAAG,CACpD,KAAK,CAAC,GAAG,OAAO,EAAE;;AAG3B,SAAgB,EAAW,GAAO,IAAY,KAAK;AAC/C,QAAO,EAAM,KAAK,MAAQ,GAAmB,EAAI,CAA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