@sensorup/sustudio 42.53.0 → 42.54.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/package.json +1 -1
  2. package/sustudio.mjs +2 -2
package/sustudio.mjs CHANGED
@@ -69,7 +69,7 @@ ${code2}`:code2:"",F=Function,factoryCode=`return (input) => {
69
69
  ${code2}
70
70
  }`,fn;try{fn=new F(...constantNames,factoryCode)(...constantValues)}catch(err2){throw new ZodCompileUnsupportedError(`this schema (generated code failed to evaluate: ${err2.message})`)}return options?.debug&&(fn.code=fullCode),fn.definite=ctx.definite,fn}function addConstant(ctx,value2){for(let[name3,v]of ctx.constants)if(v===value2)return name3;let name2=`c${ctx.constantCounter++}`;return ctx.constants.set(name2,value2),name2}function addUserConstant(ctx,fn){return ctx.definite=!1,addConstant(ctx,fn)}function newVar(ctx){return`v${ctx.varCounter++}`}function runtimeRun(schema,value2){let result=schema._zod.run({value:value2,issues:[]},{});if(result&&typeof result.then=="function")return INVALID;let r=result;return r.issues.length===0?r.value:INVALID}function compileChild(doc,ctx,schema,accessor,needsValue=!0){let contentLen=doc.content.length,constantCount=ctx.constants.size,constantCounter=ctx.constantCounter,varCounter=ctx.varCounter;try{return generateCheck(doc,ctx,schema,accessor,needsValue)}catch(err2){if(!(err2 instanceof ZodCompileUnsupportedError)||!err2.islandable)throw err2;if(doc.content.length=contentLen,ctx.constants.size>constantCount){let trailing=Array.from(ctx.constants.keys()).slice(constantCount);for(let k of trailing)ctx.constants.delete(k)}return ctx.constantCounter=constantCounter,ctx.varCounter=varCounter,emitRuntimeIsland(doc,ctx,schema,accessor)}}function emitRuntimeIsland(doc,ctx,schema,accessor){ctx.definite=!1;let schemaConst=addConstant(ctx,schema),runConst=addConstant(ctx,runtimeRun),outVar=newVar(ctx);return doc.write(`const ${outVar} = ${runConst}(${schemaConst}, ${accessor});`),doc.write(`if (${outVar} === INVALID) return INVALID;`),outVar}var WHEN_DEFAULTED_CHECKS=new Set(["max_size","min_size","size_equals","max_length","min_length","length_equals"]);function generateChecks(doc,ctx,schema,accessor){let schemaChecks=schema._zod.def.checks;if(!schemaChecks||schemaChecks.length===0)return accessor;let currentAccessor=accessor;for(let check2 of schemaChecks){let def=check2._zod.def;if(def.when&&!WHEN_DEFAULTED_CHECKS.has(def.check))throw new ZodCompileUnsupportedError('check with a custom "when" condition');switch(def.check){case"greater_than":generateGreaterThanCheck(doc,ctx,def,currentAccessor);break;case"less_than":generateLessThanCheck(doc,ctx,def,currentAccessor);break;case"multiple_of":generateMultipleOfCheck(doc,ctx,def,currentAccessor);break;case"number_format":generateNumberFormatCheck(doc,def,currentAccessor);break;case"min_length":{let min=numericOperand(def.minimum,"min_length"),len=codePointLengthVar(doc,ctx,currentAccessor,`${currentAccessor}.length >= ${min} && ${currentAccessor}.length < ${def.minimum*2}`);doc.write(`if (${len} < ${min}) return INVALID;`);break}case"max_length":{let max2=numericOperand(def.maximum,"max_length"),len=codePointLengthVar(doc,ctx,currentAccessor,`${currentAccessor}.length > ${max2}`);doc.write(`if (${len} > ${max2}) return INVALID;`);break}case"length_equals":{let exact=numericOperand(def.length,"length_equals"),len=codePointLengthVar(doc,ctx,currentAccessor,`${currentAccessor}.length >= ${exact} && ${currentAccessor}.length <= ${def.length*2}`);doc.write(`if (${len} !== ${exact}) return INVALID;`);break}case"min_size":doc.write(`if (${currentAccessor}.size < ${numericOperand(def.minimum,"min_size")}) return INVALID;`);break;case"max_size":doc.write(`if (${currentAccessor}.size > ${numericOperand(def.maximum,"max_size")}) return INVALID;`);break;case"size_equals":doc.write(`if (${currentAccessor}.size !== ${numericOperand(def.size,"size_equals")}) return INVALID;`);break;case"string_format":currentAccessor=generateStringFormatCheck(doc,ctx,def,currentAccessor);break;case"custom":currentAccessor=generateCustomRefineCheck(doc,ctx,check2,currentAccessor);break;case"bigint_format":generateBigIntFormatCheck(doc,def,currentAccessor);break;case"mime_type":generateMimeTypeCheck(doc,ctx,def,currentAccessor);break;case"property":generatePropertyCheck(doc,ctx,def,currentAccessor);break;case"properties":generatePropertiesChecks(doc,ctx,def,currentAccessor);break;case"overwrite":{let newAccessor=newVar(ctx);generateOverwriteCheck(doc,ctx,check2,currentAccessor,newAccessor),currentAccessor=newAccessor;break}default:throw new ZodCompileUnsupportedError(`check type ${def.check}`)}}return currentAccessor}function codePointLengthVar(doc,ctx,accessor,inDoubt){let cpLen=addConstant(ctx,codePointLength),v=newVar(ctx);return doc.write(`const ${v} = typeof ${accessor} === "string" && ${inDoubt} ? ${cpLen}(${accessor}) : ${accessor}.length;`),v}function numericOperand(value2,label){if(typeof value2!="number"||!Number.isFinite(value2))throw new ZodCompileUnsupportedError(`${label} bound of type ${typeof value2}`);return`${value2}`}function comparisonOperand(ctx,value2){if(typeof value2=="bigint")return`${value2}n`;if(typeof value2=="number"){if(Number.isNaN(value2))throw new ZodCompileUnsupportedError("comparison check with NaN bound");return`${value2}`}if(value2 instanceof Date){if(Number.isNaN(value2.getTime()))throw new ZodCompileUnsupportedError("comparison check with Invalid Date bound");return addConstant(ctx,value2)}throw new ZodCompileUnsupportedError(`comparison check bound of type ${typeof value2}`)}function generateGreaterThanCheck(doc,ctx,def,accessor){let op=def.inclusive?"<":"<=";doc.write(`if (${accessor} ${op} ${comparisonOperand(ctx,def.value)}) return INVALID;`)}function generateLessThanCheck(doc,ctx,def,accessor){let op=def.inclusive?">":">=";doc.write(`if (${accessor} ${op} ${comparisonOperand(ctx,def.value)}) return INVALID;`)}function generateMultipleOfCheck(doc,ctx,def,accessor){if(typeof def.value=="bigint"){if(def.value===BigInt(0))throw new ZodCompileUnsupportedError("multiple_of check with a zero divisor");doc.write(`if (${accessor} % ${def.value}n !== 0n) return INVALID;`)}else{let remainder=addConstant(ctx,floatSafeRemainder);doc.write(`if (${remainder}(${accessor}, ${numericOperand(def.value,"multiple_of")}) !== 0) return INVALID;`)}}function generateNumberFormatCheck(doc,def,accessor){let format=def.format;switch(format){case"safeint":doc.write(`if (!Number.isSafeInteger(${accessor})) return INVALID;`);break;case"int32":doc.write(`if (!Number.isInteger(${accessor}) || ${accessor} < -2147483648 || ${accessor} > 2147483647) return INVALID;`);break;case"uint32":doc.write(`if (!Number.isInteger(${accessor}) || ${accessor} < 0 || ${accessor} > 4294967295) return INVALID;`);break;case"float32":doc.write(`if (!Number.isFinite(${accessor}) || ${accessor} < -3.4028234663852886e38 || ${accessor} > 3.4028234663852886e38) return INVALID;`);break;case"float64":doc.write(`if (!Number.isFinite(${accessor})) return INVALID;`);break;default:throw new ZodCompileUnsupportedError(`number format ${format}`)}}function generateBigIntFormatCheck(doc,def,accessor){let format=def.format;if(format)switch(format){case"int64":doc.write(`if (${accessor} < -9223372036854775808n || ${accessor} > 9223372036854775807n) return INVALID;`);break;case"uint64":doc.write(`if (${accessor} < 0n || ${accessor} > 18446744073709551615n) return INVALID;`);break;default:throw new ZodCompileUnsupportedError(`bigint format ${format}`)}}function generateMimeTypeCheck(doc,ctx,def,accessor){let mimeTypes=def.mime;if(mimeTypes&&mimeTypes.length>0){let mimeSet=addConstant(ctx,new Set(mimeTypes));doc.write(`if (!${mimeSet}.has(${accessor}.type)) return INVALID;`)}}function generatePropertiesChecks(doc,ctx,def,accessor){if(def.when)throw new ZodCompileUnsupportedError('check with a custom "when" condition');doc.write(`if (${accessor} == null) return INVALID;`);let shape=def.shape;for(let key of Reflect.ownKeys(shape)){let keyExpr=typeof key=="symbol"?addConstant(ctx,key):esc(key),inputVar=newVar(ctx);doc.write(`const ${inputVar} = ${accessor}[${keyExpr}];`),compileChild(doc,ctx,shape[key],inputVar,!1)}}function generatePropertyCheck(doc,ctx,def,accessor){let propAccessor=`${accessor}[${JSON.stringify(def.property)}]`;generateCheck(doc,ctx,def.schema,propAccessor)}function generateOverwriteCheck(doc,ctx,check2,currentAccessor,newAccessor){let tx=check2._zod.def.tx;if(!tx)throw new ZodCompileUnsupportedError("overwrite check without a transform function");if(isAsyncFunction(tx))throw new ZodCompileAsyncError("z.compile: async overwrite transforms are not supported");let txConst=addConstant(ctx,tx);doc.write(`const ${newAccessor} = ${txConst}(${currentAccessor});`)}function throwAsync(){throw new $ZodAsyncError}function pushIssue(issue2){this.issues.push(issue2)}function generateCustomRefineCheck(doc,ctx,check2,accessor){let def=check2._zod.def;if(def.fn){if(isAsyncFunction(def.fn))throw new ZodCompileAsyncError("z.compile: async .refine() predicates are not supported");let fnConst=addUserConstant(ctx,def.fn),throwAsyncConst=addConstant(ctx,throwAsync),resVar=newVar(ctx);return doc.write(`const ${resVar} = ${fnConst}(${accessor});`),doc.write(`if (${resVar} instanceof Promise) ${throwAsyncConst}();`),doc.write(`if (!${resVar}) return INVALID;`),accessor}if(check2._zod.check){if(isAsyncFunction(check2._zod.check))throw new ZodCompileAsyncError("z.compile: async .superRefine() / check functions are not supported");let checkFn=check2._zod.check,helperConst=addUserConstant(ctx,value2=>{let fakePayload={value:value2,issues:[],addIssue:pushIssue};return checkFn(fakePayload)instanceof Promise&&throwAsync(),fakePayload.issues.length===0?fakePayload.value:INVALID}),outVar=newVar(ctx);return doc.write(`const ${outVar} = ${helperConst}(${accessor});`),doc.write(`if (${outVar} === INVALID) return INVALID;`),outVar}throw new ZodCompileUnsupportedError("custom check without a predicate or check function")}var PATTERN_IS_COMPLETE=new Set(["cidrv4","cuid","cuid2","date","datetime","duration","e164","email","emoji","ends_with","guid","includes","ipv4","ksuid","lowercase","mac","nanoid","regex","starts_with","time","ulid","uppercase","uuid","xid"]);function generateStringFormatCheck(doc,ctx,def,accessor,needsValue=!0){let fmt=def.format;if(fmt==="base64"){let validator=addConstant(ctx,isValidBase64);return doc.write(`if (!${validator}(${accessor})) return INVALID;`),accessor}if(fmt==="base64url"){let validator=addConstant(ctx,isValidBase64URL);return doc.write(`if (!${validator}(${accessor})) return INVALID;`),accessor}if(fmt==="jwt"){let validator=addConstant(ctx,isValidJWT),alg=addConstant(ctx,def.alg??null);return doc.write(`if (!${validator}(${accessor}, ${alg})) return INVALID;`),accessor}if(fmt==="ipv6"){let validator=addConstant(ctx,isValidIPv6);return doc.write(`if (!${validator}(${accessor})) return INVALID;`),accessor}if(fmt==="cidrv6"){let validator=addConstant(ctx,isValidCIDRv6);return doc.write(`if (!${validator}(${accessor})) return INVALID;`),accessor}if(fmt==="credit_card"){let validator=addConstant(ctx,isValidCreditCard);return doc.write(`if (!${validator}(${accessor})) return INVALID;`),accessor}if(fmt==="iban"){let validator=addConstant(ctx,isValidIBAN);return doc.write(`if (!${validator}(${accessor})) return INVALID;`),accessor}let formatDef=def;if(fmt==="url"||fmt==="httpurl"||formatDef.normalize||formatDef.hostname!==void 0||formatDef.protocol!==void 0){let parseConst=addConstant(ctx,validateURL),defConst=addConstant(ctx,def),trimVar=newVar(ctx),urlVar=newVar(ctx);if(doc.write(`const ${trimVar} = ${accessor}.trim();`),doc.write(`const ${urlVar} = ${parseConst}(${trimVar}, ${defConst});`),doc.write(`if (typeof ${urlVar} === "number") return INVALID;`),formatDef.hostname!==void 0){let hostnameConst=addConstant(ctx,urlHostnameOk);doc.write(`if (!${hostnameConst}(${urlVar}, ${defConst}.hostname)) return INVALID;`)}if(formatDef.protocol!==void 0){let protocolConst=addConstant(ctx,urlProtocolOk);doc.write(`if (!${protocolConst}(${urlVar}, ${defConst}.protocol)) return INVALID;`)}if(!needsValue)return null;let outputVar=newVar(ctx),outputExpr=formatDef.normalize?`${urlVar}.href`:`${addConstant(ctx,stripTabAndNewline)}(${trimVar})`;return doc.write(`const ${outputVar} = ${outputExpr};`),outputVar}let customFn=def.fn;if(customFn){if(isAsyncFunction(customFn))throw new ZodCompileUnsupportedError(`async string format ${fmt}`);let fnConst=addConstant(ctx,customFn);return doc.write(`if (!${fnConst}(${accessor})) return INVALID;`),accessor}if(PATTERN_IS_COMPLETE.has(fmt)&&def.pattern){let patternConst=addConstant(ctx,def.pattern);return doc.write(`${patternConst}.lastIndex = 0;`),doc.write(`if (!${patternConst}.test(${accessor})) return INVALID;`),accessor}let format=def.format;switch(format){case"regex":throw new ZodCompileUnsupportedError("regex format without a pattern");case"lowercase":doc.write(`if (${accessor} !== ${accessor}.toLowerCase()) return INVALID;`);break;case"uppercase":doc.write(`if (${accessor} !== ${accessor}.toUpperCase()) return INVALID;`);break;case"includes":doc.write(`if (!${accessor}.includes(${esc(def.includes)})) return INVALID;`);break;case"starts_with":{let prefix=def.prefix;doc.write(`if (${accessor}.slice(0, ${prefix.length}) !== ${esc(prefix)}) return INVALID;`);break}case"ends_with":{let suffix=def.suffix;doc.write(`if (${accessor}.slice(-${suffix.length}) !== ${esc(suffix)}) return INVALID;`);break}default:throw new ZodCompileUnsupportedError(`string format ${format}`)}return accessor}function generateCheck(doc,ctx,schema,accessor,needsValue=!0){let def=schema._zod.def,type=def.type;if(def.coerce)throw new ZodCompileUnsupportedError(`coercion (z.coerce.${type}())`);let buildsValue=needsValue||!!def.checks?.length,typeAccessor;switch(type){case"string":typeAccessor=generateStringCheck(doc,ctx,schema,accessor,buildsValue);break;case"number":typeAccessor=generateNumberCheck(doc,schema,accessor);break;case"boolean":typeAccessor=generateBooleanCheck(doc,accessor);break;case"bigint":typeAccessor=generateBigIntCheck(doc,schema,accessor);break;case"symbol":typeAccessor=generateSymbolCheck(doc,accessor);break;case"undefined":typeAccessor=generateUndefinedCheck(doc,accessor);break;case"null":typeAccessor=generateNullCheck(doc,accessor);break;case"any":case"unknown":typeAccessor=accessor;break;case"never":doc.write("return INVALID;"),typeAccessor=accessor;break;case"void":typeAccessor=generateVoidCheck(doc,accessor);break;case"nan":typeAccessor=generateNaNCheck(doc,accessor);break;case"date":typeAccessor=generateDateCheck(doc,accessor);break;case"object":typeAccessor=generateObjectCheck(doc,ctx,schema,accessor,buildsValue);break;case"optional":typeAccessor=generateOptionalCheck(doc,ctx,schema,accessor,buildsValue);break;case"nullable":typeAccessor=generateNullableCheck(doc,ctx,schema,accessor,buildsValue);break;case"array":typeAccessor=generateArrayCheck(doc,ctx,schema,accessor,buildsValue);break;case"literal":typeAccessor=generateLiteralCheck(doc,ctx,schema,accessor);break;case"enum":typeAccessor=generateEnumCheck(doc,ctx,schema,accessor);break;case"readonly":{let innerOut=generateWrapperCheck(doc,ctx,schema,accessor),frozenVar=newVar(ctx);doc.write(`const ${frozenVar} = Object.freeze(${innerOut});`),typeAccessor=frozenVar;break}case"success":generateWrapperCheck(doc,ctx,schema,accessor),typeAccessor="true";break;case"default":case"prefault":typeAccessor=generateDefaultCheck(doc,ctx,schema,accessor);break;case"nonoptional":typeAccessor=generateNonOptionalCheck(doc,ctx,schema,accessor);break;case"tuple":typeAccessor=generateTupleCheck(doc,ctx,schema,accessor);break;case"union":typeAccessor=generateUnionCheck(doc,ctx,schema,accessor);break;case"intersection":typeAccessor=generateIntersectionCheck(doc,ctx,schema,accessor);break;case"record":typeAccessor=generateRecordCheck(doc,ctx,schema,accessor);break;case"map":typeAccessor=generateMapCheck(doc,ctx,schema,accessor);break;case"set":typeAccessor=generateSetCheck(doc,ctx,schema,accessor);break;case"file":typeAccessor=generateFileCheck(doc,accessor);break;case"template_literal":typeAccessor=generateTemplateLiteralCheck(doc,ctx,schema,accessor);break;case"lazy":typeAccessor=generateLazyCheck(doc,ctx,schema,accessor);break;case"pipe":typeAccessor=generatePipeCheck(doc,ctx,schema,accessor);break;case"custom":typeAccessor=generateCustomCheck(doc,ctx,schema,accessor);break;case"transform":typeAccessor=generateTransformCheck(doc,ctx,schema,accessor);break;case"catch":typeAccessor=generateCatchCheck(doc,ctx,schema,accessor);break;default:throw new ZodCompileUnsupportedError(`schema type ${type}`)}return typeAccessor===null?null:generateChecks(doc,ctx,schema,typeAccessor)}function generateStringCheck(doc,ctx,schema,accessor,needsValue=!0){doc.write(`if (typeof ${accessor} !== "string") return INVALID;`);let def=schema._zod.def;return def.format===void 0?accessor:generateStringFormatCheck(doc,ctx,def,accessor,needsValue)}function generateNumberCheck(doc,schema,accessor){doc.write(`if (typeof ${accessor} !== "number" || !Number.isFinite(${accessor})) return INVALID;`);let def=schema._zod.def;return def.check==="number_format"&&def.format&&generateNumberFormatCheck(doc,{format:def.format},accessor),accessor}function generateBooleanCheck(doc,accessor){return doc.write(`if (typeof ${accessor} !== "boolean") return INVALID;`),accessor}function generateBigIntCheck(doc,schema,accessor){doc.write(`if (typeof ${accessor} !== "bigint") return INVALID;`);let def=schema._zod.def;if(def.format)switch(def.format){case"int64":doc.write(`if (${accessor} < -9223372036854775808n || ${accessor} > 9223372036854775807n) return INVALID;`);break;case"uint64":doc.write(`if (${accessor} < 0n || ${accessor} > 18446744073709551615n) return INVALID;`);break}return accessor}function generateSymbolCheck(doc,accessor){return doc.write(`if (typeof ${accessor} !== "symbol") return INVALID;`),accessor}function generateUndefinedCheck(doc,accessor){return doc.write(`if (${accessor} !== undefined) return INVALID;`),accessor}function generateNullCheck(doc,accessor){return doc.write(`if (${accessor} !== null) return INVALID;`),accessor}function generateVoidCheck(doc,accessor){return doc.write(`if (${accessor} !== undefined) return INVALID;`),accessor}function generateNaNCheck(doc,accessor){return doc.write(`if (typeof ${accessor} !== "number" || !Number.isNaN(${accessor})) return INVALID;`),accessor}function generateDateCheck(doc,accessor){return doc.write(`if (!(${accessor} instanceof Date) || Number.isNaN(${accessor}.getTime())) return INVALID;`),accessor}function generateObjectCheck(doc,ctx,schema,accessor,buildsValue=!0){let def=schema._zod.def;doc.write(`if (typeof ${accessor} !== "object" || ${accessor} === null || Array.isArray(${accessor})) return INVALID;`);let shape=def.shape,keys=Object.keys(shape),symbolKeys=Object.getOwnPropertySymbols(shape),allKeys=symbolKeys.length?[...keys,...symbolKeys]:keys,keyExpr=k=>typeof k=="symbol"?addConstant(ctx,k):esc(k),propKey=k=>typeof k=="symbol"?`[${keyExpr(k)}]`:esc(k),propShape=shape;if(keys.includes("__proto__"))throw new ZodCompileUnsupportedError('object shape key "__proto__"');let propOutputs=new Map;for(let key of allKeys){let propSchema=propShape[key],kx=keyExpr(key),inputVar=newVar(ctx);if(doc.write(`const ${inputVar} = ${accessor}[${kx}];`),propSchema._zod.optin!==void 0){let outputVar2=newVar(ctx);doc.write(`let ${outputVar2} = (() => {`),doc.indented(d=>{let outputAccessor=compileChild(d,ctx,propSchema,inputVar);d.write(`return ${outputAccessor};`)}),doc.write("})();"),propSchema._zod.optout==="optional"?(doc.write(`if (${outputVar2} === INVALID) {`),doc.indented(d=>{d.write(`if (${kx} in ${accessor}) return INVALID;`),d.write(`${outputVar2} = undefined;`)}),doc.write("}")):doc.write(`if (${outputVar2} === INVALID) return INVALID;`),propOutputs.set(key,outputVar2)}else{requiresPresenceCheck(propSchema)&&doc.write(`if (!(${kx} in ${accessor})) return INVALID;`);let outputAccessor=compileChild(doc,ctx,propSchema,inputVar,buildsValue);outputAccessor!==null&&propOutputs.set(key,outputAccessor)}}let catchall=def.catchall,unknownKeysMode="none";if(catchall){let catchallType=catchall._zod.def.type;if(catchallType==="never"){let condition=keys.map(k=>`k !== ${esc(k)}`).join(" && ")||"true";doc.write(`for (const k in ${accessor}) {`),doc.indented(d=>{d.write(`if (${condition}) return INVALID;`)}),doc.write("}")}else(catchallType==="unknown"||catchallType==="any")&&!catchall._zod.def.checks?.length?unknownKeysMode="passthrough":unknownKeysMode="schema"}let outputVar=newVar(ctx),hasConditionalKeys=allKeys.some(k=>mayOmitUndefined(propShape[k])||dropsWhenAbsent(propShape[k]));if(!buildsValue){if(unknownKeysMode==="schema"){let knownSet=keys.length>0?addConstant(ctx,new Set(keys)):null;doc.write(`for (const k in ${accessor}) {`),doc.indented(d=>{d.write('if (k === "__proto__") continue;'),knownSet&&d.write(`if (${knownSet}.has(k)) continue;`);let valVar=newVar(ctx);d.write(`const ${valVar} = ${accessor}[k];`),compileChild(d,ctx,catchall,valVar,!1)}),doc.write("}")}return null}if(hasConditionalKeys){doc.write(`const ${outputVar} = {};`);for(let k of allKeys){let kx=keyExpr(k),out=propOutputs.get(k);dropsWhenAbsent(propShape[k])?doc.write(`if (${kx} in ${accessor}) ${outputVar}[${kx}] = ${out};`):mayOmitUndefined(propShape[k])?doc.write(`if (${out} !== undefined || ${kx} in ${accessor}) ${outputVar}[${kx}] = ${out};`):doc.write(`${outputVar}[${kx}] = ${out};`)}}else{let propLiterals=allKeys.map(k=>`${propKey(k)}: ${propOutputs.get(k)}`).join(", ");doc.write(`const ${outputVar} = { ${propLiterals} };`)}if(unknownKeysMode!=="none"){let knownSet=keys.length>0?addConstant(ctx,new Set(keys)):null;doc.write(`for (const k in ${accessor}) {`),doc.indented(d=>{if(d.write('if (k === "__proto__") continue;'),knownSet&&d.write(`if (${knownSet}.has(k)) continue;`),unknownKeysMode==="passthrough")d.write(`${outputVar}[k] = ${accessor}[k];`);else{let valVar=newVar(ctx);d.write(`const ${valVar} = ${accessor}[k];`);let catchallOut=compileChild(d,ctx,catchall,valVar);d.write(`${outputVar}[k] = ${catchallOut};`)}}),doc.write("}")}return outputVar}function generateOptionalCheck(doc,ctx,schema,accessor,buildsValue=!0){let def=schema._zod.def;if(isExactOptional(schema))return generateCheck(doc,ctx,def.innerType,accessor,buildsValue);if(def.innerType._zod.optin==="defaulted"){let outputVar2=newVar(ctx),branchVar=newVar(ctx);return doc.write(`let ${outputVar2};`),doc.write(`if (${accessor} === undefined) {`),doc.indented(d=>{d.write(`const ${branchVar} = (() => {`),d.indented(d2=>{let innerOutput=generateCheck(d2,ctx,def.innerType,accessor);d2.write(`return ${innerOutput};`)}),d.write("})();"),d.write(`if (${branchVar} !== INVALID) ${outputVar2} = ${branchVar};`)}),doc.write("} else {"),doc.indented(d=>{let innerOutput=generateCheck(d,ctx,def.innerType,accessor);d.write(`${outputVar2} = ${innerOutput};`)}),doc.write("}"),outputVar2}let outputVar=buildsValue?newVar(ctx):null;return outputVar&&doc.write(`let ${outputVar};`),doc.write(`if (${accessor} !== undefined) {`),doc.indented(d=>{let innerOutput=generateCheck(d,ctx,def.innerType,accessor,buildsValue);outputVar&&innerOutput!==null&&d.write(`${outputVar} = ${innerOutput};`)}),doc.write("}"),outputVar}function isExactOptional(schema){return schema._zod.traits?.has("$ZodExactOptional")===!0}function requiresPresenceCheck(schema){return schema._zod.optin===void 0&&fastPathAcceptsAbsence(schema)}function fastPathAcceptsAbsence(schema){if(schema._zod.def.coerce)return!0;let def=schema._zod.def;switch(def.type){case"any":case"unknown":case"undefined":case"void":case"default":case"prefault":case"transform":case"custom":case"lazy":return!0;case"string":case"number":case"boolean":case"bigint":case"symbol":case"null":case"never":case"nan":case"date":case"object":case"array":case"tuple":case"record":case"map":case"set":case"file":case"template_literal":return!1;case"nonoptional":return def.innerType?fastPathAcceptsAbsence(def.innerType):!1;case"literal":return!!def.values?.includes(void 0);case"enum":return!!schema._zod.values?.has(void 0);case"optional":case"nullable":case"readonly":case"success":return def.innerType?fastPathAcceptsAbsence(def.innerType):!0;case"catch":return!0;case"union":return def.options?def.options.some(fastPathAcceptsAbsence):!0;case"intersection":return!def.left||!def.right?!0:fastPathAcceptsAbsence(def.left)&&fastPathAcceptsAbsence(def.right);case"pipe":return def.in?fastPathAcceptsAbsence(def.in):!0;default:return!0}}function dropsWhenAbsent(schema){return schema._zod.optin==="optional"&&schema._zod.optout==="optional"}function mayOmitUndefined(schema){return(schema._zod.optin!=="defaulted"||schema._zod.optout==="optional")&&mayOutputUndefined(schema)}function mayOutputUndefined(schema){let def=schema._zod.def;switch(def.type){case"string":case"number":case"boolean":case"bigint":case"symbol":case"null":case"nan":case"date":case"object":case"array":case"tuple":case"record":case"map":case"set":case"file":case"template_literal":case"never":case"success":return!1;case"literal":return!!def.values?.includes(void 0);case"enum":return!!schema._zod.values?.has(void 0);case"optional":return!0;case"nullable":case"readonly":case"nonoptional":return def.innerType?mayOutputUndefined(def.innerType):!0;case"union":return def.options?def.options.some(mayOutputUndefined):!0;case"intersection":return!def.left||!def.right||mayOutputUndefined(def.left)||mayOutputUndefined(def.right);case"pipe":return def.out?mayOutputUndefined(def.out):!0;default:return!0}}function generateNullableCheck(doc,ctx,schema,accessor,buildsValue=!0){let def=schema._zod.def,outputVar=buildsValue?newVar(ctx):null;return outputVar&&doc.write(`let ${outputVar} = null;`),doc.write(`if (${accessor} !== null) {`),doc.indented(d=>{let innerOutput=generateCheck(d,ctx,def.innerType,accessor,buildsValue);outputVar&&innerOutput!==null&&d.write(`${outputVar} = ${innerOutput};`)}),doc.write("}"),outputVar}function generateSizeGate(doc,schema,size){for(let[max2,check2]of sizeCaps(schema._zod.def.checks))doc.write(`if (${size} > ${numericOperand(max2,check2._zod.def.check)}) return INVALID;`)}function generateArrayCheck(doc,ctx,schema,accessor,buildsValue=!0){let def=schema._zod.def;doc.write(`if (!Array.isArray(${accessor})) return INVALID;`),generateSizeGate(doc,schema,`${accessor}.length`);let outputVar=buildsValue?newVar(ctx):null,iVar=newVar(ctx),elemVar=newVar(ctx);return outputVar&&doc.write(`const ${outputVar} = new Array(${accessor}.length);`),doc.write(`for (let ${iVar} = 0; ${iVar} < ${accessor}.length; ${iVar}++) {`),doc.indented(d=>{d.write(`const ${elemVar} = ${accessor}[${iVar}];`);let elemOutput=compileChild(d,ctx,def.element,elemVar,buildsValue);outputVar&&elemOutput!==null&&d.write(`${outputVar}[${iVar}] = ${elemOutput};`)}),doc.write("}"),outputVar}function generateLiteralCheck(doc,ctx,schema,accessor){let values2=schema._zod.def.values;if(values2.length!==1){let literalSet=addConstant(ctx,new Set(values2));return doc.write(`if (!${literalSet}.has(${accessor})) return INVALID;`),accessor}let value2=values2[0];if(typeof value2=="number"&&Number.isNaN(value2)){let literalSet=addConstant(ctx,new Set(values2));return doc.write(`if (!${literalSet}.has(${accessor})) return INVALID;`),accessor}if(typeof value2=="string")doc.write(`if (${accessor} !== ${esc(value2)}) return INVALID;`);else if(typeof value2=="number"||typeof value2=="boolean")doc.write(`if (${accessor} !== ${value2}) return INVALID;`);else if(value2===null)doc.write(`if (${accessor} !== null) return INVALID;`);else if(value2===void 0)doc.write(`if (${accessor} !== undefined) return INVALID;`);else if(typeof value2=="bigint")doc.write(`if (${accessor} !== ${value2}n) return INVALID;`);else throw new ZodCompileUnsupportedError(`literal type ${typeof value2}`);return accessor}function generateEnumCheck(doc,ctx,schema,accessor){let values2=schema._zod.values;if(!values2)throw new ZodCompileUnsupportedError("enum schema without enumerated values");let enumSet=addConstant(ctx,values2);return doc.write(`if (!${enumSet}.has(${accessor})) return INVALID;`),accessor}function generateWrapperCheck(doc,ctx,schema,accessor){let def=schema._zod.def;return generateCheck(doc,ctx,def.innerType,accessor)}function generateDefaultCheck(doc,ctx,schema,accessor){let def=schema._zod.def,defaultGetter=Object.getOwnPropertyDescriptor(schema._zod.def,"defaultValue")?()=>schema._zod.def.defaultValue:void 0;if(schema._zod.def.type==="prefault"){if(!defaultGetter)return generateCheck(doc,ctx,def.innerType,accessor);let defaultFn=addConstant(ctx,defaultGetter),inputVar=newVar(ctx);return doc.write(`let ${inputVar} = ${accessor};`),doc.write(`if (${accessor} === undefined) ${inputVar} = ${defaultFn}();`),generateCheck(doc,ctx,def.innerType,inputVar)}let outputVar=newVar(ctx);if(defaultGetter){let defaultFn=addConstant(ctx,defaultGetter),cloneFn=addConstant(ctx,shallowClone);doc.write(`let ${outputVar};`),doc.write(`if (${accessor} === undefined) {`),doc.indented(d=>{d.write(`${outputVar} = ${cloneFn}(${defaultFn}());`)}),doc.write("} else {"),doc.indented(d=>{let innerOutput=generateCheck(d,ctx,def.innerType,accessor);d.write(`${outputVar} = ${innerOutput} === undefined ? ${cloneFn}(${defaultFn}()) : ${innerOutput};`)}),doc.write("}")}else doc.write(`let ${outputVar};`),doc.write(`if (${accessor} !== undefined) {`),doc.indented(d=>{let innerOutput=generateCheck(d,ctx,def.innerType,accessor);d.write(`${outputVar} = ${innerOutput};`)}),doc.write("}");return outputVar}function generateNonOptionalCheck(doc,ctx,schema,accessor){let def=schema._zod.def,innerOutput=generateCheck(doc,ctx,def.innerType,accessor),outputVar=newVar(ctx);return doc.write(`const ${outputVar} = ${innerOutput};`),doc.write(`if (${outputVar} === undefined) return INVALID;`),outputVar}function generateTupleCheck(doc,ctx,schema,accessor){let def=schema._zod.def,items=def.items,rest=def.rest;doc.write(`if (!Array.isArray(${accessor})) return INVALID;`);let optinStart=getTupleOptStart2(items,"optin"),optoutStart=getTupleOptStart2(items,"optout");rest?doc.write(`if (${accessor}.length < ${optinStart}) return INVALID;`):doc.write(`if (${accessor}.length < ${optinStart} || ${accessor}.length > ${items.length}) return INVALID;`);let outputVar=newVar(ctx);doc.write(`const ${outputVar} = [];`);for(let i2=0;i2<items.length;i2++){let itemSchema=items[i2];if(i2>=optoutStart)doc.write(`if (${outputVar}.length === ${i2}) {`),doc.indented(d=>{d.write(`if (${i2} < ${accessor}.length) {`),d.indented(d2=>{let elemVar=newVar(ctx);d2.write(`const ${elemVar} = ${accessor}[${i2}];`);let elemOutput=compileChild(d2,ctx,itemSchema,elemVar);d2.write(`${outputVar}[${i2}] = ${elemOutput};`)}),d.write("} else {"),d.indented(d2=>{if(dropsWhenAbsent(itemSchema)){d2.write(`${outputVar}.length = ${i2};`);return}let elemVar=newVar(ctx),branchVar=newVar(ctx);d2.write(`const ${elemVar} = undefined;`),d2.write(`const ${branchVar} = (() => {`),d2.indented(d3=>{let elemOutput=compileChild(d3,ctx,itemSchema,elemVar);d3.write(`return ${elemOutput};`)}),d2.write("})();"),d2.write(`if (${branchVar} === INVALID || ${branchVar} === undefined) ${outputVar}.length = ${i2};`),d2.write(`else ${outputVar}[${i2}] = ${branchVar};`)}),d.write("}")}),doc.write("}");else{let elemVar=newVar(ctx);doc.write(`const ${elemVar} = ${accessor}[${i2}];`);let elemOutput=compileChild(doc,ctx,itemSchema,elemVar);doc.write(`${outputVar}[${i2}] = ${elemOutput};`)}}if(rest){let iVar=newVar(ctx),elemVar=newVar(ctx);doc.write(`for (let ${iVar} = ${items.length}; ${iVar} < ${accessor}.length; ${iVar}++) {`),doc.indented(d=>{d.write(`const ${elemVar} = ${accessor}[${iVar}];`);let elemOutput=compileChild(d,ctx,rest,elemVar);d.write(`${outputVar}[${iVar}] = ${elemOutput};`)}),doc.write("}")}return outputVar}function getTupleOptStart2(items,key){for(let i2=items.length-1;i2>=0;i2--)if(!(key==="optin"?items[i2]._zod.optin!==void 0:items[i2]._zod.optout==="optional"))return i2+1;return 0}function generateUnionCheck(doc,ctx,schema,accessor){let def=schema._zod.def,options=def.options;if(def.discriminator)return generateDiscriminatedUnionCheck(doc,ctx,def,accessor);if(def.inclusive===!1)throw new ZodCompileUnsupportedError("exclusive unions (z.xor)");if(options.length===0)return doc.write("return INVALID;"),accessor;if(options.length===1)return generateCheck(doc,ctx,options[0],accessor);if(options.every(opt=>opt._zod.def.type==="literal"&&!opt._zod.def.checks?.length)){let values2=new Set(options.flatMap(opt=>opt._zod.def.values)),valuesConst=addConstant(ctx,values2);return doc.write(`if (!${valuesConst}.has(${accessor})) return INVALID;`),accessor}let outputVar=newVar(ctx);doc.write(`let ${outputVar};`);for(let i2=0;i2<options.length;i2++){let opt=options[i2];i2===0?doc.write(`${outputVar} = (() => {`):doc.write(`if (${outputVar} === INVALID) ${outputVar} = (() => {`),doc.indented(d=>{let branchOutput=generateCheck(d,ctx,opt,accessor);d.write(`return ${branchOutput};`)}),doc.write("})();")}return doc.write(`if (${outputVar} === INVALID) return INVALID;`),outputVar}function generateDiscriminatedUnionCheck(doc,ctx,def,accessor){if(def.unionFallback)throw new ZodCompileUnsupportedError("discriminated union with unionFallback");if(def.options.length===0)return doc.write("return INVALID;"),accessor;let discVar=newVar(ctx),outputVar=newVar(ctx);doc.write(`const ${discVar} = ${accessor}?.[${esc(def.discriminator)}];`),doc.write(`let ${outputVar};`);let firstBranch=!0,claimed=new Set;for(let option of def.options){let values2=option._zod.propValues?.[def.discriminator];if(!values2||values2.size===0)throw new ZodCompileUnsupportedError("discriminated union option without static discriminator values");for(let value2 of values2){if(claimed.has(value2))throw new ZodCompileUnsupportedError(`duplicate discriminator value ${String(value2)}`);claimed.add(value2)}let conditions=Array.from(values2,value2=>literalEquality(ctx,discVar,value2)),prefix=firstBranch?"if":"else if";doc.write(`${prefix} (${conditions.join(" || ")}) {`),doc.indented(d=>{let branchOutput=generateCheck(d,ctx,option,accessor);d.write(`${outputVar} = ${branchOutput};`)}),doc.write("}"),firstBranch=!1}return doc.write("else { return INVALID; }"),outputVar}function literalEquality(ctx,accessor,value2){if(typeof value2=="string")return`${accessor} === ${esc(value2)}`;if(typeof value2=="number")return Number.isNaN(value2)?`Number.isNaN(${accessor})`:`${accessor} === ${value2}`;if(typeof value2=="boolean")return`${accessor} === ${value2}`;if(value2===null)return`${accessor} === null`;if(value2===void 0)return`${accessor} === undefined`;if(typeof value2=="bigint")return`${accessor} === ${value2}n`;if(typeof value2=="symbol"){let symbolConst=addConstant(ctx,value2);return`${accessor} === ${symbolConst}`}throw new ZodCompileUnsupportedError(`literal discriminator value ${String(value2)}`)}function generateIntersectionCheck(doc,ctx,schema,accessor){let def=schema._zod.def;ctx.definite=!1;let leftOutput=compileChild(doc,ctx,def.left,accessor),rightOutput=compileChild(doc,ctx,def.right,accessor),mergeConst=addConstant(ctx,mergeValues),mergedVar=newVar(ctx);return doc.write(`const ${mergedVar} = ${mergeConst}(${leftOutput}, ${rightOutput});`),doc.write(`if (!${mergedVar}.valid) return INVALID;`),`${mergedVar}.data`}function generateRecordCheck(doc,ctx,schema,accessor){let def=schema._zod.def,isPlainObjectConst=addConstant(ctx,isPlainObject);doc.write(`if (!${isPlainObjectConst}(${accessor})) return INVALID;`);let outputVar=newVar(ctx),kVar=newVar(ctx),valVar=newVar(ctx);doc.write(`const ${outputVar} = {};`);let recordDef=def,keyValues=recordDef.partial?void 0:def.keyType._zod.values;if(keyValues){let inputKeys=[];for(let key of keyValues){if(!(typeof key=="string"||typeof key=="number"||typeof key=="symbol"))throw new ZodCompileUnsupportedError(`record key value ${String(key)}`);let inputKey=typeof key=="number"?key.toString():key;if(inputKey==="__proto__")throw new ZodCompileUnsupportedError('record key "__proto__"');inputKeys.push(inputKey);let keyConst=addConstant(ctx,key),outKey=generateCheck(doc,ctx,def.keyType,keyConst),valueVar=newVar(ctx);doc.write(`const ${valueVar} = ${accessor}[${literalPropertyKey(ctx,inputKey)}];`);let valOutput=compileChild(doc,ctx,def.valueType,valueVar);doc.write(`${outputVar}[${outKey}] = ${valOutput};`)}let knownKeysConst=addConstant(ctx,new Set(inputKeys));return doc.write(`for (const ${kVar} in ${accessor}) {`),doc.indented(d=>{d.write(`if (${knownKeysConst}.has(${kVar})) continue;`),recordDef.mode==="loose"?d.write(`if (${kVar} !== "__proto__") ${outputVar}[${kVar}] = ${accessor}[${kVar}];`):d.write("return INVALID;")}),doc.write("}"),outputVar}let keyDef=def.keyType._zod.def;if(!(keyDef.type==="string"&&keyDef.format===void 0&&!keyDef.coerce&&(keyDef.checks?.length??0)===0)){let isLoose=def.mode==="loose",keyFn=compileFn(def.keyType);keyFn.definite===!1&&(ctx.definite=!1);let keyFast=addConstant(ctx,keyFn),numericConst=addConstant(ctx,number),outKeyVar=newVar(ctx);return emitOwnKeys(doc,ctx,accessor,kVar,d=>{d.write(`let ${outKeyVar} = ${keyFast}(${kVar});`),d.write(`if (${outKeyVar} === INVALID && typeof ${kVar} === "string" && ${numericConst}.test(${kVar})) ${outKeyVar} = ${keyFast}(Number(${kVar}));`),isLoose?d.write(`if (${outKeyVar} === INVALID) { ${outputVar}[${kVar}] = ${accessor}[${kVar}]; continue; }`):d.write(`if (${outKeyVar} === INVALID) return INVALID;`),d.write(`if (${outKeyVar} === "__proto__") continue;`);let valueVar=newVar(ctx);d.write(`const ${valueVar} = ${accessor}[${kVar}];`);let valOutput=compileChild(d,ctx,def.valueType,valueVar);d.write(`${outputVar}[${outKeyVar}] = ${valOutput};`)}),outputVar}return emitOwnKeys(doc,ctx,accessor,kVar,d=>{d.write(`const ${valVar} = ${accessor}[${kVar}];`);let valOutput=compileChild(d,ctx,def.valueType,valVar);d.write(`${outputVar}[${kVar}] = ${valOutput};`)},"return INVALID;"),outputVar}function emitOwnKeys(doc,ctx,accessor,kVar,body,onSymbol){let propIsEnumerableConst=addConstant(ctx,Object.prototype.propertyIsEnumerable),symsVar=newVar(ctx),keysVar=newVar(ctx),iVar=newVar(ctx);doc.write(`const ${symsVar} = Object.getOwnPropertySymbols(${accessor});`),doc.write(`const ${keysVar} = Object.getOwnPropertyNames(${accessor});`),doc.write(`for (let ${iVar} = 0; ${iVar} < ${keysVar}.length; ${iVar}++) {`),doc.indented(d=>{d.write(`const ${kVar} = ${keysVar}[${iVar}];`),d.write(`if (${kVar} === "__proto__" || !${propIsEnumerableConst}.call(${accessor}, ${kVar})) continue;`),body(d)}),doc.write("}"),doc.write(`for (let ${iVar} = 0; ${iVar} < ${symsVar}.length; ${iVar}++) {`),doc.indented(d=>{d.write(`const ${kVar} = ${symsVar}[${iVar}];`),d.write(`if (!${propIsEnumerableConst}.call(${accessor}, ${kVar})) continue;`),onSymbol?d.write(onSymbol):body(d)}),doc.write("}")}function literalPropertyKey(ctx,key){return typeof key=="string"?esc(key):addConstant(ctx,key)}function generateMapCheck(doc,ctx,schema,accessor){let def=schema._zod.def;doc.write(`if (!(${accessor} instanceof Map)) return INVALID;`),generateSizeGate(doc,schema,`${accessor}.size`);let outputVar=newVar(ctx),kVar=newVar(ctx),valVar=newVar(ctx);return doc.write(`const ${outputVar} = new Map();`),doc.write(`for (const [${kVar}, ${valVar}] of ${accessor}) {`),doc.indented(d=>{let keyOutput=generateCheck(d,ctx,def.keyType,kVar),valOutput=generateCheck(d,ctx,def.valueType,valVar);d.write(`${outputVar}.set(${keyOutput}, ${valOutput});`)}),doc.write("}"),outputVar}function generateSetCheck(doc,ctx,schema,accessor){let def=schema._zod.def;doc.write(`if (!(${accessor} instanceof Set)) return INVALID;`),generateSizeGate(doc,schema,`${accessor}.size`);let outputVar=newVar(ctx),valVar=newVar(ctx);return doc.write(`const ${outputVar} = new Set();`),doc.write(`for (const ${valVar} of ${accessor}) {`),doc.indented(d=>{let valOutput=generateCheck(d,ctx,def.valueType,valVar);d.write(`${outputVar}.add(${valOutput});`)}),doc.write("}"),outputVar}function generateFileCheck(doc,accessor){return doc.write(`if (!(${accessor} instanceof File)) return INVALID;`),accessor}function generateTemplateLiteralCheck(doc,ctx,schema,accessor){doc.write(`if (typeof ${accessor} !== "string") return INVALID;`);let pattern=schema._zod.pattern;if(pattern){let patternConst=addConstant(ctx,pattern);doc.write(`${patternConst}.lastIndex = 0;`),doc.write(`if (!${patternConst}.test(${accessor})) return INVALID;`)}return accessor}function generateLazyCheck(doc,ctx,schema,accessor){let def=schema._zod.def,getterConst=addUserConstant(ctx,def.getter),cacheConst=addConstant(ctx,{parser:null});doc.write(`if (!${cacheConst}.parser) {`),doc.indented(d=>{d.write(`const inner = ${getterConst}();`),d.write(`${cacheConst}.parser = function(input) {`),d.indented(d2=>{d2.write("const result = inner._zod.run({ value: input, issues: [] }, {});"),d2.write("return result.issues.length === 0 ? result.value : INVALID;")}),d.write("};")}),doc.write("}");let outputVar=newVar(ctx);return doc.write(`const ${outputVar} = ${cacheConst}.parser(${accessor});`),doc.write(`if (${outputVar} === INVALID) return INVALID;`),outputVar}function generatePipeCheck(doc,ctx,schema,accessor){let def=schema._zod.def,inputOutput=generateCheck(doc,ctx,def.in,accessor);if(def.transform){if(isAsyncFunction(def.transform))throw new ZodCompileAsyncError("z.compile: async transforms in pipes are not supported");let transformFn=def.transform,helperConst=addUserConstant(ctx,value2=>{let fakePayload={value:value2,issues:[],addIssue:pushIssue},result=transformFn(value2,fakePayload);return result instanceof Promise?INVALID:fakePayload.issues.length===0?result:INVALID}),transformedVar=newVar(ctx);return doc.write(`const ${transformedVar} = ${helperConst}(${inputOutput});`),doc.write(`if (${transformedVar} === INVALID) return INVALID;`),generateCheck(doc,ctx,def.out,transformedVar)}else return generateCheck(doc,ctx,def.out,inputOutput)}function isAsyncFunction(fn){return typeof fn=="function"&&(fn.constructor.name==="AsyncFunction"||fn[Symbol.toStringTag]==="AsyncFunction")}function generateCustomCheck(doc,ctx,schema,accessor){let def=schema._zod.def;if(def.fn){if(isAsyncFunction(def.fn))throw new ZodCompileAsyncError("z.compile: async custom predicates are not supported");let fnConst=addUserConstant(ctx,def.fn),throwAsyncConst=addConstant(ctx,throwAsync),resVar=newVar(ctx);doc.write(`const ${resVar} = ${fnConst}(${accessor});`),doc.write(`if (${resVar} instanceof Promise) ${throwAsyncConst}();`),doc.write(`if (!${resVar}) return INVALID;`)}else throw new ZodCompileUnsupportedError("custom schema without a predicate function");return accessor}function runtimeCatch(innerSchema,catchValue,value2){let result=innerSchema._zod.run({value:value2,issues:[]},{});if(result&&typeof result.then=="function")return INVALID;let r=result;return r.issues.length===0?r.value:catchValue()}function generateCatchCheck(doc,ctx,schema,accessor){let def=schema._zod.def;if(!def.catchValue[CONSTANT_CATCH])throw new ZodCompileUnsupportedError("catch with a callback (only a constant catch value compiles)",!1);let outputVar=newVar(ctx);doc.write(`let ${outputVar} = (() => {`),doc.indented(d=>{let innerOut=compileChild(d,ctx,def.innerType,accessor);d.write(`return ${innerOut};`)}),doc.write("})();");let innerConst=addConstant(ctx,def.innerType),catchConst=addUserConstant(ctx,def.catchValue),catchHelperConst=addConstant(ctx,runtimeCatch);return doc.write(`if (${outputVar} === INVALID) {`),doc.indented(d=>{d.write(`${outputVar} = ${catchHelperConst}(${innerConst}, ${catchConst}, ${accessor});`),d.write(`if (${outputVar} === INVALID) return INVALID;`)}),doc.write("}"),outputVar}function generateTransformCheck(doc,ctx,schema,accessor){let def=schema._zod.def;if(def.transform){if(isAsyncFunction(def.transform))throw new ZodCompileAsyncError("z.compile: async transforms are not supported");let transformFn=def.transform,helperConst=addUserConstant(ctx,value2=>{let fakePayload={value:value2,issues:[],addIssue:pushIssue},result=transformFn(value2,fakePayload);return result instanceof Promise?INVALID:fakePayload.issues.length===0?result:INVALID}),outputVar=newVar(ctx);return doc.write(`const ${outputVar} = ${helperConst}(${accessor});`),doc.write(`if (${outputVar} === INVALID) return INVALID;`),outputVar}return accessor}function snapshotChecks(def){return def.checks&&(def.checks=[...def.checks]),def}function _string(Class2,params){return new Class2(snapshotChecks({type:"string",...normalizeParams(params)}))}function _coercedString(Class2,params){return new Class2(snapshotChecks({type:"string",coerce:!0,...normalizeParams(params)}))}function _email(Class2,params){return new Class2({type:"string",format:"email",check:"string_format",abort:!1,...normalizeParams(params)})}function _guid(Class2,params){return new Class2({type:"string",format:"guid",check:"string_format",abort:!1,...normalizeParams(params)})}function _uuid(Class2,params){return new Class2({type:"string",format:"uuid",check:"string_format",abort:!1,...normalizeParams(params)})}function _uuidv4(Class2,params){return new Class2({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...normalizeParams(params)})}function _uuidv6(Class2,params){return new Class2({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...normalizeParams(params)})}function _uuidv7(Class2,params){return new Class2({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...normalizeParams(params)})}function _url(Class2,params){return new Class2({type:"string",format:"url",check:"string_format",abort:!1,...normalizeParams(params)})}function _emoji2(Class2,params){return new Class2({type:"string",format:"emoji",check:"string_format",abort:!1,...normalizeParams(params)})}function _nanoid(Class2,params){return new Class2({type:"string",format:"nanoid",check:"string_format",abort:!1,...normalizeParams(params)})}function _cuid(Class2,params){return new Class2({type:"string",format:"cuid",check:"string_format",abort:!1,...normalizeParams(params)})}function _cuid2(Class2,params){return new Class2({type:"string",format:"cuid2",check:"string_format",abort:!1,...normalizeParams(params)})}function _ulid(Class2,params){return new Class2({type:"string",format:"ulid",check:"string_format",abort:!1,...normalizeParams(params)})}function _xid(Class2,params){return new Class2({type:"string",format:"xid",check:"string_format",abort:!1,...normalizeParams(params)})}function _ksuid(Class2,params){return new Class2({type:"string",format:"ksuid",check:"string_format",abort:!1,...normalizeParams(params)})}function _ipv4(Class2,params){return new Class2({type:"string",format:"ipv4",check:"string_format",abort:!1,...normalizeParams(params)})}function _ipv6(Class2,params){return new Class2({type:"string",format:"ipv6",check:"string_format",abort:!1,...normalizeParams(params)})}function _mac(Class2,params){return new Class2({type:"string",format:"mac",check:"string_format",abort:!1,...normalizeParams(params)})}function _cidrv4(Class2,params){return new Class2({type:"string",format:"cidrv4",check:"string_format",abort:!1,...normalizeParams(params)})}function _cidrv6(Class2,params){return new Class2({type:"string",format:"cidrv6",check:"string_format",abort:!1,...normalizeParams(params)})}function _base64(Class2,params){return new Class2({type:"string",format:"base64",check:"string_format",abort:!1,...normalizeParams(params)})}function _base64url(Class2,params){return new Class2({type:"string",format:"base64url",check:"string_format",abort:!1,...normalizeParams(params)})}function _e164(Class2,params){return new Class2({type:"string",format:"e164",check:"string_format",abort:!1,...normalizeParams(params)})}function _creditCard(Class2,params){return new Class2({type:"string",format:"credit_card",check:"string_format",abort:!1,...normalizeParams(params)})}function _iban(Class2,params){return new Class2({type:"string",format:"iban",check:"string_format",abort:!1,...normalizeParams(params)})}function _jwt(Class2,params){return new Class2({type:"string",format:"jwt",check:"string_format",abort:!1,...normalizeParams(params)})}var TimePrecision={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6};function _isoDateTime(Class2,params){return new Class2({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...normalizeParams(params)})}function _isoDate(Class2,params){return new Class2({type:"string",format:"date",check:"string_format",...normalizeParams(params)})}function _isoTime(Class2,params){return new Class2({type:"string",format:"time",check:"string_format",precision:null,...normalizeParams(params)})}function _isoDuration(Class2,params){return new Class2({type:"string",format:"duration",check:"string_format",...normalizeParams(params)})}function _number(Class2,params){return new Class2(snapshotChecks({type:"number",checks:[],...normalizeParams(params)}))}function _coercedNumber(Class2,params){return new Class2(snapshotChecks({type:"number",coerce:!0,checks:[],...normalizeParams(params)}))}function _int(Class2,params){return new Class2({type:"number",check:"number_format",abort:!1,format:"safeint",...normalizeParams(params)})}function _float32(Class2,params){return new Class2({type:"number",check:"number_format",abort:!1,format:"float32",...normalizeParams(params)})}function _float64(Class2,params){return new Class2({type:"number",check:"number_format",abort:!1,format:"float64",...normalizeParams(params)})}function _int32(Class2,params){return new Class2({type:"number",check:"number_format",abort:!1,format:"int32",...normalizeParams(params)})}function _uint32(Class2,params){return new Class2({type:"number",check:"number_format",abort:!1,format:"uint32",...normalizeParams(params)})}function _boolean(Class2,params){return new Class2({type:"boolean",...normalizeParams(params)})}function _coercedBoolean(Class2,params){return new Class2({type:"boolean",coerce:!0,...normalizeParams(params)})}function _bigint(Class2,params){return new Class2({type:"bigint",...normalizeParams(params)})}function _coercedBigint(Class2,params){return new Class2({type:"bigint",coerce:!0,...normalizeParams(params)})}function _int64(Class2,params){return new Class2({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...normalizeParams(params)})}function _uint64(Class2,params){return new Class2({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...normalizeParams(params)})}function _symbol(Class2,params){return new Class2({type:"symbol",...normalizeParams(params)})}function _undefined2(Class2,params){return new Class2({type:"undefined",...normalizeParams(params)})}function _null2(Class2,params){return new Class2({type:"null",...normalizeParams(params)})}function _any(Class2){return new Class2({type:"any"})}function _unknown(Class2){return new Class2({type:"unknown"})}function _never(Class2,params){return new Class2({type:"never",...normalizeParams(params)})}function _void(Class2,params){return new Class2({type:"void",...normalizeParams(params)})}function _date(Class2,params){return new Class2({type:"date",...normalizeParams(params)})}function _coercedDate(Class2,params){return new Class2({type:"date",coerce:!0,...normalizeParams(params)})}function _nan(Class2,params){return new Class2({type:"nan",...normalizeParams(params)})}function _lt(value2,params){return new $ZodCheckLessThan({check:"less_than",...normalizeParams(params),value:value2,inclusive:!1})}function _lte(value2,params){return new $ZodCheckLessThan({check:"less_than",...normalizeParams(params),value:value2,inclusive:!0})}function _gt(value2,params){return new $ZodCheckGreaterThan({check:"greater_than",...normalizeParams(params),value:value2,inclusive:!1})}function _gte(value2,params){return new $ZodCheckGreaterThan({check:"greater_than",...normalizeParams(params),value:value2,inclusive:!0})}function _positive(params){return _gt(0,params)}function _negative(params){return _lt(0,params)}function _nonpositive(params){return _lte(0,params)}function _nonnegative(params){return _gte(0,params)}function _multipleOf(value2,params){return new $ZodCheckMultipleOf({check:"multiple_of",...normalizeParams(params),value:value2})}function _maxSize(maximum,params){return new $ZodCheckMaxSize({check:"max_size",...normalizeParams(params),maximum})}function _minSize(minimum,params){return new $ZodCheckMinSize({check:"min_size",...normalizeParams(params),minimum})}function _size(size,params){return new $ZodCheckSizeEquals({check:"size_equals",...normalizeParams(params),size})}function _maxLength(maximum,params){return new $ZodCheckMaxLength({check:"max_length",...normalizeParams(params),maximum})}function _minLength(minimum,params){return new $ZodCheckMinLength({check:"min_length",...normalizeParams(params),minimum})}function _length(length,params){return new $ZodCheckLengthEquals({check:"length_equals",...normalizeParams(params),length})}function _regex(pattern,params){return new $ZodCheckRegex({check:"string_format",format:"regex",...normalizeParams(params),pattern})}function _lowercase(params){return new $ZodCheckLowerCase({check:"string_format",format:"lowercase",...normalizeParams(params)})}function _uppercase(params){return new $ZodCheckUpperCase({check:"string_format",format:"uppercase",...normalizeParams(params)})}function _includes(includes,params){return new $ZodCheckIncludes({check:"string_format",format:"includes",...normalizeParams(params),includes})}function _startsWith(prefix,params){return new $ZodCheckStartsWith({check:"string_format",format:"starts_with",...normalizeParams(params),prefix})}function _endsWith(suffix,params){return new $ZodCheckEndsWith({check:"string_format",format:"ends_with",...normalizeParams(params),suffix})}function _property(property,schema,params){return new $ZodCheckProperty({check:"property",property,schema,...normalizeParams(params)})}function _properties(shape,params){return new $ZodCheckProperties({check:"properties",shape,...normalizeParams(params)})}function _mime(types,params){return new $ZodCheckMimeType({check:"mime_type",mime:types,...normalizeParams(params)})}function _overwrite(tx){return new $ZodCheckOverwrite({check:"overwrite",tx})}function _normalize(form){return _overwrite(input2=>input2.normalize(form))}function _trim(){return _overwrite(input2=>input2.trim())}function _toLowerCase(){return _overwrite(input2=>input2.toLowerCase())}function _toUpperCase(){return _overwrite(input2=>input2.toUpperCase())}function _slugify(){return _overwrite(input2=>slugify(input2))}function _array(Class2,element,params){return new Class2({type:"array",element,...normalizeParams(params)})}function _union(Class2,options,params){return new Class2({type:"union",options,...normalizeParams(params)})}function _xor(Class2,options,params){return new Class2({type:"union",options,inclusive:!1,...normalizeParams(params)})}function _discriminatedUnion(Class2,discriminator,options,params){return new Class2({type:"union",options,discriminator,...normalizeParams(params)})}function _intersection(Class2,left,right){return new Class2({type:"intersection",left,right})}function _tuple(Class2,items,_paramsOrRest,_params){let hasRest=_paramsOrRest instanceof $ZodType,params=hasRest?_params:_paramsOrRest,rest=hasRest?_paramsOrRest:null;return new Class2({type:"tuple",items,rest,...normalizeParams(params)})}function _record(Class2,keyType,valueType,params){return new Class2({type:"record",keyType,valueType,...normalizeParams(params)})}function _map(Class2,keyType,valueType,params){return new Class2({type:"map",keyType,valueType,...normalizeParams(params)})}function _set(Class2,valueType,params){return new Class2({type:"set",valueType,...normalizeParams(params)})}function _enum(Class2,values2,params){let entries=Array.isArray(values2)?Object.fromEntries(values2.map(v=>[v,v])):values2;return new Class2({type:"enum",entries,...normalizeParams(params)})}function _nativeEnum(Class2,entries,params){return new Class2({type:"enum",entries,...normalizeParams(params)})}function _literal(Class2,value2,params){return new Class2({type:"literal",values:Array.isArray(value2)?value2:[value2],...normalizeParams(params)})}function _file(Class2,params){return new Class2({type:"file",...normalizeParams(params)})}function _transform(Class2,fn){return new Class2({type:"transform",transform:fn})}function _optional(Class2,innerType){return new Class2({type:"optional",innerType})}function _nullable(Class2,innerType){return new Class2({type:"nullable",innerType})}function _default(Class2,innerType,defaultValue){return new Class2({type:"default",innerType,get defaultValue(){return typeof defaultValue=="function"?defaultValue():shallowClone(defaultValue)}})}function _nonoptional(Class2,innerType,params){return new Class2({type:"nonoptional",innerType,...normalizeParams(params)})}function _success(Class2,innerType){return new Class2({type:"success",innerType})}function _catch(Class2,innerType,catchValue){return new Class2({type:"catch",innerType,catchValue:typeof catchValue=="function"?catchValue:constantCatch(catchValue)})}function _pipe(Class2,in_,out){return new Class2({type:"pipe",in:in_,out})}function _readonly(Class2,innerType){return new Class2({type:"readonly",innerType})}function _templateLiteral(Class2,parts,params){return new Class2({type:"template_literal",parts,...normalizeParams(params)})}function _lazy(Class2,getter){return new Class2({type:"lazy",getter})}function _promise(Class2,innerType){return new Class2({type:"promise",innerType})}function _custom(Class2,fn,_params){let norm=normalizeParams(_params);return norm.abort??(norm.abort=!0),new Class2({type:"custom",check:"custom",fn,...norm})}function _refine(Class2,fn,_params){return new Class2({type:"custom",check:"custom",fn,...normalizeParams(_params)})}function _superRefine(fn,params){let ch2=_check(payload=>(payload.addIssue=issue2=>{if(typeof issue2=="string")payload.issues.push(issue(issue2,payload.value,ch2._zod.def));else{let _issue=issue2;_issue.fatal&&(_issue.continue=!1),_issue.code??(_issue.code="custom"),"input"in _issue||(_issue.input=payload.value),_issue.inst??(_issue.inst=ch2),_issue.continue??(_issue.continue=!ch2._zod.def.abort),payload.issues.push(issue(_issue))}},fn(payload.value,payload)),params);return ch2}function _check(fn,params){let ch2=new $ZodCheck({check:"custom",...normalizeParams(params)});return ch2._zod.check=fn,ch2}function describe(description){let ch2=new $ZodCheck({check:"describe"});return ch2._zod.onattach=[inst=>{let existing=globalRegistry.get(inst)??{};globalRegistry.add(inst,{...existing,description})}],ch2._zod.check=()=>{},ch2}function meta(metadata){let ch2=new $ZodCheck({check:"meta"});return ch2._zod.onattach=[inst=>{let existing=globalRegistry.get(inst)??{};globalRegistry.add(inst,{...existing,...metadata})}],ch2._zod.check=()=>{},ch2}function _stringbool(Classes,_params){let params=normalizeParams(_params),truthyArray=params.truthy??["true","1","yes","on","y","enabled"],falsyArray=params.falsy??["false","0","no","off","n","disabled"];params.case!=="sensitive"&&(truthyArray=truthyArray.map(v=>typeof v=="string"?v.toLowerCase():v),falsyArray=falsyArray.map(v=>typeof v=="string"?v.toLowerCase():v));let truthySet=new Set(truthyArray),falsySet=new Set(falsyArray),_Codec=Classes.Codec??$ZodCodec,_Boolean=Classes.Boolean??$ZodBoolean,_String=Classes.String??$ZodString,stringSchema=new _String({type:"string",error:params.error}),booleanSchema=new _Boolean({type:"boolean",error:params.error}),codec2=new _Codec({type:"pipe",in:stringSchema,out:booleanSchema,transform:((input2,payload)=>{let data=input2;return params.case!=="sensitive"&&(data=data.toLowerCase()),truthySet.has(data)?!0:falsySet.has(data)?!1:(payload.issues.push({code:"invalid_value",expected:"stringbool",values:[...truthySet,...falsySet],input:payload.value,inst:codec2,continue:!1}),{})}),reverseTransform:((input2,_payload)=>input2===!0?truthyArray[0]||"true":falsyArray[0]||"false"),error:params.error});return codec2._zod.bag.truthy=truthyArray,codec2._zod.bag.falsy=falsyArray,codec2._zod.bag.case=params.case??"insensitive",codec2}function _stringFormat(Class2,format,fnOrRegex,_params={}){let params=normalizeParams(_params),def={check:"string_format",type:"string",format,fn:typeof fnOrRegex=="function"?fnOrRegex:val=>fnOrRegex.test(val),...params};return fnOrRegex instanceof RegExp&&(def.pattern=fnOrRegex),new Class2(def)}function assignProps(target,...sources){for(let source of sources)for(let key of Reflect.ownKeys(source))Object.prototype.propertyIsEnumerable.call(source,key)&&assignProp(target,key,source[key]);return target}function initializeContext(params){let target=params?.target??"draft-2020-12";return target==="draft-4"&&(target="draft-04"),target==="draft-7"&&(target="draft-07"),{processors:params.processors??{},metadataRegistry:params?.metadata??globalRegistry,target,unrepresentable:params?.unrepresentable??"throw",override:params?.override??(()=>{}),io:params?.io??"output",counter:0,seen:new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:params?.cycles??"ref",reused:params?.reused??"inline",intersections:[],deferred:[],external:params?.external??void 0}}function handleUnrepresentable(schema,ctx,json2,params,message){let result=typeof ctx.unrepresentable=="function"?ctx.unrepresentable({zodSchema:schema,path:params.path,message}):ctx.unrepresentable;if(result==="any")return!1;if(result===void 0||result==="throw")throw new Error(message);return Object.assign(json2,result),!0}function processSchema(schema,ctx,_params={path:[],schemaPath:[]}){var _a4;let def=schema._zod.def,seen=ctx.seen.get(schema);if(seen)return seen.count++,_params.schemaPath.includes(schema)&&(seen.cycle=_params.path),seen.schema;let result={schema:{},count:1,cycle:void 0,path:_params.path};ctx.seen.set(schema,result),ctx.sharedDefsExtractedFor=void 0,ctx.sharedEmitDoneFor=void 0;let overrideSchema=schema._zod.toJSONSchema?.();if(overrideSchema)result.schema=overrideSchema;else{let params={..._params,schemaPath:[..._params.schemaPath,schema],path:_params.path};if(schema._zod.processJSONSchema)schema._zod.processJSONSchema(ctx,result.schema,params);else{let _json=result.schema,processor=ctx.processors[def.type];if(!processor)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`);processor(schema,ctx,_json,params)}let parent=schema._zod.parent;parent&&(result.ref||(result.ref=parent),processSchema(parent,ctx,params),ctx.seen.get(parent).isParent=!0)}let meta3=ctx.metadataRegistry.get(schema);return meta3&&assignProps(result.schema,meta3),ctx.io==="input"&&isTransforming(schema)&&(delete result.schema.examples,delete result.schema.default),ctx.io==="input"&&"_prefault"in result.schema&&((_a4=result.schema).default??(_a4.default=result.schema._prefault)),delete result.schema._prefault,ctx.seen.get(schema).schema}function encodeJSONPointerSegment(segment){return segment.replace(/~/g,"~0").replace(/\//g,"~1")}function extractDefs(ctx,schema){let root=ctx.seen.get(schema);if(!root)throw new Error("Unprocessed schema. This is a bug in Zod.");if(ctx.external&&ctx.sharedDefsExtractedFor===ctx.external)return;let idToSchema=new Map;for(let entry of ctx.seen.entries()){let id=ctx.metadataRegistry.get(entry[0])?.id;if(id){let existing=idToSchema.get(id);if(existing&&existing!==entry[0])throw new Error(`Duplicate schema id "${id}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);idToSchema.set(id,entry[0])}}let makeURI=entry=>{let defsSegment=ctx.target==="draft-2020-12"?"$defs":"definitions";if(ctx.external){let externalId=ctx.external.registry.get(entry[0])?.id,uriGenerator=ctx.external.uri??(id2=>id2);if(externalId)return{ref:uriGenerator(externalId)};let id=entry[1].defId??entry[1].schema.id??`schema${ctx.counter++}`;return entry[1].defId=id,{defId:id,ref:`${uriGenerator("__shared")}#/${defsSegment}/${encodeJSONPointerSegment(id)}`}}let uriPrefix="#",defUriPrefix=`${uriPrefix}/${defsSegment}/`;if(entry[1]===root&&!entry[1].schema.id)return{ref:uriPrefix};let defId=entry[1].schema.id??`__schema${ctx.counter++}`;return{defId,ref:defUriPrefix+encodeJSONPointerSegment(defId)}},extractToDef=entry=>{if(entry[1].schema.$ref)return;let seen=entry[1],{ref,defId}=makeURI(entry);seen.def={...seen.schema},defId&&(seen.defId=defId);let schema2=seen.schema;for(let key in schema2)delete schema2[key];schema2.$ref=ref};if(ctx.cycles==="throw")for(let entry of ctx.seen.entries()){let seen=entry[1];if(seen.cycle)throw new Error(`Cycle detected: #/${seen.cycle?.join("/")}/<root>
71
71
 
72
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let entry of ctx.seen.entries()){let seen=entry[1];if(schema===entry[0]){extractToDef(entry);continue}if(ctx.external){let ext=ctx.external.registry.get(entry[0])?.id;if(schema!==entry[0]&&ext){extractToDef(entry);continue}}if(ctx.metadataRegistry.get(entry[0])?.id){extractToDef(entry);continue}if(seen.cycle){extractToDef(entry);continue}seen.count>1&&ctx.reused==="ref"&&extractToDef(entry)}ctx.external&&(ctx.sharedDefsExtractedFor=ctx.external)}function compactTypeUnion(schema){let options=schema.anyOf;if(!Array.isArray(options)||options.length===0||schema.type!==void 0)return;let types=[];for(let option of options){if(!option||typeof option!="object")return;compactTypeUnion(option);let keys=Object.keys(option);if(keys.length!==1||keys[0]!=="type")return;let type=option.type;for(let member of Array.isArray(type)?type:[type]){if(typeof member!="string")return;types.includes(member)||types.push(member)}}delete schema.anyOf,schema.type=types.length===1?types[0]:types}var FOLDABLE_KEYS=new Set(["type","properties","required","additionalProperties"]),UNION_KEYS=["oneOf","anyOf"];function undeclaredConstraint(member){let extra=member.additionalProperties;return extra===void 0||extra===!1||typeof extra!="object"||extra===null?null:Object.keys(extra).length?extra:null}function foldObjects(members2){let objects=[];for(let member of members2){if(typeof member!="object"||member.type!=="object")return null;for(let key in member)if(!FOLDABLE_KEYS.has(key))return null;objects.push(member)}let properties={},required2=new Set;for(let object3 of objects){for(let key in object3.properties){if(Object.prototype.hasOwnProperty.call(properties,key))continue;let parts=[];for(let other of objects){let part2=other.properties?.[key]??undeclaredConstraint(other);part2!=null&&(parts.some(seen=>JSON.stringify(seen)===JSON.stringify(part2))||parts.push(part2))}let merged=parts.length===1?parts[0]:foldObjects(parts)??{allOf:parts};assignProp(properties,key,merged)}for(let key of object3.required??[])required2.add(key)}let folded2={type:"object",properties};if(required2.size&&(folded2.required=[...required2]),objects.every(object3=>object3.additionalProperties===!1))folded2.additionalProperties=!1;else{let constraints=[];for(let object3 of objects){let constraint=undeclaredConstraint(object3);constraint&&!constraints.some(seen=>JSON.stringify(seen)===JSON.stringify(constraint))&&constraints.push(constraint)}constraints.length===1?folded2.additionalProperties=constraints[0]:constraints.length>1&&(folded2.additionalProperties={allOf:constraints})}return folded2}function foldIntersection(json2){let allOf=json2.allOf;if(!Array.isArray(allOf)||allOf.length<2)return;for(let key of FOLDABLE_KEYS)if(key in json2)return;let unions=allOf.filter(m=>UNION_KEYS.some(k=>Array.isArray(m[k]))),folded2=null;if(!unions.length)folded2=foldObjects(allOf);else{let union2=unions[0],keyword=UNION_KEYS.find(k=>Array.isArray(union2[k]));if(Object.keys(union2).length!==1)return;let rest=allOf.filter(m=>m!==union2),branches=union2[keyword].map(branch=>foldObjects([...rest,branch]));if(branches.some(b=>!b))return;folded2={[keyword]:branches}}folded2&&(delete json2.allOf,assignProps(json2,folded2))}function finalize(ctx,schema){let root=ctx.seen.get(schema);if(!root)throw new Error("Unprocessed schema. This is a bug in Zod.");let flattenRef=zodSchema=>{let seen=ctx.seen.get(zodSchema);if(seen.ref===null)return;let schema2=seen.def??seen.schema,_cached={...schema2},ref=seen.ref;if(seen.ref=null,ref){flattenRef(ref);let refSeen=ctx.seen.get(ref),refSchema=refSeen.schema;if(refSchema.$ref&&(ctx.target==="draft-07"||ctx.target==="draft-04"||ctx.target==="openapi-3.0")?(schema2.allOf=schema2.allOf??[],schema2.allOf.push(refSchema)):assignProps(schema2,refSchema),assignProps(schema2,_cached),zodSchema._zod.parent===ref)for(let key in schema2)key==="$ref"||key==="allOf"||key in _cached||delete schema2[key];if(refSchema.$ref&&refSeen.def)for(let key in schema2)key==="$ref"||key==="allOf"||key in refSeen.def&&JSON.stringify(schema2[key])===JSON.stringify(refSeen.def[key])&&delete schema2[key]}let parent=zodSchema._zod.parent;if(parent&&parent!==ref){flattenRef(parent);let parentSeen=ctx.seen.get(parent);if(parentSeen?.schema.$ref&&(schema2.$ref=parentSeen.schema.$ref,parentSeen.def))for(let key in schema2)key==="$ref"||key==="allOf"||key in parentSeen.def&&JSON.stringify(schema2[key])===JSON.stringify(parentSeen.def[key])&&delete schema2[key]}ctx.override({zodSchema,jsonSchema:schema2,path:seen.path??[]})};if(!ctx.external||ctx.sharedEmitDoneFor!==ctx.external){for(let entry of[...ctx.seen.entries()].reverse())flattenRef(entry[0]);if(ctx.target!=="openapi-3.0")for(let entry of ctx.seen.entries())compactTypeUnion(entry[1].def??entry[1].schema);for(let rewrite of ctx.deferred)rewrite();if(ctx.intersections.length){let carriers=new Map;for(let seen of ctx.seen.values())for(let json2 of[seen.schema,seen.def]){let allOf=json2?.allOf;if(!Array.isArray(allOf))continue;let existing=carriers.get(allOf);existing?existing.push(json2):carriers.set(allOf,[json2])}for(let allOf of ctx.intersections)for(let json2 of carriers.get(allOf)??[])foldIntersection(json2)}}let result={};if(ctx.target==="draft-2020-12"?result.$schema="https://json-schema.org/draft/2020-12/schema":ctx.target==="draft-07"?result.$schema="http://json-schema.org/draft-07/schema#":ctx.target==="draft-04"?result.$schema="http://json-schema.org/draft-04/schema#":ctx.target,ctx.external?.uri){let id=ctx.external.registry.get(schema)?.id;if(!id)throw new Error("Schema is missing an `id` property");result.$id=ctx.external.uri(id)}assignProps(result,root.defId?root.schema:root.def??root.schema);let rootMetaId=ctx.metadataRegistry.get(schema)?.id;rootMetaId!==void 0&&result.id===rootMetaId&&delete result.id;let defs=ctx.external?.defs??{};if(!ctx.external||ctx.sharedEmitDoneFor!==ctx.external)for(let entry of ctx.seen.entries()){let seen=entry[1];seen.def&&seen.defId&&(seen.def.id===seen.defId&&delete seen.def.id,assignProp(defs,seen.defId,seen.def))}ctx.external&&(ctx.sharedEmitDoneFor=ctx.external),ctx.external||Object.keys(defs).length>0&&(ctx.target==="draft-2020-12"?result.$defs=defs:result.definitions=defs);try{let finalized=JSON.parse(JSON.stringify(result));return Object.defineProperty(finalized,"~standard",{value:{...schema["~standard"],jsonSchema:{input:createStandardJSONSchemaMethod(schema,"input",ctx.processors),output:createStandardJSONSchemaMethod(schema,"output",ctx.processors)}},enumerable:!1,writable:!1}),finalized}catch{throw new Error("Error converting schema to JSON.")}}function isTransforming(_schema,_ctx){let ctx=_ctx??{seen:new Set};if(ctx.seen.has(_schema))return!1;ctx.seen.add(_schema);let def=_schema._zod.def;if(def.type==="transform")return!0;if(def.type==="array")return isTransforming(def.element,ctx);if(def.type==="set")return isTransforming(def.valueType,ctx);if(def.type==="lazy")return isTransforming(def.getter(),ctx);if(def.type==="promise"||def.type==="optional"||def.type==="nonoptional"||def.type==="nullable"||def.type==="readonly"||def.type==="default"||def.type==="prefault"||def.type==="catch")return isTransforming(def.innerType,ctx);if(def.type==="intersection")return isTransforming(def.left,ctx)||isTransforming(def.right,ctx);if(def.type==="record"||def.type==="map")return isTransforming(def.keyType,ctx)||isTransforming(def.valueType,ctx);if(def.type==="pipe")return _schema._zod.traits.has("$ZodCodec")?!0:isTransforming(def.in,ctx)||isTransforming(def.out,ctx);if(def.type==="object"){for(let key in def.shape)if(isTransforming(def.shape[key],ctx))return!0;return!1}if(def.type==="union"){for(let option of def.options)if(isTransforming(option,ctx))return!0;return!1}if(def.type==="tuple"){for(let item of def.items)if(isTransforming(item,ctx))return!0;return!!(def.rest&&isTransforming(def.rest,ctx))}return!1}var createToJSONSchemaMethod=(schema,processors={})=>params=>{let ctx=initializeContext({...params,processors});return processSchema(schema,ctx),extractDefs(ctx,schema),finalize(ctx,schema)},createStandardJSONSchemaMethod=(schema,io,processors={})=>params=>{let{libraryOptions,target}=params??{},ctx=initializeContext({...libraryOptions??{},target,io,processors});return processSchema(schema,ctx),extractDefs(ctx,schema),finalize(ctx,schema)};var narrowMin=(agg,key,value2)=>{(agg[key]===void 0||value2>agg[key])&&(agg[key]=value2)},narrowMax=(agg,key,value2)=>{(agg[key]===void 0||value2<agg[key])&&(agg[key]=value2)},narrowBoth=(agg,value2)=>{narrowMin(agg,"minimum",value2),narrowMax(agg,"maximum",value2)},addDivisor=(agg,value2)=>{agg.multipleOf??(agg.multipleOf=[]),agg.multipleOf.includes(value2)||agg.multipleOf.push(value2)},addPattern=(agg,pattern)=>{agg.patterns??(agg.patterns=new Set),agg.patterns.add(pattern)},intersectMime=(agg,mime)=>{agg.mime=agg.mime?agg.mime.filter(m=>mime.includes(m)):[...mime]},setFormat=(agg,format)=>{agg.format=format,format.includes("int")&&(agg.isInt=!0)},minContributor=(agg,def)=>narrowMin(agg,"minimum",def.minimum),maxContributor=(agg,def)=>narrowMax(agg,"maximum",def.maximum),formatContributor=ranges=>(agg,def)=>{setFormat(agg,def.format);let[minimum,maximum]=ranges[def.format];narrowMin(agg,"minimum",minimum),narrowMax(agg,"maximum",maximum)},contributors={greater_than:(agg,def)=>narrowMin(agg,def.inclusive?"minimum":"exclusiveMinimum",def.value),less_than:(agg,def)=>narrowMax(agg,def.inclusive?"maximum":"exclusiveMaximum",def.value),multiple_of:(agg,def)=>addDivisor(agg,def.value),number_format:formatContributor(NUMBER_FORMAT_RANGES),bigint_format:formatContributor(BIGINT_FORMAT_RANGES),min_length:minContributor,max_length:maxContributor,length_equals:(agg,def)=>narrowBoth(agg,def.length),min_size:minContributor,max_size:maxContributor,size_equals:(agg,def)=>narrowBoth(agg,def.size),string_format:(agg,def)=>{setFormat(agg,def.format),def.pattern&&addPattern(agg,def.pattern),(def.format==="base64"||def.format==="base64url")&&(agg.contentEncoding=def.format),(def.local||def.precision===-1)&&(agg.laxFormat=!0)},mime_type:(agg,def)=>intersectMime(agg,def.mime)};function aggregateChecks(schema){let agg={},def=schema._zod.def,list=schema._zod.traits.has("$ZodCheck")?[schema,...def.checks??[]]:def.checks??[];for(let ch2 of list)contributors[ch2._zod.def.check]?.(agg,ch2._zod.def);let bag=schema._zod.bag;bag.minimum!==void 0&&narrowMin(agg,"minimum",bag.minimum),bag.exclusiveMinimum!==void 0&&narrowMin(agg,"exclusiveMinimum",bag.exclusiveMinimum),bag.maximum!==void 0&&narrowMax(agg,"maximum",bag.maximum),bag.exclusiveMaximum!==void 0&&narrowMax(agg,"exclusiveMaximum",bag.exclusiveMaximum),bag.multipleOf!==void 0&&addDivisor(agg,bag.multipleOf),bag.format!==void 0&&(agg.format??(agg.format=bag.format),bag.format.includes("int")&&(agg.isInt=!0)),bag.mime&&intersectMime(agg,bag.mime);for(let pattern of bag.patterns??[])addPattern(agg,pattern);return agg}var formatMap={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},exactPatterns=new Map([[base64Charset,base64],[base64urlCharset,base64url]]),exactPattern=p=>exactPatterns.get(p)??p,stringProcessor=(schema,ctx,_json,_params)=>{let json2=_json;json2.type="string";let{minimum,maximum,format,patterns,contentEncoding,laxFormat}=aggregateChecks(schema);if(typeof minimum=="number"&&(json2.minLength=minimum),typeof maximum=="number"&&(json2.maxLength=maximum),format&&(json2.format=formatMap[format]??format,json2.format===""&&delete json2.format,(format==="time"||laxFormat)&&delete json2.format),contentEncoding&&(json2.contentEncoding=contentEncoding),patterns&&patterns.size>0){let patternList=[...patterns].map(exactPattern);patternList.length===1?json2.pattern=patternList[0].source:patternList.length>1&&(json2.allOf=[...patternList.map(regex=>({...ctx.target==="draft-07"||ctx.target==="draft-04"||ctx.target==="openapi-3.0"?{type:"string"}:{},pattern:regex.source}))])}},numberProcessor=(schema,ctx,_json,params)=>{let json2=_json,{minimum,maximum,multipleOf,exclusiveMaximum,exclusiveMinimum,isInt}=aggregateChecks(schema);json2.type=isInt?"integer":"number";let exMin=typeof exclusiveMinimum=="number"&&exclusiveMinimum>=(minimum??Number.NEGATIVE_INFINITY),exMax=typeof exclusiveMaximum=="number"&&exclusiveMaximum<=(maximum??Number.POSITIVE_INFINITY),legacy=ctx.target==="draft-04"||ctx.target==="openapi-3.0";if(exMin?legacy?(json2.minimum=exclusiveMinimum,json2.exclusiveMinimum=!0):json2.exclusiveMinimum=exclusiveMinimum:typeof minimum=="number"&&(json2.minimum=minimum),exMax?legacy?(json2.maximum=exclusiveMaximum,json2.exclusiveMaximum=!0):json2.exclusiveMaximum=exclusiveMaximum:typeof maximum=="number"&&(json2.maximum=maximum),multipleOf){let divisors=new Set;for(let divisor of multipleOf)Number.isFinite(divisor)&&divisor!==0?divisors.add(Math.abs(divisor)):handleUnrepresentable(schema,ctx,json2,params,`A multipleOf divisor of ${divisor} cannot be represented in JSON Schema`);let[first,...rest]=divisors;first!==void 0&&(json2.multipleOf=first),rest.length&&(json2.allOf=[...json2.allOf??[],...rest.map(m=>({multipleOf:m}))])}},booleanProcessor=(_schema,_ctx,json2,_params)=>{json2.type="boolean"},bigintProcessor=(schema,ctx,json2,params)=>{handleUnrepresentable(schema,ctx,json2,params,"BigInt cannot be represented in JSON Schema")},symbolProcessor=(schema,ctx,json2,params)=>{handleUnrepresentable(schema,ctx,json2,params,"Symbols cannot be represented in JSON Schema")},nullProcessor=(_schema,ctx,json2,_params)=>{ctx.target==="openapi-3.0"?(json2.type="string",json2.nullable=!0,json2.enum=[null]):json2.type="null"},undefinedProcessor=(schema,ctx,json2,params)=>{handleUnrepresentable(schema,ctx,json2,params,"Undefined cannot be represented in JSON Schema")},voidProcessor=(schema,ctx,json2,params)=>{handleUnrepresentable(schema,ctx,json2,params,"Void cannot be represented in JSON Schema")},neverProcessor=(_schema,_ctx,json2,_params)=>{json2.not={}},anyProcessor=(_schema,_ctx,_json,_params)=>{},unknownProcessor=(_schema,_ctx,_json,_params)=>{},dateProcessor=(schema,ctx,json2,params)=>{handleUnrepresentable(schema,ctx,json2,params,"Date cannot be represented in JSON Schema")},enumProcessor=(schema,_ctx,json2,_params)=>{let def=schema._zod.def,values2=getEnumValues(def.entries);if(values2.length===0){json2.not={};return}values2.every(v=>typeof v=="number")&&(json2.type="number"),values2.every(v=>typeof v=="string")&&(json2.type="string"),json2.enum=values2},literalProcessor=(schema,ctx,json2,params)=>{let def=schema._zod.def;if(def.values.length===0){json2.not={};return}let vals=[];for(let val of def.values)if(val===void 0){if(handleUnrepresentable(schema,ctx,json2,params,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof val=="bigint"){if(handleUnrepresentable(schema,ctx,json2,params,"BigInt literals cannot be represented in JSON Schema"))return;vals.push(Number(val))}else vals.push(val);if(vals.length!==0)if(vals.length===1){let val=vals[0];json2.type=val===null?"null":typeof val,ctx.target==="draft-04"||ctx.target==="openapi-3.0"?json2.enum=[val]:json2.const=val}else vals.every(v=>typeof v=="number")&&(json2.type="number"),vals.every(v=>typeof v=="string")&&(json2.type="string"),vals.every(v=>typeof v=="boolean")&&(json2.type="boolean"),vals.every(v=>v===null)&&(json2.type="null"),json2.enum=vals},nanProcessor=(schema,ctx,json2,params)=>{handleUnrepresentable(schema,ctx,json2,params,"NaN cannot be represented in JSON Schema")},templateLiteralProcessor=(schema,_ctx,json2,_params)=>{let _json=json2,pattern=schema._zod.pattern;if(!pattern)throw new Error("Pattern not found in template literal");_json.type="string",_json.pattern=pattern.source},fileProcessor=(schema,_ctx,json2,_params)=>{let _json=json2;_json.type="string",_json.format="binary",_json.contentEncoding="binary";let{minimum,maximum,mime}=aggregateChecks(schema);minimum!==void 0&&(_json.minLength=minimum),maximum!==void 0&&(_json.maxLength=maximum),mime&&(mime.length===0?_json.not={}:mime.length===1?_json.contentMediaType=mime[0]:_json.anyOf=mime.map(m=>({contentMediaType:m})))},successProcessor=(_schema,_ctx,json2,_params)=>{json2.type="boolean"},customProcessor=(schema,ctx,json2,params)=>{handleUnrepresentable(schema,ctx,json2,params,"Custom types cannot be represented in JSON Schema")},functionProcessor=(schema,ctx,json2,params)=>{handleUnrepresentable(schema,ctx,json2,params,"Function types cannot be represented in JSON Schema")},transformProcessor=(schema,ctx,json2,params)=>{handleUnrepresentable(schema,ctx,json2,params,"Transforms cannot be represented in JSON Schema")},mapProcessor=(schema,ctx,json2,params)=>{handleUnrepresentable(schema,ctx,json2,params,"Map cannot be represented in JSON Schema")},setProcessor=(schema,ctx,json2,params)=>{handleUnrepresentable(schema,ctx,json2,params,"Set cannot be represented in JSON Schema")},arrayProcessor=(schema,ctx,_json,params)=>{let json2=_json,def=schema._zod.def,{minimum,maximum}=aggregateChecks(schema);typeof minimum=="number"&&(json2.minItems=minimum),typeof maximum=="number"&&(json2.maxItems=maximum),json2.type="array",json2.items=processSchema(def.element,ctx,{...params,path:[...params.path,"items"]})};function inputOptin(schema){let def=schema._zod.def;return def.type==="pipe"&&def.in._zod.traits.has("$ZodTransform")?inputOptin(def.out):def.type==="catch"?inputOptin(def.innerType):schema._zod.optin}var objectProcessor=(schema,ctx,_json,params)=>{let json2=_json,def=schema._zod.def,shape=def.shape;if(Object.getOwnPropertySymbols(shape).length&&handleUnrepresentable(schema,ctx,json2,params,"Symbol keys cannot be represented in JSON Schema"))return;json2.type="object",json2.properties={};for(let key in shape)assignProp(json2.properties,key,processSchema(shape[key],ctx,{...params,path:[...params.path,"properties",key]}));let requiredKeys=[];for(let key of Object.keys(shape)){let field=def.shape[key];(ctx.io==="input"?inputOptin(field)===void 0:field._zod.optout===void 0)&&requiredKeys.push(key)}requiredKeys.length>0&&(json2.required=requiredKeys),def.catchall?._zod.def.type==="never"?json2.additionalProperties=!1:def.catchall?def.catchall&&(json2.additionalProperties=processSchema(def.catchall,ctx,{...params,path:[...params.path,"additionalProperties"]})):ctx.io==="output"&&(json2.additionalProperties=!1)},unionProcessor=(schema,ctx,json2,params)=>{let def=schema._zod.def,isExclusive=def.inclusive===!1,options=def.options.map((x2,i2)=>processSchema(x2,ctx,{...params,path:[...params.path,isExclusive?"oneOf":"anyOf",i2]}));isExclusive?json2.oneOf=options:json2.anyOf=options},intersectionProcessor=(schema,ctx,json2,params)=>{let def=schema._zod.def,a=processSchema(def.left,ctx,{...params,path:[...params.path,"allOf",0]}),b=processSchema(def.right,ctx,{...params,path:[...params.path,"allOf",1]}),isSimpleIntersection=val=>"allOf"in val&&Object.keys(val).length===1,allOf=[...isSimpleIntersection(a)?a.allOf:[a],...isSimpleIntersection(b)?b.allOf:[b]];json2.allOf=allOf,ctx.intersections.push(allOf)},tupleProcessor=(schema,ctx,_json,params)=>{let json2=_json,def=schema._zod.def;json2.type="array";let prefixPath=ctx.target==="draft-2020-12"?"prefixItems":"items",restPath=ctx.target==="draft-2020-12"||ctx.target==="openapi-3.0"?"items":"additionalItems",prefixItems=def.items.map((x2,i2)=>processSchema(x2,ctx,{...params,path:[...params.path,prefixPath,i2]})),rest=def.rest?processSchema(def.rest,ctx,{...params,path:[...params.path,restPath,...ctx.target==="openapi-3.0"?[def.items.length]:[]]}):null,minItems=def.items.length;for(;minItems>0;){let item=def.items[minItems-1];if(!(ctx.io==="input"?inputOptin(item)!==void 0:item._zod.optout==="optional"))break;minItems--}let maxItems=def.items.length,isClosed=!def.rest;ctx.target==="draft-2020-12"?(json2.prefixItems=prefixItems,isClosed?json2.items=!1:rest&&(json2.items=rest),minItems>0&&(json2.minItems=minItems),isClosed&&(json2.maxItems=maxItems)):ctx.target==="openapi-3.0"?(json2.items={anyOf:prefixItems},rest&&json2.items.anyOf.push(rest),minItems>0&&(json2.minItems=minItems),isClosed&&(json2.maxItems=maxItems)):(json2.items=prefixItems,isClosed?json2.additionalItems=!1:rest&&(json2.additionalItems=rest),minItems>0&&(json2.minItems=minItems),isClosed&&(json2.maxItems=maxItems));let{minimum,maximum}=aggregateChecks(schema);typeof minimum=="number"&&(json2.minItems=minimum),typeof maximum=="number"&&(json2.maxItems=maximum)};function stringifyKeyNames(bySchema,json2,visited){if(json2.$ref){if(visited.has(json2))return json2;visited.add(json2);let def=bySchema.get(json2)?.def;if(!def)return json2;let inlined=stringifyKeyNames(bySchema,def,visited);return inlined===def?json2:inlined}for(let keyword of["anyOf","oneOf"]){let branches=json2[keyword];if(!Array.isArray(branches))continue;let mapped=branches.map(branch=>stringifyKeyNames(bySchema,branch,visited));mapped.some((branch,i2)=>branch!==branches[i2])&&(json2={...json2,[keyword]:mapped})}let types=Array.isArray(json2.type)?json2.type:[json2.type],numericType=!types.includes("string")&&types.some(t2=>t2==="number"||t2==="integer"),values2=json2.enum??(json2.const!==void 0?[json2.const]:void 0);if(!numericType&&!values2?.some(v=>typeof v=="number"))return json2;let{minimum,maximum,exclusiveMinimum,exclusiveMaximum,multipleOf,format,id,...rest}=json2;return rest.enum?rest.enum=rest.enum.map(v=>typeof v=="number"?String(v):v):typeof rest.const=="number"&&(rest.const=String(rest.const)),numericType&&(rest.type="string",values2||(rest.pattern=(types.includes("number")?number:integer).source)),rest}var pendingRecords=new WeakMap;function rewriteKeyNames(ctx){let bySchema=new Map;for(let entry of ctx.seen.values())entry.def&&!bySchema.has(entry.schema)&&bySchema.set(entry.schema,entry);let rewrites=new Map;for(let record2 of pendingRecords.get(ctx)??[]){let seen=ctx.seen.get(record2),names=(seen?.def??seen?.schema)?.propertyNames;if(!names||names===!0||rewrites.has(names))continue;let rewritten=stringifyKeyNames(bySchema,names,new Set);rewritten!==names&&rewrites.set(names,rewritten)}if(rewrites.size)for(let entry of ctx.seen.values())for(let carrier of[entry.schema,entry.def]){let rewritten=carrier&&rewrites.get(carrier.propertyNames);rewritten&&(carrier.propertyNames=rewritten)}}var recordProcessor=(schema,ctx,_json,params)=>{let json2=_json,def=schema._zod.def;json2.type="object";let keyType=def.keyType,patterns=aggregateChecks(keyType).patterns;if(def.mode==="loose"&&patterns&&patterns.size>0){let valueSchema=processSchema(def.valueType,ctx,{...params,path:[...params.path,"patternProperties","*"]});json2.patternProperties={};for(let pattern of patterns)assignProp(json2.patternProperties,exactPattern(pattern).source,valueSchema)}else{if(ctx.target==="draft-07"||ctx.target==="draft-2020-12"){json2.propertyNames=processSchema(def.keyType,ctx,{...params,path:[...params.path,"propertyNames"]});let pending2=pendingRecords.get(ctx);pending2||(pending2=[],pendingRecords.set(ctx,pending2),ctx.deferred.push(()=>rewriteKeyNames(ctx))),pending2.push(schema)}json2.additionalProperties=processSchema(def.valueType,ctx,{...params,path:[...params.path,"additionalProperties"]})}let keyValues=keyType._zod.values,omittableOnInput=ctx.io==="input"&&inputOptin(def.valueType)!==void 0;if(keyValues&&!def.partial&&!omittableOnInput){let validKeyValues=[...keyValues].filter(v=>typeof v=="string"||typeof v=="number");validKeyValues.length>0&&(json2.required=validKeyValues.map(String))}},nullableProcessor=(schema,ctx,json2,params)=>{let def=schema._zod.def,inner=processSchema(def.innerType,ctx,params),seen=ctx.seen.get(schema);ctx.target==="openapi-3.0"?(seen.ref=def.innerType,json2.nullable=!0):json2.anyOf=[inner,{type:"null"}]},nonoptionalProcessor=(schema,ctx,_json,params)=>{let def=schema._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType},UNREPRESENTABLE_DEFAULT=Symbol();function serializeDefaultValue(value2,schema,ctx,json2,params){let unrepresentable=!1,serialized=JSON.stringify(value2,(_,val)=>typeof val!="bigint"?val:(unrepresentable=!0,null));return unrepresentable?(handleUnrepresentable(schema,ctx,json2,params,"BigInt defaults cannot be represented in JSON Schema"),UNREPRESENTABLE_DEFAULT):JSON.parse(serialized)}var defaultProcessor=(schema,ctx,json2,params)=>{let def=schema._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType;let value2=serializeDefaultValue(def.defaultValue,schema,ctx,json2,params);value2!==UNREPRESENTABLE_DEFAULT&&(json2.default=value2)},prefaultProcessor=(schema,ctx,json2,params)=>{let def=schema._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema);if(seen.ref=def.innerType,ctx.io!=="input")return;let value2=serializeDefaultValue(def.defaultValue,schema,ctx,json2,params);value2!==UNREPRESENTABLE_DEFAULT&&(json2._prefault=value2)},catchProcessor=(schema,ctx,json2,params)=>{let def=schema._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType;let catchValue;try{catchValue=def.catchValue(void 0)}catch{handleUnrepresentable(schema,ctx,json2,params,"Dynamic catch values are not supported in JSON Schema");return}json2.default=catchValue},pipeProcessor=(schema,ctx,_json,params)=>{let def=schema._zod.def,inIsTransform=def.in._zod.traits.has("$ZodTransform"),innerType=ctx.io==="input"?inIsTransform?def.out:def.in:def.out;processSchema(innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=innerType},readonlyProcessor=(schema,ctx,json2,params)=>{let def=schema._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType,json2.readOnly=!0},promiseProcessor=(schema,ctx,_json,params)=>{let def=schema._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType},optionalProcessor=(schema,ctx,_json,params)=>{let def=schema._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType},lazyProcessor=(schema,ctx,_json,params)=>{let innerType=schema._zod.innerType;processSchema(innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=innerType},allProcessors={string:stringProcessor,number:numberProcessor,boolean:booleanProcessor,bigint:bigintProcessor,symbol:symbolProcessor,null:nullProcessor,undefined:undefinedProcessor,void:voidProcessor,never:neverProcessor,any:anyProcessor,unknown:unknownProcessor,date:dateProcessor,enum:enumProcessor,literal:literalProcessor,nan:nanProcessor,template_literal:templateLiteralProcessor,file:fileProcessor,success:successProcessor,custom:customProcessor,function:functionProcessor,transform:transformProcessor,map:mapProcessor,set:setProcessor,array:arrayProcessor,object:objectProcessor,union:unionProcessor,intersection:intersectionProcessor,tuple:tupleProcessor,record:recordProcessor,nullable:nullableProcessor,nonoptional:nonoptionalProcessor,default:defaultProcessor,prefault:prefaultProcessor,catch:catchProcessor,pipe:pipeProcessor,readonly:readonlyProcessor,promise:promiseProcessor,optional:optionalProcessor,lazy:lazyProcessor};function toJSONSchema(input2,params){if("_idmap"in input2){let registry2=input2,ctx2=initializeContext({...params,processors:allProcessors}),defs={};for(let entry of registry2._idmap.entries()){let[_,schema]=entry;processSchema(schema,ctx2)}let schemas={},external={registry:registry2,uri:params?.uri,defs};ctx2.external=external;for(let entry of registry2._idmap.entries()){let[key,schema]=entry;extractDefs(ctx2,schema),assignProp(schemas,key,finalize(ctx2,schema))}if(Object.keys(defs).length>0){let defsSegment=ctx2.target==="draft-2020-12"?"$defs":"definitions";schemas.__shared={[defsSegment]:defs}}return{schemas}}let ctx=initializeContext({...params,processors:allProcessors});return processSchema(input2,ctx),extractDefs(ctx,input2),finalize(ctx,input2)}var JSONSchemaGenerator=class{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter(value2){this.ctx.counter=value2}get seen(){return this.ctx.seen}constructor(params){let normalizedTarget=params?.target??"draft-2020-12";normalizedTarget==="draft-4"&&(normalizedTarget="draft-04"),normalizedTarget==="draft-7"&&(normalizedTarget="draft-07"),this.ctx=initializeContext({processors:allProcessors,target:normalizedTarget,...params?.metadata&&{metadata:params.metadata},...params?.unrepresentable&&{unrepresentable:params.unrepresentable},...params?.override&&{override:params.override},...params?.io&&{io:params.io}})}process(schema,_params={path:[],schemaPath:[]}){return processSchema(schema,this.ctx,_params)}emit(schema,_params){_params&&(_params.cycles&&(this.ctx.cycles=_params.cycles),_params.reused&&(this.ctx.reused=_params.reused),_params.external&&(this.ctx.external=_params.external)),this.ctx.sharedDefsExtractedFor=void 0,this.ctx.sharedEmitDoneFor=void 0,extractDefs(this.ctx,schema);let result=finalize(this.ctx,schema),{"~standard":_,...plainResult}=result;return plainResult}};var json_schema_exports={};var schemas_exports2={};__export(schemas_exports2,{ZodAny:()=>ZodAny,ZodArray:()=>ZodArray,ZodBase64:()=>ZodBase64,ZodBase64URL:()=>ZodBase64URL,ZodBigInt:()=>ZodBigInt,ZodBigIntFormat:()=>ZodBigIntFormat,ZodBoolean:()=>ZodBoolean,ZodCIDRv4:()=>ZodCIDRv4,ZodCIDRv6:()=>ZodCIDRv6,ZodCUID:()=>ZodCUID,ZodCUID2:()=>ZodCUID2,ZodCatch:()=>ZodCatch,ZodCodec:()=>ZodCodec,ZodCreditCard:()=>ZodCreditCard,ZodCustom:()=>ZodCustom,ZodCustomStringFormat:()=>ZodCustomStringFormat,ZodDate:()=>ZodDate,ZodDefault:()=>ZodDefault,ZodDiscriminatedUnion:()=>ZodDiscriminatedUnion,ZodE164:()=>ZodE164,ZodEmail:()=>ZodEmail,ZodEmoji:()=>ZodEmoji,ZodEnum:()=>ZodEnum,ZodExactOptional:()=>ZodExactOptional,ZodFile:()=>ZodFile,ZodFunction:()=>ZodFunction,ZodGUID:()=>ZodGUID,ZodIBAN:()=>ZodIBAN,ZodIPv4:()=>ZodIPv4,ZodIPv6:()=>ZodIPv6,ZodISODate:()=>ZodISODate,ZodISODateTime:()=>ZodISODateTime,ZodISODuration:()=>ZodISODuration,ZodISOTime:()=>ZodISOTime,ZodInstanceOf:()=>ZodInstanceOf,ZodIntersection:()=>ZodIntersection,ZodJWT:()=>ZodJWT,ZodKSUID:()=>ZodKSUID,ZodLazy:()=>ZodLazy,ZodLiteral:()=>ZodLiteral,ZodMAC:()=>ZodMAC,ZodMap:()=>ZodMap,ZodNaN:()=>ZodNaN,ZodNanoID:()=>ZodNanoID,ZodNever:()=>ZodNever,ZodNonOptional:()=>ZodNonOptional,ZodNull:()=>ZodNull,ZodNullable:()=>ZodNullable,ZodNumber:()=>ZodNumber,ZodNumberFormat:()=>ZodNumberFormat,ZodObject:()=>ZodObject,ZodOptional:()=>ZodOptional,ZodPipe:()=>ZodPipe,ZodPrefault:()=>ZodPrefault,ZodPreprocess:()=>ZodPreprocess,ZodPromise:()=>ZodPromise,ZodReadonly:()=>ZodReadonly,ZodRecord:()=>ZodRecord,ZodSet:()=>ZodSet,ZodString:()=>ZodString,ZodStringFormat:()=>ZodStringFormat,ZodSuccess:()=>ZodSuccess,ZodSymbol:()=>ZodSymbol,ZodTemplateLiteral:()=>ZodTemplateLiteral,ZodTransform:()=>ZodTransform,ZodTuple:()=>ZodTuple,ZodType:()=>ZodType,ZodULID:()=>ZodULID,ZodURL:()=>ZodURL,ZodUUID:()=>ZodUUID,ZodUndefined:()=>ZodUndefined,ZodUnion:()=>ZodUnion,ZodUnknown:()=>ZodUnknown,ZodVoid:()=>ZodVoid,ZodXID:()=>ZodXID,ZodXor:()=>ZodXor,_ZodString:()=>_ZodString,_default:()=>_default2,_function:()=>_function,any:()=>any,array:()=>array,base64:()=>base642,base64url:()=>base64url2,bigint:()=>bigint2,boolean:()=>boolean2,catch:()=>_catch2,check:()=>check,cidrv4:()=>cidrv42,cidrv6:()=>cidrv62,codec:()=>codec,creditCard:()=>creditCard2,cuid:()=>cuid3,cuid2:()=>cuid22,currencyCode:()=>currencyCode2,custom:()=>custom,date:()=>date2,describe:()=>describe2,discriminatedUnion:()=>discriminatedUnion,e164:()=>e1642,email:()=>email2,emoji:()=>emoji2,enum:()=>_enum2,exactOptional:()=>exactOptional,file:()=>file,float32:()=>float32,float64:()=>float64,function:()=>_function,guid:()=>guid2,hash:()=>hash,hex:()=>hex2,hostname:()=>hostname2,httpUrl:()=>httpUrl,iban:()=>iban2,instanceof:()=>_instanceof,int:()=>int,int32:()=>int32,int64:()=>int64,intersection:()=>intersection,invertCodec:()=>invertCodec,ipv4:()=>ipv42,ipv6:()=>ipv62,json:()=>json,jwt:()=>jwt,keyof:()=>keyof,ksuid:()=>ksuid2,lazy:()=>lazy,literal:()=>literal,looseObject:()=>looseObject,looseRecord:()=>looseRecord,mac:()=>mac2,map:()=>map,meta:()=>meta2,nan:()=>nan,nanoid:()=>nanoid2,nativeEnum:()=>nativeEnum,never:()=>never,nonoptional:()=>nonoptional,null:()=>_null3,nullable:()=>nullable,nullish:()=>nullish2,number:()=>number2,object:()=>object,optional:()=>optional,partialRecord:()=>partialRecord,pipe:()=>pipe,prefault:()=>prefault,preprocess:()=>preprocess,promise:()=>promise,readonly:()=>readonly,record:()=>record,refine:()=>refine,set:()=>set,strictObject:()=>strictObject,string:()=>string2,stringFormat:()=>stringFormat,stringbool:()=>stringbool,success:()=>success,superRefine:()=>superRefine,symbol:()=>symbol,templateLiteral:()=>templateLiteral,transform:()=>transform,tuple:()=>tuple,uint32:()=>uint32,uint64:()=>uint64,ulid:()=>ulid2,undefined:()=>_undefined3,union:()=>union,unknown:()=>unknown,url:()=>url,uuid:()=>uuid2,uuidv4:()=>uuidv4,uuidv6:()=>uuidv6,uuidv7:()=>uuidv7,void:()=>_void2,xid:()=>xid2,xor:()=>xor});var checks_exports2={};__export(checks_exports2,{endsWith:()=>_endsWith,gt:()=>_gt,gte:()=>_gte,includes:()=>_includes,length:()=>_length,lowercase:()=>_lowercase,lt:()=>_lt,lte:()=>_lte,maxLength:()=>_maxLength,maxSize:()=>_maxSize,mime:()=>_mime,minLength:()=>_minLength,minSize:()=>_minSize,multipleOf:()=>_multipleOf,negative:()=>_negative,nonnegative:()=>_nonnegative,nonpositive:()=>_nonpositive,normalize:()=>_normalize,overwrite:()=>_overwrite,positive:()=>_positive,properties:()=>_properties,property:()=>_property,regex:()=>_regex,size:()=>_size,slugify:()=>_slugify,startsWith:()=>_startsWith,toLowerCase:()=>_toLowerCase,toUpperCase:()=>_toUpperCase,trim:()=>_trim,uppercase:()=>_uppercase});var _installedErrorProtos=new WeakSet([Object.prototype,Error.prototype]);function _lazyMethod(proto,key,make){Object.defineProperty(proto,key,{configurable:!0,enumerable:!1,get(){let value2=make(this);return Object.defineProperty(this,key,{value:value2,configurable:!0,writable:!0}),value2},set(value2){Object.defineProperty(this,key,{value:value2,configurable:!0,writable:!0})}})}var initializer2=(inst,issues)=>{$ZodError.init(inst,issues),inst.name="ZodError";let proto=Object.getPrototypeOf(inst);_installedErrorProtos.has(proto)||(_installedErrorProtos.add(proto),_lazyMethod(proto,"format",self=>mapper=>formatError(self,mapper)),_lazyMethod(proto,"flatten",self=>mapper=>flattenError(self,mapper)),_lazyMethod(proto,"addIssue",self=>issue2=>{self.issues.push(issue2),self.message=JSON.stringify(self.issues,jsonStringifyReplacer,2)}),_lazyMethod(proto,"addIssues",self=>issues2=>{self.issues.push(...issues2),self.message=JSON.stringify(self.issues,jsonStringifyReplacer,2)}),Object.defineProperty(proto,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},ZodError=$constructor("ZodError",initializer2),ZodRealError=$constructor("ZodError",initializer2,void 0,{Parent:Error});var parse2=_parse(ZodRealError),parseAsync2=_parseAsync(ZodRealError),safeParse2=_safeParse(ZodRealError),safeParseAsync2=_safeParseAsync(ZodRealError),encode2=_encode(ZodRealError),decode2=_decode(ZodRealError),encodeAsync2=_encodeAsync(ZodRealError),decodeAsync2=_decodeAsync(ZodRealError),safeEncode2=_safeEncode(ZodRealError),safeDecode2=_safeDecode(ZodRealError),safeEncodeAsync2=_safeEncodeAsync(ZodRealError),safeDecodeAsync2=_safeDecodeAsync(ZodRealError);function _ensureDefaultLocale(){globalConfig.localeError||config(en_default())}function _ensureDefaultMemoizer(){globalConfig.memoizer||config({memoizer:memoizer()})}var ZodType=$constructor("ZodType",(inst,def)=>(_ensureDefaultLocale(),$ZodType.init(inst,def),inst.def=def,inst.type=def.type,inst),{check(...chks){let def=this.def;return this.clone(util_exports.mergeDefs(def,{checks:[...def.checks??[],...chks.map(ch2=>typeof ch2=="function"?{_zod:{check:ch2,def:{check:"custom"},onattach:[]}}:ch2)]}),{parent:!0})},with(...chks){return this.check(...chks)},clone(def,params){return clone(this,def,params)},brand(){return this},register(reg,meta3){return reg.add(this,meta3),this},refine(check2,params){return this.check(refine(check2,params))},superRefine(refinement,params){return this.check(superRefine(refinement,params))},overwrite(fn){return this.check(_overwrite(fn))},optional(){return optional(this)},exactOptional(){return exactOptional(this)},nullable(){return nullable(this)},nullish(){return optional(nullable(this))},nonoptional(params){return nonoptional(this,params)},array(){return array(this)},or(arg){return union([this,arg])},and(arg){return intersection(this,arg)},transform(tx){return pipe(this,transform(tx))},default(d){return _default2(this,d)},prefault(d){return prefault(this,d)},catch(params){return _catch2(this,params)},pipe(target){return pipe(this,target)},readonly(){return readonly(this)},describe(description){let cl=this.clone();return globalRegistry.add(cl,{description}),cl},meta(...args){if(args.length===0)return globalRegistry.get(this);let cl=this.clone();return globalRegistry.add(cl,args[0]),cl},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(fn,...args){return args.length===0?fn(this):fn(this,...args)},get"~standard"(){return util_exports.hide(this,"~standard",{...standardProps(this),jsonSchema:{input:createStandardJSONSchemaMethod(this,"input"),output:createStandardJSONSchemaMethod(this,"output")}})},set"~standard"(value2){util_exports.own(this,"~standard",value2)},parse:function _parse2(data,params){return parse2(this,data,params,{callee:_parse2})},parseAsync:async function _parseAsync2(data,params){return await parseAsync2(this,data,params,{callee:_parseAsync2})},safeParse(data,params){return safeParse2(this,data,params)},async safeParseAsync(data,params){return safeParseAsync2(this,data,params)},get spa(){return this?.safeParseAsync},set spa(value2){util_exports.own(this,"spa",value2)},validate(data,params){return validate(this,data,params)},validateAsync(data,params){return validateAsync(this,data,params)},encode:function _encode2(data,params){return encode2(this,data,params,{callee:_encode2})},decode:function _decode2(data,params){return decode2(this,data,params,{callee:_decode2})},encodeAsync:async function _encodeAsync2(data,params){return await encodeAsync2(this,data,params,{callee:_encodeAsync2})},decodeAsync:async function _decodeAsync2(data,params){return await decodeAsync2(this,data,params,{callee:_decodeAsync2})},safeEncode(data,params){return safeEncode2(this,data,params)},safeDecode(data,params){return safeDecode2(this,data,params)},async safeEncodeAsync(data,params){return safeEncodeAsync2(this,data,params)},async safeDecodeAsync(data,params){return safeDecodeAsync2(this,data,params)},toJSONSchema(params){return createToJSONSchemaMethod(this,{})(params)},get description(){return globalRegistry.get(this)?.description},get _def(){return this._zod.def}}),_ZodString=$constructor("_ZodString",(inst,def)=>{$ZodString.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>stringProcessor(inst,ctx,json2,params)},util_exports.derived({format:inst=>aggregateChecks(inst).format??null,minLength:inst=>aggregateChecks(inst).minimum??null,maxLength:inst=>aggregateChecks(inst).maximum??null},{regex(...args){return this.check(_regex(...args))},includes(...args){return this.check(_includes(...args))},startsWith(...args){return this.check(_startsWith(...args))},endsWith(...args){return this.check(_endsWith(...args))},min(...args){return this.check(_minLength(...args))},max(...args){return this.check(_maxLength(...args))},length(...args){return this.check(_length(...args))},nonempty(...args){return this.check(_minLength(1,...args))},lowercase(params){return this.check(_lowercase(params))},uppercase(params){return this.check(_uppercase(params))},trim(){return this.check(_trim())},normalize(...args){return this.check(_normalize(...args))},toLowerCase(){return this.check(_toLowerCase())},toUpperCase(){return this.check(_toUpperCase())},slugify(){return this.check(_slugify())}})),ZodString=$constructor("ZodString",(inst,def)=>{$ZodString.init(inst,def),_ZodString.init(inst,def)},{email(params){return this.check(_email(ZodEmail,params))},url(params){return this.check(_url(ZodURL,params))},jwt(params){return this.check(_jwt(ZodJWT,params))},emoji(params){return this.check(_emoji2(ZodEmoji,params))},guid(params){return this.check(_guid(ZodGUID,params))},uuid(params){return this.check(_uuid(ZodUUID,params))},uuidv4(params){return this.check(_uuidv4(ZodUUID,params))},uuidv6(params){return this.check(_uuidv6(ZodUUID,params))},uuidv7(params){return this.check(_uuidv7(ZodUUID,params))},nanoid(params){return this.check(_nanoid(ZodNanoID,params))},cuid(params){return this.check(_cuid(ZodCUID,params))},cuid2(params){return this.check(_cuid2(ZodCUID2,params))},ulid(params){return this.check(_ulid(ZodULID,params))},base64(params){return this.check(_base64(ZodBase64,params))},base64url(params){return this.check(_base64url(ZodBase64URL,params))},xid(params){return this.check(_xid(ZodXID,params))},ksuid(params){return this.check(_ksuid(ZodKSUID,params))},ipv4(params){return this.check(_ipv4(ZodIPv4,params))},ipv6(params){return this.check(_ipv6(ZodIPv6,params))},cidrv4(params){return this.check(_cidrv4(ZodCIDRv4,params))},cidrv6(params){return this.check(_cidrv6(ZodCIDRv6,params))},e164(params){return this.check(_e164(ZodE164,params))},datetime(params){return this.check(_isoDateTime(ZodISODateTime,params))},date(params){return this.check(_isoDate(ZodISODate,params))},time(params){return this.check(_isoTime(ZodISOTime,params))},duration(params){return this.check(_isoDuration(ZodISODuration,params))}});function string2(params){return _string(ZodString,params)}var ZodStringFormat=$constructor("ZodStringFormat",(inst,def)=>{$ZodStringFormat.init(inst,def),_ZodString.init(inst,def)}),ZodISODateTime=$constructor("ZodISODateTime",(inst,def)=>{$ZodISODateTime.init(inst,def),ZodStringFormat.init(inst,def)}),ZodISODate=$constructor("ZodISODate",(inst,def)=>{$ZodISODate.init(inst,def),ZodStringFormat.init(inst,def)}),ZodISOTime=$constructor("ZodISOTime",(inst,def)=>{$ZodISOTime.init(inst,def),ZodStringFormat.init(inst,def)}),ZodISODuration=$constructor("ZodISODuration",(inst,def)=>{$ZodISODuration.init(inst,def),ZodStringFormat.init(inst,def)}),ZodEmail=$constructor("ZodEmail",(inst,def)=>{$ZodEmail.init(inst,def),ZodStringFormat.init(inst,def)});function email2(params){return _email(ZodEmail,params)}var ZodGUID=$constructor("ZodGUID",(inst,def)=>{$ZodGUID.init(inst,def),ZodStringFormat.init(inst,def)});function guid2(params){return _guid(ZodGUID,params)}var ZodUUID=$constructor("ZodUUID",(inst,def)=>{$ZodUUID.init(inst,def),ZodStringFormat.init(inst,def)});function uuid2(params){return _uuid(ZodUUID,params)}function uuidv4(params){return _uuidv4(ZodUUID,params)}function uuidv6(params){return _uuidv6(ZodUUID,params)}function uuidv7(params){return _uuidv7(ZodUUID,params)}var ZodURL=$constructor("ZodURL",(inst,def)=>{$ZodURL.init(inst,def),ZodStringFormat.init(inst,def)});function url(params){return _url(ZodURL,params)}function httpUrl(params){return _url(ZodURL,{protocol:httpProtocol,hostname:domain,...util_exports.normalizeParams(params)})}var ZodEmoji=$constructor("ZodEmoji",(inst,def)=>{$ZodEmoji.init(inst,def),ZodStringFormat.init(inst,def)});function emoji2(params){return _emoji2(ZodEmoji,params)}var ZodNanoID=$constructor("ZodNanoID",(inst,def)=>{$ZodNanoID.init(inst,def),ZodStringFormat.init(inst,def)});function nanoid2(params){return _nanoid(ZodNanoID,params)}var ZodCUID=$constructor("ZodCUID",(inst,def)=>{$ZodCUID.init(inst,def),ZodStringFormat.init(inst,def)});function cuid3(params){return _cuid(ZodCUID,params)}var ZodCUID2=$constructor("ZodCUID2",(inst,def)=>{$ZodCUID2.init(inst,def),ZodStringFormat.init(inst,def)});function cuid22(params){return _cuid2(ZodCUID2,params)}var ZodULID=$constructor("ZodULID",(inst,def)=>{$ZodULID.init(inst,def),ZodStringFormat.init(inst,def)});function ulid2(params){return _ulid(ZodULID,params)}var ZodXID=$constructor("ZodXID",(inst,def)=>{$ZodXID.init(inst,def),ZodStringFormat.init(inst,def)});function xid2(params){return _xid(ZodXID,params)}var ZodKSUID=$constructor("ZodKSUID",(inst,def)=>{$ZodKSUID.init(inst,def),ZodStringFormat.init(inst,def)});function ksuid2(params){return _ksuid(ZodKSUID,params)}var ZodIPv4=$constructor("ZodIPv4",(inst,def)=>{$ZodIPv4.init(inst,def),ZodStringFormat.init(inst,def)});function ipv42(params){return _ipv4(ZodIPv4,params)}var ZodMAC=$constructor("ZodMAC",(inst,def)=>{$ZodMAC.init(inst,def),ZodStringFormat.init(inst,def)});function mac2(params){return _mac(ZodMAC,params)}var ZodIPv6=$constructor("ZodIPv6",(inst,def)=>{$ZodIPv6.init(inst,def),ZodStringFormat.init(inst,def)});function ipv62(params){return _ipv6(ZodIPv6,params)}var ZodCIDRv4=$constructor("ZodCIDRv4",(inst,def)=>{$ZodCIDRv4.init(inst,def),ZodStringFormat.init(inst,def)});function cidrv42(params){return _cidrv4(ZodCIDRv4,params)}var ZodCIDRv6=$constructor("ZodCIDRv6",(inst,def)=>{$ZodCIDRv6.init(inst,def),ZodStringFormat.init(inst,def)});function cidrv62(params){return _cidrv6(ZodCIDRv6,params)}var ZodBase64=$constructor("ZodBase64",(inst,def)=>{$ZodBase64.init(inst,def),ZodStringFormat.init(inst,def)});function base642(params){return _base64(ZodBase64,params)}var ZodBase64URL=$constructor("ZodBase64URL",(inst,def)=>{$ZodBase64URL.init(inst,def),ZodStringFormat.init(inst,def)});function base64url2(params){return _base64url(ZodBase64URL,params)}var ZodE164=$constructor("ZodE164",(inst,def)=>{$ZodE164.init(inst,def),ZodStringFormat.init(inst,def)});function e1642(params){return _e164(ZodE164,params)}var ZodCreditCard=$constructor("ZodCreditCard",(inst,def)=>{$ZodCreditCard.init(inst,def),ZodStringFormat.init(inst,def)});function creditCard2(params){return _creditCard(ZodCreditCard,params)}var ZodIBAN=$constructor("ZodIBAN",(inst,def)=>{$ZodIBAN.init(inst,def),ZodStringFormat.init(inst,def)});function iban2(params){return _iban(ZodIBAN,params)}var ZodJWT=$constructor("ZodJWT",(inst,def)=>{$ZodJWT.init(inst,def),ZodStringFormat.init(inst,def)});function jwt(params){return _jwt(ZodJWT,params)}var ZodCustomStringFormat=$constructor("ZodCustomStringFormat",(inst,def)=>{$ZodCustomStringFormat.init(inst,def),ZodStringFormat.init(inst,def)});function stringFormat(format,fnOrRegex,_params={}){return _stringFormat(ZodCustomStringFormat,format,fnOrRegex,_params)}function hostname2(_params){return _stringFormat(ZodCustomStringFormat,"hostname",hostname,_params)}function hex2(_params){return _stringFormat(ZodCustomStringFormat,"hex",hex,_params)}function currencyCode2(_params){return _stringFormat(ZodCustomStringFormat,"currency_code",currencyCode,_params)}function hash(alg,params){let enc=params?.enc??"hex",format=`${alg}_${enc}`,regex=regexes_exports[format];if(!regex)throw new Error(`Unrecognized hash format: ${format}`);return _stringFormat(ZodCustomStringFormat,format,regex,params)}var ZodNumber=$constructor("ZodNumber",(inst,def)=>{$ZodNumber.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>numberProcessor(inst,ctx,json2,params),inst.isFinite=!0},util_exports.derived({minValue:inst=>{let{minimum,exclusiveMinimum}=aggregateChecks(inst);return Math.max(minimum??Number.NEGATIVE_INFINITY,exclusiveMinimum??Number.NEGATIVE_INFINITY)},maxValue:inst=>{let{maximum,exclusiveMaximum}=aggregateChecks(inst);return Math.min(maximum??Number.POSITIVE_INFINITY,exclusiveMaximum??Number.POSITIVE_INFINITY)},isInt:inst=>{let{isInt,multipleOf}=aggregateChecks(inst);return!!isInt||!!multipleOf?.some(Number.isSafeInteger)},format:inst=>aggregateChecks(inst).format??null},{gt(value2,params){return this.check(_gt(value2,params))},gte(value2,params){return this.check(_gte(value2,params))},min(value2,params){return this.check(_gte(value2,params))},lt(value2,params){return this.check(_lt(value2,params))},lte(value2,params){return this.check(_lte(value2,params))},max(value2,params){return this.check(_lte(value2,params))},int(params){return this.check(int(params))},safe(params){return this.check(int(params))},positive(params){return this.check(_gt(0,params))},nonnegative(params){return this.check(_gte(0,params))},negative(params){return this.check(_lt(0,params))},nonpositive(params){return this.check(_lte(0,params))},multipleOf(value2,params){return this.check(_multipleOf(value2,params))},step(value2,params){return this.check(_multipleOf(value2,params))},finite(){return this}}));function number2(params){return _number(ZodNumber,params)}var ZodNumberFormat=$constructor("ZodNumberFormat",(inst,def)=>{$ZodNumberFormat.init(inst,def),ZodNumber.init(inst,def)});function int(params){return _int(ZodNumberFormat,params)}function float32(params){return _float32(ZodNumberFormat,params)}function float64(params){return _float64(ZodNumberFormat,params)}function int32(params){return _int32(ZodNumberFormat,params)}function uint32(params){return _uint32(ZodNumberFormat,params)}var ZodBoolean=$constructor("ZodBoolean",(inst,def)=>{$ZodBoolean.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>booleanProcessor(inst,ctx,json2,params)});function boolean2(params){return _boolean(ZodBoolean,params)}var ZodBigInt=$constructor("ZodBigInt",(inst,def)=>{$ZodBigInt.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>bigintProcessor(inst,ctx,json2,params)},util_exports.derived({minValue:inst=>aggregateChecks(inst).minimum??null,maxValue:inst=>aggregateChecks(inst).maximum??null,format:inst=>aggregateChecks(inst).format??null},{gte(value2,params){return this.check(_gte(value2,params))},min(value2,params){return this.check(_gte(value2,params))},gt(value2,params){return this.check(_gt(value2,params))},lt(value2,params){return this.check(_lt(value2,params))},lte(value2,params){return this.check(_lte(value2,params))},max(value2,params){return this.check(_lte(value2,params))},positive(params){return this.check(_gt(BigInt(0),params))},negative(params){return this.check(_lt(BigInt(0),params))},nonpositive(params){return this.check(_lte(BigInt(0),params))},nonnegative(params){return this.check(_gte(BigInt(0),params))},multipleOf(value2,params){return this.check(_multipleOf(value2,params))}}));function bigint2(params){return _bigint(ZodBigInt,params)}var ZodBigIntFormat=$constructor("ZodBigIntFormat",(inst,def)=>{$ZodBigIntFormat.init(inst,def),ZodBigInt.init(inst,def)});function int64(params){return _int64(ZodBigIntFormat,params)}function uint64(params){return _uint64(ZodBigIntFormat,params)}var ZodSymbol=$constructor("ZodSymbol",(inst,def)=>{$ZodSymbol.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>symbolProcessor(inst,ctx,json2,params)});function symbol(params){return _symbol(ZodSymbol,params)}var ZodUndefined=$constructor("ZodUndefined",(inst,def)=>{$ZodUndefined.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>undefinedProcessor(inst,ctx,json2,params)});function _undefined3(params){return _undefined2(ZodUndefined,params)}var ZodNull=$constructor("ZodNull",(inst,def)=>{$ZodNull.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>nullProcessor(inst,ctx,json2,params)});function _null3(params){return _null2(ZodNull,params)}var ZodAny=$constructor("ZodAny",(inst,def)=>{$ZodAny.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>anyProcessor(inst,ctx,json2,params)});function any(){return _any(ZodAny)}var ZodUnknown=$constructor("ZodUnknown",(inst,def)=>{$ZodUnknown.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>unknownProcessor(inst,ctx,json2,params)});function unknown(){return _unknown(ZodUnknown)}var ZodNever=$constructor("ZodNever",(inst,def)=>{$ZodNever.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>neverProcessor(inst,ctx,json2,params)});function never(params){return _never(ZodNever,params)}var ZodVoid=$constructor("ZodVoid",(inst,def)=>{$ZodVoid.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>voidProcessor(inst,ctx,json2,params)});function _void2(params){return _void(ZodVoid,params)}var ZodDate=$constructor("ZodDate",(inst,def)=>{$ZodDate.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>dateProcessor(inst,ctx,json2,params),inst.min=(value2,params)=>inst.check(_gte(value2,params)),inst.max=(value2,params)=>inst.check(_lte(value2,params))},util_exports.derived({minDate:inst=>{let{minimum}=aggregateChecks(inst);return minimum?new Date(minimum):null},maxDate:inst=>{let{maximum}=aggregateChecks(inst);return maximum?new Date(maximum):null}},{}));function date2(params){return _date(ZodDate,params)}var ZodArray=$constructor("ZodArray",(inst,def)=>{_ensureDefaultMemoizer(),$ZodArray.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>arrayProcessor(inst,ctx,json2,params),inst.element=def.element},{min(n,params){return this.check(_minLength(n,params))},nonempty(params){return this.check(_minLength(1,params))},max(n,params){return this.check(_maxLength(n,params))},length(n,params){return this.check(_length(n,params))},unwrap(){return this.element}});function array(element,params){return _array(ZodArray,element,params)}function keyof(schema){let shape=schema._zod.def.shape;return _enum2(Object.keys(shape))}var ZodObject=$constructor("ZodObject",(inst,def)=>{_ensureDefaultMemoizer(),$ZodObjectJIT.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>objectProcessor(inst,ctx,json2,params),util_exports.installLazyProp(inst,"shape",self=>self._zod.def.shape,!1)},{keyof(){return _enum2(Object.keys(this._zod.def.shape))},catchall(catchall){return this.clone(util_exports.mergeDefs(this._zod.def,{catchall}))},passthrough(){return this.clone(util_exports.mergeDefs(this._zod.def,{catchall:unknown()}))},loose(){return this.clone(util_exports.mergeDefs(this._zod.def,{catchall:unknown()}))},strict(){return this.clone(util_exports.mergeDefs(this._zod.def,{catchall:never()}))},strip(){return this.clone(util_exports.mergeDefs(this._zod.def,{catchall:void 0}))},extend(incoming){return util_exports.extend(this,incoming)},safeExtend(incoming){return util_exports.safeExtend(this,incoming)},merge(other){return util_exports.merge(this,other)},pick(mask){return util_exports.pick(this,mask)},omit(mask){return util_exports.omit(this,mask)},partial(...args){return util_exports.partial(ZodOptional,this,args[0])},exactPartial(...args){return util_exports.partial(ZodExactOptional,this,args[0],"exactPartial")},required(...args){return util_exports.required(ZodNonOptional,this,args[0])}});function object(shape,params){let def={type:"object",shape:shape??{},...util_exports.normalizeParams(params)};return new ZodObject(def)}function strictObject(shape,params){return new ZodObject({type:"object",shape,catchall:never(),...util_exports.normalizeParams(params)})}function looseObject(shape,params){return new ZodObject({type:"object",shape,catchall:unknown(),...util_exports.normalizeParams(params)})}var ZodUnion=$constructor("ZodUnion",(inst,def)=>{$ZodUnion.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>unionProcessor(inst,ctx,json2,params),inst.options=def.options});function union(options,params){return new ZodUnion({type:"union",options,...util_exports.normalizeParams(params)})}var ZodXor=$constructor("ZodXor",(inst,def)=>{ZodUnion.init(inst,def),$ZodXor.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>unionProcessor(inst,ctx,json2,params),inst.options=def.options});function xor(options,params){return new ZodXor({type:"union",options,inclusive:!1,...util_exports.normalizeParams(params)})}var ZodDiscriminatedUnion=$constructor("ZodDiscriminatedUnion",(inst,def)=>{ZodUnion.init(inst,def),$ZodDiscriminatedUnion.init(inst,def)});function discriminatedUnion(discriminator,options,params){return new ZodDiscriminatedUnion({type:"union",options,discriminator,...util_exports.normalizeParams(params)})}var ZodIntersection=$constructor("ZodIntersection",(inst,def)=>{$ZodIntersection.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>intersectionProcessor(inst,ctx,json2,params)});function intersection(left,right){return new ZodIntersection({type:"intersection",left,right})}var ZodTuple=$constructor("ZodTuple",(inst,def)=>{_ensureDefaultMemoizer(),$ZodTuple.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>tupleProcessor(inst,ctx,json2,params)},{rest(rest){return this.clone({...this._zod.def,rest})},partial(){let def=this._zod.def;if(def.checks?.length)throw new Error(".partial() cannot be used on tuple schemas containing refinements");return this.clone({...def,items:def.items.map(item=>new ZodOptional({type:"optional",innerType:item}))})}});function tuple(items,_paramsOrRest,_params){let hasRest=_paramsOrRest instanceof $ZodType,params=hasRest?_params:_paramsOrRest,rest=hasRest?_paramsOrRest:null;return new ZodTuple({type:"tuple",items,rest,...util_exports.normalizeParams(params)})}var ZodRecord=$constructor("ZodRecord",(inst,def)=>{_ensureDefaultMemoizer(),$ZodRecord.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>recordProcessor(inst,ctx,json2,params),inst.keyType=def.keyType,inst.valueType=def.valueType});function record(keyType,valueType,params){return!valueType||!valueType._zod?new ZodRecord({type:"record",keyType:string2(),valueType:keyType,...util_exports.normalizeParams(valueType)}):new ZodRecord({type:"record",keyType,valueType,...util_exports.normalizeParams(params)})}function partialRecord(keyType,valueType,params){return new ZodRecord({type:"record",keyType,valueType,...util_exports.normalizeParams(params),partial:!0})}function looseRecord(keyType,valueType,params){return new ZodRecord({type:"record",keyType,valueType,mode:"loose",...util_exports.normalizeParams(params)})}var ZodMap=$constructor("ZodMap",(inst,def)=>{_ensureDefaultMemoizer(),$ZodMap.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>mapProcessor(inst,ctx,json2,params),inst.keyType=def.keyType,inst.valueType=def.valueType,inst.min=(...args)=>inst.check(_minSize(...args)),inst.nonempty=params=>inst.check(_minSize(1,params)),inst.max=(...args)=>inst.check(_maxSize(...args)),inst.size=(...args)=>inst.check(_size(...args))});function map(keyType,valueType,params){return new ZodMap({type:"map",keyType,valueType,...util_exports.normalizeParams(params)})}var ZodSet=$constructor("ZodSet",(inst,def)=>{_ensureDefaultMemoizer(),$ZodSet.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>setProcessor(inst,ctx,json2,params),inst.min=(...args)=>inst.check(_minSize(...args)),inst.nonempty=params=>inst.check(_minSize(1,params)),inst.max=(...args)=>inst.check(_maxSize(...args)),inst.size=(...args)=>inst.check(_size(...args))});function set(valueType,params){return new ZodSet({type:"set",valueType,...util_exports.normalizeParams(params)})}var ZodEnum=$constructor("ZodEnum",(inst,def)=>{$ZodEnum.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>enumProcessor(inst,ctx,json2,params),inst.enum=def.entries,inst.options=[...inst._zod.values];let keys=new Set(Object.keys(def.entries));inst.extract=(values2,params)=>{let newEntries={};for(let value2 of values2)if(keys.has(value2))newEntries[value2]=def.entries[value2];else throw new Error(`Key ${value2} not found in enum`);return new ZodEnum({...def,checks:[],...util_exports.normalizeParams(params),entries:newEntries})},inst.exclude=(values2,params)=>{let newEntries={...def.entries};for(let value2 of values2)if(keys.has(value2))delete newEntries[value2];else throw new Error(`Key ${value2} not found in enum`);return new ZodEnum({...def,checks:[],...util_exports.normalizeParams(params),entries:newEntries})}});function _enum2(values2,params){let entries=Array.isArray(values2)?Object.fromEntries(values2.map(v=>[v,v])):values2;return new ZodEnum({type:"enum",entries,...util_exports.normalizeParams(params)})}function nativeEnum(entries,params){return new ZodEnum({type:"enum",entries,...util_exports.normalizeParams(params)})}var ZodLiteral=$constructor("ZodLiteral",(inst,def)=>{$ZodLiteral.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>literalProcessor(inst,ctx,json2,params),inst.values=new Set(def.values),Object.defineProperty(inst,"value",{get(){if(def.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return def.values[0]}})});function literal(value2,params){return new ZodLiteral({type:"literal",values:Array.isArray(value2)?value2:[value2],...util_exports.normalizeParams(params)})}var ZodFile=$constructor("ZodFile",(inst,def)=>{$ZodFile.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>fileProcessor(inst,ctx,json2,params),inst.min=(size,params)=>inst.check(_minSize(size,params)),inst.max=(size,params)=>inst.check(_maxSize(size,params)),inst.mime=(types,params)=>inst.check(_mime(Array.isArray(types)?types:[types],params))});function file(params){return _file(ZodFile,params)}var ZodTransform=$constructor("ZodTransform",(inst,def)=>{_ensureDefaultMemoizer(),$ZodTransform.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>transformProcessor(inst,ctx,json2,params),inst._zod.parse=(payload,_ctx)=>{if(_ctx.direction==="backward")throw new $ZodEncodeError(inst.constructor.name);payload.addIssue=issue2=>{if(typeof issue2=="string")payload.issues.push(util_exports.issue(issue2,payload.value,def));else{let _issue=issue2;_issue.fatal&&(_issue.continue=!1),_issue.code??(_issue.code="custom"),"input"in _issue||(_issue.input=payload.value),_issue.inst??(_issue.inst=inst),payload.issues.push(util_exports.issue(_issue))}};let output2=def.transform(payload.value,payload);return output2 instanceof Promise?output2.then(output3=>(payload.value=output3,payload)):(payload.value=output2,payload)}});function transform(fn){return new ZodTransform({type:"transform",transform:fn})}var ZodOptional=$constructor("ZodOptional",(inst,def)=>{$ZodOptional.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>optionalProcessor(inst,ctx,json2,params),inst.unwrap=()=>inst._zod.def.innerType});function optional(innerType){return new ZodOptional({type:"optional",innerType})}var ZodExactOptional=$constructor("ZodExactOptional",(inst,def)=>{$ZodExactOptional.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>optionalProcessor(inst,ctx,json2,params),inst.unwrap=()=>inst._zod.def.innerType});function exactOptional(innerType){return new ZodExactOptional({type:"optional",innerType})}var ZodNullable=$constructor("ZodNullable",(inst,def)=>{$ZodNullable.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>nullableProcessor(inst,ctx,json2,params),inst.unwrap=()=>inst._zod.def.innerType});function nullable(innerType){return new ZodNullable({type:"nullable",innerType})}function nullish2(innerType){return optional(nullable(innerType))}var ZodDefault=$constructor("ZodDefault",(inst,def)=>{$ZodDefault.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>defaultProcessor(inst,ctx,json2,params),inst.unwrap=()=>inst._zod.def.innerType,inst.removeDefault=inst.unwrap});function _default2(innerType,defaultValue){return new ZodDefault({type:"default",innerType,get defaultValue(){return typeof defaultValue=="function"?defaultValue():util_exports.shallowClone(defaultValue)}})}var ZodPrefault=$constructor("ZodPrefault",(inst,def)=>{$ZodPrefault.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>prefaultProcessor(inst,ctx,json2,params),inst.unwrap=()=>inst._zod.def.innerType});function prefault(innerType,defaultValue){return new ZodPrefault({type:"prefault",innerType,get defaultValue(){return typeof defaultValue=="function"?defaultValue():util_exports.shallowClone(defaultValue)}})}var ZodNonOptional=$constructor("ZodNonOptional",(inst,def)=>{$ZodNonOptional.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>nonoptionalProcessor(inst,ctx,json2,params),inst.unwrap=()=>inst._zod.def.innerType});function nonoptional(innerType,params){return new ZodNonOptional({type:"nonoptional",innerType,...util_exports.normalizeParams(params)})}var ZodSuccess=$constructor("ZodSuccess",(inst,def)=>{$ZodSuccess.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>successProcessor(inst,ctx,json2,params),inst.unwrap=()=>inst._zod.def.innerType});function success(innerType){return new ZodSuccess({type:"success",innerType})}var ZodCatch=$constructor("ZodCatch",(inst,def)=>{$ZodCatch.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>catchProcessor(inst,ctx,json2,params),inst.unwrap=()=>inst._zod.def.innerType,inst.removeCatch=inst.unwrap});function _catch2(innerType,catchValue){return new ZodCatch({type:"catch",innerType,catchValue:typeof catchValue=="function"?catchValue:util_exports.constantCatch(catchValue)})}var ZodNaN=$constructor("ZodNaN",(inst,def)=>{$ZodNaN.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>nanProcessor(inst,ctx,json2,params)});function nan(params){return _nan(ZodNaN,params)}var ZodPipe=$constructor("ZodPipe",(inst,def)=>{$ZodPipe.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>pipeProcessor(inst,ctx,json2,params),inst.in=def.in,inst.out=def.out});function pipe(in_,out){return new ZodPipe({type:"pipe",in:in_,out})}var ZodCodec=$constructor("ZodCodec",(inst,def)=>{ZodPipe.init(inst,def),$ZodCodec.init(inst,def)});function codec(in_,out,params){return new ZodCodec({type:"pipe",in:in_,out,transform:params.decode,reverseTransform:params.encode})}function invertCodec(codec2){let def=codec2._zod.def;return new ZodCodec({type:"pipe",in:def.out,out:def.in,transform:def.reverseTransform,reverseTransform:def.transform})}var ZodPreprocess=$constructor("ZodPreprocess",(inst,def)=>{ZodPipe.init(inst,def),$ZodPreprocess.init(inst,def)}),ZodReadonly=$constructor("ZodReadonly",(inst,def)=>{$ZodReadonly.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>readonlyProcessor(inst,ctx,json2,params),inst.unwrap=()=>inst._zod.def.innerType});function readonly(innerType){return new ZodReadonly({type:"readonly",innerType})}var ZodTemplateLiteral=$constructor("ZodTemplateLiteral",(inst,def)=>{$ZodTemplateLiteral.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>templateLiteralProcessor(inst,ctx,json2,params)});function templateLiteral(parts,params){return new ZodTemplateLiteral({type:"template_literal",parts,...util_exports.normalizeParams(params)})}var ZodLazy=$constructor("ZodLazy",(inst,def)=>{$ZodLazy.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>lazyProcessor(inst,ctx,json2,params),inst.unwrap=()=>inst._zod.def.getter()});function lazy(getter){return new ZodLazy({type:"lazy",getter})}var ZodPromise=$constructor("ZodPromise",(inst,def)=>{$ZodPromise.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>promiseProcessor(inst,ctx,json2,params),inst.unwrap=()=>inst._zod.def.innerType});function promise(innerType){return new ZodPromise({type:"promise",innerType})}var ZodFunction=$constructor("ZodFunction",(inst,def)=>{$ZodFunction.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>functionProcessor(inst,ctx,json2,params)});function _function(params){return new ZodFunction({type:"function",input:Array.isArray(params?.input)?tuple(params?.input):params?.input??array(unknown()),output:params?.output??unknown()})}var ZodCustom=$constructor("ZodCustom",(inst,def)=>{$ZodCustom.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>customProcessor(inst,ctx,json2,params)});function check(fn){let ch2=new $ZodCheck({check:"custom"});return ch2._zod.check=fn,ch2}function custom(fn,_params){return _custom(ZodCustom,fn??(()=>!0),_params)}function refine(fn,_params={}){return _refine(ZodCustom,fn,_params)}function superRefine(fn,params){return _superRefine(fn,params)}var describe2=describe,meta2=meta,ZodInstanceOf=$constructor("ZodInstanceOf",(inst,def)=>{ZodCustom.init(inst,def)},{properties(shape,params){return this.check(_properties(shape,params))}});function _instanceof(cls,params={}){let inst=new ZodInstanceOf({type:"custom",check:"custom",fn:data=>data instanceof cls,abort:!0,...util_exports.normalizeParams(params)});return inst._zod.bag.Class=cls,inst._zod.check=payload=>{payload.value instanceof cls||payload.issues.push({code:"invalid_type",expected:cls.name,input:payload.value,inst,path:[...inst._zod.def.path??[]]})},inst}var stringbool=(...args)=>_stringbool({Codec:ZodCodec,Boolean:ZodBoolean,String:ZodString},...args);function json(params){let jsonSchema=lazy(()=>union([string2(params),number2(),boolean2(),_null3(),array(jsonSchema),record(string2(),jsonSchema)]));return jsonSchema}function preprocess(fn,schema){return new ZodPreprocess({type:"pipe",in:transform(fn),out:schema})}var ZodIssueCode={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};function setErrorMap(map2){config({customError:map2})}function getErrorMap(){return config().customError}var ZodFirstPartyTypeKind;ZodFirstPartyTypeKind||(ZodFirstPartyTypeKind={});var iso_exports={};__export(iso_exports,{ZodISODate:()=>ZodISODate,ZodISODateTime:()=>ZodISODateTime,ZodISODuration:()=>ZodISODuration,ZodISOTime:()=>ZodISOTime,date:()=>date3,datetime:()=>datetime2,duration:()=>duration2,time:()=>time2});function datetime2(params){return _isoDateTime(ZodISODateTime,params)}function date3(params){return _isoDate(ZodISODate,params)}function time2(params){return _isoTime(ZodISOTime,params)}function duration2(params){return _isoDuration(ZodISODuration,params)}var z={...schemas_exports2,...checks_exports2,iso:iso_exports},RECOGNIZED_KEYS=new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"]);function detectVersion(schema,defaultTarget){let $schema=schema.$schema;return $schema==="https://json-schema.org/draft/2020-12/schema"?"draft-2020-12":$schema==="http://json-schema.org/draft-07/schema#"?"draft-7":$schema==="http://json-schema.org/draft-04/schema#"?"draft-4":defaultTarget??"draft-2020-12"}function applyMinItems(items,minItems){return items.map((item,index)=>index<minItems?item:item.optional())}function decodeJSONPointerSegment(segment){return segment.replace(/~1/g,"/").replace(/~0/g,"~")}function resolveRef(ref,ctx){if(!ref.startsWith("#"))throw new Error("External $ref is not supported, only local refs (#/...) are allowed");let path3=ref.slice(1).split("/").filter(Boolean);if(path3.length===0)return ctx.rootSchema;let defsKey=ctx.version==="draft-2020-12"?"$defs":"definitions";if(path3[0]===defsKey){let key=path3[1]===void 0?void 0:decodeJSONPointerSegment(path3[1]);if(!key||!ctx.defs[key])throw new Error(`Reference not found: ${ref}`);return ctx.defs[key]}throw new Error(`Reference not found: ${ref}`)}function checkObjectGuards(objectSchema,guards){return z.transform(value2=>value2).check(payload=>{let value2=payload.value;if(typeof value2!="object"||value2===null||Array.isArray(value2))return;let keys=Object.getOwnPropertyNames(value2);if(guards.minProperties!==void 0&&keys.length<guards.minProperties&&payload.issues.push({origin:"object",code:"too_small",minimum:guards.minProperties,inclusive:!0,message:`Too small: expected object to have >=${guards.minProperties} properties`,input:value2,inst:objectSchema,continue:!0}),guards.maxProperties!==void 0&&keys.length>guards.maxProperties&&payload.issues.push({origin:"object",code:"too_big",maximum:guards.maxProperties,inclusive:!0,message:`Too big: expected object to have <=${guards.maxProperties} properties`,input:value2,inst:objectSchema,continue:!0}),guards.keySchema)for(let key of keys){let result=guards.keySchema.safeParse(key);result.success||payload.issues.push({code:"invalid_key",origin:"record",issues:result.error.issues,input:key,path:[key],continue:!0})}}).pipe(objectSchema)}function canonicalKey(value2,seen){if(value2===null)return"z";let type=typeof value2;if(type!=="object"){if(type==="number"&&Number.isNaN(value2))return null;let raw=String(value2);return`${type[0]}${raw.length}:${raw}`}if(seen.has(value2))return null;seen.add(value2);try{if(Array.isArray(value2)){let parts2=[];for(let item of value2){let key=canonicalKey(item,seen);if(key===null)return null;parts2.push(key)}return`a${parts2.length}:[${parts2.join(",")}]`}let keys=Object.keys(value2).sort(),parts=[];for(let k of keys){let key=canonicalKey(value2[k],seen);if(key===null)return null;parts.push(`${k.length}:${k}=${key}`)}return`o${parts.length}:{${parts.join(",")}}`}finally{seen.delete(value2)}}var SCHEMA_KEYWORDS=new Set(["items","prefixItems","additionalItems","additionalProperties","contains","propertyNames","not","if","then","else","allOf","anyOf","oneOf","unevaluatedItems","unevaluatedProperties","contentSchema"]),SCHEMA_MAP_KEYWORDS=new Set(["properties","patternProperties","dependentSchemas","dependencies","$defs","definitions"]);function containsRef(value2){return typeof value2!="object"||value2===null?!1:Array.isArray(value2)?value2.some(containsRef):typeof value2.$ref=="string"?!0:Object.entries(value2).some(([key,sub])=>SCHEMA_KEYWORDS.has(key)?containsRef(sub):!SCHEMA_MAP_KEYWORDS.has(key)||typeof sub!="object"||sub===null?!1:Object.values(sub).some(containsRef))}function plural(n){return n===1?"element":"elements"}function checkArrayGuards(arraySchema,guards){return z.transform(value2=>value2).check(payload=>{let items=payload.value;if(Array.isArray(items)){if(guards.uniqueItems===!0){let firstSeen=new Map;for(let i2=0;i2<items.length;i2++){let key=canonicalKey(items[i2],new Set);if(key===null)continue;let first=firstSeen.get(key);if(first===void 0){firstSeen.set(key,i2);continue}payload.issues.push({code:"custom",message:`Array items must be unique: element at index ${i2} duplicates the one at index ${first}`,input:items,path:[i2],continue:!0})}}if(guards.containsSchema){let minContains=guards.minContains??1,ceiling=guards.maxContains!==void 0?guards.maxContains+1:Number.POSITIVE_INFINITY,matches=0;for(let item of items)if(guards.containsSchema.safeParse(item).success&&++matches>=ceiling)break;matches<minContains&&payload.issues.push({code:"custom",message:`Array must contain at least ${minContains} matching ${plural(minContains)}; found ${matches}`,input:items,continue:!0}),guards.maxContains!==void 0&&matches>guards.maxContains&&payload.issues.push({code:"custom",message:`Array must contain at most ${guards.maxContains} matching ${plural(guards.maxContains)}`,input:items,continue:!0})}}}).pipe(arraySchema)}function getTupleRest(restSchema,ctx){if(restSchema!==!1)return restSchema===void 0||restSchema===!0?z.any():convertSchema(restSchema,ctx)}var fullTime=/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;function convertBaseSchema(schema,ctx){if(schema.not!==void 0){if(typeof schema.not=="object"&&Object.keys(schema.not).length===0)return z.never();throw new Error("not is not supported in Zod (except { not: {} } for never)")}if(schema.unevaluatedItems!==void 0)throw new Error("unevaluatedItems is not supported");if(schema.unevaluatedProperties!==void 0)throw new Error("unevaluatedProperties is not supported");if(schema.if!==void 0||schema.then!==void 0||schema.else!==void 0)throw new Error("Conditional schemas (if/then/else) are not supported");if(schema.dependentSchemas!==void 0||schema.dependentRequired!==void 0)throw new Error("dependentSchemas and dependentRequired are not supported");if(schema.$ref){let refPath=schema.$ref;if(ctx.refs.has(refPath))return ctx.refs.get(refPath);if(ctx.processing.has(refPath))return z.lazy(()=>{if(!ctx.refs.has(refPath))throw new Error(`Circular reference not resolved: ${refPath}`);return ctx.refs.get(refPath)});ctx.processing.add(refPath);let resolved=resolveRef(refPath,ctx),zodSchema2=convertSchema(resolved,ctx);return ctx.refs.set(refPath,zodSchema2),ctx.processing.delete(refPath),zodSchema2}if(schema.enum!==void 0){let enumValues=schema.enum;if(ctx.version==="openapi-3.0"&&schema.nullable===!0&&enumValues.length===1&&enumValues[0]===null)return z.null();if(enumValues.length===0)return z.never();if(enumValues.length===1)return z.literal(enumValues[0]);if(enumValues.every(v=>typeof v=="string"))return z.enum(enumValues);let literalSchemas=enumValues.map(v=>z.literal(v));return literalSchemas.length<2?literalSchemas[0]:z.union([literalSchemas[0],literalSchemas[1],...literalSchemas.slice(2)])}if(schema.const!==void 0)return z.literal(schema.const);let type=schema.type;if(Array.isArray(type)){let typeSchemas=type.map(t2=>{let typeSchema={...schema,type:t2};return convertBaseSchema(typeSchema,ctx)});return typeSchemas.length===0?z.never():typeSchemas.length===1?typeSchemas[0]:z.union(typeSchemas)}if(!type)return z.any();let zodSchema;switch(type){case"string":{let stringSchema=z.string();if(schema.format){let format=schema.format;format==="email"?stringSchema=stringSchema.check(z.email()):format==="uri"||format==="uri-reference"?stringSchema=stringSchema.check(z.url()):format==="uuid"||format==="guid"?stringSchema=stringSchema.check(z.uuid()):format==="date-time"?stringSchema=stringSchema.check(z.iso.datetime({offset:!0})):format==="date"?stringSchema=stringSchema.check(z.iso.date()):format==="time"?stringSchema=stringSchema.check(z.regex(fullTime)):format==="duration"?stringSchema=stringSchema.check(z.iso.duration()):format==="hostname"?stringSchema=stringSchema.check(z.hostname()):format==="ipv4"?stringSchema=stringSchema.check(z.ipv4()):format==="ipv6"?stringSchema=stringSchema.check(z.ipv6()):format==="mac"?stringSchema=stringSchema.check(z.mac()):format==="cidr"?stringSchema=stringSchema.check(z.cidrv4()):format==="cidr-v6"?stringSchema=stringSchema.check(z.cidrv6()):format==="base64"?stringSchema=stringSchema.check(z.base64()):format==="base64url"?stringSchema=stringSchema.check(z.base64url()):format==="e164"?stringSchema=stringSchema.check(z.e164()):format==="credit_card"?stringSchema=stringSchema.check(z.creditCard()):format==="iban"?stringSchema=stringSchema.check(z.iban()):format==="jwt"?stringSchema=stringSchema.check(z.jwt()):format==="emoji"?stringSchema=stringSchema.check(z.emoji()):format==="nanoid"?stringSchema=stringSchema.check(z.nanoid()):format==="cuid"?stringSchema=stringSchema.check(z.cuid()):format==="cuid2"?stringSchema=stringSchema.check(z.cuid2()):format==="ulid"?stringSchema=stringSchema.check(z.ulid()):format==="xid"?stringSchema=stringSchema.check(z.xid()):format==="ksuid"&&(stringSchema=stringSchema.check(z.ksuid()))}typeof schema.minLength=="number"&&(stringSchema=stringSchema.min(schema.minLength)),typeof schema.maxLength=="number"&&(stringSchema=stringSchema.max(schema.maxLength)),schema.pattern&&(stringSchema=stringSchema.regex(new RegExp(schema.pattern))),zodSchema=stringSchema;break}case"number":case"integer":{let numberSchema=type==="integer"?z.number().int():z.number();typeof schema.minimum=="number"&&schema.exclusiveMinimum!==!0&&(numberSchema=numberSchema.min(schema.minimum)),typeof schema.maximum=="number"&&schema.exclusiveMaximum!==!0&&(numberSchema=numberSchema.max(schema.maximum)),typeof schema.exclusiveMinimum=="number"?numberSchema=numberSchema.gt(schema.exclusiveMinimum):schema.exclusiveMinimum===!0&&typeof schema.minimum=="number"&&(numberSchema=numberSchema.gt(schema.minimum)),typeof schema.exclusiveMaximum=="number"?numberSchema=numberSchema.lt(schema.exclusiveMaximum):schema.exclusiveMaximum===!0&&typeof schema.maximum=="number"&&(numberSchema=numberSchema.lt(schema.maximum)),typeof schema.multipleOf=="number"&&(numberSchema=numberSchema.multipleOf(schema.multipleOf)),zodSchema=numberSchema;break}case"boolean":{zodSchema=z.boolean();break}case"null":{zodSchema=z.null();break}case"object":{let shape={},properties=schema.properties||{},requiredSet=new Set(schema.required||[]),additionalSchema=typeof schema.additionalProperties=="object"?convertSchema(schema.additionalProperties,ctx):void 0;for(let[key,propSchema]of Object.entries(properties)){let propZodSchema=convertSchema(propSchema,ctx);assignProp(shape,key,requiredSet.has(key)?propZodSchema:propZodSchema.optional())}if(schema.patternProperties){let patternProps=schema.patternProperties,patternKeys=Object.keys(patternProps),looseRecords=[];for(let pattern of patternKeys){let patternValue=convertSchema(patternProps[pattern],ctx),keySchema=z.string().regex(new RegExp(pattern));looseRecords.push(z.looseRecord(keySchema,patternValue))}let schemasToIntersect=[];if(Object.keys(shape).length>0&&schemasToIntersect.push(z.object(shape).passthrough()),schemasToIntersect.push(...looseRecords),schemasToIntersect.length===0)zodSchema=z.object({}).passthrough();else if(schemasToIntersect.length===1)zodSchema=schemasToIntersect[0];else{let result=z.intersection(schemasToIntersect[0],schemasToIntersect[1]);for(let i2=2;i2<schemasToIntersect.length;i2++)result=z.intersection(result,schemasToIntersect[i2]);zodSchema=result}if(schema.additionalProperties===!1){let propertyKeys=Object.keys(shape),patterns=patternKeys.map(p=>new RegExp(p)),basePatternSchema=zodSchema;zodSchema=zodSchema.check(payload=>{if(!isPlainObject(payload.value))return;let unrecognized=[];for(let key of Object.keys(payload.value))propertyKeys.includes(key)||patterns.some(regex=>regex.test(key))||unrecognized.push(key);unrecognized.length&&payload.issues.push({code:"unrecognized_keys",keys:unrecognized,input:payload.value,inst:basePatternSchema})})}}else{let objectSchema=z.object(shape);schema.additionalProperties===!1?zodSchema=objectSchema.strict():additionalSchema?zodSchema=objectSchema.catchall(additionalSchema):zodSchema=objectSchema.passthrough()}let hasKeyGuard=schema.propertyNames!==void 0&&schema.propertyNames!==!0,minProperties=typeof schema.minProperties=="number"?schema.minProperties:void 0,maxProperties=typeof schema.maxProperties=="number"?schema.maxProperties:void 0;if(hasKeyGuard||minProperties!==void 0||maxProperties!==void 0){let keySchema;if(hasKeyGuard){let keyJSONSchema=typeof schema.propertyNames=="object"&&schema.propertyNames.type===void 0?{type:"string",...schema.propertyNames}:schema.propertyNames;keySchema=convertSchema(keyJSONSchema,ctx)}zodSchema=checkObjectGuards(zodSchema,{keySchema,minProperties,maxProperties})}break}case"array":{let prefixItems=schema.prefixItems,items=schema.items;if(prefixItems&&Array.isArray(prefixItems)){let minItems=typeof schema.minItems=="number"?schema.minItems:0,tupleItems=prefixItems.map(item=>convertSchema(item,ctx)),positionalItems=applyMinItems(tupleItems,minItems),rest=Array.isArray(items)?void 0:getTupleRest(items,ctx),tupleSchema=z.tuple(positionalItems);zodSchema=rest?tupleSchema.rest(rest):tupleSchema,typeof schema.minItems=="number"&&(zodSchema=zodSchema.check(z.minLength(schema.minItems))),typeof schema.maxItems=="number"&&(zodSchema=zodSchema.check(z.maxLength(schema.maxItems)))}else if(Array.isArray(items)){let minItems=typeof schema.minItems=="number"?schema.minItems:0,tupleItems=items.map(item=>convertSchema(item,ctx)),positionalItems=applyMinItems(tupleItems,minItems),rest=getTupleRest(schema.additionalItems,ctx),tupleSchema=z.tuple(positionalItems);zodSchema=rest?tupleSchema.rest(rest):tupleSchema,typeof schema.minItems=="number"&&(zodSchema=zodSchema.check(z.minLength(schema.minItems))),typeof schema.maxItems=="number"&&(zodSchema=zodSchema.check(z.maxLength(schema.maxItems)))}else if(items!==void 0){let element=convertSchema(items,ctx),arraySchema=z.array(element);typeof schema.minItems=="number"&&(arraySchema=arraySchema.min(schema.minItems)),typeof schema.maxItems=="number"&&(arraySchema=arraySchema.max(schema.maxItems)),zodSchema=arraySchema}else zodSchema=z.array(z.any());(schema.uniqueItems===!0||schema.contains!==void 0)&&(zodSchema=checkArrayGuards(zodSchema,{uniqueItems:schema.uniqueItems===!0,containsSchema:schema.contains!==void 0?convertSchema(schema.contains,ctx):void 0,minContains:typeof schema.minContains=="number"?schema.minContains:void 0,maxContains:typeof schema.maxContains=="number"?schema.maxContains:void 0}));break}default:throw new Error(`Unsupported type: ${type}`)}return zodSchema}function convertSchema(schema,ctx){if(typeof schema=="boolean")return schema?z.any():z.never();let baseSchema=convertBaseSchema(schema,ctx),hasExplicitType=schema.type||schema.enum!==void 0||schema.const!==void 0;if(schema.anyOf&&Array.isArray(schema.anyOf)){let options=schema.anyOf.map(s=>convertSchema(s,ctx)),anyOfUnion=z.union(options);baseSchema=hasExplicitType?z.intersection(baseSchema,anyOfUnion):anyOfUnion}if(schema.oneOf&&Array.isArray(schema.oneOf)){let options=schema.oneOf.map(s=>convertSchema(s,ctx)),oneOfUnion=z.xor(options);baseSchema=hasExplicitType?z.intersection(baseSchema,oneOfUnion):oneOfUnion}if(schema.allOf&&Array.isArray(schema.allOf))if(schema.allOf.length===0)baseSchema=hasExplicitType?baseSchema:z.any();else{let result=hasExplicitType?baseSchema:convertSchema(schema.allOf[0],ctx),startIdx=hasExplicitType?0:1;for(let i2=startIdx;i2<schema.allOf.length;i2++)result=z.intersection(result,convertSchema(schema.allOf[i2],ctx));baseSchema=result}schema.nullable===!0&&ctx.version==="openapi-3.0"&&(baseSchema=z.nullable(baseSchema)),schema.readOnly===!0&&(baseSchema=z.readonly(baseSchema)),schema.default!==void 0&&(baseSchema=baseSchema.default(schema.default));let extraMeta={},coreMetadataKeys=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let key of coreMetadataKeys)key in schema&&(extraMeta[key]=schema[key]);let contentMetadataKeys=["contentEncoding","contentMediaType","contentSchema"];for(let key of contentMetadataKeys)key in schema&&(extraMeta[key]=schema[key]);if(schema.type==="object"&&schema.$ref===void 0){schema.propertyNames!==void 0&&!containsRef(schema.propertyNames)&&(extraMeta.propertyNames=schema.propertyNames);for(let key of["minProperties","maxProperties"])schema[key]!==void 0&&(extraMeta[key]=schema[key])}if(schema.type==="array"&&schema.$ref===void 0){schema.contains!==void 0&&!containsRef(schema.contains)&&(extraMeta.contains=schema.contains);for(let key of["uniqueItems","minContains","maxContains"])schema[key]!==void 0&&(extraMeta[key]=schema[key])}for(let key of Object.keys(schema))RECOGNIZED_KEYS.has(key)||assignProp(extraMeta,key,schema[key]);return Object.keys(extraMeta).length>0&&ctx.registry.add(baseSchema,extraMeta),schema.description&&(baseSchema=baseSchema.describe(schema.description)),baseSchema}function fromJSONSchema(schema,params){if(typeof schema=="boolean")return schema?z.any():z.never();let normalized;try{normalized=JSON.parse(JSON.stringify(schema))}catch{throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas")}let version2=detectVersion(normalized,params?.defaultTarget),defs=normalized.$defs||normalized.definitions||{},ctx={version:version2,defs,refs:new Map,processing:new Set,rootSchema:normalized,registry:params?.registry??globalRegistry};return convertSchema(normalized,ctx)}var RESOLVING=Symbol("z.visit/resolving");function visit(schema,fnOrHandlers){let fn=typeof fnOrHandlers=="function"?fnOrHandlers:(node2,rewritten)=>{let h=fnOrHandlers[node2._zod.def.type];return h?h(node2,rewritten):node2},cache=new Map;function run(s){let cached2=cache.get(s);if(cached2===RESOLVING)return new $ZodLazy({type:"lazy",getter:()=>cache.get(s)});if(cached2!==void 0)return cached2;cache.set(s,RESOLVING);let inner=mapInner(s),mapped=fn(inner,inner!==s);return cache.set(s,mapped),mapped}function mapInner(s){let def=s._zod.def,kind=def.type;switch(kind){case"object":{let oldShape=def.shape,keys=Object.keys(oldShape),changed=!1,newShape={};for(let k of keys){let mapped=run(oldShape[k]);mapped!==oldShape[k]&&(changed=!0),newShape[k]=mapped}let newCatchall=def.catchall;return def.catchall&&(newCatchall=run(def.catchall),newCatchall!==def.catchall&&(changed=!0)),changed?clone(s,{...def,shape:newShape,catchall:newCatchall}):s}case"array":{let mapped=run(def.element);return mapped===def.element?s:clone(s,{...def,element:mapped})}case"tuple":{let oldItems=def.items,changed=!1,newItems=[];for(let item of oldItems){let mapped=run(item);mapped!==item&&(changed=!0),newItems.push(mapped)}let newRest=def.rest;return def.rest&&(newRest=run(def.rest),newRest!==def.rest&&(changed=!0)),changed?clone(s,{...def,items:newItems,rest:newRest}):s}case"record":case"map":{let newKey=run(def.keyType),newVal=run(def.valueType);return newKey===def.keyType&&newVal===def.valueType?s:clone(s,{...def,keyType:newKey,valueType:newVal})}case"set":{let newVal=run(def.valueType);return newVal===def.valueType?s:clone(s,{...def,valueType:newVal})}case"union":{let oldOptions=def.options,changed=!1,newOptions=[];for(let opt of oldOptions){let mapped=run(opt);mapped!==opt&&(changed=!0),newOptions.push(mapped)}return changed?clone(s,{...def,options:newOptions}):s}case"intersection":{let newLeft=run(def.left),newRight=run(def.right);return newLeft===def.left&&newRight===def.right?s:clone(s,{...def,left:newLeft,right:newRight})}case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":{let newInner=run(def.innerType);return newInner===def.innerType?s:clone(s,{...def,innerType:newInner})}case"pipe":{let newIn=run(def.in),newOut=run(def.out);return newIn===def.in&&newOut===def.out?s:clone(s,{...def,in:newIn,out:newOut})}case"function":{let newInput=run(def.input),newOutput=run(def.output);return newInput===def.input&&newOutput===def.output?s:clone(s,{...def,input:newInput,output:newOutput})}case"lazy":{let original=def.getter,{_cachedInner,...rest}=def;return clone(s,{...rest,getter:()=>run(original())})}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":return s;default:return s}}return run(schema)}function deepPartial(schema){return visit(schema,{object:s=>s.partial(),union:s=>{let def=s._zod.def;return def.discriminator===void 0?s:union(def.options)}})}function withChecks(side,checks){if(!checks?.length)return side;let def=side._zod.def;return clone(side,mergeDefs(def,{checks:[...def.checks??[],...checks]}),{parent:!0})}function outSide(def){return withChecks(def.out,def.checks)}function inSide(def){return def.in._zod.traits.has("$ZodTransform")?outSide(def):def.in}function input(schema){return visit(schema,{pipe:s=>inSide(s._zod.def),default:(s,rewritten)=>rewritten?optional(s._zod.def.innerType):s,catch:(s,rewritten)=>rewritten?s._zod.def.innerType:s})}function output(schema){return visit(schema,{pipe:s=>outSide(s._zod.def),prefault:(s,rewritten)=>rewritten?s._zod.def.innerType:s})}var coerce_exports={};__export(coerce_exports,{bigint:()=>bigint3,boolean:()=>boolean3,date:()=>date4,number:()=>number3,string:()=>string3});function string3(params){return _coercedString(ZodString,params)}function number3(params){return _coercedNumber(ZodNumber,params)}function boolean3(params){return _coercedBoolean(ZodBoolean,params)}function bigint3(params){return _coercedBigint(ZodBigInt,params)}function date4(params){return _coercedDate(ZodDate,params)}var UNSTAMPED_ARTIFACT_VERSION="0.0.0-unstamped",resolveArtifactVersion=stamped=>{let trimmed=stamped?.trim();return trimmed===void 0||trimmed===""?UNSTAMPED_ARTIFACT_VERSION:trimmed},FORGE_ARTIFACT_VERSION=resolveArtifactVersion("42.53.0"),UNSTAMPED_BUILD_DETAIL="this process carries no build stamp, so it is NOT a packaged extension \u2014 it is a dev checkout, or a build made without FORGE_ARTIFACT_VERSION set. An installed extension always reports a real version here; for one that does not, read it from the desktop app under Settings \u2192 Extensions \u2192 this extension \u2192 Details.",artifactBuildReport=(options={})=>{let version2=options.version??FORGE_ARTIFACT_VERSION,stamped=version2!==UNSTAMPED_ARTIFACT_VERSION;return{...options.module===void 0?{}:{module:options.module},version:version2,stamped,...stamped?{}:{detail:UNSTAMPED_BUILD_DETAIL}}};var CONTRACT_DESCRIPTIONS=Object.freeze({assets:{list:"Every asset visible to the caller's tenant as a bare `AssetRef` \u2014 an `assetId` and nothing else. This is the cross-domain reference list, the shape another domain holds to point at an asset. It takes no input, accepts no filter, and does not page. For the asset rows themselves \u2014 name, type, status, filters, paging \u2014 call `crud.list` instead.",snapshot:"The domain's snapshot mint \u2014 the ONE polymorphic mint the platform convention gives every snapshot-referable domain. An idempotent DERIVATION, not a Record-writing verb: `tenantRead`, writes nothing, never a composition step. Output is the platform kernel `EntitySnapshotRef` verbatim; an unsupported `type` refuses at parse through the ask's enum.\n\nA NOOP mint over the version row: `snapshot` := the asset's CURRENT version row id, the same value the display resolver honours on a ref's `version`. Asset version rows are append-only, so the value denotes frozen content by construction.\n\nRefuses the declared `NOT_FOUND` for an id that names no live asset \u2014 unknown, malformed, soft-deleted, or another tenant's.","crud.create":"Create an asset under a type whose template validates its properties.","crud.get":'Fetch one version of an asset by `assetId`. Optional `asOf` selects the version effective at that instant (half-open `effectiveFrom <= asOf < effectiveTo`); absent \u2192 the current version. No version effective then (pre-creation / post-soft-delete) \u2192 NOT_FOUND. As of an instant, `properties` are the merged values then: a dated value covering the instant replaces the version\'s (a dated "no value" removes the key), and `appliedDatedValueIds` names each one taken. Optional `knownAt` replays that read as known then: only dated values recorded by then and not retired by then; versions read as stored. A future `knownAt` is refused at parse; one without `asOf` is BAD_REQUEST (`data.code = KNOWN_AT_WITHOUT_AS_OF`).',"crud.list":"List assets with filters + offset/limit pagination. Optional `asOf` mirrors `get`'s point-in-time semantics: every returned row (and `total`) is the version effective at that instant, its `properties` merged with the dated values covering the instant and named in `appliedDatedValueIds`, property filters and conditions reading the merged values; absent \u2192 the CURRENT population, byte-identical to the pre-existing current-population call. `knownAt` replays an as-of page, its count and its filters as known then, as `get`'s does. Refused together with `hasGeometry` (BAD_REQUEST naming both) \u2014 a spatial capability read has no past-instant notion.\n\n`categoryIds` resolves through TODAY's live asset types regardless of `asOf` \u2014 the temporal window applies to asset VERSIONS, not to which types currently exist. A past `asOf` naming a category whose type has SINCE been deleted silently omits assets of that type; `assetTypeIds` names concrete governed ids directly and is unaffected.\n\nREFUSAL, declared: `TX_BUDGET_OVERRUN` (422) when the read outlived the request's transaction budget \u2014 a big selection or a busy system; a `nameContains` or `search` text reads every asset the tenant holds, and so does a property or external-ID condition alone. `data.budgetMs` is the budget. Narrow the list (an id, a type, category or lifecycle filter), or retry once the system is quieter.\n\n`conditions`: operator conditions over asset fields, properties and external IDs, combined by All or Any and ANDed with every other filter. A condition its field cannot honour is refused `INVALID_CONDITION` (400, `data.index` names the row) before anything is read. The selection-taking verbs (`count`, the bulk relationship writes) and the export do NOT take it: sending it there is refused.\n\n`search`: the search box. An asset matches when its name contains the trimmed text (any case) OR it holds a current external ID, in any system, that equals it exactly (case-sensitive, no numeric coercion, the `ext:` `is` rule); `%`, `_` and `\\` are literal in the name. ANDed with every other filter and honoured at `asOf`; `nameContains` is unchanged and name-only. Unlike `conditions`, `search` IS part of the selection, so `count`, the bulk relationship writes and the export take it and describe the set the box found. When a request carries `search`, the output's `matchedExternalIds` names, for each row on the page found by an external ID and not by its name, the binding that matched.","crud.distinctValues":"The values a condition FIELD holds on the assets a list filter selects, with the number of those assets holding each \u2014 what a person picks from instead of guessing a value. `tenantRead`: writes nothing, records nothing.\n\n`{ field, filter, prefix?, limit? }`: `field` is a condition field (`asset:status`, `prop:<code>`, `ext:<system>` / `ext:*`,...), `filter` the rest of the list filter verbatim (`asOf` included), `prefix` a case-insensitive literal prefix, `limit` 1..20 (default 20). Most common first, then by value; a response of exactly `limit` entries may have more, and there is no next page. Values `is` treats as one (case, a number and \"42\") are one entry, the most common spelling, counted over the whole group; external IDs group exactly. `count` counts assets, once each.\n\n`prefix` is REQUIRED for `asset:name` and `ext:` fields (about one value per asset): without one the read is refused `INVALID_CONDITION` (`reason: 'prefix-required'`).\n\n`values` asks instead for EXACT counts of up to 20 listed values of a `prop:` field \u2014 JSON-typed and case-exact, the `propertyFilters` equality \u2014 so one read tells a caller which values of a `oneOf` / `noneOf` list no selected asset holds (they are absent). Any other field, or a `prefix` beside it, is refused `INVALID_CONDITION` (`reason: 'values-not-allowed'`).\n\nREFUSAL, declared: `TX_BUDGET_OVERRUN` (422), exactly as `list`, when the scan outlived the budget \u2014 a property or external-ID field over a whole tenant reads every asset; narrow the filter by a type or category first.","crud.index":"A LEAN sibling of `list` \u2014 the SAME filters MINUS `asOf`, plus a REQUIRED `fields` projection. Listing 129 facilities over `list` returned 92,061 characters \u2014 every property of every asset \u2014 when the caller needed only `{name, assetId}`. `locations` below was already built as exactly this lean-sibling shape for the map read; this generalizes the pattern to an arbitrary field selection.\n\nPROJECTS AFTER THE FETCH, never a second query \u2014 the `locations` precedent: `list` runs unchanged, then each row is narrowed to the requested fields in JS. `assetId` is ALWAYS present regardless of `fields` \u2014 a caller listing assets needs an id to act on any of them, the same implicit guarantee `list`/`locations` make.\n\nThe output item type is one flat object DERIVED from `AssetSchema` \u2014 every field optional except the always-present `assetId` \u2014 not a shape that varies with the selection. A per-selection output would have no single OpenAPI rendering for a non-TS consumer to code against, and a hand-authored parallel shape could drift from `AssetSchema`.\n\nREFUSAL, declared: `TX_BUDGET_OVERRUN` (422), exactly as `list` \u2014 it IS `list` \u2014 when the read outlived the request's transaction budget. `INVALID_CONDITION`, exactly as `list`: a `conditions` row its field cannot honour is refused, naming the row, before anything is read.","crud.count":"HOW MANY assets a predicate matches, in ONE query with NO pagination \u2014 plus, optionally, a capped SAMPLE of matching ids in the same round trip. `tenantRead`: writes nothing, records nothing, stages nothing.\n\nNOT A MODE OF `list`, and the distinction is the reason it exists. `list` answers \"which slice do I show\" and carries `total` as a rider on the FIRST page only \u2014 a cursor page omits it by design \u2014 so a caller who wants only the number has to either page or reason about which page still carries it. Its first consumer did the former: the calculations authoring scope preview resolved \"resolves N assets\" by paging `list` to exhaustion at 200 ids a page over the cross-domain loopback and taking the array's LENGTH, which measured 132 s at the observed 543,391-asset estate for a number the first page had already counted.\n\n`asOf` mirrors `list`'s point-in-time semantics \u2014 the same half-open `effectiveFrom <= asOf < effectiveTo` window, applied to the same seek-free filter \u2014 so a past-instant count and a past-instant PAGE of one predicate always describe the same population. ABSENT \u2192 the CURRENT population. Refused together with `selection.hasGeometry`, exactly as `list` refuses the pair and for the same reason.\n\n`selection.categoryIds` resolves through TODAY's live asset types regardless of `asOf` \u2014 the same caveat `list` carries, inherited rather than restated, because this IS `list`'s count.\n\nThe sample is drawn from the first page of `list`'s own default order (name ascending, `assetId`-tiebroken). It is a SAMPLE, not a page: there is no cursor and no way to ask for the next one. For rows, call `list`.\n\nREFUSAL, declared: `TX_BUDGET_OVERRUN` (422), exactly as `list`, when the count outlived the request's transaction budget.","crud.exportEstimate":"Pre-flight an export WITHOUT authorizing one (`tenantRead`): resolve the selection, COUNT it, and report how WIDE the file would be. A count and a column count, never rows.\n\nSTAGES NOTHING, GRANTS NOTHING, RECORDS NOTHING \u2014 call it freely to refuse an over-cap or empty export BEFORE the confirm action. The authorization itself is `export`, which re-resolves on its own and does not trust this answer.\n\n`maxRows` on the answer is the deployment's EFFECTIVE row cap \u2014 the same injected policy the mint enforces. State THAT number in any copy or pre-guard; never bake the assembly default into a client, or a deployment override splits UI-refused from server-granted.\n\n`columnCount` is what makes WIDTH knowable up front \u2014 the file's column set is derived from the data in the selection, so two exports with different filters legitimately differ in width. It is SKIPPED (reported as 0) where `rowCount` already exceeds `maxRows`: an export that will be refused does not pay for column math.\n\n`maxColumns` is the WIDTH cap the mint enforces, echoed for the same reason `maxRows` is: width is the export's second scaling term (peak memory is tile rows \xD7 columns), so a selection can be refused for being too WIDE with a row count well under the cap. State that number in copy too.\n\nAnswers even where the deployment has no export store, because it touches no store.\n\nA count that outlives the request's transaction budget is refused with the declared `TX_BUDGET_OVERRUN` (422), as `count` is.","crud.exportStatus":"Where ONE authorized export has got to (`tenantRead`, un-recorded).\n\n `pending` \u2192 still building, with an HONEST fraction (`tilesDone` of\n `tilesTotal`) rather than a synthesized percentage, plus the\n row and column counts so a client can keep describing the\n file while it waits.\n `ready` \u2192 the GRANT: `{url, headers, expiresAt, mediaType, filename,\n rowCount}` plus `byteSize`. The URL is presigned FRESH on\n every read, so its lifetime starts when you are told about\n it rather than when the build finished.\n `failed` \u2192 why, in one sentence. A build that stopped making progress\n reports failed rather than pending forever, so a dead worker\n is legible instead of invisible.\n\nONE EXPORT, BY ID \u2014 there is deliberately no list, no paging and no filter. A read that enumerated a tenant's exports would misrepresent a transient movement artifact as a persisted published representation, so an `exportId` you no longer hold names an export you can no longer reach. Another tenant's id resolves to NOT_FOUND exactly as an id that never existed does.","crud.export":'Authorize ONE export of the assets a selection matches (`tenantWrite`, a GOVERNED verb \u2014 every mint leaves an actor-stamped Record naming the SELECTION, its ordering, its scoping and the resolved row count; the pre-flight, the build and the transfer do not).\n\nReturns a HANDLE, not the file and not yet a link: `{exportId, state, rowCount, columnCount, tilesTotal}`. Poll `crud.exportStatus` with that `exportId` for the grant. The build is ASYNCHRONOUS because it measured too slow to hold a request open \u2014 a full-estate export took ~60s unfiltered and ~200s subtree-scoped against a ~60s gateway envelope \u2014 so the mint validates, refuses, records and enqueues, and nothing more.\n\nThe response carries NO bucket, key or other storage location, and the request cannot name one \u2014 a caller-supplied `objectKey`, `bucket`, `prefix` or `tenantId` is refused at parse.\n\nThe file carries EVERYTHING the asset is known by, and the column set is derived from the DATA in the selection rather than from template declarations: the durable `assetId`, the name, resolved category and type names, lifecycle, the validity window, the location as well-known text (the column ABSENT where the deployment has no geometry \u2014 an empty cell would falsely assert "no location"), a `Parent`/`Parent ID` pair for each of the four HIERARCHY relationship types, one `prop.*` column per static property key present, and one `derived.*` column per materialized derived code present. NO column INDEX is stable across exports \u2014 read by header. A blank `derived.*` cell may mean "not rebuilt yet" rather than "no value": that table is a rebuildable projection, not governed history.\n\n`descendantOf` scopes the export to a hierarchy SUBTREE, node-inclusive and DISTINCT on asset id \u2014 the asset graph is a DAG, so one asset can be reachable from two unrelated roots. It exists on THIS input only, never on the shared bulk selection the mutating verbs take.\n\nTHE GRANT IS NOT SINGLE-USE: within its lifetime (`expiresAt`, 900s by default) it may be fetched more than once, and a transfer that begins before expiry completes even if expiry passes mid-stream. Single-use is unenforceable on a signed object-store URL. An expired grant is refused by the store; poll again for a fresh one rather than storing grant URLs. NOTHING ENUMERATES PAST EXPORTS \u2014 `exportStatus` answers about ONE id and there is no list, so a lost `exportId` is a lost export. The sealed Record is the only durable trace.\n\n`idempotencyKey` is REQUIRED, unique per (tenant, caller, key): a mint that times out may well have completed, and the SAME-KEY retry returns the one existing authorization with a FRESH usable grant. A reused key with a different selection or format is refused as `BAD_REQUEST` with `data.code = "KEY_PARAM_MISMATCH"` (another caller\'s key: `data.code = "KEY_ACTOR_MISMATCH"`); `CONFLICT` is reserved for two CONCURRENT mints racing the same key, where the loser retries into the replay.\n\nREFUSALS, declared and ordered: `SERVICE_UNAVAILABLE` with `data.code = "EXPORT_STORE_UNAVAILABLE"` (this deployment has no export store; the pre-flight still answers) \u2192 `FORMAT_UNAVAILABLE` (XLSX is a declared format this capability does not serve yet; ask for CSV) \u2192 `OVER_CAP` with `data.reason = "search-cap"` \u2192 `EMPTY_RESULT` (zero assets; nothing to stage) \u2192 `OVER_CAP` with no `data` (the selection exceeds the deployment\'s row cap; narrow it \u2014 never truncated, never queued, because a silently partial 700,000-row file is more dangerous than a refusal that names the count and the cap) \u2192 `TOO_MANY_COLUMNS` (the selection is too WIDE: the column set is derived from the data, so a selection whose assets carry thousands of distinct property keys scales the file\'s second dimension. `exportEstimate` reports both `columnCount` and `maxColumns`, so this is readable before the confirm).',"crud.locations":"The MAP's read \u2014 located assets under the same filter facets, projected to the three fields a canvas draws (`assetId`, `name`, `geometry`) and capped at a map-scale ceiling rather than the table's 200.\n\nA sibling of `list` rather than a mode of it, for two reasons: the lean projection is what makes the raised ceiling affordable (measured 248 kB vs 681 kB for the same 1,110-asset estate), and it keeps that ceiling off `crud.list`, where no caller needs a page past 200. Unpaged and unordered by construction \u2014 a map has no pager, so a page-2 pin is an invisible pin.\n\nCapability-gated like every geometry surface: a PostGIS-less deployment refuses LOUDLY (SERVICE_UNAVAILABLE, typed `data.code`), never a silent empty canvas. tenantRead in the api wiring. A read that outlives the request's transaction budget is refused with the declared `TX_BUDGET_OVERRUN` (422), as `list` is.","crud.update":"Full-state-replace update \u2014 a new version row pinning the current template. With `effectiveFrom`, the dated values of each property it changes are replaced from that date onward. A lost race is `CONFLICT` with `data.code = DATED_VALUES_RACE`: nothing was saved, retry.","crud.delete":"Soft-delete \u2014 close the current version, no successor; returns it.\n\n`SERVICE_UNAVAILABLE` with `data.reason: 'deadlock'` is TRANSIENT: a concurrent write to the same assets deadlocked with this one and nothing was written \u2014 retry the same call.","crud.deleteImpact":"Delete-impact PREFLIGHT \u2014 a READ over a bounded batch of assetIds reporting what a delete WOULD hit (hierarchy edges, storage-only edges, live external-ID bindings) + a per-asset verdict (deletable / reparentable / reparentable-too-wide / blocked / not-found). ADVISORY: no lock between preflight and delete \u2014 the delete's own guards stay the authority (TOCTOU by design). `tenantRead`, leaves no Record.","crud.deleteMany":"GOVERNED bulk soft-delete \u2014 a bounded batch of DISTINCT assetIds with per-item success/refusal reporting, ONE actor-stamped Record for the batch (`assets.deleteMany`), and one `assets.deleted` event per deleted asset. Per-item independence: a refused item never rolls back the deleted ones. REFUSE semantics only (no reparent \u2014 that stays single `crud.delete`). `tenantWrite`. Extends the audit-receipt discipline to bulk.","crud.setLocation":'Set (or clear) the asset\'s location. A GOVERNED, version-creating verb: the successor carries the new geometry (GeoJSON in/out, native PostGIS storage); every other field copies forward. `geometry: null` clears the location. Distinct from `update` \u2014 full-state `update` carries no geometry. On a PostGIS-less deployment this refuses LOUDLY (SERVICE_UNAVAILABLE, typed `data.code`), never a 500 or a silent no-op. `tenantWrite`.\n\nIT COMPARES BEFORE WRITING. A placement that would store the geometry the asset ALREADY HOLDS \u2014 including `geometry: null` over an asset with no location \u2014 creates no version, emits no `assets.location.set`, and answers with the CURRENT version. So re-sending a placement YOU JUST SENT is free, and a client may retry one without minting history.\n\n"Free" is exact equality of the stored geometry, not proximity: same coordinates in the same order, same geometry type, same SRID. A shape change at the same centre, and a different shape with the same bounding box, are both WRITES. Reading a location and sending it straight back is free too, because reads render at full stored precision \u2014 but a client that rounds, re-projects, reorders a ring, or promotes a Point to a MultiPoint is sending a different geometry and will mint a version.\n\nWHAT A CALLER CANNOT TELL, deliberately: whether this call wrote. The output is an `Asset` either way, so a caller that reports "location updated" over the response over-claims on a converged placement. Compare the returned `id` against the version you held if you need to know.\n\nA converged placement still leaves a Record, with `reads` naming the asset and `effects` EMPTY \u2014 so an automation bound to `assets.setLocation` does NOT fire for it (an empty `effects` is trigger-ineligible).\n\nNOT TRUE OF THE BULK SIBLING. `setLocationMany` writes every row it resolves, unconditionally; see its own note.',"crud.setLocationMany":`GOVERNED BULK PLACEMENT \u2014 place many assets in ONE call: the bulk sibling of \`setLocation\`, and the same operation per row (same GeoJSON surface, same PostGIS validation, its own append-only version row, its own \`assets.location.set\` event). What changes is the grain of the receipt, not the semantics.
72
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let entry of ctx.seen.entries()){let seen=entry[1];if(schema===entry[0]){extractToDef(entry);continue}if(ctx.external){let ext=ctx.external.registry.get(entry[0])?.id;if(schema!==entry[0]&&ext){extractToDef(entry);continue}}if(ctx.metadataRegistry.get(entry[0])?.id){extractToDef(entry);continue}if(seen.cycle){extractToDef(entry);continue}seen.count>1&&ctx.reused==="ref"&&extractToDef(entry)}ctx.external&&(ctx.sharedDefsExtractedFor=ctx.external)}function compactTypeUnion(schema){let options=schema.anyOf;if(!Array.isArray(options)||options.length===0||schema.type!==void 0)return;let types=[];for(let option of options){if(!option||typeof option!="object")return;compactTypeUnion(option);let keys=Object.keys(option);if(keys.length!==1||keys[0]!=="type")return;let type=option.type;for(let member of Array.isArray(type)?type:[type]){if(typeof member!="string")return;types.includes(member)||types.push(member)}}delete schema.anyOf,schema.type=types.length===1?types[0]:types}var FOLDABLE_KEYS=new Set(["type","properties","required","additionalProperties"]),UNION_KEYS=["oneOf","anyOf"];function undeclaredConstraint(member){let extra=member.additionalProperties;return extra===void 0||extra===!1||typeof extra!="object"||extra===null?null:Object.keys(extra).length?extra:null}function foldObjects(members2){let objects=[];for(let member of members2){if(typeof member!="object"||member.type!=="object")return null;for(let key in member)if(!FOLDABLE_KEYS.has(key))return null;objects.push(member)}let properties={},required2=new Set;for(let object3 of objects){for(let key in object3.properties){if(Object.prototype.hasOwnProperty.call(properties,key))continue;let parts=[];for(let other of objects){let part2=other.properties?.[key]??undeclaredConstraint(other);part2!=null&&(parts.some(seen=>JSON.stringify(seen)===JSON.stringify(part2))||parts.push(part2))}let merged=parts.length===1?parts[0]:foldObjects(parts)??{allOf:parts};assignProp(properties,key,merged)}for(let key of object3.required??[])required2.add(key)}let folded2={type:"object",properties};if(required2.size&&(folded2.required=[...required2]),objects.every(object3=>object3.additionalProperties===!1))folded2.additionalProperties=!1;else{let constraints=[];for(let object3 of objects){let constraint=undeclaredConstraint(object3);constraint&&!constraints.some(seen=>JSON.stringify(seen)===JSON.stringify(constraint))&&constraints.push(constraint)}constraints.length===1?folded2.additionalProperties=constraints[0]:constraints.length>1&&(folded2.additionalProperties={allOf:constraints})}return folded2}function foldIntersection(json2){let allOf=json2.allOf;if(!Array.isArray(allOf)||allOf.length<2)return;for(let key of FOLDABLE_KEYS)if(key in json2)return;let unions=allOf.filter(m=>UNION_KEYS.some(k=>Array.isArray(m[k]))),folded2=null;if(!unions.length)folded2=foldObjects(allOf);else{let union2=unions[0],keyword=UNION_KEYS.find(k=>Array.isArray(union2[k]));if(Object.keys(union2).length!==1)return;let rest=allOf.filter(m=>m!==union2),branches=union2[keyword].map(branch=>foldObjects([...rest,branch]));if(branches.some(b=>!b))return;folded2={[keyword]:branches}}folded2&&(delete json2.allOf,assignProps(json2,folded2))}function finalize(ctx,schema){let root=ctx.seen.get(schema);if(!root)throw new Error("Unprocessed schema. This is a bug in Zod.");let flattenRef=zodSchema=>{let seen=ctx.seen.get(zodSchema);if(seen.ref===null)return;let schema2=seen.def??seen.schema,_cached={...schema2},ref=seen.ref;if(seen.ref=null,ref){flattenRef(ref);let refSeen=ctx.seen.get(ref),refSchema=refSeen.schema;if(refSchema.$ref&&(ctx.target==="draft-07"||ctx.target==="draft-04"||ctx.target==="openapi-3.0")?(schema2.allOf=schema2.allOf??[],schema2.allOf.push(refSchema)):assignProps(schema2,refSchema),assignProps(schema2,_cached),zodSchema._zod.parent===ref)for(let key in schema2)key==="$ref"||key==="allOf"||key in _cached||delete schema2[key];if(refSchema.$ref&&refSeen.def)for(let key in schema2)key==="$ref"||key==="allOf"||key in refSeen.def&&JSON.stringify(schema2[key])===JSON.stringify(refSeen.def[key])&&delete schema2[key]}let parent=zodSchema._zod.parent;if(parent&&parent!==ref){flattenRef(parent);let parentSeen=ctx.seen.get(parent);if(parentSeen?.schema.$ref&&(schema2.$ref=parentSeen.schema.$ref,parentSeen.def))for(let key in schema2)key==="$ref"||key==="allOf"||key in parentSeen.def&&JSON.stringify(schema2[key])===JSON.stringify(parentSeen.def[key])&&delete schema2[key]}ctx.override({zodSchema,jsonSchema:schema2,path:seen.path??[]})};if(!ctx.external||ctx.sharedEmitDoneFor!==ctx.external){for(let entry of[...ctx.seen.entries()].reverse())flattenRef(entry[0]);if(ctx.target!=="openapi-3.0")for(let entry of ctx.seen.entries())compactTypeUnion(entry[1].def??entry[1].schema);for(let rewrite of ctx.deferred)rewrite();if(ctx.intersections.length){let carriers=new Map;for(let seen of ctx.seen.values())for(let json2 of[seen.schema,seen.def]){let allOf=json2?.allOf;if(!Array.isArray(allOf))continue;let existing=carriers.get(allOf);existing?existing.push(json2):carriers.set(allOf,[json2])}for(let allOf of ctx.intersections)for(let json2 of carriers.get(allOf)??[])foldIntersection(json2)}}let result={};if(ctx.target==="draft-2020-12"?result.$schema="https://json-schema.org/draft/2020-12/schema":ctx.target==="draft-07"?result.$schema="http://json-schema.org/draft-07/schema#":ctx.target==="draft-04"?result.$schema="http://json-schema.org/draft-04/schema#":ctx.target,ctx.external?.uri){let id=ctx.external.registry.get(schema)?.id;if(!id)throw new Error("Schema is missing an `id` property");result.$id=ctx.external.uri(id)}assignProps(result,root.defId?root.schema:root.def??root.schema);let rootMetaId=ctx.metadataRegistry.get(schema)?.id;rootMetaId!==void 0&&result.id===rootMetaId&&delete result.id;let defs=ctx.external?.defs??{};if(!ctx.external||ctx.sharedEmitDoneFor!==ctx.external)for(let entry of ctx.seen.entries()){let seen=entry[1];seen.def&&seen.defId&&(seen.def.id===seen.defId&&delete seen.def.id,assignProp(defs,seen.defId,seen.def))}ctx.external&&(ctx.sharedEmitDoneFor=ctx.external),ctx.external||Object.keys(defs).length>0&&(ctx.target==="draft-2020-12"?result.$defs=defs:result.definitions=defs);try{let finalized=JSON.parse(JSON.stringify(result));return Object.defineProperty(finalized,"~standard",{value:{...schema["~standard"],jsonSchema:{input:createStandardJSONSchemaMethod(schema,"input",ctx.processors),output:createStandardJSONSchemaMethod(schema,"output",ctx.processors)}},enumerable:!1,writable:!1}),finalized}catch{throw new Error("Error converting schema to JSON.")}}function isTransforming(_schema,_ctx){let ctx=_ctx??{seen:new Set};if(ctx.seen.has(_schema))return!1;ctx.seen.add(_schema);let def=_schema._zod.def;if(def.type==="transform")return!0;if(def.type==="array")return isTransforming(def.element,ctx);if(def.type==="set")return isTransforming(def.valueType,ctx);if(def.type==="lazy")return isTransforming(def.getter(),ctx);if(def.type==="promise"||def.type==="optional"||def.type==="nonoptional"||def.type==="nullable"||def.type==="readonly"||def.type==="default"||def.type==="prefault"||def.type==="catch")return isTransforming(def.innerType,ctx);if(def.type==="intersection")return isTransforming(def.left,ctx)||isTransforming(def.right,ctx);if(def.type==="record"||def.type==="map")return isTransforming(def.keyType,ctx)||isTransforming(def.valueType,ctx);if(def.type==="pipe")return _schema._zod.traits.has("$ZodCodec")?!0:isTransforming(def.in,ctx)||isTransforming(def.out,ctx);if(def.type==="object"){for(let key in def.shape)if(isTransforming(def.shape[key],ctx))return!0;return!1}if(def.type==="union"){for(let option of def.options)if(isTransforming(option,ctx))return!0;return!1}if(def.type==="tuple"){for(let item of def.items)if(isTransforming(item,ctx))return!0;return!!(def.rest&&isTransforming(def.rest,ctx))}return!1}var createToJSONSchemaMethod=(schema,processors={})=>params=>{let ctx=initializeContext({...params,processors});return processSchema(schema,ctx),extractDefs(ctx,schema),finalize(ctx,schema)},createStandardJSONSchemaMethod=(schema,io,processors={})=>params=>{let{libraryOptions,target}=params??{},ctx=initializeContext({...libraryOptions??{},target,io,processors});return processSchema(schema,ctx),extractDefs(ctx,schema),finalize(ctx,schema)};var narrowMin=(agg,key,value2)=>{(agg[key]===void 0||value2>agg[key])&&(agg[key]=value2)},narrowMax=(agg,key,value2)=>{(agg[key]===void 0||value2<agg[key])&&(agg[key]=value2)},narrowBoth=(agg,value2)=>{narrowMin(agg,"minimum",value2),narrowMax(agg,"maximum",value2)},addDivisor=(agg,value2)=>{agg.multipleOf??(agg.multipleOf=[]),agg.multipleOf.includes(value2)||agg.multipleOf.push(value2)},addPattern=(agg,pattern)=>{agg.patterns??(agg.patterns=new Set),agg.patterns.add(pattern)},intersectMime=(agg,mime)=>{agg.mime=agg.mime?agg.mime.filter(m=>mime.includes(m)):[...mime]},setFormat=(agg,format)=>{agg.format=format,format.includes("int")&&(agg.isInt=!0)},minContributor=(agg,def)=>narrowMin(agg,"minimum",def.minimum),maxContributor=(agg,def)=>narrowMax(agg,"maximum",def.maximum),formatContributor=ranges=>(agg,def)=>{setFormat(agg,def.format);let[minimum,maximum]=ranges[def.format];narrowMin(agg,"minimum",minimum),narrowMax(agg,"maximum",maximum)},contributors={greater_than:(agg,def)=>narrowMin(agg,def.inclusive?"minimum":"exclusiveMinimum",def.value),less_than:(agg,def)=>narrowMax(agg,def.inclusive?"maximum":"exclusiveMaximum",def.value),multiple_of:(agg,def)=>addDivisor(agg,def.value),number_format:formatContributor(NUMBER_FORMAT_RANGES),bigint_format:formatContributor(BIGINT_FORMAT_RANGES),min_length:minContributor,max_length:maxContributor,length_equals:(agg,def)=>narrowBoth(agg,def.length),min_size:minContributor,max_size:maxContributor,size_equals:(agg,def)=>narrowBoth(agg,def.size),string_format:(agg,def)=>{setFormat(agg,def.format),def.pattern&&addPattern(agg,def.pattern),(def.format==="base64"||def.format==="base64url")&&(agg.contentEncoding=def.format),(def.local||def.precision===-1)&&(agg.laxFormat=!0)},mime_type:(agg,def)=>intersectMime(agg,def.mime)};function aggregateChecks(schema){let agg={},def=schema._zod.def,list=schema._zod.traits.has("$ZodCheck")?[schema,...def.checks??[]]:def.checks??[];for(let ch2 of list)contributors[ch2._zod.def.check]?.(agg,ch2._zod.def);let bag=schema._zod.bag;bag.minimum!==void 0&&narrowMin(agg,"minimum",bag.minimum),bag.exclusiveMinimum!==void 0&&narrowMin(agg,"exclusiveMinimum",bag.exclusiveMinimum),bag.maximum!==void 0&&narrowMax(agg,"maximum",bag.maximum),bag.exclusiveMaximum!==void 0&&narrowMax(agg,"exclusiveMaximum",bag.exclusiveMaximum),bag.multipleOf!==void 0&&addDivisor(agg,bag.multipleOf),bag.format!==void 0&&(agg.format??(agg.format=bag.format),bag.format.includes("int")&&(agg.isInt=!0)),bag.mime&&intersectMime(agg,bag.mime);for(let pattern of bag.patterns??[])addPattern(agg,pattern);return agg}var formatMap={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},exactPatterns=new Map([[base64Charset,base64],[base64urlCharset,base64url]]),exactPattern=p=>exactPatterns.get(p)??p,stringProcessor=(schema,ctx,_json,_params)=>{let json2=_json;json2.type="string";let{minimum,maximum,format,patterns,contentEncoding,laxFormat}=aggregateChecks(schema);if(typeof minimum=="number"&&(json2.minLength=minimum),typeof maximum=="number"&&(json2.maxLength=maximum),format&&(json2.format=formatMap[format]??format,json2.format===""&&delete json2.format,(format==="time"||laxFormat)&&delete json2.format),contentEncoding&&(json2.contentEncoding=contentEncoding),patterns&&patterns.size>0){let patternList=[...patterns].map(exactPattern);patternList.length===1?json2.pattern=patternList[0].source:patternList.length>1&&(json2.allOf=[...patternList.map(regex=>({...ctx.target==="draft-07"||ctx.target==="draft-04"||ctx.target==="openapi-3.0"?{type:"string"}:{},pattern:regex.source}))])}},numberProcessor=(schema,ctx,_json,params)=>{let json2=_json,{minimum,maximum,multipleOf,exclusiveMaximum,exclusiveMinimum,isInt}=aggregateChecks(schema);json2.type=isInt?"integer":"number";let exMin=typeof exclusiveMinimum=="number"&&exclusiveMinimum>=(minimum??Number.NEGATIVE_INFINITY),exMax=typeof exclusiveMaximum=="number"&&exclusiveMaximum<=(maximum??Number.POSITIVE_INFINITY),legacy=ctx.target==="draft-04"||ctx.target==="openapi-3.0";if(exMin?legacy?(json2.minimum=exclusiveMinimum,json2.exclusiveMinimum=!0):json2.exclusiveMinimum=exclusiveMinimum:typeof minimum=="number"&&(json2.minimum=minimum),exMax?legacy?(json2.maximum=exclusiveMaximum,json2.exclusiveMaximum=!0):json2.exclusiveMaximum=exclusiveMaximum:typeof maximum=="number"&&(json2.maximum=maximum),multipleOf){let divisors=new Set;for(let divisor of multipleOf)Number.isFinite(divisor)&&divisor!==0?divisors.add(Math.abs(divisor)):handleUnrepresentable(schema,ctx,json2,params,`A multipleOf divisor of ${divisor} cannot be represented in JSON Schema`);let[first,...rest]=divisors;first!==void 0&&(json2.multipleOf=first),rest.length&&(json2.allOf=[...json2.allOf??[],...rest.map(m=>({multipleOf:m}))])}},booleanProcessor=(_schema,_ctx,json2,_params)=>{json2.type="boolean"},bigintProcessor=(schema,ctx,json2,params)=>{handleUnrepresentable(schema,ctx,json2,params,"BigInt cannot be represented in JSON Schema")},symbolProcessor=(schema,ctx,json2,params)=>{handleUnrepresentable(schema,ctx,json2,params,"Symbols cannot be represented in JSON Schema")},nullProcessor=(_schema,ctx,json2,_params)=>{ctx.target==="openapi-3.0"?(json2.type="string",json2.nullable=!0,json2.enum=[null]):json2.type="null"},undefinedProcessor=(schema,ctx,json2,params)=>{handleUnrepresentable(schema,ctx,json2,params,"Undefined cannot be represented in JSON Schema")},voidProcessor=(schema,ctx,json2,params)=>{handleUnrepresentable(schema,ctx,json2,params,"Void cannot be represented in JSON Schema")},neverProcessor=(_schema,_ctx,json2,_params)=>{json2.not={}},anyProcessor=(_schema,_ctx,_json,_params)=>{},unknownProcessor=(_schema,_ctx,_json,_params)=>{},dateProcessor=(schema,ctx,json2,params)=>{handleUnrepresentable(schema,ctx,json2,params,"Date cannot be represented in JSON Schema")},enumProcessor=(schema,_ctx,json2,_params)=>{let def=schema._zod.def,values2=getEnumValues(def.entries);if(values2.length===0){json2.not={};return}values2.every(v=>typeof v=="number")&&(json2.type="number"),values2.every(v=>typeof v=="string")&&(json2.type="string"),json2.enum=values2},literalProcessor=(schema,ctx,json2,params)=>{let def=schema._zod.def;if(def.values.length===0){json2.not={};return}let vals=[];for(let val of def.values)if(val===void 0){if(handleUnrepresentable(schema,ctx,json2,params,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof val=="bigint"){if(handleUnrepresentable(schema,ctx,json2,params,"BigInt literals cannot be represented in JSON Schema"))return;vals.push(Number(val))}else vals.push(val);if(vals.length!==0)if(vals.length===1){let val=vals[0];json2.type=val===null?"null":typeof val,ctx.target==="draft-04"||ctx.target==="openapi-3.0"?json2.enum=[val]:json2.const=val}else vals.every(v=>typeof v=="number")&&(json2.type="number"),vals.every(v=>typeof v=="string")&&(json2.type="string"),vals.every(v=>typeof v=="boolean")&&(json2.type="boolean"),vals.every(v=>v===null)&&(json2.type="null"),json2.enum=vals},nanProcessor=(schema,ctx,json2,params)=>{handleUnrepresentable(schema,ctx,json2,params,"NaN cannot be represented in JSON Schema")},templateLiteralProcessor=(schema,_ctx,json2,_params)=>{let _json=json2,pattern=schema._zod.pattern;if(!pattern)throw new Error("Pattern not found in template literal");_json.type="string",_json.pattern=pattern.source},fileProcessor=(schema,_ctx,json2,_params)=>{let _json=json2;_json.type="string",_json.format="binary",_json.contentEncoding="binary";let{minimum,maximum,mime}=aggregateChecks(schema);minimum!==void 0&&(_json.minLength=minimum),maximum!==void 0&&(_json.maxLength=maximum),mime&&(mime.length===0?_json.not={}:mime.length===1?_json.contentMediaType=mime[0]:_json.anyOf=mime.map(m=>({contentMediaType:m})))},successProcessor=(_schema,_ctx,json2,_params)=>{json2.type="boolean"},customProcessor=(schema,ctx,json2,params)=>{handleUnrepresentable(schema,ctx,json2,params,"Custom types cannot be represented in JSON Schema")},functionProcessor=(schema,ctx,json2,params)=>{handleUnrepresentable(schema,ctx,json2,params,"Function types cannot be represented in JSON Schema")},transformProcessor=(schema,ctx,json2,params)=>{handleUnrepresentable(schema,ctx,json2,params,"Transforms cannot be represented in JSON Schema")},mapProcessor=(schema,ctx,json2,params)=>{handleUnrepresentable(schema,ctx,json2,params,"Map cannot be represented in JSON Schema")},setProcessor=(schema,ctx,json2,params)=>{handleUnrepresentable(schema,ctx,json2,params,"Set cannot be represented in JSON Schema")},arrayProcessor=(schema,ctx,_json,params)=>{let json2=_json,def=schema._zod.def,{minimum,maximum}=aggregateChecks(schema);typeof minimum=="number"&&(json2.minItems=minimum),typeof maximum=="number"&&(json2.maxItems=maximum),json2.type="array",json2.items=processSchema(def.element,ctx,{...params,path:[...params.path,"items"]})};function inputOptin(schema){let def=schema._zod.def;return def.type==="pipe"&&def.in._zod.traits.has("$ZodTransform")?inputOptin(def.out):def.type==="catch"?inputOptin(def.innerType):schema._zod.optin}var objectProcessor=(schema,ctx,_json,params)=>{let json2=_json,def=schema._zod.def,shape=def.shape;if(Object.getOwnPropertySymbols(shape).length&&handleUnrepresentable(schema,ctx,json2,params,"Symbol keys cannot be represented in JSON Schema"))return;json2.type="object",json2.properties={};for(let key in shape)assignProp(json2.properties,key,processSchema(shape[key],ctx,{...params,path:[...params.path,"properties",key]}));let requiredKeys=[];for(let key of Object.keys(shape)){let field=def.shape[key];(ctx.io==="input"?inputOptin(field)===void 0:field._zod.optout===void 0)&&requiredKeys.push(key)}requiredKeys.length>0&&(json2.required=requiredKeys),def.catchall?._zod.def.type==="never"?json2.additionalProperties=!1:def.catchall?def.catchall&&(json2.additionalProperties=processSchema(def.catchall,ctx,{...params,path:[...params.path,"additionalProperties"]})):ctx.io==="output"&&(json2.additionalProperties=!1)},unionProcessor=(schema,ctx,json2,params)=>{let def=schema._zod.def,isExclusive=def.inclusive===!1,options=def.options.map((x2,i2)=>processSchema(x2,ctx,{...params,path:[...params.path,isExclusive?"oneOf":"anyOf",i2]}));isExclusive?json2.oneOf=options:json2.anyOf=options},intersectionProcessor=(schema,ctx,json2,params)=>{let def=schema._zod.def,a=processSchema(def.left,ctx,{...params,path:[...params.path,"allOf",0]}),b=processSchema(def.right,ctx,{...params,path:[...params.path,"allOf",1]}),isSimpleIntersection=val=>"allOf"in val&&Object.keys(val).length===1,allOf=[...isSimpleIntersection(a)?a.allOf:[a],...isSimpleIntersection(b)?b.allOf:[b]];json2.allOf=allOf,ctx.intersections.push(allOf)},tupleProcessor=(schema,ctx,_json,params)=>{let json2=_json,def=schema._zod.def;json2.type="array";let prefixPath=ctx.target==="draft-2020-12"?"prefixItems":"items",restPath=ctx.target==="draft-2020-12"||ctx.target==="openapi-3.0"?"items":"additionalItems",prefixItems=def.items.map((x2,i2)=>processSchema(x2,ctx,{...params,path:[...params.path,prefixPath,i2]})),rest=def.rest?processSchema(def.rest,ctx,{...params,path:[...params.path,restPath,...ctx.target==="openapi-3.0"?[def.items.length]:[]]}):null,minItems=def.items.length;for(;minItems>0;){let item=def.items[minItems-1];if(!(ctx.io==="input"?inputOptin(item)!==void 0:item._zod.optout==="optional"))break;minItems--}let maxItems=def.items.length,isClosed=!def.rest;ctx.target==="draft-2020-12"?(json2.prefixItems=prefixItems,isClosed?json2.items=!1:rest&&(json2.items=rest),minItems>0&&(json2.minItems=minItems),isClosed&&(json2.maxItems=maxItems)):ctx.target==="openapi-3.0"?(json2.items={anyOf:prefixItems},rest&&json2.items.anyOf.push(rest),minItems>0&&(json2.minItems=minItems),isClosed&&(json2.maxItems=maxItems)):(json2.items=prefixItems,isClosed?json2.additionalItems=!1:rest&&(json2.additionalItems=rest),minItems>0&&(json2.minItems=minItems),isClosed&&(json2.maxItems=maxItems));let{minimum,maximum}=aggregateChecks(schema);typeof minimum=="number"&&(json2.minItems=minimum),typeof maximum=="number"&&(json2.maxItems=maximum)};function stringifyKeyNames(bySchema,json2,visited){if(json2.$ref){if(visited.has(json2))return json2;visited.add(json2);let def=bySchema.get(json2)?.def;if(!def)return json2;let inlined=stringifyKeyNames(bySchema,def,visited);return inlined===def?json2:inlined}for(let keyword of["anyOf","oneOf"]){let branches=json2[keyword];if(!Array.isArray(branches))continue;let mapped=branches.map(branch=>stringifyKeyNames(bySchema,branch,visited));mapped.some((branch,i2)=>branch!==branches[i2])&&(json2={...json2,[keyword]:mapped})}let types=Array.isArray(json2.type)?json2.type:[json2.type],numericType=!types.includes("string")&&types.some(t2=>t2==="number"||t2==="integer"),values2=json2.enum??(json2.const!==void 0?[json2.const]:void 0);if(!numericType&&!values2?.some(v=>typeof v=="number"))return json2;let{minimum,maximum,exclusiveMinimum,exclusiveMaximum,multipleOf,format,id,...rest}=json2;return rest.enum?rest.enum=rest.enum.map(v=>typeof v=="number"?String(v):v):typeof rest.const=="number"&&(rest.const=String(rest.const)),numericType&&(rest.type="string",values2||(rest.pattern=(types.includes("number")?number:integer).source)),rest}var pendingRecords=new WeakMap;function rewriteKeyNames(ctx){let bySchema=new Map;for(let entry of ctx.seen.values())entry.def&&!bySchema.has(entry.schema)&&bySchema.set(entry.schema,entry);let rewrites=new Map;for(let record2 of pendingRecords.get(ctx)??[]){let seen=ctx.seen.get(record2),names=(seen?.def??seen?.schema)?.propertyNames;if(!names||names===!0||rewrites.has(names))continue;let rewritten=stringifyKeyNames(bySchema,names,new Set);rewritten!==names&&rewrites.set(names,rewritten)}if(rewrites.size)for(let entry of ctx.seen.values())for(let carrier of[entry.schema,entry.def]){let rewritten=carrier&&rewrites.get(carrier.propertyNames);rewritten&&(carrier.propertyNames=rewritten)}}var recordProcessor=(schema,ctx,_json,params)=>{let json2=_json,def=schema._zod.def;json2.type="object";let keyType=def.keyType,patterns=aggregateChecks(keyType).patterns;if(def.mode==="loose"&&patterns&&patterns.size>0){let valueSchema=processSchema(def.valueType,ctx,{...params,path:[...params.path,"patternProperties","*"]});json2.patternProperties={};for(let pattern of patterns)assignProp(json2.patternProperties,exactPattern(pattern).source,valueSchema)}else{if(ctx.target==="draft-07"||ctx.target==="draft-2020-12"){json2.propertyNames=processSchema(def.keyType,ctx,{...params,path:[...params.path,"propertyNames"]});let pending2=pendingRecords.get(ctx);pending2||(pending2=[],pendingRecords.set(ctx,pending2),ctx.deferred.push(()=>rewriteKeyNames(ctx))),pending2.push(schema)}json2.additionalProperties=processSchema(def.valueType,ctx,{...params,path:[...params.path,"additionalProperties"]})}let keyValues=keyType._zod.values,omittableOnInput=ctx.io==="input"&&inputOptin(def.valueType)!==void 0;if(keyValues&&!def.partial&&!omittableOnInput){let validKeyValues=[...keyValues].filter(v=>typeof v=="string"||typeof v=="number");validKeyValues.length>0&&(json2.required=validKeyValues.map(String))}},nullableProcessor=(schema,ctx,json2,params)=>{let def=schema._zod.def,inner=processSchema(def.innerType,ctx,params),seen=ctx.seen.get(schema);ctx.target==="openapi-3.0"?(seen.ref=def.innerType,json2.nullable=!0):json2.anyOf=[inner,{type:"null"}]},nonoptionalProcessor=(schema,ctx,_json,params)=>{let def=schema._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType},UNREPRESENTABLE_DEFAULT=Symbol();function serializeDefaultValue(value2,schema,ctx,json2,params){let unrepresentable=!1,serialized=JSON.stringify(value2,(_,val)=>typeof val!="bigint"?val:(unrepresentable=!0,null));return unrepresentable?(handleUnrepresentable(schema,ctx,json2,params,"BigInt defaults cannot be represented in JSON Schema"),UNREPRESENTABLE_DEFAULT):JSON.parse(serialized)}var defaultProcessor=(schema,ctx,json2,params)=>{let def=schema._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType;let value2=serializeDefaultValue(def.defaultValue,schema,ctx,json2,params);value2!==UNREPRESENTABLE_DEFAULT&&(json2.default=value2)},prefaultProcessor=(schema,ctx,json2,params)=>{let def=schema._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema);if(seen.ref=def.innerType,ctx.io!=="input")return;let value2=serializeDefaultValue(def.defaultValue,schema,ctx,json2,params);value2!==UNREPRESENTABLE_DEFAULT&&(json2._prefault=value2)},catchProcessor=(schema,ctx,json2,params)=>{let def=schema._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType;let catchValue;try{catchValue=def.catchValue(void 0)}catch{handleUnrepresentable(schema,ctx,json2,params,"Dynamic catch values are not supported in JSON Schema");return}json2.default=catchValue},pipeProcessor=(schema,ctx,_json,params)=>{let def=schema._zod.def,inIsTransform=def.in._zod.traits.has("$ZodTransform"),innerType=ctx.io==="input"?inIsTransform?def.out:def.in:def.out;processSchema(innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=innerType},readonlyProcessor=(schema,ctx,json2,params)=>{let def=schema._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType,json2.readOnly=!0},promiseProcessor=(schema,ctx,_json,params)=>{let def=schema._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType},optionalProcessor=(schema,ctx,_json,params)=>{let def=schema._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType},lazyProcessor=(schema,ctx,_json,params)=>{let innerType=schema._zod.innerType;processSchema(innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=innerType},allProcessors={string:stringProcessor,number:numberProcessor,boolean:booleanProcessor,bigint:bigintProcessor,symbol:symbolProcessor,null:nullProcessor,undefined:undefinedProcessor,void:voidProcessor,never:neverProcessor,any:anyProcessor,unknown:unknownProcessor,date:dateProcessor,enum:enumProcessor,literal:literalProcessor,nan:nanProcessor,template_literal:templateLiteralProcessor,file:fileProcessor,success:successProcessor,custom:customProcessor,function:functionProcessor,transform:transformProcessor,map:mapProcessor,set:setProcessor,array:arrayProcessor,object:objectProcessor,union:unionProcessor,intersection:intersectionProcessor,tuple:tupleProcessor,record:recordProcessor,nullable:nullableProcessor,nonoptional:nonoptionalProcessor,default:defaultProcessor,prefault:prefaultProcessor,catch:catchProcessor,pipe:pipeProcessor,readonly:readonlyProcessor,promise:promiseProcessor,optional:optionalProcessor,lazy:lazyProcessor};function toJSONSchema(input2,params){if("_idmap"in input2){let registry2=input2,ctx2=initializeContext({...params,processors:allProcessors}),defs={};for(let entry of registry2._idmap.entries()){let[_,schema]=entry;processSchema(schema,ctx2)}let schemas={},external={registry:registry2,uri:params?.uri,defs};ctx2.external=external;for(let entry of registry2._idmap.entries()){let[key,schema]=entry;extractDefs(ctx2,schema),assignProp(schemas,key,finalize(ctx2,schema))}if(Object.keys(defs).length>0){let defsSegment=ctx2.target==="draft-2020-12"?"$defs":"definitions";schemas.__shared={[defsSegment]:defs}}return{schemas}}let ctx=initializeContext({...params,processors:allProcessors});return processSchema(input2,ctx),extractDefs(ctx,input2),finalize(ctx,input2)}var JSONSchemaGenerator=class{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter(value2){this.ctx.counter=value2}get seen(){return this.ctx.seen}constructor(params){let normalizedTarget=params?.target??"draft-2020-12";normalizedTarget==="draft-4"&&(normalizedTarget="draft-04"),normalizedTarget==="draft-7"&&(normalizedTarget="draft-07"),this.ctx=initializeContext({processors:allProcessors,target:normalizedTarget,...params?.metadata&&{metadata:params.metadata},...params?.unrepresentable&&{unrepresentable:params.unrepresentable},...params?.override&&{override:params.override},...params?.io&&{io:params.io}})}process(schema,_params={path:[],schemaPath:[]}){return processSchema(schema,this.ctx,_params)}emit(schema,_params){_params&&(_params.cycles&&(this.ctx.cycles=_params.cycles),_params.reused&&(this.ctx.reused=_params.reused),_params.external&&(this.ctx.external=_params.external)),this.ctx.sharedDefsExtractedFor=void 0,this.ctx.sharedEmitDoneFor=void 0,extractDefs(this.ctx,schema);let result=finalize(this.ctx,schema),{"~standard":_,...plainResult}=result;return plainResult}};var json_schema_exports={};var schemas_exports2={};__export(schemas_exports2,{ZodAny:()=>ZodAny,ZodArray:()=>ZodArray,ZodBase64:()=>ZodBase64,ZodBase64URL:()=>ZodBase64URL,ZodBigInt:()=>ZodBigInt,ZodBigIntFormat:()=>ZodBigIntFormat,ZodBoolean:()=>ZodBoolean,ZodCIDRv4:()=>ZodCIDRv4,ZodCIDRv6:()=>ZodCIDRv6,ZodCUID:()=>ZodCUID,ZodCUID2:()=>ZodCUID2,ZodCatch:()=>ZodCatch,ZodCodec:()=>ZodCodec,ZodCreditCard:()=>ZodCreditCard,ZodCustom:()=>ZodCustom,ZodCustomStringFormat:()=>ZodCustomStringFormat,ZodDate:()=>ZodDate,ZodDefault:()=>ZodDefault,ZodDiscriminatedUnion:()=>ZodDiscriminatedUnion,ZodE164:()=>ZodE164,ZodEmail:()=>ZodEmail,ZodEmoji:()=>ZodEmoji,ZodEnum:()=>ZodEnum,ZodExactOptional:()=>ZodExactOptional,ZodFile:()=>ZodFile,ZodFunction:()=>ZodFunction,ZodGUID:()=>ZodGUID,ZodIBAN:()=>ZodIBAN,ZodIPv4:()=>ZodIPv4,ZodIPv6:()=>ZodIPv6,ZodISODate:()=>ZodISODate,ZodISODateTime:()=>ZodISODateTime,ZodISODuration:()=>ZodISODuration,ZodISOTime:()=>ZodISOTime,ZodInstanceOf:()=>ZodInstanceOf,ZodIntersection:()=>ZodIntersection,ZodJWT:()=>ZodJWT,ZodKSUID:()=>ZodKSUID,ZodLazy:()=>ZodLazy,ZodLiteral:()=>ZodLiteral,ZodMAC:()=>ZodMAC,ZodMap:()=>ZodMap,ZodNaN:()=>ZodNaN,ZodNanoID:()=>ZodNanoID,ZodNever:()=>ZodNever,ZodNonOptional:()=>ZodNonOptional,ZodNull:()=>ZodNull,ZodNullable:()=>ZodNullable,ZodNumber:()=>ZodNumber,ZodNumberFormat:()=>ZodNumberFormat,ZodObject:()=>ZodObject,ZodOptional:()=>ZodOptional,ZodPipe:()=>ZodPipe,ZodPrefault:()=>ZodPrefault,ZodPreprocess:()=>ZodPreprocess,ZodPromise:()=>ZodPromise,ZodReadonly:()=>ZodReadonly,ZodRecord:()=>ZodRecord,ZodSet:()=>ZodSet,ZodString:()=>ZodString,ZodStringFormat:()=>ZodStringFormat,ZodSuccess:()=>ZodSuccess,ZodSymbol:()=>ZodSymbol,ZodTemplateLiteral:()=>ZodTemplateLiteral,ZodTransform:()=>ZodTransform,ZodTuple:()=>ZodTuple,ZodType:()=>ZodType,ZodULID:()=>ZodULID,ZodURL:()=>ZodURL,ZodUUID:()=>ZodUUID,ZodUndefined:()=>ZodUndefined,ZodUnion:()=>ZodUnion,ZodUnknown:()=>ZodUnknown,ZodVoid:()=>ZodVoid,ZodXID:()=>ZodXID,ZodXor:()=>ZodXor,_ZodString:()=>_ZodString,_default:()=>_default2,_function:()=>_function,any:()=>any,array:()=>array,base64:()=>base642,base64url:()=>base64url2,bigint:()=>bigint2,boolean:()=>boolean2,catch:()=>_catch2,check:()=>check,cidrv4:()=>cidrv42,cidrv6:()=>cidrv62,codec:()=>codec,creditCard:()=>creditCard2,cuid:()=>cuid3,cuid2:()=>cuid22,currencyCode:()=>currencyCode2,custom:()=>custom,date:()=>date2,describe:()=>describe2,discriminatedUnion:()=>discriminatedUnion,e164:()=>e1642,email:()=>email2,emoji:()=>emoji2,enum:()=>_enum2,exactOptional:()=>exactOptional,file:()=>file,float32:()=>float32,float64:()=>float64,function:()=>_function,guid:()=>guid2,hash:()=>hash,hex:()=>hex2,hostname:()=>hostname2,httpUrl:()=>httpUrl,iban:()=>iban2,instanceof:()=>_instanceof,int:()=>int,int32:()=>int32,int64:()=>int64,intersection:()=>intersection,invertCodec:()=>invertCodec,ipv4:()=>ipv42,ipv6:()=>ipv62,json:()=>json,jwt:()=>jwt,keyof:()=>keyof,ksuid:()=>ksuid2,lazy:()=>lazy,literal:()=>literal,looseObject:()=>looseObject,looseRecord:()=>looseRecord,mac:()=>mac2,map:()=>map,meta:()=>meta2,nan:()=>nan,nanoid:()=>nanoid2,nativeEnum:()=>nativeEnum,never:()=>never,nonoptional:()=>nonoptional,null:()=>_null3,nullable:()=>nullable,nullish:()=>nullish2,number:()=>number2,object:()=>object,optional:()=>optional,partialRecord:()=>partialRecord,pipe:()=>pipe,prefault:()=>prefault,preprocess:()=>preprocess,promise:()=>promise,readonly:()=>readonly,record:()=>record,refine:()=>refine,set:()=>set,strictObject:()=>strictObject,string:()=>string2,stringFormat:()=>stringFormat,stringbool:()=>stringbool,success:()=>success,superRefine:()=>superRefine,symbol:()=>symbol,templateLiteral:()=>templateLiteral,transform:()=>transform,tuple:()=>tuple,uint32:()=>uint32,uint64:()=>uint64,ulid:()=>ulid2,undefined:()=>_undefined3,union:()=>union,unknown:()=>unknown,url:()=>url,uuid:()=>uuid2,uuidv4:()=>uuidv4,uuidv6:()=>uuidv6,uuidv7:()=>uuidv7,void:()=>_void2,xid:()=>xid2,xor:()=>xor});var checks_exports2={};__export(checks_exports2,{endsWith:()=>_endsWith,gt:()=>_gt,gte:()=>_gte,includes:()=>_includes,length:()=>_length,lowercase:()=>_lowercase,lt:()=>_lt,lte:()=>_lte,maxLength:()=>_maxLength,maxSize:()=>_maxSize,mime:()=>_mime,minLength:()=>_minLength,minSize:()=>_minSize,multipleOf:()=>_multipleOf,negative:()=>_negative,nonnegative:()=>_nonnegative,nonpositive:()=>_nonpositive,normalize:()=>_normalize,overwrite:()=>_overwrite,positive:()=>_positive,properties:()=>_properties,property:()=>_property,regex:()=>_regex,size:()=>_size,slugify:()=>_slugify,startsWith:()=>_startsWith,toLowerCase:()=>_toLowerCase,toUpperCase:()=>_toUpperCase,trim:()=>_trim,uppercase:()=>_uppercase});var _installedErrorProtos=new WeakSet([Object.prototype,Error.prototype]);function _lazyMethod(proto,key,make){Object.defineProperty(proto,key,{configurable:!0,enumerable:!1,get(){let value2=make(this);return Object.defineProperty(this,key,{value:value2,configurable:!0,writable:!0}),value2},set(value2){Object.defineProperty(this,key,{value:value2,configurable:!0,writable:!0})}})}var initializer2=(inst,issues)=>{$ZodError.init(inst,issues),inst.name="ZodError";let proto=Object.getPrototypeOf(inst);_installedErrorProtos.has(proto)||(_installedErrorProtos.add(proto),_lazyMethod(proto,"format",self=>mapper=>formatError(self,mapper)),_lazyMethod(proto,"flatten",self=>mapper=>flattenError(self,mapper)),_lazyMethod(proto,"addIssue",self=>issue2=>{self.issues.push(issue2),self.message=JSON.stringify(self.issues,jsonStringifyReplacer,2)}),_lazyMethod(proto,"addIssues",self=>issues2=>{self.issues.push(...issues2),self.message=JSON.stringify(self.issues,jsonStringifyReplacer,2)}),Object.defineProperty(proto,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},ZodError=$constructor("ZodError",initializer2),ZodRealError=$constructor("ZodError",initializer2,void 0,{Parent:Error});var parse2=_parse(ZodRealError),parseAsync2=_parseAsync(ZodRealError),safeParse2=_safeParse(ZodRealError),safeParseAsync2=_safeParseAsync(ZodRealError),encode2=_encode(ZodRealError),decode2=_decode(ZodRealError),encodeAsync2=_encodeAsync(ZodRealError),decodeAsync2=_decodeAsync(ZodRealError),safeEncode2=_safeEncode(ZodRealError),safeDecode2=_safeDecode(ZodRealError),safeEncodeAsync2=_safeEncodeAsync(ZodRealError),safeDecodeAsync2=_safeDecodeAsync(ZodRealError);function _ensureDefaultLocale(){globalConfig.localeError||config(en_default())}function _ensureDefaultMemoizer(){globalConfig.memoizer||config({memoizer:memoizer()})}var ZodType=$constructor("ZodType",(inst,def)=>(_ensureDefaultLocale(),$ZodType.init(inst,def),inst.def=def,inst.type=def.type,inst),{check(...chks){let def=this.def;return this.clone(util_exports.mergeDefs(def,{checks:[...def.checks??[],...chks.map(ch2=>typeof ch2=="function"?{_zod:{check:ch2,def:{check:"custom"},onattach:[]}}:ch2)]}),{parent:!0})},with(...chks){return this.check(...chks)},clone(def,params){return clone(this,def,params)},brand(){return this},register(reg,meta3){return reg.add(this,meta3),this},refine(check2,params){return this.check(refine(check2,params))},superRefine(refinement,params){return this.check(superRefine(refinement,params))},overwrite(fn){return this.check(_overwrite(fn))},optional(){return optional(this)},exactOptional(){return exactOptional(this)},nullable(){return nullable(this)},nullish(){return optional(nullable(this))},nonoptional(params){return nonoptional(this,params)},array(){return array(this)},or(arg){return union([this,arg])},and(arg){return intersection(this,arg)},transform(tx){return pipe(this,transform(tx))},default(d){return _default2(this,d)},prefault(d){return prefault(this,d)},catch(params){return _catch2(this,params)},pipe(target){return pipe(this,target)},readonly(){return readonly(this)},describe(description){let cl=this.clone();return globalRegistry.add(cl,{description}),cl},meta(...args){if(args.length===0)return globalRegistry.get(this);let cl=this.clone();return globalRegistry.add(cl,args[0]),cl},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(fn,...args){return args.length===0?fn(this):fn(this,...args)},get"~standard"(){return util_exports.hide(this,"~standard",{...standardProps(this),jsonSchema:{input:createStandardJSONSchemaMethod(this,"input"),output:createStandardJSONSchemaMethod(this,"output")}})},set"~standard"(value2){util_exports.own(this,"~standard",value2)},parse:function _parse2(data,params){return parse2(this,data,params,{callee:_parse2})},parseAsync:async function _parseAsync2(data,params){return await parseAsync2(this,data,params,{callee:_parseAsync2})},safeParse(data,params){return safeParse2(this,data,params)},async safeParseAsync(data,params){return safeParseAsync2(this,data,params)},get spa(){return this?.safeParseAsync},set spa(value2){util_exports.own(this,"spa",value2)},validate(data,params){return validate(this,data,params)},validateAsync(data,params){return validateAsync(this,data,params)},encode:function _encode2(data,params){return encode2(this,data,params,{callee:_encode2})},decode:function _decode2(data,params){return decode2(this,data,params,{callee:_decode2})},encodeAsync:async function _encodeAsync2(data,params){return await encodeAsync2(this,data,params,{callee:_encodeAsync2})},decodeAsync:async function _decodeAsync2(data,params){return await decodeAsync2(this,data,params,{callee:_decodeAsync2})},safeEncode(data,params){return safeEncode2(this,data,params)},safeDecode(data,params){return safeDecode2(this,data,params)},async safeEncodeAsync(data,params){return safeEncodeAsync2(this,data,params)},async safeDecodeAsync(data,params){return safeDecodeAsync2(this,data,params)},toJSONSchema(params){return createToJSONSchemaMethod(this,{})(params)},get description(){return globalRegistry.get(this)?.description},get _def(){return this._zod.def}}),_ZodString=$constructor("_ZodString",(inst,def)=>{$ZodString.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>stringProcessor(inst,ctx,json2,params)},util_exports.derived({format:inst=>aggregateChecks(inst).format??null,minLength:inst=>aggregateChecks(inst).minimum??null,maxLength:inst=>aggregateChecks(inst).maximum??null},{regex(...args){return this.check(_regex(...args))},includes(...args){return this.check(_includes(...args))},startsWith(...args){return this.check(_startsWith(...args))},endsWith(...args){return this.check(_endsWith(...args))},min(...args){return this.check(_minLength(...args))},max(...args){return this.check(_maxLength(...args))},length(...args){return this.check(_length(...args))},nonempty(...args){return this.check(_minLength(1,...args))},lowercase(params){return this.check(_lowercase(params))},uppercase(params){return this.check(_uppercase(params))},trim(){return this.check(_trim())},normalize(...args){return this.check(_normalize(...args))},toLowerCase(){return this.check(_toLowerCase())},toUpperCase(){return this.check(_toUpperCase())},slugify(){return this.check(_slugify())}})),ZodString=$constructor("ZodString",(inst,def)=>{$ZodString.init(inst,def),_ZodString.init(inst,def)},{email(params){return this.check(_email(ZodEmail,params))},url(params){return this.check(_url(ZodURL,params))},jwt(params){return this.check(_jwt(ZodJWT,params))},emoji(params){return this.check(_emoji2(ZodEmoji,params))},guid(params){return this.check(_guid(ZodGUID,params))},uuid(params){return this.check(_uuid(ZodUUID,params))},uuidv4(params){return this.check(_uuidv4(ZodUUID,params))},uuidv6(params){return this.check(_uuidv6(ZodUUID,params))},uuidv7(params){return this.check(_uuidv7(ZodUUID,params))},nanoid(params){return this.check(_nanoid(ZodNanoID,params))},cuid(params){return this.check(_cuid(ZodCUID,params))},cuid2(params){return this.check(_cuid2(ZodCUID2,params))},ulid(params){return this.check(_ulid(ZodULID,params))},base64(params){return this.check(_base64(ZodBase64,params))},base64url(params){return this.check(_base64url(ZodBase64URL,params))},xid(params){return this.check(_xid(ZodXID,params))},ksuid(params){return this.check(_ksuid(ZodKSUID,params))},ipv4(params){return this.check(_ipv4(ZodIPv4,params))},ipv6(params){return this.check(_ipv6(ZodIPv6,params))},cidrv4(params){return this.check(_cidrv4(ZodCIDRv4,params))},cidrv6(params){return this.check(_cidrv6(ZodCIDRv6,params))},e164(params){return this.check(_e164(ZodE164,params))},datetime(params){return this.check(_isoDateTime(ZodISODateTime,params))},date(params){return this.check(_isoDate(ZodISODate,params))},time(params){return this.check(_isoTime(ZodISOTime,params))},duration(params){return this.check(_isoDuration(ZodISODuration,params))}});function string2(params){return _string(ZodString,params)}var ZodStringFormat=$constructor("ZodStringFormat",(inst,def)=>{$ZodStringFormat.init(inst,def),_ZodString.init(inst,def)}),ZodISODateTime=$constructor("ZodISODateTime",(inst,def)=>{$ZodISODateTime.init(inst,def),ZodStringFormat.init(inst,def)}),ZodISODate=$constructor("ZodISODate",(inst,def)=>{$ZodISODate.init(inst,def),ZodStringFormat.init(inst,def)}),ZodISOTime=$constructor("ZodISOTime",(inst,def)=>{$ZodISOTime.init(inst,def),ZodStringFormat.init(inst,def)}),ZodISODuration=$constructor("ZodISODuration",(inst,def)=>{$ZodISODuration.init(inst,def),ZodStringFormat.init(inst,def)}),ZodEmail=$constructor("ZodEmail",(inst,def)=>{$ZodEmail.init(inst,def),ZodStringFormat.init(inst,def)});function email2(params){return _email(ZodEmail,params)}var ZodGUID=$constructor("ZodGUID",(inst,def)=>{$ZodGUID.init(inst,def),ZodStringFormat.init(inst,def)});function guid2(params){return _guid(ZodGUID,params)}var ZodUUID=$constructor("ZodUUID",(inst,def)=>{$ZodUUID.init(inst,def),ZodStringFormat.init(inst,def)});function uuid2(params){return _uuid(ZodUUID,params)}function uuidv4(params){return _uuidv4(ZodUUID,params)}function uuidv6(params){return _uuidv6(ZodUUID,params)}function uuidv7(params){return _uuidv7(ZodUUID,params)}var ZodURL=$constructor("ZodURL",(inst,def)=>{$ZodURL.init(inst,def),ZodStringFormat.init(inst,def)});function url(params){return _url(ZodURL,params)}function httpUrl(params){return _url(ZodURL,{protocol:httpProtocol,hostname:domain,...util_exports.normalizeParams(params)})}var ZodEmoji=$constructor("ZodEmoji",(inst,def)=>{$ZodEmoji.init(inst,def),ZodStringFormat.init(inst,def)});function emoji2(params){return _emoji2(ZodEmoji,params)}var ZodNanoID=$constructor("ZodNanoID",(inst,def)=>{$ZodNanoID.init(inst,def),ZodStringFormat.init(inst,def)});function nanoid2(params){return _nanoid(ZodNanoID,params)}var ZodCUID=$constructor("ZodCUID",(inst,def)=>{$ZodCUID.init(inst,def),ZodStringFormat.init(inst,def)});function cuid3(params){return _cuid(ZodCUID,params)}var ZodCUID2=$constructor("ZodCUID2",(inst,def)=>{$ZodCUID2.init(inst,def),ZodStringFormat.init(inst,def)});function cuid22(params){return _cuid2(ZodCUID2,params)}var ZodULID=$constructor("ZodULID",(inst,def)=>{$ZodULID.init(inst,def),ZodStringFormat.init(inst,def)});function ulid2(params){return _ulid(ZodULID,params)}var ZodXID=$constructor("ZodXID",(inst,def)=>{$ZodXID.init(inst,def),ZodStringFormat.init(inst,def)});function xid2(params){return _xid(ZodXID,params)}var ZodKSUID=$constructor("ZodKSUID",(inst,def)=>{$ZodKSUID.init(inst,def),ZodStringFormat.init(inst,def)});function ksuid2(params){return _ksuid(ZodKSUID,params)}var ZodIPv4=$constructor("ZodIPv4",(inst,def)=>{$ZodIPv4.init(inst,def),ZodStringFormat.init(inst,def)});function ipv42(params){return _ipv4(ZodIPv4,params)}var ZodMAC=$constructor("ZodMAC",(inst,def)=>{$ZodMAC.init(inst,def),ZodStringFormat.init(inst,def)});function mac2(params){return _mac(ZodMAC,params)}var ZodIPv6=$constructor("ZodIPv6",(inst,def)=>{$ZodIPv6.init(inst,def),ZodStringFormat.init(inst,def)});function ipv62(params){return _ipv6(ZodIPv6,params)}var ZodCIDRv4=$constructor("ZodCIDRv4",(inst,def)=>{$ZodCIDRv4.init(inst,def),ZodStringFormat.init(inst,def)});function cidrv42(params){return _cidrv4(ZodCIDRv4,params)}var ZodCIDRv6=$constructor("ZodCIDRv6",(inst,def)=>{$ZodCIDRv6.init(inst,def),ZodStringFormat.init(inst,def)});function cidrv62(params){return _cidrv6(ZodCIDRv6,params)}var ZodBase64=$constructor("ZodBase64",(inst,def)=>{$ZodBase64.init(inst,def),ZodStringFormat.init(inst,def)});function base642(params){return _base64(ZodBase64,params)}var ZodBase64URL=$constructor("ZodBase64URL",(inst,def)=>{$ZodBase64URL.init(inst,def),ZodStringFormat.init(inst,def)});function base64url2(params){return _base64url(ZodBase64URL,params)}var ZodE164=$constructor("ZodE164",(inst,def)=>{$ZodE164.init(inst,def),ZodStringFormat.init(inst,def)});function e1642(params){return _e164(ZodE164,params)}var ZodCreditCard=$constructor("ZodCreditCard",(inst,def)=>{$ZodCreditCard.init(inst,def),ZodStringFormat.init(inst,def)});function creditCard2(params){return _creditCard(ZodCreditCard,params)}var ZodIBAN=$constructor("ZodIBAN",(inst,def)=>{$ZodIBAN.init(inst,def),ZodStringFormat.init(inst,def)});function iban2(params){return _iban(ZodIBAN,params)}var ZodJWT=$constructor("ZodJWT",(inst,def)=>{$ZodJWT.init(inst,def),ZodStringFormat.init(inst,def)});function jwt(params){return _jwt(ZodJWT,params)}var ZodCustomStringFormat=$constructor("ZodCustomStringFormat",(inst,def)=>{$ZodCustomStringFormat.init(inst,def),ZodStringFormat.init(inst,def)});function stringFormat(format,fnOrRegex,_params={}){return _stringFormat(ZodCustomStringFormat,format,fnOrRegex,_params)}function hostname2(_params){return _stringFormat(ZodCustomStringFormat,"hostname",hostname,_params)}function hex2(_params){return _stringFormat(ZodCustomStringFormat,"hex",hex,_params)}function currencyCode2(_params){return _stringFormat(ZodCustomStringFormat,"currency_code",currencyCode,_params)}function hash(alg,params){let enc=params?.enc??"hex",format=`${alg}_${enc}`,regex=regexes_exports[format];if(!regex)throw new Error(`Unrecognized hash format: ${format}`);return _stringFormat(ZodCustomStringFormat,format,regex,params)}var ZodNumber=$constructor("ZodNumber",(inst,def)=>{$ZodNumber.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>numberProcessor(inst,ctx,json2,params),inst.isFinite=!0},util_exports.derived({minValue:inst=>{let{minimum,exclusiveMinimum}=aggregateChecks(inst);return Math.max(minimum??Number.NEGATIVE_INFINITY,exclusiveMinimum??Number.NEGATIVE_INFINITY)},maxValue:inst=>{let{maximum,exclusiveMaximum}=aggregateChecks(inst);return Math.min(maximum??Number.POSITIVE_INFINITY,exclusiveMaximum??Number.POSITIVE_INFINITY)},isInt:inst=>{let{isInt,multipleOf}=aggregateChecks(inst);return!!isInt||!!multipleOf?.some(Number.isSafeInteger)},format:inst=>aggregateChecks(inst).format??null},{gt(value2,params){return this.check(_gt(value2,params))},gte(value2,params){return this.check(_gte(value2,params))},min(value2,params){return this.check(_gte(value2,params))},lt(value2,params){return this.check(_lt(value2,params))},lte(value2,params){return this.check(_lte(value2,params))},max(value2,params){return this.check(_lte(value2,params))},int(params){return this.check(int(params))},safe(params){return this.check(int(params))},positive(params){return this.check(_gt(0,params))},nonnegative(params){return this.check(_gte(0,params))},negative(params){return this.check(_lt(0,params))},nonpositive(params){return this.check(_lte(0,params))},multipleOf(value2,params){return this.check(_multipleOf(value2,params))},step(value2,params){return this.check(_multipleOf(value2,params))},finite(){return this}}));function number2(params){return _number(ZodNumber,params)}var ZodNumberFormat=$constructor("ZodNumberFormat",(inst,def)=>{$ZodNumberFormat.init(inst,def),ZodNumber.init(inst,def)});function int(params){return _int(ZodNumberFormat,params)}function float32(params){return _float32(ZodNumberFormat,params)}function float64(params){return _float64(ZodNumberFormat,params)}function int32(params){return _int32(ZodNumberFormat,params)}function uint32(params){return _uint32(ZodNumberFormat,params)}var ZodBoolean=$constructor("ZodBoolean",(inst,def)=>{$ZodBoolean.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>booleanProcessor(inst,ctx,json2,params)});function boolean2(params){return _boolean(ZodBoolean,params)}var ZodBigInt=$constructor("ZodBigInt",(inst,def)=>{$ZodBigInt.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>bigintProcessor(inst,ctx,json2,params)},util_exports.derived({minValue:inst=>aggregateChecks(inst).minimum??null,maxValue:inst=>aggregateChecks(inst).maximum??null,format:inst=>aggregateChecks(inst).format??null},{gte(value2,params){return this.check(_gte(value2,params))},min(value2,params){return this.check(_gte(value2,params))},gt(value2,params){return this.check(_gt(value2,params))},lt(value2,params){return this.check(_lt(value2,params))},lte(value2,params){return this.check(_lte(value2,params))},max(value2,params){return this.check(_lte(value2,params))},positive(params){return this.check(_gt(BigInt(0),params))},negative(params){return this.check(_lt(BigInt(0),params))},nonpositive(params){return this.check(_lte(BigInt(0),params))},nonnegative(params){return this.check(_gte(BigInt(0),params))},multipleOf(value2,params){return this.check(_multipleOf(value2,params))}}));function bigint2(params){return _bigint(ZodBigInt,params)}var ZodBigIntFormat=$constructor("ZodBigIntFormat",(inst,def)=>{$ZodBigIntFormat.init(inst,def),ZodBigInt.init(inst,def)});function int64(params){return _int64(ZodBigIntFormat,params)}function uint64(params){return _uint64(ZodBigIntFormat,params)}var ZodSymbol=$constructor("ZodSymbol",(inst,def)=>{$ZodSymbol.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>symbolProcessor(inst,ctx,json2,params)});function symbol(params){return _symbol(ZodSymbol,params)}var ZodUndefined=$constructor("ZodUndefined",(inst,def)=>{$ZodUndefined.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>undefinedProcessor(inst,ctx,json2,params)});function _undefined3(params){return _undefined2(ZodUndefined,params)}var ZodNull=$constructor("ZodNull",(inst,def)=>{$ZodNull.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>nullProcessor(inst,ctx,json2,params)});function _null3(params){return _null2(ZodNull,params)}var ZodAny=$constructor("ZodAny",(inst,def)=>{$ZodAny.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>anyProcessor(inst,ctx,json2,params)});function any(){return _any(ZodAny)}var ZodUnknown=$constructor("ZodUnknown",(inst,def)=>{$ZodUnknown.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>unknownProcessor(inst,ctx,json2,params)});function unknown(){return _unknown(ZodUnknown)}var ZodNever=$constructor("ZodNever",(inst,def)=>{$ZodNever.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>neverProcessor(inst,ctx,json2,params)});function never(params){return _never(ZodNever,params)}var ZodVoid=$constructor("ZodVoid",(inst,def)=>{$ZodVoid.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>voidProcessor(inst,ctx,json2,params)});function _void2(params){return _void(ZodVoid,params)}var ZodDate=$constructor("ZodDate",(inst,def)=>{$ZodDate.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>dateProcessor(inst,ctx,json2,params),inst.min=(value2,params)=>inst.check(_gte(value2,params)),inst.max=(value2,params)=>inst.check(_lte(value2,params))},util_exports.derived({minDate:inst=>{let{minimum}=aggregateChecks(inst);return minimum?new Date(minimum):null},maxDate:inst=>{let{maximum}=aggregateChecks(inst);return maximum?new Date(maximum):null}},{}));function date2(params){return _date(ZodDate,params)}var ZodArray=$constructor("ZodArray",(inst,def)=>{_ensureDefaultMemoizer(),$ZodArray.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>arrayProcessor(inst,ctx,json2,params),inst.element=def.element},{min(n,params){return this.check(_minLength(n,params))},nonempty(params){return this.check(_minLength(1,params))},max(n,params){return this.check(_maxLength(n,params))},length(n,params){return this.check(_length(n,params))},unwrap(){return this.element}});function array(element,params){return _array(ZodArray,element,params)}function keyof(schema){let shape=schema._zod.def.shape;return _enum2(Object.keys(shape))}var ZodObject=$constructor("ZodObject",(inst,def)=>{_ensureDefaultMemoizer(),$ZodObjectJIT.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>objectProcessor(inst,ctx,json2,params),util_exports.installLazyProp(inst,"shape",self=>self._zod.def.shape,!1)},{keyof(){return _enum2(Object.keys(this._zod.def.shape))},catchall(catchall){return this.clone(util_exports.mergeDefs(this._zod.def,{catchall}))},passthrough(){return this.clone(util_exports.mergeDefs(this._zod.def,{catchall:unknown()}))},loose(){return this.clone(util_exports.mergeDefs(this._zod.def,{catchall:unknown()}))},strict(){return this.clone(util_exports.mergeDefs(this._zod.def,{catchall:never()}))},strip(){return this.clone(util_exports.mergeDefs(this._zod.def,{catchall:void 0}))},extend(incoming){return util_exports.extend(this,incoming)},safeExtend(incoming){return util_exports.safeExtend(this,incoming)},merge(other){return util_exports.merge(this,other)},pick(mask){return util_exports.pick(this,mask)},omit(mask){return util_exports.omit(this,mask)},partial(...args){return util_exports.partial(ZodOptional,this,args[0])},exactPartial(...args){return util_exports.partial(ZodExactOptional,this,args[0],"exactPartial")},required(...args){return util_exports.required(ZodNonOptional,this,args[0])}});function object(shape,params){let def={type:"object",shape:shape??{},...util_exports.normalizeParams(params)};return new ZodObject(def)}function strictObject(shape,params){return new ZodObject({type:"object",shape,catchall:never(),...util_exports.normalizeParams(params)})}function looseObject(shape,params){return new ZodObject({type:"object",shape,catchall:unknown(),...util_exports.normalizeParams(params)})}var ZodUnion=$constructor("ZodUnion",(inst,def)=>{$ZodUnion.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>unionProcessor(inst,ctx,json2,params),inst.options=def.options});function union(options,params){return new ZodUnion({type:"union",options,...util_exports.normalizeParams(params)})}var ZodXor=$constructor("ZodXor",(inst,def)=>{ZodUnion.init(inst,def),$ZodXor.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>unionProcessor(inst,ctx,json2,params),inst.options=def.options});function xor(options,params){return new ZodXor({type:"union",options,inclusive:!1,...util_exports.normalizeParams(params)})}var ZodDiscriminatedUnion=$constructor("ZodDiscriminatedUnion",(inst,def)=>{ZodUnion.init(inst,def),$ZodDiscriminatedUnion.init(inst,def)});function discriminatedUnion(discriminator,options,params){return new ZodDiscriminatedUnion({type:"union",options,discriminator,...util_exports.normalizeParams(params)})}var ZodIntersection=$constructor("ZodIntersection",(inst,def)=>{$ZodIntersection.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>intersectionProcessor(inst,ctx,json2,params)});function intersection(left,right){return new ZodIntersection({type:"intersection",left,right})}var ZodTuple=$constructor("ZodTuple",(inst,def)=>{_ensureDefaultMemoizer(),$ZodTuple.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>tupleProcessor(inst,ctx,json2,params)},{rest(rest){return this.clone({...this._zod.def,rest})},partial(){let def=this._zod.def;if(def.checks?.length)throw new Error(".partial() cannot be used on tuple schemas containing refinements");return this.clone({...def,items:def.items.map(item=>new ZodOptional({type:"optional",innerType:item}))})}});function tuple(items,_paramsOrRest,_params){let hasRest=_paramsOrRest instanceof $ZodType,params=hasRest?_params:_paramsOrRest,rest=hasRest?_paramsOrRest:null;return new ZodTuple({type:"tuple",items,rest,...util_exports.normalizeParams(params)})}var ZodRecord=$constructor("ZodRecord",(inst,def)=>{_ensureDefaultMemoizer(),$ZodRecord.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>recordProcessor(inst,ctx,json2,params),inst.keyType=def.keyType,inst.valueType=def.valueType});function record(keyType,valueType,params){return!valueType||!valueType._zod?new ZodRecord({type:"record",keyType:string2(),valueType:keyType,...util_exports.normalizeParams(valueType)}):new ZodRecord({type:"record",keyType,valueType,...util_exports.normalizeParams(params)})}function partialRecord(keyType,valueType,params){return new ZodRecord({type:"record",keyType,valueType,...util_exports.normalizeParams(params),partial:!0})}function looseRecord(keyType,valueType,params){return new ZodRecord({type:"record",keyType,valueType,mode:"loose",...util_exports.normalizeParams(params)})}var ZodMap=$constructor("ZodMap",(inst,def)=>{_ensureDefaultMemoizer(),$ZodMap.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>mapProcessor(inst,ctx,json2,params),inst.keyType=def.keyType,inst.valueType=def.valueType,inst.min=(...args)=>inst.check(_minSize(...args)),inst.nonempty=params=>inst.check(_minSize(1,params)),inst.max=(...args)=>inst.check(_maxSize(...args)),inst.size=(...args)=>inst.check(_size(...args))});function map(keyType,valueType,params){return new ZodMap({type:"map",keyType,valueType,...util_exports.normalizeParams(params)})}var ZodSet=$constructor("ZodSet",(inst,def)=>{_ensureDefaultMemoizer(),$ZodSet.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>setProcessor(inst,ctx,json2,params),inst.min=(...args)=>inst.check(_minSize(...args)),inst.nonempty=params=>inst.check(_minSize(1,params)),inst.max=(...args)=>inst.check(_maxSize(...args)),inst.size=(...args)=>inst.check(_size(...args))});function set(valueType,params){return new ZodSet({type:"set",valueType,...util_exports.normalizeParams(params)})}var ZodEnum=$constructor("ZodEnum",(inst,def)=>{$ZodEnum.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>enumProcessor(inst,ctx,json2,params),inst.enum=def.entries,inst.options=[...inst._zod.values];let keys=new Set(Object.keys(def.entries));inst.extract=(values2,params)=>{let newEntries={};for(let value2 of values2)if(keys.has(value2))newEntries[value2]=def.entries[value2];else throw new Error(`Key ${value2} not found in enum`);return new ZodEnum({...def,checks:[],...util_exports.normalizeParams(params),entries:newEntries})},inst.exclude=(values2,params)=>{let newEntries={...def.entries};for(let value2 of values2)if(keys.has(value2))delete newEntries[value2];else throw new Error(`Key ${value2} not found in enum`);return new ZodEnum({...def,checks:[],...util_exports.normalizeParams(params),entries:newEntries})}});function _enum2(values2,params){let entries=Array.isArray(values2)?Object.fromEntries(values2.map(v=>[v,v])):values2;return new ZodEnum({type:"enum",entries,...util_exports.normalizeParams(params)})}function nativeEnum(entries,params){return new ZodEnum({type:"enum",entries,...util_exports.normalizeParams(params)})}var ZodLiteral=$constructor("ZodLiteral",(inst,def)=>{$ZodLiteral.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>literalProcessor(inst,ctx,json2,params),inst.values=new Set(def.values),Object.defineProperty(inst,"value",{get(){if(def.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return def.values[0]}})});function literal(value2,params){return new ZodLiteral({type:"literal",values:Array.isArray(value2)?value2:[value2],...util_exports.normalizeParams(params)})}var ZodFile=$constructor("ZodFile",(inst,def)=>{$ZodFile.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>fileProcessor(inst,ctx,json2,params),inst.min=(size,params)=>inst.check(_minSize(size,params)),inst.max=(size,params)=>inst.check(_maxSize(size,params)),inst.mime=(types,params)=>inst.check(_mime(Array.isArray(types)?types:[types],params))});function file(params){return _file(ZodFile,params)}var ZodTransform=$constructor("ZodTransform",(inst,def)=>{_ensureDefaultMemoizer(),$ZodTransform.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>transformProcessor(inst,ctx,json2,params),inst._zod.parse=(payload,_ctx)=>{if(_ctx.direction==="backward")throw new $ZodEncodeError(inst.constructor.name);payload.addIssue=issue2=>{if(typeof issue2=="string")payload.issues.push(util_exports.issue(issue2,payload.value,def));else{let _issue=issue2;_issue.fatal&&(_issue.continue=!1),_issue.code??(_issue.code="custom"),"input"in _issue||(_issue.input=payload.value),_issue.inst??(_issue.inst=inst),payload.issues.push(util_exports.issue(_issue))}};let output2=def.transform(payload.value,payload);return output2 instanceof Promise?output2.then(output3=>(payload.value=output3,payload)):(payload.value=output2,payload)}});function transform(fn){return new ZodTransform({type:"transform",transform:fn})}var ZodOptional=$constructor("ZodOptional",(inst,def)=>{$ZodOptional.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>optionalProcessor(inst,ctx,json2,params),inst.unwrap=()=>inst._zod.def.innerType});function optional(innerType){return new ZodOptional({type:"optional",innerType})}var ZodExactOptional=$constructor("ZodExactOptional",(inst,def)=>{$ZodExactOptional.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>optionalProcessor(inst,ctx,json2,params),inst.unwrap=()=>inst._zod.def.innerType});function exactOptional(innerType){return new ZodExactOptional({type:"optional",innerType})}var ZodNullable=$constructor("ZodNullable",(inst,def)=>{$ZodNullable.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>nullableProcessor(inst,ctx,json2,params),inst.unwrap=()=>inst._zod.def.innerType});function nullable(innerType){return new ZodNullable({type:"nullable",innerType})}function nullish2(innerType){return optional(nullable(innerType))}var ZodDefault=$constructor("ZodDefault",(inst,def)=>{$ZodDefault.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>defaultProcessor(inst,ctx,json2,params),inst.unwrap=()=>inst._zod.def.innerType,inst.removeDefault=inst.unwrap});function _default2(innerType,defaultValue){return new ZodDefault({type:"default",innerType,get defaultValue(){return typeof defaultValue=="function"?defaultValue():util_exports.shallowClone(defaultValue)}})}var ZodPrefault=$constructor("ZodPrefault",(inst,def)=>{$ZodPrefault.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>prefaultProcessor(inst,ctx,json2,params),inst.unwrap=()=>inst._zod.def.innerType});function prefault(innerType,defaultValue){return new ZodPrefault({type:"prefault",innerType,get defaultValue(){return typeof defaultValue=="function"?defaultValue():util_exports.shallowClone(defaultValue)}})}var ZodNonOptional=$constructor("ZodNonOptional",(inst,def)=>{$ZodNonOptional.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>nonoptionalProcessor(inst,ctx,json2,params),inst.unwrap=()=>inst._zod.def.innerType});function nonoptional(innerType,params){return new ZodNonOptional({type:"nonoptional",innerType,...util_exports.normalizeParams(params)})}var ZodSuccess=$constructor("ZodSuccess",(inst,def)=>{$ZodSuccess.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>successProcessor(inst,ctx,json2,params),inst.unwrap=()=>inst._zod.def.innerType});function success(innerType){return new ZodSuccess({type:"success",innerType})}var ZodCatch=$constructor("ZodCatch",(inst,def)=>{$ZodCatch.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>catchProcessor(inst,ctx,json2,params),inst.unwrap=()=>inst._zod.def.innerType,inst.removeCatch=inst.unwrap});function _catch2(innerType,catchValue){return new ZodCatch({type:"catch",innerType,catchValue:typeof catchValue=="function"?catchValue:util_exports.constantCatch(catchValue)})}var ZodNaN=$constructor("ZodNaN",(inst,def)=>{$ZodNaN.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>nanProcessor(inst,ctx,json2,params)});function nan(params){return _nan(ZodNaN,params)}var ZodPipe=$constructor("ZodPipe",(inst,def)=>{$ZodPipe.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>pipeProcessor(inst,ctx,json2,params),inst.in=def.in,inst.out=def.out});function pipe(in_,out){return new ZodPipe({type:"pipe",in:in_,out})}var ZodCodec=$constructor("ZodCodec",(inst,def)=>{ZodPipe.init(inst,def),$ZodCodec.init(inst,def)});function codec(in_,out,params){return new ZodCodec({type:"pipe",in:in_,out,transform:params.decode,reverseTransform:params.encode})}function invertCodec(codec2){let def=codec2._zod.def;return new ZodCodec({type:"pipe",in:def.out,out:def.in,transform:def.reverseTransform,reverseTransform:def.transform})}var ZodPreprocess=$constructor("ZodPreprocess",(inst,def)=>{ZodPipe.init(inst,def),$ZodPreprocess.init(inst,def)}),ZodReadonly=$constructor("ZodReadonly",(inst,def)=>{$ZodReadonly.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>readonlyProcessor(inst,ctx,json2,params),inst.unwrap=()=>inst._zod.def.innerType});function readonly(innerType){return new ZodReadonly({type:"readonly",innerType})}var ZodTemplateLiteral=$constructor("ZodTemplateLiteral",(inst,def)=>{$ZodTemplateLiteral.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>templateLiteralProcessor(inst,ctx,json2,params)});function templateLiteral(parts,params){return new ZodTemplateLiteral({type:"template_literal",parts,...util_exports.normalizeParams(params)})}var ZodLazy=$constructor("ZodLazy",(inst,def)=>{$ZodLazy.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>lazyProcessor(inst,ctx,json2,params),inst.unwrap=()=>inst._zod.def.getter()});function lazy(getter){return new ZodLazy({type:"lazy",getter})}var ZodPromise=$constructor("ZodPromise",(inst,def)=>{$ZodPromise.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>promiseProcessor(inst,ctx,json2,params),inst.unwrap=()=>inst._zod.def.innerType});function promise(innerType){return new ZodPromise({type:"promise",innerType})}var ZodFunction=$constructor("ZodFunction",(inst,def)=>{$ZodFunction.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>functionProcessor(inst,ctx,json2,params)});function _function(params){return new ZodFunction({type:"function",input:Array.isArray(params?.input)?tuple(params?.input):params?.input??array(unknown()),output:params?.output??unknown()})}var ZodCustom=$constructor("ZodCustom",(inst,def)=>{$ZodCustom.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json2,params)=>customProcessor(inst,ctx,json2,params)});function check(fn){let ch2=new $ZodCheck({check:"custom"});return ch2._zod.check=fn,ch2}function custom(fn,_params){return _custom(ZodCustom,fn??(()=>!0),_params)}function refine(fn,_params={}){return _refine(ZodCustom,fn,_params)}function superRefine(fn,params){return _superRefine(fn,params)}var describe2=describe,meta2=meta,ZodInstanceOf=$constructor("ZodInstanceOf",(inst,def)=>{ZodCustom.init(inst,def)},{properties(shape,params){return this.check(_properties(shape,params))}});function _instanceof(cls,params={}){let inst=new ZodInstanceOf({type:"custom",check:"custom",fn:data=>data instanceof cls,abort:!0,...util_exports.normalizeParams(params)});return inst._zod.bag.Class=cls,inst._zod.check=payload=>{payload.value instanceof cls||payload.issues.push({code:"invalid_type",expected:cls.name,input:payload.value,inst,path:[...inst._zod.def.path??[]]})},inst}var stringbool=(...args)=>_stringbool({Codec:ZodCodec,Boolean:ZodBoolean,String:ZodString},...args);function json(params){let jsonSchema=lazy(()=>union([string2(params),number2(),boolean2(),_null3(),array(jsonSchema),record(string2(),jsonSchema)]));return jsonSchema}function preprocess(fn,schema){return new ZodPreprocess({type:"pipe",in:transform(fn),out:schema})}var ZodIssueCode={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};function setErrorMap(map2){config({customError:map2})}function getErrorMap(){return config().customError}var ZodFirstPartyTypeKind;ZodFirstPartyTypeKind||(ZodFirstPartyTypeKind={});var iso_exports={};__export(iso_exports,{ZodISODate:()=>ZodISODate,ZodISODateTime:()=>ZodISODateTime,ZodISODuration:()=>ZodISODuration,ZodISOTime:()=>ZodISOTime,date:()=>date3,datetime:()=>datetime2,duration:()=>duration2,time:()=>time2});function datetime2(params){return _isoDateTime(ZodISODateTime,params)}function date3(params){return _isoDate(ZodISODate,params)}function time2(params){return _isoTime(ZodISOTime,params)}function duration2(params){return _isoDuration(ZodISODuration,params)}var z={...schemas_exports2,...checks_exports2,iso:iso_exports},RECOGNIZED_KEYS=new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"]);function detectVersion(schema,defaultTarget){let $schema=schema.$schema;return $schema==="https://json-schema.org/draft/2020-12/schema"?"draft-2020-12":$schema==="http://json-schema.org/draft-07/schema#"?"draft-7":$schema==="http://json-schema.org/draft-04/schema#"?"draft-4":defaultTarget??"draft-2020-12"}function applyMinItems(items,minItems){return items.map((item,index)=>index<minItems?item:item.optional())}function decodeJSONPointerSegment(segment){return segment.replace(/~1/g,"/").replace(/~0/g,"~")}function resolveRef(ref,ctx){if(!ref.startsWith("#"))throw new Error("External $ref is not supported, only local refs (#/...) are allowed");let path3=ref.slice(1).split("/").filter(Boolean);if(path3.length===0)return ctx.rootSchema;let defsKey=ctx.version==="draft-2020-12"?"$defs":"definitions";if(path3[0]===defsKey){let key=path3[1]===void 0?void 0:decodeJSONPointerSegment(path3[1]);if(!key||!ctx.defs[key])throw new Error(`Reference not found: ${ref}`);return ctx.defs[key]}throw new Error(`Reference not found: ${ref}`)}function checkObjectGuards(objectSchema,guards){return z.transform(value2=>value2).check(payload=>{let value2=payload.value;if(typeof value2!="object"||value2===null||Array.isArray(value2))return;let keys=Object.getOwnPropertyNames(value2);if(guards.minProperties!==void 0&&keys.length<guards.minProperties&&payload.issues.push({origin:"object",code:"too_small",minimum:guards.minProperties,inclusive:!0,message:`Too small: expected object to have >=${guards.minProperties} properties`,input:value2,inst:objectSchema,continue:!0}),guards.maxProperties!==void 0&&keys.length>guards.maxProperties&&payload.issues.push({origin:"object",code:"too_big",maximum:guards.maxProperties,inclusive:!0,message:`Too big: expected object to have <=${guards.maxProperties} properties`,input:value2,inst:objectSchema,continue:!0}),guards.keySchema)for(let key of keys){let result=guards.keySchema.safeParse(key);result.success||payload.issues.push({code:"invalid_key",origin:"record",issues:result.error.issues,input:key,path:[key],continue:!0})}}).pipe(objectSchema)}function canonicalKey(value2,seen){if(value2===null)return"z";let type=typeof value2;if(type!=="object"){if(type==="number"&&Number.isNaN(value2))return null;let raw=String(value2);return`${type[0]}${raw.length}:${raw}`}if(seen.has(value2))return null;seen.add(value2);try{if(Array.isArray(value2)){let parts2=[];for(let item of value2){let key=canonicalKey(item,seen);if(key===null)return null;parts2.push(key)}return`a${parts2.length}:[${parts2.join(",")}]`}let keys=Object.keys(value2).sort(),parts=[];for(let k of keys){let key=canonicalKey(value2[k],seen);if(key===null)return null;parts.push(`${k.length}:${k}=${key}`)}return`o${parts.length}:{${parts.join(",")}}`}finally{seen.delete(value2)}}var SCHEMA_KEYWORDS=new Set(["items","prefixItems","additionalItems","additionalProperties","contains","propertyNames","not","if","then","else","allOf","anyOf","oneOf","unevaluatedItems","unevaluatedProperties","contentSchema"]),SCHEMA_MAP_KEYWORDS=new Set(["properties","patternProperties","dependentSchemas","dependencies","$defs","definitions"]);function containsRef(value2){return typeof value2!="object"||value2===null?!1:Array.isArray(value2)?value2.some(containsRef):typeof value2.$ref=="string"?!0:Object.entries(value2).some(([key,sub])=>SCHEMA_KEYWORDS.has(key)?containsRef(sub):!SCHEMA_MAP_KEYWORDS.has(key)||typeof sub!="object"||sub===null?!1:Object.values(sub).some(containsRef))}function plural(n){return n===1?"element":"elements"}function checkArrayGuards(arraySchema,guards){return z.transform(value2=>value2).check(payload=>{let items=payload.value;if(Array.isArray(items)){if(guards.uniqueItems===!0){let firstSeen=new Map;for(let i2=0;i2<items.length;i2++){let key=canonicalKey(items[i2],new Set);if(key===null)continue;let first=firstSeen.get(key);if(first===void 0){firstSeen.set(key,i2);continue}payload.issues.push({code:"custom",message:`Array items must be unique: element at index ${i2} duplicates the one at index ${first}`,input:items,path:[i2],continue:!0})}}if(guards.containsSchema){let minContains=guards.minContains??1,ceiling=guards.maxContains!==void 0?guards.maxContains+1:Number.POSITIVE_INFINITY,matches=0;for(let item of items)if(guards.containsSchema.safeParse(item).success&&++matches>=ceiling)break;matches<minContains&&payload.issues.push({code:"custom",message:`Array must contain at least ${minContains} matching ${plural(minContains)}; found ${matches}`,input:items,continue:!0}),guards.maxContains!==void 0&&matches>guards.maxContains&&payload.issues.push({code:"custom",message:`Array must contain at most ${guards.maxContains} matching ${plural(guards.maxContains)}`,input:items,continue:!0})}}}).pipe(arraySchema)}function getTupleRest(restSchema,ctx){if(restSchema!==!1)return restSchema===void 0||restSchema===!0?z.any():convertSchema(restSchema,ctx)}var fullTime=/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;function convertBaseSchema(schema,ctx){if(schema.not!==void 0){if(typeof schema.not=="object"&&Object.keys(schema.not).length===0)return z.never();throw new Error("not is not supported in Zod (except { not: {} } for never)")}if(schema.unevaluatedItems!==void 0)throw new Error("unevaluatedItems is not supported");if(schema.unevaluatedProperties!==void 0)throw new Error("unevaluatedProperties is not supported");if(schema.if!==void 0||schema.then!==void 0||schema.else!==void 0)throw new Error("Conditional schemas (if/then/else) are not supported");if(schema.dependentSchemas!==void 0||schema.dependentRequired!==void 0)throw new Error("dependentSchemas and dependentRequired are not supported");if(schema.$ref){let refPath=schema.$ref;if(ctx.refs.has(refPath))return ctx.refs.get(refPath);if(ctx.processing.has(refPath))return z.lazy(()=>{if(!ctx.refs.has(refPath))throw new Error(`Circular reference not resolved: ${refPath}`);return ctx.refs.get(refPath)});ctx.processing.add(refPath);let resolved=resolveRef(refPath,ctx),zodSchema2=convertSchema(resolved,ctx);return ctx.refs.set(refPath,zodSchema2),ctx.processing.delete(refPath),zodSchema2}if(schema.enum!==void 0){let enumValues=schema.enum;if(ctx.version==="openapi-3.0"&&schema.nullable===!0&&enumValues.length===1&&enumValues[0]===null)return z.null();if(enumValues.length===0)return z.never();if(enumValues.length===1)return z.literal(enumValues[0]);if(enumValues.every(v=>typeof v=="string"))return z.enum(enumValues);let literalSchemas=enumValues.map(v=>z.literal(v));return literalSchemas.length<2?literalSchemas[0]:z.union([literalSchemas[0],literalSchemas[1],...literalSchemas.slice(2)])}if(schema.const!==void 0)return z.literal(schema.const);let type=schema.type;if(Array.isArray(type)){let typeSchemas=type.map(t2=>{let typeSchema={...schema,type:t2};return convertBaseSchema(typeSchema,ctx)});return typeSchemas.length===0?z.never():typeSchemas.length===1?typeSchemas[0]:z.union(typeSchemas)}if(!type)return z.any();let zodSchema;switch(type){case"string":{let stringSchema=z.string();if(schema.format){let format=schema.format;format==="email"?stringSchema=stringSchema.check(z.email()):format==="uri"||format==="uri-reference"?stringSchema=stringSchema.check(z.url()):format==="uuid"||format==="guid"?stringSchema=stringSchema.check(z.uuid()):format==="date-time"?stringSchema=stringSchema.check(z.iso.datetime({offset:!0})):format==="date"?stringSchema=stringSchema.check(z.iso.date()):format==="time"?stringSchema=stringSchema.check(z.regex(fullTime)):format==="duration"?stringSchema=stringSchema.check(z.iso.duration()):format==="hostname"?stringSchema=stringSchema.check(z.hostname()):format==="ipv4"?stringSchema=stringSchema.check(z.ipv4()):format==="ipv6"?stringSchema=stringSchema.check(z.ipv6()):format==="mac"?stringSchema=stringSchema.check(z.mac()):format==="cidr"?stringSchema=stringSchema.check(z.cidrv4()):format==="cidr-v6"?stringSchema=stringSchema.check(z.cidrv6()):format==="base64"?stringSchema=stringSchema.check(z.base64()):format==="base64url"?stringSchema=stringSchema.check(z.base64url()):format==="e164"?stringSchema=stringSchema.check(z.e164()):format==="credit_card"?stringSchema=stringSchema.check(z.creditCard()):format==="iban"?stringSchema=stringSchema.check(z.iban()):format==="jwt"?stringSchema=stringSchema.check(z.jwt()):format==="emoji"?stringSchema=stringSchema.check(z.emoji()):format==="nanoid"?stringSchema=stringSchema.check(z.nanoid()):format==="cuid"?stringSchema=stringSchema.check(z.cuid()):format==="cuid2"?stringSchema=stringSchema.check(z.cuid2()):format==="ulid"?stringSchema=stringSchema.check(z.ulid()):format==="xid"?stringSchema=stringSchema.check(z.xid()):format==="ksuid"&&(stringSchema=stringSchema.check(z.ksuid()))}typeof schema.minLength=="number"&&(stringSchema=stringSchema.min(schema.minLength)),typeof schema.maxLength=="number"&&(stringSchema=stringSchema.max(schema.maxLength)),schema.pattern&&(stringSchema=stringSchema.regex(new RegExp(schema.pattern))),zodSchema=stringSchema;break}case"number":case"integer":{let numberSchema=type==="integer"?z.number().int():z.number();typeof schema.minimum=="number"&&schema.exclusiveMinimum!==!0&&(numberSchema=numberSchema.min(schema.minimum)),typeof schema.maximum=="number"&&schema.exclusiveMaximum!==!0&&(numberSchema=numberSchema.max(schema.maximum)),typeof schema.exclusiveMinimum=="number"?numberSchema=numberSchema.gt(schema.exclusiveMinimum):schema.exclusiveMinimum===!0&&typeof schema.minimum=="number"&&(numberSchema=numberSchema.gt(schema.minimum)),typeof schema.exclusiveMaximum=="number"?numberSchema=numberSchema.lt(schema.exclusiveMaximum):schema.exclusiveMaximum===!0&&typeof schema.maximum=="number"&&(numberSchema=numberSchema.lt(schema.maximum)),typeof schema.multipleOf=="number"&&(numberSchema=numberSchema.multipleOf(schema.multipleOf)),zodSchema=numberSchema;break}case"boolean":{zodSchema=z.boolean();break}case"null":{zodSchema=z.null();break}case"object":{let shape={},properties=schema.properties||{},requiredSet=new Set(schema.required||[]),additionalSchema=typeof schema.additionalProperties=="object"?convertSchema(schema.additionalProperties,ctx):void 0;for(let[key,propSchema]of Object.entries(properties)){let propZodSchema=convertSchema(propSchema,ctx);assignProp(shape,key,requiredSet.has(key)?propZodSchema:propZodSchema.optional())}if(schema.patternProperties){let patternProps=schema.patternProperties,patternKeys=Object.keys(patternProps),looseRecords=[];for(let pattern of patternKeys){let patternValue=convertSchema(patternProps[pattern],ctx),keySchema=z.string().regex(new RegExp(pattern));looseRecords.push(z.looseRecord(keySchema,patternValue))}let schemasToIntersect=[];if(Object.keys(shape).length>0&&schemasToIntersect.push(z.object(shape).passthrough()),schemasToIntersect.push(...looseRecords),schemasToIntersect.length===0)zodSchema=z.object({}).passthrough();else if(schemasToIntersect.length===1)zodSchema=schemasToIntersect[0];else{let result=z.intersection(schemasToIntersect[0],schemasToIntersect[1]);for(let i2=2;i2<schemasToIntersect.length;i2++)result=z.intersection(result,schemasToIntersect[i2]);zodSchema=result}if(schema.additionalProperties===!1){let propertyKeys=Object.keys(shape),patterns=patternKeys.map(p=>new RegExp(p)),basePatternSchema=zodSchema;zodSchema=zodSchema.check(payload=>{if(!isPlainObject(payload.value))return;let unrecognized=[];for(let key of Object.keys(payload.value))propertyKeys.includes(key)||patterns.some(regex=>regex.test(key))||unrecognized.push(key);unrecognized.length&&payload.issues.push({code:"unrecognized_keys",keys:unrecognized,input:payload.value,inst:basePatternSchema})})}}else{let objectSchema=z.object(shape);schema.additionalProperties===!1?zodSchema=objectSchema.strict():additionalSchema?zodSchema=objectSchema.catchall(additionalSchema):zodSchema=objectSchema.passthrough()}let hasKeyGuard=schema.propertyNames!==void 0&&schema.propertyNames!==!0,minProperties=typeof schema.minProperties=="number"?schema.minProperties:void 0,maxProperties=typeof schema.maxProperties=="number"?schema.maxProperties:void 0;if(hasKeyGuard||minProperties!==void 0||maxProperties!==void 0){let keySchema;if(hasKeyGuard){let keyJSONSchema=typeof schema.propertyNames=="object"&&schema.propertyNames.type===void 0?{type:"string",...schema.propertyNames}:schema.propertyNames;keySchema=convertSchema(keyJSONSchema,ctx)}zodSchema=checkObjectGuards(zodSchema,{keySchema,minProperties,maxProperties})}break}case"array":{let prefixItems=schema.prefixItems,items=schema.items;if(prefixItems&&Array.isArray(prefixItems)){let minItems=typeof schema.minItems=="number"?schema.minItems:0,tupleItems=prefixItems.map(item=>convertSchema(item,ctx)),positionalItems=applyMinItems(tupleItems,minItems),rest=Array.isArray(items)?void 0:getTupleRest(items,ctx),tupleSchema=z.tuple(positionalItems);zodSchema=rest?tupleSchema.rest(rest):tupleSchema,typeof schema.minItems=="number"&&(zodSchema=zodSchema.check(z.minLength(schema.minItems))),typeof schema.maxItems=="number"&&(zodSchema=zodSchema.check(z.maxLength(schema.maxItems)))}else if(Array.isArray(items)){let minItems=typeof schema.minItems=="number"?schema.minItems:0,tupleItems=items.map(item=>convertSchema(item,ctx)),positionalItems=applyMinItems(tupleItems,minItems),rest=getTupleRest(schema.additionalItems,ctx),tupleSchema=z.tuple(positionalItems);zodSchema=rest?tupleSchema.rest(rest):tupleSchema,typeof schema.minItems=="number"&&(zodSchema=zodSchema.check(z.minLength(schema.minItems))),typeof schema.maxItems=="number"&&(zodSchema=zodSchema.check(z.maxLength(schema.maxItems)))}else if(items!==void 0){let element=convertSchema(items,ctx),arraySchema=z.array(element);typeof schema.minItems=="number"&&(arraySchema=arraySchema.min(schema.minItems)),typeof schema.maxItems=="number"&&(arraySchema=arraySchema.max(schema.maxItems)),zodSchema=arraySchema}else zodSchema=z.array(z.any());(schema.uniqueItems===!0||schema.contains!==void 0)&&(zodSchema=checkArrayGuards(zodSchema,{uniqueItems:schema.uniqueItems===!0,containsSchema:schema.contains!==void 0?convertSchema(schema.contains,ctx):void 0,minContains:typeof schema.minContains=="number"?schema.minContains:void 0,maxContains:typeof schema.maxContains=="number"?schema.maxContains:void 0}));break}default:throw new Error(`Unsupported type: ${type}`)}return zodSchema}function convertSchema(schema,ctx){if(typeof schema=="boolean")return schema?z.any():z.never();let baseSchema=convertBaseSchema(schema,ctx),hasExplicitType=schema.type||schema.enum!==void 0||schema.const!==void 0;if(schema.anyOf&&Array.isArray(schema.anyOf)){let options=schema.anyOf.map(s=>convertSchema(s,ctx)),anyOfUnion=z.union(options);baseSchema=hasExplicitType?z.intersection(baseSchema,anyOfUnion):anyOfUnion}if(schema.oneOf&&Array.isArray(schema.oneOf)){let options=schema.oneOf.map(s=>convertSchema(s,ctx)),oneOfUnion=z.xor(options);baseSchema=hasExplicitType?z.intersection(baseSchema,oneOfUnion):oneOfUnion}if(schema.allOf&&Array.isArray(schema.allOf))if(schema.allOf.length===0)baseSchema=hasExplicitType?baseSchema:z.any();else{let result=hasExplicitType?baseSchema:convertSchema(schema.allOf[0],ctx),startIdx=hasExplicitType?0:1;for(let i2=startIdx;i2<schema.allOf.length;i2++)result=z.intersection(result,convertSchema(schema.allOf[i2],ctx));baseSchema=result}schema.nullable===!0&&ctx.version==="openapi-3.0"&&(baseSchema=z.nullable(baseSchema)),schema.readOnly===!0&&(baseSchema=z.readonly(baseSchema)),schema.default!==void 0&&(baseSchema=baseSchema.default(schema.default));let extraMeta={},coreMetadataKeys=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let key of coreMetadataKeys)key in schema&&(extraMeta[key]=schema[key]);let contentMetadataKeys=["contentEncoding","contentMediaType","contentSchema"];for(let key of contentMetadataKeys)key in schema&&(extraMeta[key]=schema[key]);if(schema.type==="object"&&schema.$ref===void 0){schema.propertyNames!==void 0&&!containsRef(schema.propertyNames)&&(extraMeta.propertyNames=schema.propertyNames);for(let key of["minProperties","maxProperties"])schema[key]!==void 0&&(extraMeta[key]=schema[key])}if(schema.type==="array"&&schema.$ref===void 0){schema.contains!==void 0&&!containsRef(schema.contains)&&(extraMeta.contains=schema.contains);for(let key of["uniqueItems","minContains","maxContains"])schema[key]!==void 0&&(extraMeta[key]=schema[key])}for(let key of Object.keys(schema))RECOGNIZED_KEYS.has(key)||assignProp(extraMeta,key,schema[key]);return Object.keys(extraMeta).length>0&&ctx.registry.add(baseSchema,extraMeta),schema.description&&(baseSchema=baseSchema.describe(schema.description)),baseSchema}function fromJSONSchema(schema,params){if(typeof schema=="boolean")return schema?z.any():z.never();let normalized;try{normalized=JSON.parse(JSON.stringify(schema))}catch{throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas")}let version2=detectVersion(normalized,params?.defaultTarget),defs=normalized.$defs||normalized.definitions||{},ctx={version:version2,defs,refs:new Map,processing:new Set,rootSchema:normalized,registry:params?.registry??globalRegistry};return convertSchema(normalized,ctx)}var RESOLVING=Symbol("z.visit/resolving");function visit(schema,fnOrHandlers){let fn=typeof fnOrHandlers=="function"?fnOrHandlers:(node2,rewritten)=>{let h=fnOrHandlers[node2._zod.def.type];return h?h(node2,rewritten):node2},cache=new Map;function run(s){let cached2=cache.get(s);if(cached2===RESOLVING)return new $ZodLazy({type:"lazy",getter:()=>cache.get(s)});if(cached2!==void 0)return cached2;cache.set(s,RESOLVING);let inner=mapInner(s),mapped=fn(inner,inner!==s);return cache.set(s,mapped),mapped}function mapInner(s){let def=s._zod.def,kind=def.type;switch(kind){case"object":{let oldShape=def.shape,keys=Object.keys(oldShape),changed=!1,newShape={};for(let k of keys){let mapped=run(oldShape[k]);mapped!==oldShape[k]&&(changed=!0),newShape[k]=mapped}let newCatchall=def.catchall;return def.catchall&&(newCatchall=run(def.catchall),newCatchall!==def.catchall&&(changed=!0)),changed?clone(s,{...def,shape:newShape,catchall:newCatchall}):s}case"array":{let mapped=run(def.element);return mapped===def.element?s:clone(s,{...def,element:mapped})}case"tuple":{let oldItems=def.items,changed=!1,newItems=[];for(let item of oldItems){let mapped=run(item);mapped!==item&&(changed=!0),newItems.push(mapped)}let newRest=def.rest;return def.rest&&(newRest=run(def.rest),newRest!==def.rest&&(changed=!0)),changed?clone(s,{...def,items:newItems,rest:newRest}):s}case"record":case"map":{let newKey=run(def.keyType),newVal=run(def.valueType);return newKey===def.keyType&&newVal===def.valueType?s:clone(s,{...def,keyType:newKey,valueType:newVal})}case"set":{let newVal=run(def.valueType);return newVal===def.valueType?s:clone(s,{...def,valueType:newVal})}case"union":{let oldOptions=def.options,changed=!1,newOptions=[];for(let opt of oldOptions){let mapped=run(opt);mapped!==opt&&(changed=!0),newOptions.push(mapped)}return changed?clone(s,{...def,options:newOptions}):s}case"intersection":{let newLeft=run(def.left),newRight=run(def.right);return newLeft===def.left&&newRight===def.right?s:clone(s,{...def,left:newLeft,right:newRight})}case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":{let newInner=run(def.innerType);return newInner===def.innerType?s:clone(s,{...def,innerType:newInner})}case"pipe":{let newIn=run(def.in),newOut=run(def.out);return newIn===def.in&&newOut===def.out?s:clone(s,{...def,in:newIn,out:newOut})}case"function":{let newInput=run(def.input),newOutput=run(def.output);return newInput===def.input&&newOutput===def.output?s:clone(s,{...def,input:newInput,output:newOutput})}case"lazy":{let original=def.getter,{_cachedInner,...rest}=def;return clone(s,{...rest,getter:()=>run(original())})}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":return s;default:return s}}return run(schema)}function deepPartial(schema){return visit(schema,{object:s=>s.partial(),union:s=>{let def=s._zod.def;return def.discriminator===void 0?s:union(def.options)}})}function withChecks(side,checks){if(!checks?.length)return side;let def=side._zod.def;return clone(side,mergeDefs(def,{checks:[...def.checks??[],...checks]}),{parent:!0})}function outSide(def){return withChecks(def.out,def.checks)}function inSide(def){return def.in._zod.traits.has("$ZodTransform")?outSide(def):def.in}function input(schema){return visit(schema,{pipe:s=>inSide(s._zod.def),default:(s,rewritten)=>rewritten?optional(s._zod.def.innerType):s,catch:(s,rewritten)=>rewritten?s._zod.def.innerType:s})}function output(schema){return visit(schema,{pipe:s=>outSide(s._zod.def),prefault:(s,rewritten)=>rewritten?s._zod.def.innerType:s})}var coerce_exports={};__export(coerce_exports,{bigint:()=>bigint3,boolean:()=>boolean3,date:()=>date4,number:()=>number3,string:()=>string3});function string3(params){return _coercedString(ZodString,params)}function number3(params){return _coercedNumber(ZodNumber,params)}function boolean3(params){return _coercedBoolean(ZodBoolean,params)}function bigint3(params){return _coercedBigint(ZodBigInt,params)}function date4(params){return _coercedDate(ZodDate,params)}var UNSTAMPED_ARTIFACT_VERSION="0.0.0-unstamped",resolveArtifactVersion=stamped=>{let trimmed=stamped?.trim();return trimmed===void 0||trimmed===""?UNSTAMPED_ARTIFACT_VERSION:trimmed},FORGE_ARTIFACT_VERSION=resolveArtifactVersion("42.54.0"),UNSTAMPED_BUILD_DETAIL="this process carries no build stamp, so it is NOT a packaged extension \u2014 it is a dev checkout, or a build made without FORGE_ARTIFACT_VERSION set. An installed extension always reports a real version here; for one that does not, read it from the desktop app under Settings \u2192 Extensions \u2192 this extension \u2192 Details.",artifactBuildReport=(options={})=>{let version2=options.version??FORGE_ARTIFACT_VERSION,stamped=version2!==UNSTAMPED_ARTIFACT_VERSION;return{...options.module===void 0?{}:{module:options.module},version:version2,stamped,...stamped?{}:{detail:UNSTAMPED_BUILD_DETAIL}}};var CONTRACT_DESCRIPTIONS=Object.freeze({assets:{list:"Every asset visible to the caller's tenant as a bare `AssetRef` \u2014 an `assetId` and nothing else. This is the cross-domain reference list, the shape another domain holds to point at an asset. It takes no input, accepts no filter, and does not page. For the asset rows themselves \u2014 name, type, status, filters, paging \u2014 call `crud.list` instead.",snapshot:"The domain's snapshot mint \u2014 the ONE polymorphic mint the platform convention gives every snapshot-referable domain. An idempotent DERIVATION, not a Record-writing verb: `tenantRead`, writes nothing, never a composition step. Output is the platform kernel `EntitySnapshotRef` verbatim; an unsupported `type` refuses at parse through the ask's enum.\n\nA NOOP mint over the version row: `snapshot` := the asset's CURRENT version row id, the same value the display resolver honours on a ref's `version`. Asset version rows are append-only, so the value denotes frozen content by construction.\n\nRefuses the declared `NOT_FOUND` for an id that names no live asset \u2014 unknown, malformed, soft-deleted, or another tenant's.","crud.create":"Create an asset under a type whose template validates its properties.","crud.get":'Fetch one version of an asset by `assetId`. Optional `asOf` selects the version effective at that instant (half-open `effectiveFrom <= asOf < effectiveTo`); absent \u2192 the current version. No version effective then (pre-creation / post-soft-delete) \u2192 NOT_FOUND. As of an instant, `properties` are the merged values then: a dated value covering the instant replaces the version\'s (a dated "no value" removes the key), and `appliedDatedValueIds` names each one taken. Optional `knownAt` replays that read as known then: only dated values recorded by then and not retired by then; versions read as stored. A future `knownAt` is refused at parse; one without `asOf` is BAD_REQUEST (`data.code = KNOWN_AT_WITHOUT_AS_OF`).',"crud.list":"List assets with filters + offset/limit pagination. Optional `asOf` mirrors `get`'s point-in-time semantics: every returned row (and `total`) is the version effective at that instant, its `properties` merged with the dated values covering the instant and named in `appliedDatedValueIds`, property filters and conditions reading the merged values; absent \u2192 the CURRENT population, byte-identical to the pre-existing current-population call. `knownAt` replays an as-of page, its count and its filters as known then, as `get`'s does. Refused together with `hasGeometry` (BAD_REQUEST naming both) \u2014 a spatial capability read has no past-instant notion.\n\n`categoryIds` resolves through TODAY's live asset types regardless of `asOf` \u2014 the temporal window applies to asset VERSIONS, not to which types currently exist. A past `asOf` naming a category whose type has SINCE been deleted silently omits assets of that type; `assetTypeIds` names concrete governed ids directly and is unaffected.\n\nREFUSAL, declared: `TX_BUDGET_OVERRUN` (422) when the read outlived the request's transaction budget \u2014 a big selection or a busy system; a `nameContains` or `search` text reads every asset the tenant holds, and so does a property or external-ID condition alone. `data.budgetMs` is the budget. Narrow the list (an id, a type, category or lifecycle filter), or retry once the system is quieter.\n\n`conditions`: operator conditions over asset fields, properties and external IDs, combined by All or Any and ANDed with every other filter. A condition its field cannot honour is refused `INVALID_CONDITION` (400, `data.index` names the row) before anything is read. The selection-taking verbs (`count`, the bulk relationship writes) and the export do NOT take it: sending it there is refused.\n\n`search`: the search box. An asset matches when its name contains the trimmed text (any case) OR it holds a current external ID, in any system, that equals it exactly (case-sensitive, no numeric coercion, the `ext:` `is` rule); `%`, `_` and `\\` are literal in the name. ANDed with every other filter and honoured at `asOf`; `nameContains` is unchanged and name-only. Unlike `conditions`, `search` IS part of the selection, so `count`, the bulk relationship writes and the export take it and describe the set the box found. When a request carries `search`, the output's `matchedExternalIds` names, for each row on the page found by an external ID and not by its name, the binding that matched.","crud.distinctValues":"The values a condition FIELD holds on the assets a list filter selects, with the number of those assets holding each \u2014 what a person picks from instead of guessing a value. `tenantRead`: writes nothing, records nothing.\n\n`{ field, filter, prefix?, limit? }`: `field` is a condition field (`asset:status`, `prop:<code>`, `ext:<system>` / `ext:*`,...), `filter` the rest of the list filter verbatim (`asOf` included), `prefix` a case-insensitive literal prefix, `limit` 1..20 (default 20). Most common first, then by value; a response of exactly `limit` entries may have more, and there is no next page. Values `is` treats as one (case, a number and \"42\") are one entry, the most common spelling, counted over the whole group; external IDs group exactly. `count` counts assets, once each.\n\n`prefix` is REQUIRED for `asset:name` and `ext:` fields (about one value per asset): without one the read is refused `INVALID_CONDITION` (`reason: 'prefix-required'`).\n\n`values` asks instead for EXACT counts of up to 20 listed values of a `prop:` field \u2014 JSON-typed and case-exact, the `propertyFilters` equality \u2014 so one read tells a caller which values of a `oneOf` / `noneOf` list no selected asset holds (they are absent). Any other field, or a `prefix` beside it, is refused `INVALID_CONDITION` (`reason: 'values-not-allowed'`).\n\nREFUSAL, declared: `TX_BUDGET_OVERRUN` (422), exactly as `list`, when the scan outlived the budget \u2014 a property or external-ID field over a whole tenant reads every asset; narrow the filter by a type or category first.","crud.index":"A LEAN sibling of `list` \u2014 the SAME filters MINUS `asOf`, plus a REQUIRED `fields` projection. Listing 129 facilities over `list` returned 92,061 characters \u2014 every property of every asset \u2014 when the caller needed only `{name, assetId}`. `locations` below was already built as exactly this lean-sibling shape for the map read; this generalizes the pattern to an arbitrary field selection.\n\nPROJECTS AFTER THE FETCH, never a second query \u2014 the `locations` precedent: `list` runs unchanged, then each row is narrowed to the requested fields in JS. `assetId` is ALWAYS present regardless of `fields` \u2014 a caller listing assets needs an id to act on any of them, the same implicit guarantee `list`/`locations` make.\n\nThe output item type is one flat object DERIVED from `AssetSchema` \u2014 every field optional except the always-present `assetId` \u2014 not a shape that varies with the selection. A per-selection output would have no single OpenAPI rendering for a non-TS consumer to code against, and a hand-authored parallel shape could drift from `AssetSchema`.\n\nREFUSAL, declared: `TX_BUDGET_OVERRUN` (422), exactly as `list` \u2014 it IS `list` \u2014 when the read outlived the request's transaction budget. `INVALID_CONDITION`, exactly as `list`: a `conditions` row its field cannot honour is refused, naming the row, before anything is read.","crud.count":"HOW MANY assets a predicate matches, in ONE query with NO pagination \u2014 plus, optionally, a capped SAMPLE of matching ids in the same round trip. `tenantRead`: writes nothing, records nothing, stages nothing.\n\nNOT A MODE OF `list`, and the distinction is the reason it exists. `list` answers \"which slice do I show\" and carries `total` as a rider on the FIRST page only \u2014 a cursor page omits it by design \u2014 so a caller who wants only the number has to either page or reason about which page still carries it. Its first consumer did the former: the calculations authoring scope preview resolved \"resolves N assets\" by paging `list` to exhaustion at 200 ids a page over the cross-domain loopback and taking the array's LENGTH, which measured 132 s at the observed 543,391-asset estate for a number the first page had already counted.\n\n`asOf` mirrors `list`'s point-in-time semantics \u2014 the same half-open `effectiveFrom <= asOf < effectiveTo` window, applied to the same seek-free filter \u2014 so a past-instant count and a past-instant PAGE of one predicate always describe the same population. ABSENT \u2192 the CURRENT population. Refused together with `selection.hasGeometry`, exactly as `list` refuses the pair and for the same reason.\n\n`selection.categoryIds` resolves through TODAY's live asset types regardless of `asOf` \u2014 the same caveat `list` carries, inherited rather than restated, because this IS `list`'s count.\n\nThe sample is drawn from the first page of `list`'s own default order (name ascending, `assetId`-tiebroken). It is a SAMPLE, not a page: there is no cursor and no way to ask for the next one. For rows, call `list`.\n\nREFUSAL, declared: `TX_BUDGET_OVERRUN` (422), exactly as `list`, when the count outlived the request's transaction budget.","crud.exportEstimate":"Pre-flight an export WITHOUT authorizing one (`tenantRead`): resolve the selection, COUNT it, and report how WIDE the file would be. A count and a column count, never rows.\n\nSTAGES NOTHING, GRANTS NOTHING, RECORDS NOTHING \u2014 call it freely to refuse an over-cap or empty export BEFORE the confirm action. The authorization itself is `export`, which re-resolves on its own and does not trust this answer.\n\n`maxRows` on the answer is the deployment's EFFECTIVE row cap \u2014 the same injected policy the mint enforces. State THAT number in any copy or pre-guard; never bake the assembly default into a client, or a deployment override splits UI-refused from server-granted.\n\n`columnCount` is what makes WIDTH knowable up front \u2014 the file's column set is derived from the data in the selection, so two exports with different filters legitimately differ in width. It is SKIPPED (reported as 0) where `rowCount` already exceeds `maxRows`: an export that will be refused does not pay for column math.\n\n`maxColumns` is the WIDTH cap the mint enforces, echoed for the same reason `maxRows` is: width is the export's second scaling term (peak memory is tile rows \xD7 columns), so a selection can be refused for being too WIDE with a row count well under the cap. State that number in copy too.\n\nAnswers even where the deployment has no export store, because it touches no store.\n\nA count that outlives the request's transaction budget is refused with the declared `TX_BUDGET_OVERRUN` (422), as `count` is.","crud.exportStatus":"Where ONE authorized export has got to (`tenantRead`, un-recorded).\n\n `pending` \u2192 still building, with an HONEST fraction (`tilesDone` of\n `tilesTotal`) rather than a synthesized percentage, plus the\n row and column counts so a client can keep describing the\n file while it waits.\n `ready` \u2192 the GRANT: `{url, headers, expiresAt, mediaType, filename,\n rowCount}` plus `byteSize`. The URL is presigned FRESH on\n every read, so its lifetime starts when you are told about\n it rather than when the build finished.\n `failed` \u2192 why, in one sentence. A build that stopped making progress\n reports failed rather than pending forever, so a dead worker\n is legible instead of invisible.\n\nONE EXPORT, BY ID \u2014 there is deliberately no list, no paging and no filter. A read that enumerated a tenant's exports would misrepresent a transient movement artifact as a persisted published representation, so an `exportId` you no longer hold names an export you can no longer reach. Another tenant's id resolves to NOT_FOUND exactly as an id that never existed does.","crud.export":'Authorize ONE export of the assets a selection matches (`tenantWrite`, a GOVERNED verb \u2014 every mint leaves an actor-stamped Record naming the SELECTION, its ordering, its scoping and the resolved row count; the pre-flight, the build and the transfer do not).\n\nReturns a HANDLE, not the file and not yet a link: `{exportId, state, rowCount, columnCount, tilesTotal}`. Poll `crud.exportStatus` with that `exportId` for the grant. The build is ASYNCHRONOUS because it measured too slow to hold a request open \u2014 a full-estate export took ~60s unfiltered and ~200s subtree-scoped against a ~60s gateway envelope \u2014 so the mint validates, refuses, records and enqueues, and nothing more.\n\nThe response carries NO bucket, key or other storage location, and the request cannot name one \u2014 a caller-supplied `objectKey`, `bucket`, `prefix` or `tenantId` is refused at parse.\n\nThe file carries EVERYTHING the asset is known by, and the column set is derived from the DATA in the selection rather than from template declarations: the durable `assetId`, the name, resolved category and type names, lifecycle, the validity window, the location as well-known text (the column ABSENT where the deployment has no geometry \u2014 an empty cell would falsely assert "no location"), a `Parent`/`Parent ID` pair for each of the four HIERARCHY relationship types, one `prop.*` column per static property key present, and one `derived.*` column per materialized derived code present. NO column INDEX is stable across exports \u2014 read by header. A blank `derived.*` cell may mean "not rebuilt yet" rather than "no value": that table is a rebuildable projection, not governed history.\n\n`descendantOf` scopes the export to a hierarchy SUBTREE, node-inclusive and DISTINCT on asset id \u2014 the asset graph is a DAG, so one asset can be reachable from two unrelated roots. It exists on THIS input only, never on the shared bulk selection the mutating verbs take.\n\nTHE GRANT IS NOT SINGLE-USE: within its lifetime (`expiresAt`, 900s by default) it may be fetched more than once, and a transfer that begins before expiry completes even if expiry passes mid-stream. Single-use is unenforceable on a signed object-store URL. An expired grant is refused by the store; poll again for a fresh one rather than storing grant URLs. NOTHING ENUMERATES PAST EXPORTS \u2014 `exportStatus` answers about ONE id and there is no list, so a lost `exportId` is a lost export. The sealed Record is the only durable trace.\n\n`idempotencyKey` is REQUIRED, unique per (tenant, caller, key): a mint that times out may well have completed, and the SAME-KEY retry returns the one existing authorization with a FRESH usable grant. A reused key with a different selection or format is refused as `BAD_REQUEST` with `data.code = "KEY_PARAM_MISMATCH"` (another caller\'s key: `data.code = "KEY_ACTOR_MISMATCH"`); `CONFLICT` is reserved for two CONCURRENT mints racing the same key, where the loser retries into the replay.\n\nREFUSALS, declared and ordered: `SERVICE_UNAVAILABLE` with `data.code = "EXPORT_STORE_UNAVAILABLE"` (this deployment has no export store; the pre-flight still answers) \u2192 `FORMAT_UNAVAILABLE` (XLSX is a declared format this capability does not serve yet; ask for CSV) \u2192 `OVER_CAP` with `data.reason = "search-cap"` \u2192 `EMPTY_RESULT` (zero assets; nothing to stage) \u2192 `OVER_CAP` with no `data` (the selection exceeds the deployment\'s row cap; narrow it \u2014 never truncated, never queued, because a silently partial 700,000-row file is more dangerous than a refusal that names the count and the cap) \u2192 `TOO_MANY_COLUMNS` (the selection is too WIDE: the column set is derived from the data, so a selection whose assets carry thousands of distinct property keys scales the file\'s second dimension. `exportEstimate` reports both `columnCount` and `maxColumns`, so this is readable before the confirm).',"crud.locations":"The MAP's read \u2014 located assets under the same filter facets, projected to the three fields a canvas draws (`assetId`, `name`, `geometry`) and capped at a map-scale ceiling rather than the table's 200.\n\nA sibling of `list` rather than a mode of it, for two reasons: the lean projection is what makes the raised ceiling affordable (measured 248 kB vs 681 kB for the same 1,110-asset estate), and it keeps that ceiling off `crud.list`, where no caller needs a page past 200. Unpaged and unordered by construction \u2014 a map has no pager, so a page-2 pin is an invisible pin.\n\nCapability-gated like every geometry surface: a PostGIS-less deployment refuses LOUDLY (SERVICE_UNAVAILABLE, typed `data.code`), never a silent empty canvas. tenantRead in the api wiring. A read that outlives the request's transaction budget is refused with the declared `TX_BUDGET_OVERRUN` (422), as `list` is.","crud.update":"Full-state-replace update \u2014 a new version row pinning the current template. With `effectiveFrom`, the dated values of each property it changes are replaced from that date onward. A lost race is `CONFLICT` with `data.code = DATED_VALUES_RACE`: nothing was saved, retry.","crud.delete":"Soft-delete \u2014 close the current version, no successor; returns it.\n\n`SERVICE_UNAVAILABLE` with `data.reason: 'deadlock'` is TRANSIENT: a concurrent write to the same assets deadlocked with this one and nothing was written \u2014 retry the same call.","crud.deleteImpact":"Delete-impact PREFLIGHT \u2014 a READ over a bounded batch of assetIds reporting what a delete WOULD hit (hierarchy edges, storage-only edges, live external-ID bindings) + a per-asset verdict (deletable / reparentable / reparentable-too-wide / blocked / not-found). ADVISORY: no lock between preflight and delete \u2014 the delete's own guards stay the authority (TOCTOU by design). `tenantRead`, leaves no Record.","crud.deleteMany":"GOVERNED bulk soft-delete \u2014 a bounded batch of DISTINCT assetIds with per-item success/refusal reporting, ONE actor-stamped Record for the batch (`assets.deleteMany`), and one `assets.deleted` event per deleted asset. Per-item independence: a refused item never rolls back the deleted ones. REFUSE semantics only (no reparent \u2014 that stays single `crud.delete`). `tenantWrite`. Extends the audit-receipt discipline to bulk.","crud.setLocation":'Set (or clear) the asset\'s location. A GOVERNED, version-creating verb: the successor carries the new geometry (GeoJSON in/out, native PostGIS storage); every other field copies forward. `geometry: null` clears the location. Distinct from `update` \u2014 full-state `update` carries no geometry. On a PostGIS-less deployment this refuses LOUDLY (SERVICE_UNAVAILABLE, typed `data.code`), never a 500 or a silent no-op. `tenantWrite`.\n\nIT COMPARES BEFORE WRITING. A placement that would store the geometry the asset ALREADY HOLDS \u2014 including `geometry: null` over an asset with no location \u2014 creates no version, emits no `assets.location.set`, and answers with the CURRENT version. So re-sending a placement YOU JUST SENT is free, and a client may retry one without minting history.\n\n"Free" is exact equality of the stored geometry, not proximity: same coordinates in the same order, same geometry type, same SRID. A shape change at the same centre, and a different shape with the same bounding box, are both WRITES. Reading a location and sending it straight back is free too, because reads render at full stored precision \u2014 but a client that rounds, re-projects, reorders a ring, or promotes a Point to a MultiPoint is sending a different geometry and will mint a version.\n\nWHAT A CALLER CANNOT TELL, deliberately: whether this call wrote. The output is an `Asset` either way, so a caller that reports "location updated" over the response over-claims on a converged placement. Compare the returned `id` against the version you held if you need to know.\n\nA converged placement still leaves a Record, with `reads` naming the asset and `effects` EMPTY \u2014 so an automation bound to `assets.setLocation` does NOT fire for it (an empty `effects` is trigger-ineligible).\n\nNOT TRUE OF THE BULK SIBLING. `setLocationMany` writes every row it resolves, unconditionally; see its own note.',"crud.setLocationMany":`GOVERNED BULK PLACEMENT \u2014 place many assets in ONE call: the bulk sibling of \`setLocation\`, and the same operation per row (same GeoJSON surface, same PostGIS validation, its own append-only version row, its own \`assets.location.set\` event). What changes is the grain of the receipt, not the semantics.
73
73
 
74
74
  ONE DIVERGENCE FROM THE SINGLE VERB: this one does NOT compare before writing. Every row it resolves takes a version row and emits an event even when the geometry it would store is already there, so re-sending a converged batch is NOT free the way re-sending a single placement is. Extending the compare into the set-based bulk interior is tracked as its own decision.
75
75
 
@@ -191,7 +191,7 @@ EPHEMERAL, like the probe: no row, no Record. What a browse DISCOVERS becomes du
191
191
 
192
192
  An entry this platform cannot READ is returned with \`readable: false\`, never filtered out: a row silently missing from a listing leaves the operator looking for a table the surface decided not to mention.
193
193
 
194
- What refuses: the share saying no in a way the caller can act on (\`SHARE_CONTENTS_REFUSED\`) \u2014 the browse and the probe translate the same port refusals, so they answer the same declared code (see \`testConnection\`).`},obligations:{refs:"The domain-root Ref seam \u2014 named `refs`, never `list`, so it does not read as duplication beside a capability-scoped list added later. Declares `NOT_IMPLEMENTED` the way Work's `refs` does for the phase before any verb can create a `Plan` row.","framework.list":"List visible Library frameworks with editions, filtered and cursor-paged. `tenantRead`. Refuses `WORK_CLAUSE_CODE_INVALID` when stored requirement or suggestion content carries a Work clause type that does not satisfy Work type code grammar.","framework.get":"Get a visible framework by id with editions, citation checks, suggestions and recorded pack provenance. `tenantRead`. Refuses `NOT_FOUND` when the framework does not exist, and `WORK_CLAUSE_CODE_INVALID` when stored requirement or suggestion content carries a Work clause type that does not satisfy Work type code grammar.","requirement.list":"List saved requirements and authoring trees for one visible framework version, cursor-paged. `tenantRead`. Refuses `NOT_FOUND` when the framework version does not exist, and `WORK_CLAUSE_CODE_INVALID` when a stored requirement tree carries a Work clause type that does not satisfy Work type code grammar.",frameworkImportBrowse:"The framework packs offered to this tenant for import, one entry per framework at its newest offered version. `tenantRead`, `edit` authority on `obligations.framework`, the authority `frameworkImport` needs. A pack item whose payload is not a framework this domain can import is left out.",frameworkImportVersions:"Every version of one offered framework pack item, retired ones included and flagged, for choosing which to import. `tenantRead`, the same authority as `frameworkImportBrowse`. A pack not offered to this tenant, or outside its reach, lists no versions, and a version that no longer resolves or whose payload is not an importable framework is left out. Refuses `BAD_REQUEST` when `packRef` is not a well-formed pack coordinate.",frameworkImportPreview:"One version of an offered framework pack as `frameworkImport` would write it: its framework, edition, requirements with translated schedules, suggested plans and the subject fact paths their subject rules read. Also returns `workProducerWarnings`: the Work producer codes the edition's evidence names that the tenant's Work lacks or that could not be checked, so this verb reads Work as well as the pack. `tenantRead`, the same authority as `frameworkImportBrowse`. Refuses `NOT_FOUND` when the pack is not offered to this tenant, is outside its reach, has no such version, or its payload is not an importable framework, and `BAD_REQUEST` when `packRef` is not a well-formed pack coordinate.","program.list":"List this tenant's programs with framework, pinned edition, owner and counts, cursor-paged. `tenantRead`. Refuses `BAD_REQUEST` for a cursor this read did not return.","program.get":"Get one program by id, the row `program.list` returns. `tenantRead`. Refuses `NOT_FOUND` when this tenant has no such program.","enrollment.list":"List stored enrollments under this tenant's programs, removed ones on request, cursor-paged. `tenantRead`. Refuses `BAD_REQUEST` for a cursor this read did not return.","enrollment.matchingSubjectsPreview":"Count the subjects a not-yet-stored criteria enrollment would admit. `tenantReadRunner`. Refuses `BAD_REQUEST` for criteria the determination judge cannot read, and `WORK_CLAUSE_CODE_INVALID` when the criteria carry a Work clause type that does not satisfy Work type code grammar.","enrollment.replacePreview":"Count who stays, enters, leaves or is undecided if one enrollment is replaced. `tenantReadRunner`. Refuses `WORK_CLAUSE_CODE_INVALID` for a replacement `work` clause off Work's code grammar, `BAD_REQUEST`, `NOT_FOUND` and `ENROLLMENT_ALREADY_REMOVED`.","plan.list":"List this tenant's plans with their current version's trigger and enforcement, cursor-paged. `tenantRead`. Refuses `BAD_REQUEST` for a cursor this read did not return.","plan.get":"Get one plan with its current version's content, open application and trigger-binding need. `tenantRead`. Refuses `NOT_FOUND` when this tenant has no such plan, `PLAN_STEP_EVIDENCE_REQUIREMENT_MISSING` when a stored step carries no `evidenceRequirement`, and `WORK_CLAUSE_CODE_INVALID` when the stored subject criteria or a step's evidence requirement carries a Work clause type that does not satisfy Work type code grammar.",frameworkCreate:"Mint a new content-tier Framework. Refuses `FRAMEWORK_CODE_TAKEN` when the publisher + code already names a framework for this tenant.",requirementCreate:"Create a requirement on a draft FrameworkVersion; a published edition is refused. `tenantWrite`, `edit` authority on `obligations.framework-version`. `key` is required and names the requirement across editions: restate the key a prior edition's requirement carries (read it with `requirement.list`) to continue that requirement; two requirements of one clause share a citation and differ in key. `citation` is required; on a `source_derived` requirement it is the locator of the clause the requirement comes from, exactly as the document numbers it (`Condition 4.2(b)`). It is provenance, never identity. `basis` is required: `source_derived` when `citation` locates a clause of the edition's source, `tenant_authored` otherwise. `action` is the duty the requirement imposes. `applicability` states which subjects the requirement binds and `evidenceRequirement` what evidence satisfies it. Both are requirement trees, where a node is exactly one of `{anyOf: [node, \u2026]}`, `{allOf: [node, \u2026]}`, a clause `{domain, type, match?}`, `{anyEvidence: true}` or `{attestationOnly: true}`. A clause names a subject (in `applicability`, e.g. `{domain: 'assets', type: 'asset', match: {'$facts.basin': 'permian'}}`) or an evidence record (in `evidenceRequirement`) by its `domain` and `type`, and matches one whose facts equal every scalar in `match`; without `match`, any one of that domain and type. `anyEvidence` is met by any evidence entry, and `attestationOnly` by the satisfying call itself with no evidence. A combinator is non-empty and a node carries no other key. A tree is capped at depth 5, 10 children per combinator and 64 nodes: one tree over a cap is refused `CAPS_EXCEEDED` and both trees over one `CAP_REFUSAL_MULTIPLE`, each naming the cap and the node's path. A `work` leaf's `type` and its category and template match codes must satisfy Work's code grammar, or the call refuses `WORK_CLAUSE_CODE_INVALID`. `retentionDuration` (an ISO 8601 duration such as `P7Y`) and `retentionFrom` are set together or not at all. Refuses `REQUIREMENT_KEY_TAKEN` when the edition already holds the key, `BASIS_MISMATCH` for a `source_derived` requirement on a `tenant_authored` edition or with a blank citation, `NOT_FOUND` when this tenant has no such version, `FRAMEWORK_VERSION_NOT_DRAFT` once it is published, and `BAD_REQUEST` when a database-backed requirement constraint such as retention pairing is violated.\n\n`applicability`/`evidenceRequirement` carry `RequirementNodeSchema` (`z.lazy`, D14/R48's `anyOf`/`allOf` tree), which the MCP `inputSchema` carries as local `$defs`.",requirementUpdate:"Revise a requirement on a still-draft FrameworkVersion: its trees, basis, key or citation. `tenantWrite`, `edit` authority on `obligations.requirement`. `applicability` and `evidenceRequirement` are required and replace the saved trees whole, in the grammar and under the caps `requirementCreate` describes, refused `CAPS_EXCEEDED`, `CAP_REFUSAL_MULTIPLE` or `WORK_CLAUSE_CODE_INVALID` the same way. An optional content field set to `null` clears its saved value (`tolerances` to an empty list); `key` and `citation` refuse `null`, since every requirement carries both. An omitted field leaves it as saved. A corrected `citation` keeps the requirement's `key`, so it stays the same requirement. `basis` is required and refuses `BASIS_MISMATCH` as on `requirementCreate`; a restated key the edition already holds refuses `REQUIREMENT_KEY_TAKEN`. Refuses `NOT_FOUND` when this tenant has no such requirement, `FRAMEWORK_VERSION_NOT_DRAFT` once its edition is published, and `BAD_REQUEST` when a database-backed requirement constraint such as retention pairing is violated. Same recursive-schema shape as `requirementCreate`.",frameworkVersionCreate:"Mint a new draft FrameworkVersion under an existing Framework. `tenantWrite`, `edit` authority on `obligations.framework`. The edition starts `draft`: add its requirements with `requirementCreate`, revise them with `requirementUpdate`, and read them back with `requirement.list`. `contentBasis` is required: `source_document` with its `source` when the edition is read from a document, which makes `frameworkPublish` demand the citation attestation, or `tenant_authored` when the tenant writes the content itself; `frameworkVersionSetContentBasis` changes it while the edition is a draft. The edition reaches tenants only through `frameworkPublish`, a `manage` verb authorized from the authenticated principal on every interface; the platform agent bar refuses that authority to an agent principal. Authoring through this verb changes neither who may publish nor what publish requires: the citation gate reads the declared content basis, and neither the calling interface nor the principal that drafted the edition is an input to it. `effectiveFrom`/`effectiveTo` are ISO civil dates bounding the edition's window. Refuses `NOT_FOUND` when `frameworkId` names no Framework this tenant has, and `BAD_REQUEST` when `effectiveTo` precedes `effectiveFrom`. Send `suggestedPlans` empty here: each suggestion's `requirementId` must name a requirement of this edition, which `frameworkPublish` checks, and those ids exist only once `requirementCreate` returns them, so author suggestions with `frameworkVersionSetSuggestedPlans` after that. A `suggestedPlans` list sent here is checked as that verb checks it: refuses `SUGGESTION_TRIGGER_INVALID` when a suggested plan is a schedule with no cadence, carries a cadence outside the RRULE subset, or is any trigger other than `schedule` and carries a cadence, `SUGGESTION_ID_DUPLICATE` when two suggested plans share an `id`, `SUGGESTION_CAPS_EXCEEDED` when a suggestion's `subjectCriteriaTemplate` or `evidenceClause` breaks a requirement-tree cap, `SUBJECT_CRITERIA_INVALID` when a `subjectCriteriaTemplate` is criteria `planCreate` refuses, and `WORK_CLAUSE_CODE_INVALID` when a suggestion's tree carries a `work` clause whose type or match codes break Work's code grammar.\n\n`suggestedPlans[].subjectCriteriaTemplate`/`evidenceClause` carry `RequirementNodeSchema` (`z.lazy`, D14/R48's `anyOf`/`allOf` tree), the recursive tree `requirementCreate` describes, which the MCP `inputSchema` carries as local `$defs`.",frameworkVersionSetSuggestedPlans:"Replace a draft FrameworkVersion's suggested plans with the authored list. A suggestion whose `id` is already stored keeps its stored `authoredBy`; a new one takes the value sent. Send `ai_draft` for a suggestion you drafted; it records provenance and does not gate publish. Each `subjectCriteriaTemplate` is a requirement tree in the subject form `planCreate` describes. Refuses `SUGGESTION_LIST_STALE` when the stored ids differ from `expectedSuggestionIds`, `SUGGESTION_TRIGGER_INVALID` when a suggested plan is a schedule with no cadence, carries a cadence outside the RRULE subset, or is any trigger other than `schedule` and carries a cadence, `SUGGESTION_ID_DUPLICATE` when two suggested plans share an `id`, `SUGGESTION_CAPS_EXCEEDED` when a suggestion's `subjectCriteriaTemplate` or `evidenceClause` breaks a requirement-tree cap, `SUBJECT_CRITERIA_INVALID` when a `subjectCriteriaTemplate` is criteria `planCreate` refuses (a `match` key that is neither a `$facts.` path nor `$asset.assetTypeId` with a lowercase UUID asset type id), `WORK_CLAUSE_CODE_INVALID` when a suggestion's tree carries a `work` clause whose type or match codes break Work's code grammar, `SUGGESTION_REQUIREMENT_UNKNOWN` when a suggestion names no requirement of this version, `NOT_FOUND` when this tenant has no such version, and `FRAMEWORK_VERSION_NOT_DRAFT` once the version is published. Same recursive-schema shape as `frameworkVersionCreate`, and equally reachable from CLI/MCP.",frameworkVersionSetContentBasis:"Change a draft FrameworkVersion's declared content basis. Refuses `NOT_FOUND` when this tenant has no such version, `FRAMEWORK_VERSION_NOT_DRAFT` once it is published, and `BASIS_MISMATCH` when it would leave a `source_derived` requirement on a `tenant_authored` edition.",frameworkPublish:"Publish a draft FrameworkVersion, freezing its requirement tree as the tenant-facing edition. `contentDigest` names the edition content the caller read and publishes: the SHA-256, in lowercase hex, of the JSON of `{ contentBasis, suggestedPlans, requirements }` with object keys sorted at every depth and no whitespace, where `contentBasis` and `suggestedPlans` are the edition's as `framework.get` returns them and `requirements` is every requirement of the edition as `requirement.list` returns it, less `createdAt`, sorted by `requirementId`. `framework.get` returns each edition's `contentDigest` over the same content: read `framework.get` first and keep its `contentDigest`, then read the content you review, so that anything changed after the digest was read refuses the publish. A caller that computes the digest itself computes it over exactly the content it read. Refuses `FRAMEWORK_VERSION_STALE` when the edition as stored no longer matches `contentDigest`, `FRAMEWORK_VERSION_OVERLAP` when its effective window collides with an already-published edition of the same Framework, `CITATION_CHECK_REQUIRED` when the edition's declared content basis is `source_document` and the call does not attest that its source-derived citations were checked against the source (`citationCheckCompleted: true`), and `WORK_CLAUSE_CODE_INVALID` when stored requirement or suggestion content carries a Work clause type that does not satisfy Work type code grammar, `SUGGESTION_REQUIREMENT_UNKNOWN` when a suggested Plan names no requirement of the edition, `NOT_FOUND` when this tenant has no such version, and `FRAMEWORK_VERSION_NOT_DRAFT` when it is already published. The attester recorded is the authenticated principal the call runs under. This `manage` verb is served over CLI/MCP under the same principal authority as every other interface.",frameworkImport:"Import a FrameworkVersion + requirement tree from a published pack. `tenantWrite`, `edit` authority on `obligations.framework`. A retry under an `idempotencyKey` that already committed returns that import's result before any refusal below is judged again. Refuses `NOT_FOUND` when the pack is not offered to this tenant, is outside its reach, or has no such version, `PACK_VERSION_RETIRED` when the version is retired (an item with no version still offered answers `NOT_FOUND`, R160), `PACK_PAYLOAD_INVALID` when the pack item's payload does not parse as a framework payload or a requirement's `applicability` or a suggestion's `subjectCriteriaTemplate` names an `$asset.` key (an asset type is tenant vocabulary, which a pack references none of), `CAP_REFUSAL_MULTIPLE` when any requirement in the payload violates a requirement-tree cap, `RRULE_MALFORMED` or `RRULE_INTERVAL_REQUIRES_BYMONTH` when a requirement's own cadence wording does not translate into this domain's RRULE subset, `FRAMEWORK_CODE_TAKEN` when the pack's publisher+code already names a `framework` row for this tenant, `SUGGESTION_REQUIREMENT_UNKNOWN` when a pack suggestion's `requirementKey` names no requirement key of the pack, `SUGGESTION_ID_DUPLICATE` when two pack suggestions share an `id`, `SUGGESTION_TRIGGER_INVALID` when a pack suggestion is a schedule with no cadence, carries a cadence outside the RRULE subset, or is any trigger other than `schedule` and carries a cadence, `SUGGESTION_CAPS_EXCEEDED` when a pack suggestion's tree breaks a requirement-tree cap, `SUBJECT_CRITERIA_INVALID` when a pack suggestion's `subjectCriteriaTemplate` is criteria `planCreate` refuses, `BASIS_MISMATCH` when a `source_derived` requirement sits on a `tenant_authored` pack edition or has a blank citation, and `WORK_CLAUSE_CODE_INVALID` when a requirement or suggestion tree in the pack carries a Work clause type that does not satisfy Work type code grammar, and `BAD_REQUEST` when `packRef` is not a well-formed pack coordinate, the pack's edition ends before it begins, or a requirement breaks one of its CHECK constraints. Stores the pack's own suggested plans as authored.",programCreate:"Enroll this tenant into a Program against a chosen framework, under a `name` (trimmed, 1\u2013120 characters) and an optional `description` (at most 1000; one that trims to empty is stored as none). The pack triple is supplied for a framework imported from a pack and omitted for one authored in the tenant. Refuses `PIN_REQUIRES_FRAMEWORK` when `pinnedFrameworkVersionId` is supplied without a `frameworkId` (the DB's own pairing CHECK, R103), and `PACK_PIN_INCOMPLETE` when only part of the pack triple is supplied. The pinned edition must be a published edition of `frameworkId`: another framework's edition, or an id this tenant does not have, is refused `PIN_VERSION_NOT_IN_FRAMEWORK`, and a draft is refused `PIN_VERSION_NOT_PUBLISHED`. With no pinned edition, a `frameworkId` this tenant does not have is refused `NOT_FOUND`. An `ownerPrincipal` that is no principal this tenant can use is refused `PRINCIPAL_NOT_ASSIGNABLE`.",programUpdate:"Update a program's own mutable fields (name, description, owner + pack pin) \u2014 never `status`/`archivedAt`, `programArchive`'s alone. An omitted field is left alone; a `description` of `null`, or one that trims to empty, clears it. Refuses `PACK_PIN_INCOMPLETE` when only part of the pack triple is supplied, `PRINCIPAL_NOT_ASSIGNABLE` when `ownerPrincipal` is no principal this tenant can use, and `NOT_FOUND` when this tenant has no such program.",enrollmentCreate:"Enroll a subject (e.g. an Asset) into a program, or a criteria-matched set. Refuses `ENROLLMENT_SCOPE_XOR_VIOLATION` when the explicit-subject triple and `criteria` are both or neither supplied, `WORK_CLAUSE_CODE_INVALID` when `criteria` carries a `work` leaf whose type or codes fail Work's code grammar (checked first), `SUBJECT_CRITERIA_INVALID` when `criteria` is not a requirement tree the determination judge can read (the subject form `planCreate` describes: `{domain: 'assets', type: 'asset'}` clauses with `$facts.`-prefixed `match` keys and `$asset.assetTypeId`), `NOT_FOUND` when this tenant has no such program, and `PRINCIPAL_NOT_ASSIGNABLE` when `enrolledByPrincipal` is no principal this tenant can use.",enrollmentRemove:"Remove a subject's enrollment \u2014 a soft removal: the row survives with `removedAt`/`removalReason` set. Refuses `NOT_FOUND` when this tenant has no such enrollment and `ENROLLMENT_ALREADY_REMOVED` when it was already removed.",enrollmentReplace:"Change an enrollment: record `replacement` as a new enrollment and remove `enrollmentId` with `removalReason`, as one governed act. The removed enrollment keeps its scope, basis, as-of date and enroller, and names its replacement; its governing-zone override carries to the replacement. The program's other enrollments are untouched, and subjects still enrolled keep their admissions. Refuses `ENROLLMENT_SCOPE_XOR_VIOLATION` unless the replacement names exactly one subject or one criteria clause, `WORK_CLAUSE_CODE_INVALID` for a `work` leaf off Work's code grammar, `SUBJECT_CRITERIA_INVALID` for criteria the judge cannot read, `PRINCIPAL_NOT_ASSIGNABLE` for an enroller this tenant cannot use, `NOT_FOUND` when this tenant has no such enrollment, `ENROLLMENT_ALREADY_REMOVED` for a removed one, and `ENROLLMENT_ROUTES_CHANGED` when the program's enrollments are no longer the ones `expectedScopeRevision` names. Refuses `BAD_REQUEST` for an `idempotencyKey` already spent on another enrollment, on another replacement, or by another caller.",enrollmentSetZoneOverride:"Override the resolved governing zone for one enrollment (zone-ladder rung 2, R98). Refuses `ZONE_INVALID` when `zone` names something other than an IANA time zone \u2014 a fixed UTC offset, or a name the platform's zone data does not carry. `zone: null` clears the override instead of setting one and is never validated against that. Refuses `NOT_FOUND` when this tenant has no such enrollment and `ENROLLMENT_ALREADY_REMOVED` when it was removed.",planCreate:"Author a new Plan + its first PlanVersion (a versioned obligation-generation rule). `subjectCriteria` and each step's `evidenceRequirement` are requirement trees in the grammar and under the caps `requirementCreate` describes; an attestation-only step declares `{attestationOnly: true}`. In `subjectCriteria` a clause names the subject by the EntityRef the determination judge compares, `{domain: 'assets', type: 'asset'}` for an Assets asset, and every `match` key is either a `$facts.`-prefixed path into that subject's facts, e.g. `{domain: 'assets', type: 'asset', match: {'$facts.basin': 'permian'}}`, or `$asset.assetTypeId` with a lowercase UUID Assets asset type id, which holds for an asset of that type; a clause naming any other domain or type matches no asset. Refuses `PLAN_CODE_TAKEN` when `(programId, code)` already names a plan for this tenant, and `NOT_FOUND` when `programId` or `source.frameworkVersionId` names nothing this tenant has. On save it refuses `RRULE_MALFORMED` when the schedule is not a well-formed RFC 5545 recur-value, `RRULE_UNSUPPORTED_TERM` when it carries COUNT, UNTIL, DTSTART, BYHOUR, BYMINUTE, BYSECOND, BYWEEKNO, BYYEARDAY or WKST, `RRULE_SUBDAILY_REFUSED` when its frequency is finer than daily, `RRULE_INTERVAL_REQUIRES_BYMONTH` when a daily or weekly cadence sets INTERVAL > 1 or a monthly or yearly one does so without an explicit BYMONTH, `TRIGGER_GAP_BOUNDS_INVALID` when a `periodic_with_gap` cadence sets `minGapDays` above `maxGapDays`, `ANCHOR_NOT_LIVE` when a step anchors on detection or triggerTime outside an event, work or condition plan or on an `event_window` one, `OFFSET_SIGN_INVALID` when a step sets a negative offset on a fixed-point anchor (windowStart, windowEnd, predecessorCompletion, detection or triggerTime), `ZONE_INVALID` when `fallbackZone` is not a valid IANA time zone, `PLAN_STEP_LEAD_DAYS_INVALID` when a step's `leadDays` violates its bounds (0-366, at most 6 entries, strictly descending), `CAPS_EXCEEDED` when `subjectCriteria` or a step's `evidenceRequirement` exceeds a tree cap, `SUBJECT_CRITERIA_INVALID` when a `subjectCriteria` `match` key is neither a fact path the determination judge can read nor `$asset.assetTypeId` with a lowercase UUID asset type id, `WORK_CLAUSE_CODE_INVALID` when `subjectCriteria` or a step's `evidenceRequirement` carries a Work clause type that does not satisfy Work type code grammar, `CALENDAR_NOT_FOUND` and `WORKING_DAY_OFFSET_OUT_OF_RANGE` for a working-day step no calendar walk can answer, `PLAN_STEP_PREDECESSOR_MISSING` for a chain step with no predecessor, `PLAN_STEP_ACTIVATE_WHEN_NOT_CHAINED` for an `activateWhen` off the chain, `PLAN_STEP_INDEX_DUPLICATED` for two steps sharing a `stepIndex`, `PLAN_STEP_FIELD_ANCHOR_NEEDS_NOT_AFTER` for a `predecessorField` step with no `notAfter`, `ANCHOR_CYCLE_IDENTITY_MISSING` for a scheduled `rolling_from_event` step anchored on an asset fact without a `cycleIdentityPath`, and `COVERS_REQUIREMENT_UNKNOWN` when `covers` names a requirement this tenant does not have. The trigger pair is one of `PlanVersionTriggerSchema`'s arms: `schedule` with a cadence or rolling schedule, `event`/`work`/`condition` with `rolling_from_event` or `event_window`, `manual` with none; any other pair fails input validation (`BAD_REQUEST`) and writes nothing.\n\n`subjectCriteria` and each `steps` entry's `evidenceRequirement` both carry `RequirementNodeSchema` (`z.lazy`, D14/R48's `anyOf`/`allOf` tree), which the MCP `inputSchema` carries as local `$defs`.",planRevise:"Author a new PlanVersion revising an existing Plan. `subjectCriteria` and each step's `evidenceRequirement` are requirement trees in the grammar and under the caps `requirementCreate` describes, `subjectCriteria` in the subject form `planCreate` describes. It runs `planCreate`'s save-time validation and inserts no `plan` row, so it never refuses `PLAN_CODE_TAKEN`. Refuses `NOT_FOUND` when `planId` names no plan this tenant has, and `ENFORCEMENT_GATE_NOT_ALLOWED_ON_PUBLISHED_CONTENT` when a plan carrying `source_pack_publisher` is revised to `gate`. On save it refuses `RRULE_MALFORMED` when the schedule is not a well-formed RFC 5545 recur-value, `RRULE_UNSUPPORTED_TERM` when it carries COUNT, UNTIL, DTSTART, BYHOUR, BYMINUTE, BYSECOND, BYWEEKNO, BYYEARDAY or WKST, `RRULE_SUBDAILY_REFUSED` when its frequency is finer than daily, `RRULE_INTERVAL_REQUIRES_BYMONTH` when a daily or weekly cadence sets INTERVAL > 1 or a monthly or yearly one does so without an explicit BYMONTH, `TRIGGER_GAP_BOUNDS_INVALID` when a `periodic_with_gap` cadence sets `minGapDays` above `maxGapDays`, `ANCHOR_NOT_LIVE` when a step anchors on detection or triggerTime outside an event, work or condition plan or on an `event_window` one, `OFFSET_SIGN_INVALID` when a step sets a negative offset on a fixed-point anchor (windowStart, windowEnd, predecessorCompletion, detection or triggerTime), `ZONE_INVALID` when `fallbackZone` is not a valid IANA time zone, `PLAN_STEP_LEAD_DAYS_INVALID` when a step's `leadDays` violates its bounds (0-366, at most 6 entries, strictly descending), `CAPS_EXCEEDED` when `subjectCriteria` or a step's `evidenceRequirement` exceeds a tree cap, `SUBJECT_CRITERIA_INVALID` when a `subjectCriteria` `match` key is neither a fact path the determination judge can read nor `$asset.assetTypeId` with a lowercase UUID asset type id, `WORK_CLAUSE_CODE_INVALID` when `subjectCriteria` or a step's `evidenceRequirement` carries a Work clause type that does not satisfy Work type code grammar, `CALENDAR_NOT_FOUND` and `WORKING_DAY_OFFSET_OUT_OF_RANGE` for a working-day step no calendar walk can answer, `PLAN_STEP_PREDECESSOR_MISSING` for a chain step with no predecessor, `PLAN_STEP_ACTIVATE_WHEN_NOT_CHAINED` for an `activateWhen` off the chain, `PLAN_STEP_INDEX_DUPLICATED` for two steps sharing a `stepIndex`, `PLAN_STEP_FIELD_ANCHOR_NEEDS_NOT_AFTER` for a `predecessorField` step with no `notAfter`, `ANCHOR_CYCLE_IDENTITY_MISSING` for a scheduled `rolling_from_event` step anchored on an asset fact without a `cycleIdentityPath`, and `COVERS_REQUIREMENT_UNKNOWN` when `covers` names a requirement this tenant does not have.",planEnable:"Enable a plan for generation. Refuses `NOT_FOUND` when this tenant has no such plan.",planDisable:"Disable a plan \u2014 stops future generation without deleting history. Refuses `NOT_FOUND` when this tenant has no such plan.",planCloneFromLibrary:"Clone a library (pack-provided) plan's current PlanVersion content into this tenant's own authored Plan + first PlanVersion \u2014 the same `insertPlanVersion` path and `PLAN_CODE_TAKEN` refusal `planCreate` carries, since both mint a fresh plan + version.\n\nThe cloned content is re-validated on save rather than trusted, so every `insertPlanVersion` refusal reaches this verb too. On save it refuses `RRULE_MALFORMED` when the schedule is not a well-formed RFC 5545 recur-value, `RRULE_UNSUPPORTED_TERM` when it carries COUNT, UNTIL, DTSTART, BYHOUR, BYMINUTE, BYSECOND, BYWEEKNO, BYYEARDAY or WKST, `RRULE_SUBDAILY_REFUSED` when its frequency is finer than daily, `RRULE_INTERVAL_REQUIRES_BYMONTH` when a daily or weekly cadence sets INTERVAL > 1 or a monthly or yearly one does so without an explicit BYMONTH, `TRIGGER_GAP_BOUNDS_INVALID` when a `periodic_with_gap` cadence sets `minGapDays` above `maxGapDays`, `ANCHOR_NOT_LIVE` when a step anchors on detection or triggerTime outside an event, work or condition plan or on an `event_window` one, `OFFSET_SIGN_INVALID` when a step sets a negative offset on a fixed-point anchor (windowStart, windowEnd, predecessorCompletion, detection or triggerTime), `ZONE_INVALID` when `fallbackZone` is not a valid IANA time zone, `PLAN_STEP_LEAD_DAYS_INVALID` when a step's `leadDays` violates its bounds (0-366, at most 6 entries, strictly descending), `CAPS_EXCEEDED` when `subjectCriteria` or a step's `evidenceRequirement` exceeds a tree cap, `SUBJECT_CRITERIA_INVALID` when a `subjectCriteria` `match` key is neither a fact path the determination judge can read nor `$asset.assetTypeId` with a lowercase UUID asset type id, `WORK_CLAUSE_CODE_INVALID` when `subjectCriteria` or a step's `evidenceRequirement` carries a Work clause type that does not satisfy Work type code grammar, `CALENDAR_NOT_FOUND` and `WORKING_DAY_OFFSET_OUT_OF_RANGE` for a working-day step no calendar walk can answer, `PLAN_STEP_PREDECESSOR_MISSING` for a chain step with no predecessor, `PLAN_STEP_ACTIVATE_WHEN_NOT_CHAINED` for an `activateWhen` off the chain, `PLAN_STEP_INDEX_DUPLICATED` for two steps sharing a `stepIndex`, `PLAN_STEP_FIELD_ANCHOR_NEEDS_NOT_AFTER` for a `predecessorField` step with no `notAfter`, `ANCHOR_CYCLE_IDENTITY_MISSING` for a scheduled `rolling_from_event` step anchored on an asset fact without a `cycleIdentityPath`, and `COVERS_REQUIREMENT_UNKNOWN` when `covers` names a requirement this tenant does not have. It also refuses `PLAN_STEP_EVIDENCE_REQUIREMENT_MISSING` when a cloned step carries no `evidenceRequirement` at all.\n\n`PLAN_TRIGGER_NOT_RUNNABLE` refuses a source version storing a trigger pair no plan can run on. `ENFORCEMENT_GATE_NOT_ALLOWED_ON_PUBLISHED_CONTENT` refuses a source whose version is `gate` while it carries `source_pack_publisher`, which the clone inherits. `NOT_FOUND` refuses a `libraryPlanRef` naming no plan, or a `programId` naming no program, this tenant has.",programPinVersion:"Pin the program to a specific published FrameworkVersion and/or pack version, recording the release delta as a pending `change_review` row.\n\nRefuses `PIN_TARGET_REQUIRED` when neither half of the new pin is supplied, and `PIN_REQUIRES_FRAMEWORK` when a framework-version pin is asked of a program that names no framework \u2014 the DB's own `program_pinned_version_requires_framework_check`, checked first for a clean refusal rather than a raw constraint hit (the `programCreate` convention). Refuses `PIN_REQUIRES_PACK` when a pack-version pin is asked of a program with no pack provenance, which would leave it carrying part of the pack triple. Refuses `PROGRAM_NOT_ACTIVE` for an archived program, whichever half is pinned. The new edition must be a published edition of the program's framework: another framework's edition, or an id this tenant does not have, is refused `PIN_VERSION_NOT_IN_FRAMEWORK`, and a draft is refused `PIN_VERSION_NOT_PUBLISHED`. A program whose current edition is a draft is refused `PIN_CURRENT_VERSION_NOT_PUBLISHED`, naming that edition, because a review names requirements by key and only a published edition's keys are frozen. A program this tenant does not have is refused `NOT_FOUND`. Every refusal writes nothing: the pin, the `change_review` row and the Record stay unwritten.",programArchive:"Archive a program \u2014 ends its active adoption without deleting history. Refuses `NOT_FOUND` when this tenant has no such program.",applicationCancel:"Cancel an application. Stamps `cancelledAt` regardless of window state (no open/closed guard \u2014 matches `planEnable`/`planDisable`, which refuse only a plan this tenant does not have). A repeat call re-stamps `cancelledAt` with the current time and re-runs the cascade; it is not a no-op. Refuses `NOT_FOUND` when this tenant has no such application.","application.apply":"Apply a plan to its resolved subject set, or preview it.\n\nThe output is discriminated on `mode`: the `applied` arm names the one application the call opened, the `preview` arm carries the version it previewed, the Program scope, the plan's applicability over it, and the occurrence counts of each currently applicable subject. Both arms carry the resolved `governingZone` and the rung that produced it.\n\nRefuses `APPLY_OVERLAP` for an overlapping live application, `ZONE_INVALID` naming the invalid governing-zone rung, `APPLY_WINDOW_INVALID` for an inverted window, and `ESTATE_WIDE_APPLY_REQUIRES_CONFIRMATION` when more subjects are currently applicable than the large-activation confirmation threshold allows unacknowledged. The applied arm refuses `PLAN_VERSION_CHANGED` when `expectedPlanVersionId` is no longer the plan's current version, and `PROGRAM_SCOPE_CHANGED` when `expectedScopeRevision` no longer matches the program's live enrollment routes. Refuses `REQUEST_EXPANSION_OVER_CAP` when the Program-scope candidates or a preview's expanded occurrences exceed what one request may hold \u2014 confirming a large activation (`confirmEstateWide`) does not lift it \u2014 and `WINDOW_BEYOND_HORIZON`, on both arms, for a window reaching more than `EXPANSION_HORIZON_YEARS` past today. The applied arm refuses `ADMISSION_SOURCE_CHANGED` (409, retryable) when the program's enrollments change while it resolves subjects. Refuses `PLAN_STEP_EVIDENCE_REQUIREMENT_MISSING` (409) when a stored plan-version step carries no `evidenceRequirement`, and `WORK_CLAUSE_CODE_INVALID` (409) when a stored work clause type does not satisfy Work type-code grammar. Refuses `NOT_FOUND` when this tenant has no such plan.","application.regenerate":"Move an open application onto its plan's current version \u2014 supersede the future occurrences the new version no longer produces, reopen those an earlier regenerate superseded that it produces again. The next `obligations.generate` tick creates new occurrences under that version.\n\nThe only path that clears an application's derived `stale` read. `planRevise` (`tenantWrite`) never calls it: moving an estate's live duties onto a new version is an administrative act (`tenantAdmin`), and the caller sees `planRevise`'s own preview delta before deciding to take it.\n\nA subject it cannot judge keeps its future occurrences, and a superseded future occurrence the new version produces again is reopened.\n\nRefuses `APPLICATION_NOT_OPEN` when the application is cancelled. Refuses `PLAN_VERSION_NOT_PUBLISHED` when the plan has no current version to move onto. Refuses `PLAN_VERSION_MOVED` when the plan published another version while this call expanded one; nothing is written, and a retry expands the current version. Refuses `REQUEST_EXPANSION_OVER_CAP` when the expansion, or the rows it would write, exceed what one request may hold, before any write. Refuses `PLAN_STEP_UNRESOLVABLE` (409) when the new version's steps do not carry a step an occurrence names, and `PLAN_STEP_EVIDENCE_REQUIREMENT_MISSING` (409) when a stored step carries no `evidenceRequirement`, and `WORK_CLAUSE_CODE_INVALID` (409) when a stored work clause type does not satisfy Work type-code grammar. Refuses `ADMISSION_SOURCE_CHANGED` (409) when the program's enrollments or the application change while it expands; nothing is written, and a retry expands afresh. Refuses `NOT_FOUND` when this tenant has no such application. The result counts every occurrence under the application by disposition.","application.confirmScope":"Confirm that an application applies to the subjects it now applies to, setting its confirmed count to `expectedApplicableCount`. Plan health reports an application whose applicable count grew past both the large-activation threshold and its confirmed count; this verb is the one that clears it. Duties keep generating whether or not anyone confirms.\n\nRefuses `APPLICATION_SCOPE_CHANGED` when the count the determine sweep last measured is not `expectedApplicableCount`, writing nothing; read the plan again and confirm the count it shows. Refuses `NOT_FOUND` when this tenant has no such application.","application.recordEvent":"Record a subject-side event (a detection, a work completion, a condition breach) against the plan's open application, materializing its occurrence(s) inline, using the call's `idempotencyKey` as their identity.\n\nRefuses `APPLICATION_NOT_OPEN` when no uncancelled application of the plan has opened, `APPLICATION_WINDOW_CLOSED` when the open one's window ended before today, `SUBJECT_REF_UNRESOLVED` when `subjectRef` names no single enrolled subject, `PLAN_NOT_EVENT_TRIGGERED` when the pinned version is not an `event`, `work` or `condition` plan storing an event shape \u2014 a `schedule` or `manual` plan, or a version stored with a pair no plan can run on, which `data.reason` names \u2014 and `EVENT_OUTSIDE_WINDOW` when the event's civil date (`triggeredAt`, or today without it) falls before the application's window opens or after it closes, `data.bound` naming the side. `EVENT_INSTANT_MISSING` when a `rolling_from_event` step is anchored on `triggerTime` or `detection` and the call carries no `triggeredAt` or `detectedAt`, refused before anything is expanded. Refuses `SUBJECT_NOT_APPLICABLE` when the resolved subject's plan-applicability determination has settled `not_applicable` or `indeterminate` \u2014 no occurrence materializes and no Record is written for it. `PLAN_STEP_UNRESOLVABLE` (409) and `PLAN_STEP_EVIDENCE_REQUIREMENT_MISSING` (409) when the pinned version's stored steps cannot be read for an occurrence. `DUE_DATE_OUTSIDE_CALENDAR_COVERAGE` (409) when a working-day step's due date falls outside its calendar's coverage. `ADMISSION_SOURCE_CHANGED` (409) when the program's enrollments or the application change while it judges; a retry judges afresh. A refusal rolls the request transaction back and writes no Record. `ANCHOR_UNRESOLVED` and `OCCURRENCE_COLLISION` surface as a `CONFLICT` carrying the code in `data`, the same channel `obligationCreate` uses for them.\n\n`.meta({ agenticSurface: 'excluded', agenticSurfaceReason: 'semantic' })`: semantic, because the verb has no manual use \u2014 a composition flow's verb step calls it when a `CompositionTriggerBinding` matches a Record. The verb remains callable over `/rpc` and `/api`.","determination.override":"Manually override a determination with an administrative reason. Refuses OVERRIDE_REASON_REQUIRED when no reason is supplied, CODELIST_TERM_UNKNOWN for an unknown or retired reason, REASON_CODE_RESERVED for system-only codes, and NOT_FOUND when this tenant has no such determination.","determination.revokeOverride":"Revoke a prior override, preserving its original outcome and inputs while reverting to the computed determination. Refuses NOT_FOUND when this tenant has no such determination, and DETERMINATION_NOT_OVERRIDE when it is not an override.","application.list":"List plan applications with their derived `stale`/`expired` state, cursor-paged. `tenantRead`. Refuses `BAD_REQUEST` for a cursor this read did not return.","determination.list":"List determination history for a subject, plan or application, latest first, cursor-paged. `tenantRead`. Refuses `BAD_REQUEST` for a filter naming no subject, plan or application, or a cursor this read did not return.",deviationDraft:"System-only: draft against an existing obligation. Requires a caller idempotencyKey. Refuses DEVIATION_DRAFT_SYSTEM_ONLY for a non-system principal, NOT_FOUND when this tenant has no such obligation, and BAD_REQUEST when the obligation is not the plan's.\n\n`.meta({ agenticSurface: 'excluded', agenticSurfaceReason: 'semantic' })`: semantic, because the verb has no manual use \u2014 the `obligations.deadlines` sweep and `obligationSatisfy` call it in-process under their system principals, and every wire caller, a flow step included, is refused. The verb remains mounted on `/rpc` and `/api`.",deviationRecord:"Record a deviation directly against an existing obligation. Requires a caller idempotencyKey. `DEVIATION_LIVE_EXISTS` when a live deviation of that kind already exists for the obligation, `NOT_FOUND` when this tenant has no such obligation, and `BAD_REQUEST` when the obligation is not the plan's.",deviationValidate:"Validate a draft, recording its regulatory metadata. Requires a caller idempotencyKey. Refuses NOT_FOUND when this tenant has no such deviation, DEVIATION_STATE_CONFLICT when it is not a draft, and BAD_REQUEST for a blank justification.",deviationVoid:"Void a draft deviation, with a reason code. Requires a caller idempotencyKey. Refuses VOID_REASON_REQUIRED when no reason code is supplied, CODELIST_TERM_UNKNOWN when the supplied reason code is absent or retired in this codelist, and REASON_CODE_RESERVED when it names a system-reserved code a human may not author, NOT_FOUND when this tenant has no such deviation, and DEVIATION_STATE_CONFLICT when it is not a draft.",deviationUpdate:"Update a deviation's own (non-lifecycle) fields. Refuses NOT_FOUND when this tenant has no such deviation, DEVIATION_STATE_CONFLICT when it is not open or under review, and BAD_REQUEST for a blank justification.",deviationReport:"Attach/finalize a deviation's report content. Refuses NOT_FOUND when this tenant has no such deviation, DEVIATION_STATE_CONFLICT when it is not open or under review, and DEVIATION_NOT_REPORTABLE when it was recorded as not reportable.",deviationClose:"Close a deviation, ending its lifecycle. Refuses DEVIATION_NOT_FILED when a reportable deviation has not yet been filed via `deviationReport`, NOT_FOUND when this tenant has no such deviation, and DEVIATION_STATE_CONFLICT when it is not under review or reported.",deviationMarkUnderReview:"Composition-owned open \u2192 under_review transition. Refuses NOT_FOUND when this tenant has no such deviation.\n\n`.meta({ agenticSurface: 'excluded', agenticSurfaceReason: 'semantic' })`: semantic, because the verb has no manual use \u2014 only a composition flow step calls it (R90(c), R272). The verb remains callable over `/rpc` and `/api`.",workLinkKindSet:"Make a Work link kind the current corrective link kind, and add it to the recognized kinds in the same write; no recognized kind is ever removed. `tenantAdmin`: it decides tenant-wide which completed work counts. Requires a caller idempotencyKey. Refuses `WORK_LINK_KIND_UNSUITABLE` when Work has no active kind with that code or the kind does not link to both deviations and obligations, `WORK_LINK_KIND_LIMIT_REACHED` (409) when the kind is new and the tenant already recognizes as many kinds as one Work read accepts (`WORK_LINKED_OBJECTS_RESOLVE_KINDS_MAX`), `LINKED_WORK_INACCESSIBLE` (403) when the caller cannot read Work, `LINKED_WORK_UNAVAILABLE` (503) when Work does not answer, and `BAD_REQUEST` for a malformed code or a key already spent on another kind.",workLinkKindGet:"The tenant's current corrective link kind and every kind it has recognized. `tenantRead`.",obligationCreate:"Directly author an obligation outside plan-driven generation. This manual intake creates one occurrence without a plan application. `PLAN_STEP_UNRESOLVABLE` when the named plan version has no stepIndex 0, `PLAN_STEP_EVIDENCE_REQUIREMENT_MISSING` (409) when a stored step of it carries no `evidenceRequirement`, `WORK_CLAUSE_CODE_INVALID` (409) when a stored work clause type does not satisfy Work type-code grammar, `NOT_FOUND` when this tenant has no such plan version, and `BAD_REQUEST` when the plan version is another plan's.",obligationUpdate:"Update an obligation's own (non-lifecycle) fields \u2014 owner-only. Refuses `NOT_FOUND` when this tenant has no such obligation, and `PRINCIPAL_NOT_ASSIGNABLE` when `ownerPrincipal` names no principal this tenant can use (`null` clears).",obligationCancel:"Cancel an obligation before it is satisfied, with a reason code. `ENDING_REASON_REQUIRED` when no reason is given, `CODELIST_TERM_UNKNOWN` when it names no term in this codelist, `REASON_CODE_RESERVED` when it names a system-reserved code a human may not author, `OBLIGATION_NOT_LIVE` when the obligation is not `OPEN` or `PENDING_REVIEW`, `NOT_FOUND` when this tenant has no such obligation.",obligationExempt:"Mark an obligation exempt, with a reason code. `ENDING_REASON_REQUIRED` when no reason is given, `CODELIST_TERM_UNKNOWN` when it names no term in this codelist, `REASON_CODE_RESERVED` when it names a system-reserved code a human may not author, `OBLIGATION_NOT_LIVE` when the obligation is not `OPEN` or `PENDING_REVIEW`, `NOT_FOUND` when this tenant has no such obligation.",obligationMarkNotApplicable:"Mark an obligation as not applicable to its subject, with a reason code. `ENDING_REASON_REQUIRED` when no reason is given, `CODELIST_TERM_UNKNOWN` when it names no term in this codelist, `REASON_CODE_RESERVED` when it names a system-reserved code a human may not author, `OBLIGATION_NOT_LIVE` when the obligation is not `OPEN` or `PENDING_REVIEW`, `NOT_FOUND` when this tenant has no such obligation, or no determination the supplied `determinationId` names, and `BAD_REQUEST` when that determination is not the obligation's deciding `not_applicable` determination at the call's instant or, for an obligation with no application, is not an override.",obligationSatisfy:"Satisfy an obligation with evidence entries. This verb can run in a composition. Evidence outside the current window is credited to the prior one instead of refusing (`OUT_OF_WINDOW_CREDIT_MOVED` \u2014 behavior, not a hard refusal). The answer names the obligation where the satisfaction was recorded and, as `outcome`, whether that was the named obligation, an earlier occurrence, or retained surplus on the named obligation. `PLAN_STEP_UNRESOLVABLE` when the obligation's materialized evidence requirement is not a valid requirement tree, and `PLAN_STEP_EVIDENCE_REQUIREMENT_MISSING` (409) when a stored step of its plan version carries no `evidenceRequirement`. `OBLIGATION_NOT_LIVE` when the obligation, or the prior window the evidence is credited to, is not `OPEN` or `PENDING_REVIEW` \u2014 an ended or already satisfied obligation is never satisfied again. `NOT_FOUND` when this tenant has no such obligation. `WORK_CLAUSE_CODE_INVALID` (409) when a stored work clause type does not satisfy Work type-code grammar. For Work evidence, `WORK_COMPLETION_NOT_ESTABLISHED` (400) means the reference is not a Work Record or Work says it does not establish a completion, with `evidenceIndex` naming the refused entry's position in `evidence`; `WORK_COMPLETION_INACCESSIBLE` (403) means the caller cannot access the completion; `WORK_COMPLETION_BUDGET_EXCEEDED` (422) means Work could not verify the cited completions within its transaction budget, so cite fewer; and `EVIDENCE_SOURCE_UNAVAILABLE` (503) means the Work source is missing or unavailable, and a retry can succeed. Where the evidence cites a verified Work completion, the act time is Work's, as `ObligationSatisfyInputSchema` describes. `BAD_REQUEST` when an evidence entry's `attested` fields name `ref`, `sourceType`, `verified` or `displayDetails`; when an entry carries its own `verified` block; when the evidence cites more than 500 Work completion references; or when the idempotency key was already used for a different obligation.",obligationSatisfyFromWork:"Offer a Work completion Record to every obligation its completed items link to under a link kind the tenant recognizes, in one transaction. `tenantWrite`, composable: a flow maps `$record.id` from a Work completion. Requires a caller idempotencyKey; a replay answers the first call's summary.\n\nEach obligation is decided on its own: its evidence policy writes an accepted, review-required or surplus satisfaction, on the earlier occurrence of its series when the completion falls before its window (`creditedObligationId`). Surplus retains evidence on the named obligation without changing its status, so a consumer must branch on `outcome` rather than infer review-required from an unchanged `OPEN` status. An `already-satisfied`, `ended`, `duplicate-evidence` or `refused` outcome writes nothing. Those outcomes describe the run's decision, not merely the named row's starting status: early evidence offered to a satisfied or ended named row can still redirect to an earlier open occurrence. The run refuses whole with `NOT_FOUND` for a Record this tenant does not have, `WORK_COMPLETION_INACCESSIBLE` / `LINKED_WORK_INACCESSIBLE` (403) when the caller cannot read Work, `EVIDENCE_SOURCE_UNAVAILABLE` / `LINKED_WORK_UNAVAILABLE` (503) when Work does not answer, `WORK_COMPLETION_BUDGET_EXCEEDED` (422), `LINKED_WORK_NOT_CONFIGURED` (424) when Work lacks the tenant's current link kind, and `BAD_REQUEST` for a key already spent on another Record.",obligationExtend:"Extend an obligation's due window. Requires a tenant administrator. `OBLIGATION_NOT_LIVE` when the obligation is not `OPEN` or `PENDING_REVIEW`, `NOT_FOUND` when this tenant has no such obligation.",satisfactionAccept:"Accept a pending satisfaction. The reviewer is the signed-in caller, not a body field, and `reviewRationale` is required. Refuses `REVIEW_STATE_CONFLICT` when the satisfaction's review state is already terminal (accepted or rejected), and `SURPLUS_EVIDENCE` when the evidence is retained outside this obligation's window. Refuses `OBLIGATION_ENDED` when its obligation is cancelled, exempted, not applicable or superseded \u2014 a superseded occurrence's pending satisfaction is reviewable once a regenerate reopens it. Refuses `PLAN_STEP_EVIDENCE_REQUIREMENT_MISSING` (409) when a stored step of the obligation's plan version carries no `evidenceRequirement`, `WORK_CLAUSE_CODE_INVALID` (409) when a stored work clause type does not satisfy Work type-code grammar, and `NOT_FOUND` when this tenant has no such satisfaction.",satisfactionReject:"Reject a pending satisfaction. `reasonCode` and `reviewRationale` are distinct fields. Refuses `REVIEW_STATE_CONFLICT` when its review state is already terminal, `OBLIGATION_ENDED` when its obligation is cancelled, exempted, not applicable or superseded, `CODELIST_TERM_UNKNOWN` when the reason code names no term in this codelist, `REASON_CODE_RESERVED` when it names a system-reserved code a human may not author, and `NOT_FOUND` when this tenant has no such satisfaction.","obligation.explain":"Explain an obligation's current state: its generating plan version, the citations and determination inputs behind it, its generation trace, and its evidence-retention date, by obligation id. Refuses `NOT_FOUND` for an obligation this tenant does not have. `tenantRead`.","determination.explain":"Explain why a determination resolved the way it did: the plan/subject it was computed for, its inputs and outcome, the facts it consulted with their recorded values, and any human override, by determination id. Refuses `NOT_FOUND` for a determination this tenant does not have. `tenantReadRunner`.","determination.explainMany":"Explain several determinations in one read: `determination.explain`'s payload per id, in request order, the Assets revisions read once per subject. Refuses `NOT_FOUND` for the whole request when any id is not this tenant's, and `BAD_REQUEST` for no ids or more than `DETERMINATION_EXPLAIN_MANY_MAX`. `tenantReadRunner`.","obligation.get":"Fetch one obligation by id \u2014 the same full row `obligation.list` returns; refuses `NOT_FOUND` for an obligation this tenant does not have. Its `hasLinkedWork` is read from Work under the caller's own access: refuses `LINKED_WORK_INACCESSIBLE` (403) for a caller without Work read and `LINKED_WORK_UNAVAILABLE` (503) when Work does not answer, and `LINKED_WORK_NOT_CONFIGURED` (424) when the tenant's Work lacks the corrective link kind. `tenantRead`.","obligation.history":"Fetch an obligation's status-transition history: the committed obligations Records naming it in `effects`, each with the status it moved the obligation to, oldest first, whole (no cursor). `truncated` marks a history whose oldest entries the drain bound dropped. `tenantRead`.","obligation.advisoryVerdict":"Check candidate evidence against this obligation's stored evidence requirement, writing nothing; the out-of-window redirect is not modelled. Refuses `NOT_FOUND`, `OBLIGATION_NOT_LIVE` and `PLAN_STEP_UNRESOLVABLE`. `WORK_CLAUSE_CODE_INVALID` (409) means a stored work clause type does not satisfy Work type-code grammar. For Work evidence, `WORK_COMPLETION_NOT_ESTABLISHED` (400) means the reference is not a Work Record or Work says it does not establish a completion, with `evidenceIndex` naming the refused entry's position in `evidence`; `WORK_COMPLETION_INACCESSIBLE` (403) means the caller cannot access the completion; `WORK_COMPLETION_BUDGET_EXCEEDED` (422) means Work could not verify the cited completions within its transaction budget, so cite fewer; and `EVIDENCE_SOURCE_UNAVAILABLE` (503) means the Work source is missing or unavailable, and a retry can succeed. `BAD_REQUEST` refuses caller-supplied verified facts, reserved attested fields, or more than 500 Work completion refs. `tenantRead`.","obligation.list":"List the obligations this tenant can see, earliest due first, cursor-paged and filterable by status/subject/plan/predecessor obligation and by civil due date (`dueFrom`/`dueTo`, both ends inclusive) or by a window holding the due date, the occurrence's own date or the stored window end (`dueOrOccurrenceWindow`, which takes precedence over `dueFrom`/`dueTo`). Refuses `AS_OF_IN_FUTURE` for an `asOf` no time zone has reached, and `BAD_REQUEST` for a cursor this read did not return. Each row's `hasLinkedWork` is read from Work under the caller's own access: refuses `LINKED_WORK_INACCESSIBLE` (403) for a caller without Work read and `LINKED_WORK_UNAVAILABLE` (503) when Work does not answer, and `LINKED_WORK_NOT_CONFIGURED` (424) when the tenant's Work lacks the corrective link kind. `tenantRead`.","projection.list":"Project a plan's would-be occurrences over a civil window, cursor-paged, writing nothing, with the subjects its enrollments could not decide \u2014 and so did not project \u2014 named on every page (`undecided`). A plan that does not exist or is not visible is refused `NOT_FOUND`; a window wider than `PROJECTION_WINDOW_MAX_DAYS` `PROJECTION_WINDOW_EXCEEDED`; one reaching more than `EXPANSION_HORIZON_YEARS` past today `WINDOW_BEYOND_HORIZON`; an expansion past the request cap `REQUEST_EXPANSION_OVER_CAP`; an unresolvable governing zone `ZONE_INVALID`; and a stored plan step it cannot resolve, or that names no evidence requirement, `PLAN_STEP_UNRESOLVABLE` or `PLAN_STEP_EVIDENCE_REQUIREMENT_MISSING`; `WORK_CLAUSE_CODE_INVALID` (409) for a stored work clause type that does not satisfy Work type-code grammar; a cursor this read did not return `BAD_REQUEST`. `tenantRead`.","deviation.list":"List deviations newest first, cursor-paged, filterable by status and obligation. Refuses `BAD_REQUEST` for a cursor this read did not return. `tenantRead`.","deviation.get":"Fetch one deviation by id \u2014 the same row `deviation.list` returns; refuses `NOT_FOUND` for a deviation this tenant does not have. `tenantRead`.","satisfaction.reviewQueue":"List satisfactions awaiting evidence review on reviewable obligations, oldest first, cursor-paged. Refuses `BAD_REQUEST` for a cursor this read did not return. `tenantRead`.","satisfaction.list":"List one obligation's satisfactions, oldest first, cursor-paged, whatever their `reviewState`. Refuses `BAD_REQUEST` for a cursor this read did not return. `tenantRead`.",creditOverride:"Manually override a computed credit relationship. Rewrites the one 1:1 credit row in place \u2014 never a second row \u2014 recording the reason code and the optional free-text elaboration behind the decision, and keeping the assignment, reason code and detail it replaced as `replaced`. `tenantAdmin`. Requires a caller idempotencyKey. Refuses CREDIT_OVERRIDE_REASON_REQUIRED when no reason code is supplied, CODELIST_TERM_UNKNOWN when the supplied reason code is absent or retired in this codelist, REASON_CODE_RESERVED when it names a system-reserved code a human may not author, CREDIT_REQUIREMENT_MISMATCH when the credit does not carry the requirement the override names, and NOT_FOUND when this tenant has no such credit.",changeReviewDecide:"Decide the listed items of a pending change review. `tenantAdmin`. Requires a caller idempotencyKey.\n\nDecisions are recorded PER ITEM: one call may accept one item and defer a sibling, and a review is decided incrementally across as many calls as the tenant needs. `accept` and `reject` settle an item; `defer` records the tenant's position and HOLDS that item open, so `status` flips to `decided` only once every entry in `affected_items` is accepted or rejected, and a deferred item may be decided by a later call. A suggestion-provenance item is decided the same way, and deciding it regenerates nothing \u2014 revising or retiring the named Plan is that Plan's own verbs' act.\n\nAn accepted or rejected requirement item regenerates every open application of this review's program whose plan covers the requirement the item's `requirementRef` names in either of the review's editions \u2014 by key, or by citation in a review written by a server built before requirement keys: a plan not yet revised still covers the old edition's row, and a requirement the new edition removed has only that row. Each is filed as its own `applicationRegenerate` under the key `<idempotencyKey>/regenerate/<planApplicationId>`; occurrences whose window has opened keep their plan version. An accepted item may add `extendOpenOccurrences` \u2014 the new due date plus the `basis` and `citation` the deadline moved under \u2014 and every live occurrence under those applications due on or after the new edition's effective date and before the new due date is extended through `obligationExtend` under `<idempotencyKey>/extend/<obligationId>`; a duty that fell due under the earlier edition keeps its date and its overdue stamp.\n\nRefuses CHANGE_REVIEW_AFFECTED_ITEMS_UNREADABLE when the review's stored `affected_items` do not parse, CHANGE_REVIEW_ITEM_UNKNOWN when a decision names an item the review does not carry, CHANGE_REVIEW_ITEM_ALREADY_DECIDED when it names one already accepted or rejected, and CHANGE_REVIEW_ITEM_DUPLICATE when one call names the same item twice, CHANGE_REVIEW_EXTEND_REQUIRES_ACCEPT when an extension rides a deferred or rejected item, and CHANGE_REVIEW_EXTEND_OVERLAP when two extensions reach the same open occurrence. Refuses REQUEST_EXPANSION_OVER_CAP when the decision would regenerate more applications, or extend more occurrences, than one request may hold. A child regenerate's APPLICATION_NOT_OPEN, PLAN_VERSION_MOVED, REQUEST_EXPANSION_OVER_CAP, PLAN_STEP_UNRESOLVABLE, PLAN_STEP_EVIDENCE_REQUIREMENT_MISSING and ADMISSION_SOURCE_CHANGED reach this caller as they are and roll the decision back with them, as does a child extension's OBLIGATION_NOT_LIVE when an occurrence it selected ends before the extension locks it. Refuses NOT_FOUND when this tenant has no such review. Refuses WORK_CLAUSE_CODE_INVALID when a stored `work` clause type does not satisfy Work's type-code grammar.\n\nReplaying the idempotency key returns the ORIGINAL receipt, so a key re-sent after the review has moved on answers the `status` its own call produced \u2014 never a fresh read of the row.",frameworkDraftFromDocument:'Start a framework draft from a source document (a permit, regulation or policy), for a person to review and publish. This is the first call of the document workflow; it writes a new framework and one unpublished edition whose content basis is `source_document` with `documentRef` as its source, and no requirements. `tenantWrite`, `edit` authority on `obligations.framework`.\n\nWorkflow:\n 1. Read the whole document yourself. Nothing uploads it; only what you send is kept.\n 2. Call this once: `kind` (`permit` for a permit), `code` (the document\'s own number),\n `title`, `jurisdiction`/`authority` when stated, `editionLabel` (the revision or\n issue it names), `effectiveFrom` (`YYYY-MM-DD`; `effectiveTo` only when it states an\n end), and `documentRef`: `{"kind":"url","url":\u2026}`, or `{"kind":"document","name":\u2026}`\n with the file name you were given when it has no URL.\n 3. For each obligation the document imposes, call `requirementCreate` once with the\n returned `frameworkVersionId` and `basis` `source_derived`: `key` is a name of your\n own for that obligation, unique within the edition (`sec-4.2b-inspect`); `citation`\n is the locator of the clause it comes from, exactly as the document numbers it\n (`Condition 4.2(b)`), never a paraphrase, and several obligations may cite one\n clause under different keys;\n `action` is the verb it demands; the applicability and evidence trees and any\n schedule, retention, tolerances or consequence note come from that clause.\n 4. Correct a requirement with `requirementUpdate`, restating its `basis`; a corrected\n `citation` keeps its `key`. Everything stays editable until publish.\n 5. Nothing written so far is live. A person checks every source-derived citation\n against the source and explicitly confirms the check. The assistant must not set\n `citationCheckCompleted: true` on its own judgement. Publishing is the separate\n `frameworkPublish` `manage` call: read `framework.get` first and keep the edition\'s\n `contentDigest`, then read the requirements with `requirement.list`. An authorized\n caller submits the person\'s attestation and that digest; the call refuses\n `FRAMEWORK_VERSION_STALE` if content changed after the digest was read. It records\n the publishing principal and actual time as the citation check.\n\nExample \u2014 step 2 for a two-condition air permit:\n `{"kind":"permit","code":"AQ-1234-R2","title":"Example Compressor Station Air Permit",\n "authority":"Example State DEQ","editionLabel":"Revision 2","effectiveFrom":"2025-03-01",\n "documentRef":{"kind":"url","url":"https://example.org/permits/aq-1234-r2.pdf"},\n "idempotencyKey":"<a new UUID>"}`\nthen one `requirementCreate` per obligation, each with `basis` `source_derived`, e.g. `key` `cond-5.1-inspect`, `citation` `Condition 5.1`, `action` `inspect`, and `key` `cond-7.3b-report`, `citation` `Condition 7.3(b)`, `action` `report`.\n\nRefuses `FRAMEWORK_CODE_TAKEN` when the code already names a framework this tenant publishes, `BAD_REQUEST` when `effectiveTo` is before `effectiveFrom`, and `KEY_PARAM_MISMATCH` when the key was spent on another draft.',"credit.list":"List credits with each requirement's key and citation, in id order, cursor-paged. Refuses `BAD_REQUEST` for a cursor that does not decode to a row id. `tenantRead`.","changeReview.list":"List change reviews oldest first, cursor-paged, filterable by program and status. Refuses `BAD_REQUEST` for a cursor this read did not return. `tenantRead`.","changeReview.impact":"Count what each requirement item of one change review affects in the register today. Refuses `NOT_FOUND` for a review this tenant does not have. `tenantRead`.","export.auditPack":"Generate a subject's audit pack for a period and return it inline. Refuses `OVER_CAP` for a selection larger than one pack may carry and `AS_OF_IN_FUTURE` for an `asOf` no time zone has reached. `tenantRead`.","posture.summary":"Count the Posture tiles for the tenant, each program and each subject under it. Refuses `OVER_CAP` for an `asOf` over more obligations than one read may reconstruct and `AS_OF_IN_FUTURE` for an `asOf` no time zone has reached. Refuses `WORK_CLAUSE_CODE_INVALID` when a stored `work` clause type does not satisfy Work's type-code grammar. `tenantRead`.","register.sectionCounts":"Count a program's Register sections \u2014 needs-attention, in-progress, recently-satisfied, upcoming and history \u2014 by the predicate the Register itself groups by. In-progress is read from Work under the caller's own access: refuses `LINKED_WORK_INACCESSIBLE` (403) for a caller without Work read and `LINKED_WORK_UNAVAILABLE` (503) when Work does not answer, and `LINKED_WORK_NOT_CONFIGURED` (424) when the tenant's Work lacks the corrective link kind. Refuses `WORK_CLAUSE_CODE_INVALID` when a stored `work` clause type does not satisfy Work's type-code grammar. `tenantRead`."},insights:{metricCreate:"Create a Metric \u2014 enters with a Draft v1.",metricRevise:"Revise a Metric \u2014 mint the next immutable version, Draft.",metricDescribe:"Set or clear a Metric's description, on the metric itself: no version is minted, and the edit files a Record under the caller's key. Needs the same permission as revising a metric.",metricPublish:"Publish a MetricVersion \u2014 Draft\u2192Published, in place; only Published is consumable (F-M3).",metricRetire:"Retire a MetricVersion \u2014 Published\u2192Retired, in place (F-M3).",thresholdRuleCreate:"Create a ThresholdRule \u2014 active immediately; returns the view + freshness disclosure (F-T1).",thresholdRuleRevise:"Revise a ThresholdRule \u2014 edit name/condition/severity in place, full-replace.",thresholdRuleDelete:"Delete a ThresholdRule \u2014 the rule row goes; its RuleEvents survive (F-T5, P14 rider).",metricList:"List every Metric identity visible to the tenant, with its latest-Published ordinal.",metricPaletteList:"The Solution builder's Metrics tab: published metrics only, searched and ordered by name in SQL, at most `METRIC_PALETTE_LIST_CAP` of them, with the count that matched.","datasetUses.list":"The metrics reading an asked dataset. `canSwitch` is the `metricRevise` check, or the `metricPublish` check when a staged draft that IS the switch waits to be published.","datasetUses.switch":"`metricRevise` from the latest PUBLISHED definition with its references to `from` moved to `to` (unpinned), then `metricPublish` \u2014 both as the caller, each filing its Record; a staged draft that is exactly that switch is published instead. A caller who may not publish gets the new version as a draft (`outcome: 'left-as-draft'`). A metric already reading `to` answers `switched`, writing nothing. Refuses NOT_FOUND for an unknown metric (or one with nothing live), CONFLICT `DATASET_USE_MOVED`, `DATASET_USE_DRAFT_IN_PROGRESS`, `DATASET_USE_ATTESTED` and `DATASET_USE_TARGET_MISMATCH`.",metricGet:"Fetch one Metric + all its versions by durable `metricId` (F-M4 detail).",ruleEventList:"RuleEvent history \u2014 by rule or by metric, the PR F drill path (F-T5 read surface). BOUNDED: answers the newest `limit` events (1\u2013500, and 500 when omitted) plus `total`, the uncapped count for that rule or metric. A `total` above `items.length` is the only signal older history exists and is not shown; there is no cursor, so the older events are not reachable here.",thresholdRuleList:"A metric's ThresholdRules \u2014 the read that makes a threshold DRAWABLE.\n\n**A new read surface, and the reason it is one:** the contract carried create/revise/delete and no way to discover a rule, and `MetricViewSchema` does not embed them \u2014 so a widget holding a `MetricId` could not learn there was a threshold at all, which is why no chart drew one even though rules evaluate in the background and raise severity-tagged events. Embedding rules on `MetricViewSchema` was the alternative and was rejected: it widens a read every consumer already parses for the benefit of one, and ties a metric's identity to its watching configuration.\n\nBY METRIC only (`WidgetProps.binding` carries no other identity) and BOUNDED at `THRESHOLD_RULE_PAGE_MAX_ITEMS` with a `total`, mirroring `ruleEventList`'s truncation signal \u2014 a chart silently missing a threshold looks fine, which is exactly why the signal has to exist.",watchList:'The TENANT-WIDE watch surface (QA-F) \u2014 every ThresholdRule the tenant holds, the metric each watches BY NAME, and its per-series held state.\n\n**Why a second rules read.** `thresholdRuleList` answers "what watches THIS metric", which is the question a chart placement asks. The Watchtower board asks "what is this tenant watching, and what is wrong right now" \u2014 and nothing could answer it: the only route was fanning `thresholdRuleList` over `metricList` client-side, which is N+1 requests, N boundaries, and a state count that is wrong while any one is in flight. Widening `thresholdRuleList` instead was rejected on both halves of its shape: its `metricId` would have to become optional (which a lenient parse strips \u2014 the hazard its own `strictObject` docblock argues), and its output would grow a metric-name join plus a per-series query that every chart on every dashboard would pay for and draw nothing from.\n\n**The NAME is for the CAPABILITY, not the entity, and that is deliberate.** Reads here are entity-prefixed (`metricList`/`metricGet`/`ruleEventList`/`thresholdRuleList`) because the domain has three entities and the prefix keeps the flat surface unambiguous. An entity-prefixed name is unavailable and would be wrong here on both counts: `thresholdRuleList` is taken by the read this one is NOT a variant of, and a row is more than a ThresholdRule (it carries another entity\'s name and a grain the rule row does not hold). So it is named for what the module calls the capability \u2014 **watching** \u2014 which is also the route (`/insights/watching`), the tab and the CTA vocabulary. `dimensionValues` is the standing precedent for a read named for the question rather than the entity. Grammar stays inside R5 (`verbNoun`, lowerCamelCase, no preposition) and keeps R1\'s canonical head verb: it IS a list.\n\n**COMPLETE OR REFUSED \u2014 the one place this diverges from its two sibling reads.** `ruleEventList` and `thresholdRuleList` both truncate-and-disclose, which is honest for a chart drawing decoration. This read\'s consumer GROUPS BY STATE AND COUNTS, so a truncated page becomes a confidently wrong number ("3 breaching" when there are forty) rather than a visibly partial picture \u2014 the `DIMENSION_VALUES_TOO_MANY` situation exactly. So it takes that posture: past `WATCH_LIST_MAX_ITEMS` (500) it refuses (`WATCH_LIST_TOO_MANY`, `BAD_REQUEST`) rather than answering a prefix, and therefore carries neither a `limit` nor a `total` \u2014 both describe a page, and this read has none.\n\nNO INPUT, like `metricList`: the scope is the tenant, and the tenant comes from RLS. A read, not a verb: it records nothing.',query:"The widget data path \u2014 a Metric's series over a UTC window (F-E1/F-E5). A `live` metric is compiled to the platform's generic-fold IR and executed client-side; a `verbatim` one is served from its bound promoted version, never recomputed. Returns series carrying their own unit + dimension metadata, with `state: 'empty'` making \"no data in range\" distinct from a failed fetch. A read, not a verb: it records nothing.\n\n`assetScope` narrows the figures to the assets a page's Assets filters name, each dataset by its own asset column, every dataset or none. A kind the metric cannot apply is named in `assetScopeUnapplied` on either arm, and its figures are not narrowed by it; a scope past what one read can carry refuses `ASSET_SCOPE_TOO_LARGE`, and unreadable column tags refuse `ASSET_SCOPE_UNAVAILABLE` \u2014 never a truncated or unfiltered figure. The two drills take the scope the figure applied, and refuse `ASSET_SCOPE_UNSUPPORTED` for one it could not. Past its answer bound it refuses `ANSWER_DEADLINE_EXCEEDED` (422), and the fold it was running is stopped.",metricPreview:"PREVIEW an unsaved definition \u2014 the same figures `query` would serve, for a definition that has not been created yet.\n\nWhy it exists at all: only a PUBLISHED version resolves, so a DRAFT is unreachable through a `MetricRef` \u2014 and preview-before-publish is a hard authoring guardrail, not a convenience. Without this read an author's only way to see what a definition computes is to publish it, which is the reverse of the order that keeps a wrong metric off a dashboard.\n\nA separate procedure rather than a ref-or-definition arm on `query`: widening that input would make every existing consumer's type a union and put an unsaved definition on the path that owns version resolution and the result cache.\n\nA READ, and it writes nothing \u2014 no Record, no version, no cache entry. The fold, the verbatim serve, the units boundaries and the CONSUMER-side promotion gate are the same code `query` walks, so a preview can never answer figures a published metric could not (and can never serve an ungoverned load).\n\nWhy a CUSTOM verb: `get` names the saved-definition read and `query` names folding a SAVED metric's series; evaluating a definition that does not exist yet is neither, and a canonical verb would misdescribe it. Reads here are entity-prefixed across the domain's three entities, so `metricPreview` sits beside `metricList`/`metricGet` rather than coining a second idiom. Past its answer bound it refuses `ANSWER_DEADLINE_EXCEEDED` (422), and the fold it was running is stopped.",metricSupportingRows:"The DRILL-DOWN read behind a chart point / KPI \u2014 a bounded page of the rows a Metric's figure was computed from, over the window the ask names and at the dataset version the Metric's ref resolves to.\n\nIt walks the same resolve \u2192 promotion-gate \u2192 serve path as `query`, and it takes the SAME ask (`ref`/`range`/`grain`/`dimensionFilters`) a widget's query carries, so the rows it opens are selected by exactly the window and the predicates the number on screen was served with \u2014 narrowed to one data point by `members` (the clicked series' dimension members) and `bucket` (the clicked point's period start; a row instant on a verbatim Metric).\n\nBOUNDED, twice: the engine bounds the read \u2014 an aggregated drill with no `members`, while `start + take` \u2264 10,000, reads only its first `start + take` rows plus one count when more match; any other drill refuses `RESULT_TOO_LARGE` past the engine's guardrail rather than truncating \u2014 and `rows: { start, take }` pages what crosses the wire \u2014 default 100, a `take` past 1,000 refused, a `start` past the end an empty page with `totalRows` intact. The result echoes the `source` version it READ at, which is what makes the provenance checkable \u2014 a follow-latest ref (`versionId` absent) re-resolves per read, so a promotion between two reads moves it and the echo is how a caller SEES that. A read, not a verb: it records nothing.\n\nWhy a CUSTOM verb: `get` names the definition detail and `query` names folding the series; opening the rows behind one figure is neither, and reads here are entity-prefixed (`metricList`/`metricGet`/ `metricPreview`), so `metricSupportingRows` sits in the same idiom. Past its answer bound it refuses `ANSWER_DEADLINE_EXCEEDED` (422), and the fold it was running is stopped.",resultRows:"The dataset rows behind a result, saved or not, from the moment a dataset is picked: a time column, window, conditions and a clicked point narrow them, group-by columns first. Promotion-gated like every read here. It never truncates: past its ceiling, min(100,000, 400,000 cells \xF7 the columns read), it answers `too-many` with a reason and the ceiling. A version past 1,000,000 rows, or stating no row count, joined ones included, is answered `too-large` unread; `datasetRows` is `null` when the dataset states no count, or when only a joined one is past the limit. A read; it records nothing. Past its answer bound it refuses `ANSWER_DEADLINE_EXCEEDED` (422), and the fold it was running is stopped.",metricTimeAxisGrain:"The grain a time column's period keys are published at, for the authoring form's grain picker. Resolves the binding through the preview's promotion gate, reads one capped sample of the column, and answers the coarsest period key in it (or `null`) with the `versionId` it read. Advisory: `GRAIN_FINER_THAN_DATA` at query time is the guarantee. A read, at `metricPreview`'s tier; it records nothing. Past its answer bound it refuses `ANSWER_DEADLINE_EXCEEDED` (422), and the fold it was running is stopped.",rollupHierarchies:"The tenant's named hierarchies, for the Group by roll-up picker: read from the published asset directory, promoted versions only. The Unassigned group is left out. A read. Past its answer bound it refuses `ANSWER_DEADLINE_EXCEEDED` (422), and the fold it was running is stopped.",rollupLevels:"One hierarchy's levels, top first: each level's asset type (or `null` when types are mixed), its node count and one example branch. Today's tree, from the published asset directory. A read. Past its answer bound it refuses `ANSWER_DEADLINE_EXCEEDED` (422), and the fold it was running is stopped.",rollupNodeLevels:'The "Calculation nodes" ladder: each level with its node count; refuses `ROLLUP_LEVELS_TOO_MANY` past 64. Past its answer bound it refuses `ANSWER_DEADLINE_EXCEEDED` (422), and the fold it was running is stopped.',dimensionValues:"The DISCOVERY read behind a filter picker \u2014 the distinct values one of a Metric's DECLARED dimensions actually takes, over the metric's resolved (promoted) data and optionally within a UTC window.\n\nIt walks the same resolve \u2192 promotion-gate \u2192 serve path as `query`, so it respects the promotion gate and RLS by construction and never sees a version a query could not. What it answers is different: not the metric's numbers but the values a viewer may filter them BY, so a filter picker's options and the metric-authoring dimension control stop being hand-authored lists that go stale the moment a new facility reports.\n\nBOUNDED and refuse-loudly: past 1,000 distinct values it refuses (`DIMENSION_VALUES_TOO_MANY`) rather than truncating \u2014 a shortened option list is indistinguishable from a complete one, and a viewer would filter on a set they believe is whole. The 1,000 bound is a provisional guardrail. A read, not a verb: it records nothing. Past its answer bound it refuses `ANSWER_DEADLINE_EXCEEDED` (422), and the fold it was running is stopped.",snapshot:"Pin a MetricVersion as an approval-gate subject \u2014 a `tenantRead`, NOT a verb: it writes no Record and judges nothing (B5 \u2014 gates stay composition wiring). The host's mint table is derived from `manifest.reads.snapshotMint`, which names this procedure.","views.create":"Create a saved query. Duplicate name in this tenant's explorer \u2192 CONFLICT.\n\nDECLARED refusals: a duplicate name, a reached tenant cap, or an oversized payload are this domain's own answers \u2014 `createSavedQuery`'s own \u2014 never a transport fault.","views.list":"List the tenant's saved queries \u2014 name-ascending, everyone sees all of them.","views.get":`Read ONE saved query by durable id \u2014 the shared-link read. The refusal is DECLARED: a dead link is this domain's honest "it was deleted", not a transport fault.`,"views.update":"Update a saved query's name and/or payload by id \u2014 ANY tenant member may (communal).\n\nDECLARED refusals: a rename collision, an oversized payload, or the row vanishing between the pre-read and the write (an ordinary communal-mode race \u2014 any tenant member may delete any row) are `updateSavedQuery`'s own answers, never a transport fault. A RENAME-ONLY update returns the row's STORED payload rather than one this call sent (`data` is conditional), so a drifted row answers the same schema-drifted refusal `get`/`list`/`delete` do.","views.delete":"Delete a saved query by id \u2014 ANY tenant member may; its shared links then refuse NOT_FOUND.\n\nDECLARED: the row not existing \u2014 already deleted, or racing a concurrent communal delete \u2014 is `deleteSavedQuery`'s own answer, never a transport fault. The row is parsed BEFORE the delete (`deleteSavedQuery`), so a schema-drifted row refuses rather than deleting."},events:{get:"One event, with its slot values split active/retired and whether this deployment can serve its place. With no place of its own, `inheritedPlace` is `inherited` \u2014 the location of a pinned `ASSET` link's asset at the pinned version, and that asset \u2014 by the `list` projection and tie-break; `unavailable` when an Assets or links read it needs faulted (reported, never thrown); `null` when nothing is inherited. `tenantRead`.\n\nDeclared refusals: NOT_FOUND.",list:"The filtered, paged list the table and the map share, newest first by `start` falling back to `knownDuring`, then `end`; the time window is half-open `[from, to)`. `orderBy` orders the WHOLE filtered set on the server instead \u2014 number, title, type, status (bucket, then label), severity (rank) or that time, either direction, an unknown severity last both ways. A cursor carries the order it was minted under: one sent with another order is BAD_REQUEST (`data.code: EVENTS_LIST_CURSOR_STALE`) \u2014 start again. A `bounds` filter on a PostGIS-less deployment refuses loudly rather than answering an empty map; an inverted or zero-area `bounds` or a garbled cursor is BAD_REQUEST. `linkedAssetId` narrows the page and the facets to the events whose active `ASSET` link names that asset, read on the server through ' reverse read; an asset the reader may not see answers an empty page, and one linked to more events than that read returns is BAD_REQUEST (`data.code: EVENTS_ASSET_FILTER_TOO_LARGE`, `data.bound`). `eventId` narrows to named events \u2014 the asset tab's second step after `links.reverse`. Each row carries at most the first ten of its active `ASSET` links and `assetCount`, the total. The page reads every row's `ASSET` links in one batch, so one event it refuses \u2014 one the reader cannot see, or one holding more links than one read returns \u2014 fails the page with LINK_SUBJECT_UNAVAILABLE or LINK_READ_LIMIT_EXCEEDED, `data {eventId, number}` naming it. `tenantRead`.\n\nDeclared refusals: BAD_REQUEST, SERVICE_UNAVAILABLE, LINK_SUBJECT_UNAVAILABLE, LINK_READ_LIMIT_EXCEEDED.",historyList:"The event's Record trail, newest first \u2014 the platform Records reader filtered to its address; Events keeps no audit table. `tenantRead`.\n\nDeclared refusals: NOT_FOUND, BAD_REQUEST (a garbled cursor).",create:"Raise an event of a Type: a tenant-unique number minted suggest-not-enforce, the creation-default status, and the given or defaulted severity. A person must send a title (BAD_REQUEST with `data.field` `title` otherwise) and at least one time (EVENT_TIME_REQUIRED otherwise). An automation (an agent on its own role, or a step of a composition run) may send neither: an omitted title is the template's title pattern, else the Type's label, and when neither the call nor its links supply a time, `knownDuring` is the moment of the request; the Record's `params.titleDefaulted` and `params.knownDuringDefaulted` say which, and neither is a fill. CONFLICT covers three cases: a number collision, which is retryable (`data.number` \u2014 retry mints a fresh one); an exhausted numbering scheme, which is permanent until an admin changes the scheme's prefix or suffix (`numberingConfigSet`) \u2014 `data.scheme`, `data.categoryId`, `data.highWaterNumber` \u2014 and a retry refuses the same way; and a `sourceKey` claimed at the same moment by a write that took no lock, which is retryable (`data.sourceKey` \u2014 the retry answers `existing`). Optional `links` are drawn WITH the event in its one Record, with `propose`'s rules: one refused link refuses the whole create and nothing lands; the refusal keeps its own code and names the link \u2014 the message starts `link <n> of <total> (<type> \u2192 <domain>/<type>/<id>)` and `data.link` is `{index, linkType, object}` \u2014 `<n>` is 1-based and `index` 0-based, both in the caller's order, so `index` is `<n> - 1`. An `ASSET` link is pinned to the asset version in effect at the event's time (send no `objectVersion`; BAD_REQUEST `EVENTS_ASSET_VERSION_GIVEN` otherwise), a link to a work item or an event is pinned to the moment the create draws it, one instant for every such link of the call, a link to an event folded into another refuses LINK_OBJECT_UNAVAILABLE (naming it), and a `DUPLICATE_OF` is drawn only by `merge` (BAD_REQUEST `EVENTS_FOLD_LINK`). An optional `sourceKey` (opaque, trimmed, 1\u2013200 characters) is unique per tenant AND Type across every bucket: when an event of the tenant already holds it under that Type the answer is `existing` with that event's `id` and `number`, nothing is created, and a receipt Record (no effects) is filed under the idempotency key; otherwise the event claims it and the Record's `params.sourceKey` names it. The key is looked up under a per-(tenant, Type, key) lock, so a concurrent second call naming it under that Type waits for the first, then answers `existing` once the first has committed; if the first rolled back, the second creates the event.\n\nDeclared refusals: NOT_FOUND, BAD_REQUEST, CONFLICT, EVENT_TIME_REQUIRED, EVENT_TYPE_UNKNOWN, EVENT_SEVERITY_UNKNOWN, EVENT_CODELIST_TERM_UNKNOWN, EVENT_PLACE_INVALID, SERVICE_UNAVAILABLE, LINK_OBJECT_UNAVAILABLE, LINK_OBJECT_TYPE_NOT_ALLOWED, LINK_CARDINALITY_VIOLATION, LINK_CYCLE, LINK_OBJECT_NO_STANDING, LINK_ALREADY_ACTIVE, LINK_TYPE_RETIRED, LINK_TYPE_UNDECLARED, LINK_VERSION_REQUIRED, LINK_VERSION_NOT_ALLOWED, LINK_PIN_UNRESOLVABLE.",update:"Edit title, times with their pins, place with its pin, severity and slot values. A fill by an automation takes this verb too, fill-only. A folded event refuses `EVENT_FOLDED`; a closed or dismissed one `EVENT_NOT_OPEN`. A write that moves the event's pin time (`start`, else `knownDuring`, else `end`) re-pins every active `ASSET` link to the version effective then, in the same Record: no version at the new time refuses `LINK_PIN_UNRESOLVABLE`; an asset that is deleted or that the caller cannot read keeps its old pin, recorded in `detail.events.repinSkipped[]`. More than 100 active `ASSET` links to re-pin refuses BAD_REQUEST `EVENTS_REPIN_TOO_LARGE` (`data {counted, bound}`) before anything is written \u2014 end the ones no longer needed. A value that would leave the event more values than it holds (values a Type change kept count) refuses BAD_REQUEST `EVENTS_PROPERTIES_TOO_MANY`. CONFLICT when the event's time or `ASSET` links moved while the write was being checked, or its Type changed; `LINK_OBJECT_UNAVAILABLE` only when the asset goes between that check and the redraw.\n\nDeclared refusals: NOT_FOUND, BAD_REQUEST, CONFLICT, EVENT_TIME_REQUIRED, EVENT_FOLDED, EVENT_NOT_OPEN, EVENT_SEVERITY_UNKNOWN, EVENT_CODELIST_TERM_UNKNOWN, EVENT_PLACE_INVALID, SERVICE_UNAVAILABLE, LINK_PIN_UNRESOLVABLE, LINK_OBJECT_UNAVAILABLE.",changeTypePreview:"What changing the event to another Type would do \u2014 a READ, no Record: each value the event holds in a field of its current Type, and each value an earlier change kept (`sources[].kept`: its origin Type and field), with every field of the new Type it fits (`sources[].targets`, the value as it would be stored, converted between units of one quantity; `keepRefused` when it cannot be kept); each kept value that goes back to its origin Type's field (`restored[]`); each fill the new Type's rules would WRITE from the event's existing links, each one whose source could not be read (`cannotRead[]`) and a draw that would not happen and why (`skipped[]`); and the `fingerprint` `changeType` checks. The reading, work-item, subject, asset-version and asset-pin reads it needs run with no transaction held. Refuses as `changeType` would: a folded event `EVENT_FOLDED`, a closed or dismissed one `EVENT_NOT_OPEN`, a retired or unknown Type `EVENT_TYPE_UNKNOWN`, the event's own Type BAD_REQUEST (`data.code: EVENTS_CHANGE_TYPE_SAME`), more active links than one change reads BAD_REQUEST (`data.code: EVENTS_CHANGE_TYPE_TOO_LARGE`, `data {bound}`). `tenantReadRunner`.\n\nDeclared refusals: NOT_FOUND, BAD_REQUEST, EVENT_FOLDED, EVENT_NOT_OPEN, EVENT_TYPE_UNKNOWN.",changeType:"Change a proposed or open event's Type in place: the number, links, comments, times, severity and status stay; each mapped value (a kept one too) moves onto its field of the new Type (a measurement converted), every other value of the old Type is kept \u2014 read back under the event view's `keptValues`, by its origin Type and field code \u2014 and a kept value whose origin the new Type is goes back to its field when it fits; the fills the preview listed are applied or skipped as decided; the template pointer is cleared; a `sourceKey` stays claimed under the Type it was sent with. A person only: not composable. Policy: required fields of the new Type left blank (`requireSlots`) and a missing reason (`reasonOnTypeChange`, a check word only this verb's `EventChangeTypeResult` carries) warn and can be overridden (`warned`, nothing written). Refuses a folded event `EVENT_FOLDED`, a closed or dismissed one `EVENT_NOT_OPEN`, a retired or unknown Type `EVENT_TYPE_UNKNOWN`; BAD_REQUEST for the event's own Type (`EVENTS_CHANGE_TYPE_SAME`), a mapping or value that does not fit (`EVENTS_CHANGE_TYPE_MAPPING`, `data.issues` \u2014 more values than an event holds too), fill decisions that are not the preview's (`EVENTS_CHANGE_TYPE_FILL_DECISIONS`), more links than one change reads (`EVENTS_CHANGE_TYPE_TOO_LARGE`), more `ASSET` links than one change of its time re-pins (`EVENTS_REPIN_TOO_LARGE`), fills that would leave the event more values than it holds, kept ones included (`EVENTS_PROPERTIES_TOO_MANY`); CONFLICT when what the preview showed has changed (`EVENTS_CHANGE_TYPE_PREVIEW_STALE`: read the preview again), another change of the event's Type committed first (`EVENTS_EVENT_TYPE_CHANGED`), or the event or a Type moved while the write was being checked. A time fill that moves the pin time re-pins the `ASSET` links as `update` does.\n\nDeclared refusals: NOT_FOUND, BAD_REQUEST, CONFLICT, EVENT_FOLDED, EVENT_NOT_OPEN, EVENT_TYPE_UNKNOWN, EVENT_CODELIST_TERM_UNKNOWN, LINK_PIN_UNRESOLVABLE, LINK_OBJECT_UNAVAILABLE.",transition:"Status \u2192 status, from an open, closed or dismissed event to any live open, closed or dismissed status \u2014 `closed` \u2192 `repaired` is one move. Both `statusCode` and `bucket` are written from the status's own bucket; the optional note lives in the Record and is projected only when the move lands terminal (landing open clears it). Into or out of `candidate` refuses `EVENT_CANDIDATE_TRANSITION`; a folded event, `EVENT_FOLDED`. CONFLICT when the event moved while the write was being checked, or when a close's `requireLinkTypesToClose` newly fails on the locked policy re-check.\n\nDeclared refusals: NOT_FOUND, BAD_REQUEST, CONFLICT, EVENT_FOLDED, EVENT_STATUS_UNKNOWN, EVENT_STATUS_RETIRED, EVENT_CANDIDATE_TRANSITION.",accept:'`candidate` \u2192 an open status, by a person or an automation; omitted \u2192 the tenant\'s creation default, and CONFLICT when the tenant has none. A non-candidate refuses `EVENT_NOT_CANDIDATE`; a named status outside `open`, BAD_REQUEST with `data.code = "EVENTS_TARGET_BUCKET"`.\n\nDeclared refusals: NOT_FOUND, BAD_REQUEST, CONFLICT, EVENT_FOLDED, EVENT_STATUS_UNKNOWN, EVENT_STATUS_RETIRED, EVENT_NOT_CANDIDATE.',dismiss:'`candidate` or `open` \u2192 the named dismissed status, any live one the tenant has; `statusCode` is required. A named status outside `dismissed` refuses BAD_REQUEST with `data.code = "EVENTS_TARGET_BUCKET"`. A terminal event refuses `EVENT_NOT_OPEN` \u2014 reopen it first.\n\nDeclared refusals: NOT_FOUND, BAD_REQUEST, CONFLICT, EVENT_FOLDED, EVENT_STATUS_UNKNOWN, EVENT_STATUS_RETIRED, EVENT_NOT_OPEN.',reopen:'`closed` or `dismissed` \u2192 an open status; omitted \u2192 the tenant\'s creation default, and CONFLICT when the tenant has none. A named status outside `open` refuses BAD_REQUEST with `data.code = "EVENTS_TARGET_BUCKET"`. It clears the terminal note, and on a folded event the same Record clears the fold and ends its `DUPLICATE_OF` link. The one write a folded event takes. An event already open refuses CONFLICT.\n\nDeclared refusals: NOT_FOUND, BAD_REQUEST, CONFLICT, EVENT_STATUS_UNKNOWN, EVENT_STATUS_RETIRED.',linkList:"The event's own links, forward \u2014 active by default, `includeEnded` for history. `tenantRead`; what the reader may see is decided as `links.forward` decides it. `nextCursor` is an offset: a caller walking pages dedupes by `linkId`. A cursor this read did not issue refuses BAD_REQUEST `EVENTS_LINK_CURSOR`.\n\nDeclared refusals: NOT_FOUND, BAD_REQUEST.",linkedEvents:"Which events link THIS object, and with which role \u2014 the reverse of `linkList`: every link Events drew whose object is `object`, ACTIVE by default, `includeEnded` for ended ones too (each with its `effectiveTo`), `linkType` for one role. Events' links only \u2014 another domain's links at the same object never appear. `tenantRead`; what the reader may see is decided as `links.reverse` decides it (a link whose event the reader may not see is left out, never refused; a reader whose roles do not reach the events domain gets the \"nothing links\" answer). ONE page, newest link first, at most 200 (`MAX_LINK_READ_TAKE`), with no paging: `count` is the page's, never a total, and `truncated` says older links exist; `first` is the event of the newest VISIBLE item on that page \u2014 `null` with `truncated: true` when every row on the page was unreadable, even if visible links exist past it (see `EventLinkedEventsOutputSchema`). `statusLabel` is `null` when the tenant holds no status row for the code \u2014 show `statusCode`. An object nothing links answers `{first: null, items: [], count: 0, truncated: false}`. A `linkType` no slice of the tenant declares refuses `LINK_TYPE_UNDECLARED` (422, `data {kind:'type'}`), whoever reads; one declared only by ANOTHER slice (Media's `EVIDENCE`, say) is accepted and answers that empty shape \u2014 no event link holds it. Published:.\n\nDeclared refusals: BAD_REQUEST (the input fails its schema), FORBIDDEN (the `tenantRead` tier: no `tenant:member`), LINK_TYPE_UNDECLARED \u2014 declared so a classifying caller (a flow's read step) reads each as a refusal, never an outage (Work's `linkedWorkResolve` precedent).",linkedEventsComplete:"`linkedEvents`' complete-or-refuse sibling \u2014 the read a flow's read contract can declare (Events' `readContracts` entry), never `linkedEvents` itself. The SAME input; it answers EVERY event linking `object` as the caller, or refuses EVENT_READ_INCOMPLETE \u2014 one message for every case, neither a count nor which case. No privileged path: the host ports, as given; the reverse page's `withheld` refuses through `requireNoneWithheld`. The answer is `{first, items, count}`, no `truncated` (`EventLinkedEventsCompleteOutputSchema`); nothing linked answers `{first: null, items: [], count: 0}`. Inside a tenant Events has no per-event visibility today (RLS only), so in practice it refuses on the page bound.\n\nDeclared refusals: BAD_REQUEST, FORBIDDEN, LINK_TYPE_UNDECLARED (all as `linkedEvents`), EVENT_READ_INCOMPLETE \u2014 declared so a flow reads it as a refusal, never an outage.",linkDraw:"Draw one link from the event. An `ASSET` link is pinned to the asset version effective at the event's pin time, which Events resolves (send no `objectVersion`; BAD_REQUEST `EVENTS_ASSET_VERSION_GIVEN` otherwise), and points at an asset only (LINK_OBJECT_TYPE_NOT_ALLOWED otherwise). Every evidence type is pinned: a draw to a dataset version (or an asset as evidence) names its `objectVersion` (LINK_VERSION_REQUIRED otherwise), while a draw to a work item, an event or an observation declaration names none \u2014 Events pins it to the moment it draws the link, the database's statement time (BAD_REQUEST `EVENTS_EVIDENCE_VERSION_GIVEN` when one is sent \u2014 before a `CUSTOM_*` type's own refusal, so a version named on an undeclared, retired or disallowed `CUSTOM_*` type to a work item or an event answers that). Evidence outside the event's window is drawn anyway, never refused. `DUPLICATE_OF` is drawn only by `merge` (BAD_REQUEST `EVENTS_FOLD_LINK`). The draw may fill the event's place or times, recorded in the Record's `detail.events.fills[]`; a fill that moves the pin time re-pins the `ASSET` links as `update` does, refusing BAD_REQUEST `EVENTS_REPIN_TOO_LARGE` past 100 of them. A soft-deleted asset refuses LINK_OBJECT_UNAVAILABLE, whatever the event's time, and so does a link to an event folded into another (naming it \u2014 link that event instead). CONFLICT when the event's time or `ASSET` links moved while the draw was being checked.\n\nA draw to a dataset version under an evidence type may cite observation READINGS of that version: each is an evidence record beside the link, written in the same Record. BAD_REQUEST `EVENTS_CITATION_OBJECT` on any other link, `EVENTS_CITATION_VERSION_MISMATCH` for a ref naming another version than `objectVersion`, `EVENTS_CITATION_REPEATED` for a reading named twice, `EVENTS_CITATION_REF_TOO_LARGE` for a ref over its size bounds (an identity value or `basis` over 512 characters, more than 16 identity columns, or over 4 KB of JSON), `EVENTS_CITATION_OMITTED_ALONE` for an `omittedCount` with no readings beside it. To cite a reading on a link the event already holds, use `citeReadings`. A draw to an observation DECLARATION (`{observations, declaration, <declarationId>}`) may cite readings that FOLLOW the sensor instead: each of that declaration (`EVENTS_CITATION_DECLARATION_MISMATCH` otherwise), and resolved to the sensor's latest reading whenever it is read. A pinned ref on a declaration, or a following one on a version, is `EVENTS_CITATION_OBJECT`; a draw to a declaration with no following refs is `EVENTS_CITATION_DECLARATION_NEEDS_REFS` (that link only carries them). A follow of a REPLACED declaration is drawn onto the current one of its chain (the link's object and each ref); of a RETIRED one, `EVENTS_CITATION_DECLARATION_RETIRED`. The Record keeps each following reading as it resolved when drawn (`detail.events.latestAtCite`).\n\nDeclared refusals: NOT_FOUND, BAD_REQUEST, CONFLICT, EVENT_FOLDED, LINK_OBJECT_UNAVAILABLE, LINK_OBJECT_TYPE_NOT_ALLOWED, LINK_CARDINALITY_VIOLATION, LINK_CYCLE, LINK_OBJECT_NO_STANDING, LINK_ALREADY_ACTIVE, LINK_TYPE_RETIRED, LINK_TYPE_UNDECLARED, LINK_VERSION_REQUIRED, LINK_VERSION_NOT_ALLOWED, LINK_PIN_UNRESOLVABLE.",linkEnd:`End a link this event drew \u2014 stamped, never deleted. Ending an ended link is the recorded no-op; a link the event did not draw (another event's, or one where this event is the object) is NOT_FOUND. The event's place is left as it is, even when it was filled from that link. Every observation reading the link cited is ended with it.
194
+ What refuses: the share saying no in a way the caller can act on (\`SHARE_CONTENTS_REFUSED\`) \u2014 the browse and the probe translate the same port refusals, so they answer the same declared code (see \`testConnection\`).`},obligations:{refs:"The domain-root Ref seam \u2014 named `refs`, never `list`, so it does not read as duplication beside a capability-scoped list added later. Declares `NOT_IMPLEMENTED` the way Work's `refs` does for the phase before any verb can create a `Plan` row.","framework.list":"List visible Library frameworks with editions, filtered and cursor-paged. `tenantRead`. Refuses `WORK_CLAUSE_CODE_INVALID` when stored requirement or suggestion content carries a Work clause type that does not satisfy Work type code grammar.","framework.get":"Get a visible framework by id with editions, citation checks, suggestions and recorded pack provenance. `tenantRead`. Refuses `NOT_FOUND` when the framework does not exist, and `WORK_CLAUSE_CODE_INVALID` when stored requirement or suggestion content carries a Work clause type that does not satisfy Work type code grammar.","requirement.list":"List saved requirements and authoring trees for one visible framework version, cursor-paged. `tenantRead`. Refuses `NOT_FOUND` when the framework version does not exist, and `WORK_CLAUSE_CODE_INVALID` when a stored requirement tree carries a Work clause type that does not satisfy Work type code grammar.",frameworkImportBrowse:"The framework packs offered to this tenant for import, one entry per framework at its newest offered version. `tenantRead`, `edit` authority on `obligations.framework`, the authority `frameworkImport` needs. A pack item whose payload is not a framework this domain can import is left out.",frameworkImportVersions:"Every version of one offered framework pack item, retired ones included and flagged, for choosing which to import. `tenantRead`, the same authority as `frameworkImportBrowse`. A pack not offered to this tenant, or outside its reach, lists no versions, and a version that no longer resolves or whose payload is not an importable framework is left out. Refuses `BAD_REQUEST` when `packRef` is not a well-formed pack coordinate.",frameworkImportPreview:"One version of an offered framework pack as `frameworkImport` would write it: its framework, edition, requirements with translated schedules, suggested plans and the subject fact paths their subject rules read. Also returns `workProducerWarnings`: the Work producer codes the edition's evidence names that the tenant's Work lacks or that could not be checked, so this verb reads Work as well as the pack. `tenantRead`, the same authority as `frameworkImportBrowse`. Refuses `NOT_FOUND` when the pack is not offered to this tenant, is outside its reach, has no such version, or its payload is not an importable framework, and `BAD_REQUEST` when `packRef` is not a well-formed pack coordinate.","program.list":"List this tenant's programs with framework, pinned edition, owner and counts, cursor-paged. `tenantRead`. Refuses `BAD_REQUEST` for a cursor this read did not return.","program.get":"Get one program by id, the row `program.list` returns. `tenantRead`. Refuses `NOT_FOUND` when this tenant has no such program.","enrollment.list":"List stored enrollments under this tenant's programs, removed ones on request, cursor-paged. `tenantRead`. Refuses `BAD_REQUEST` for a cursor this read did not return.","enrollment.matchingSubjectsPreview":"Count the subjects a not-yet-stored criteria enrollment would admit. `tenantReadRunner`. Refuses `BAD_REQUEST` for criteria the determination judge cannot read, and `WORK_CLAUSE_CODE_INVALID` when the criteria carry a Work clause type that does not satisfy Work type code grammar.","enrollment.replacePreview":"Count who stays, enters, leaves or is undecided if one enrollment is replaced. `tenantReadRunner`. Refuses `WORK_CLAUSE_CODE_INVALID` for a replacement `work` clause off Work's code grammar, `BAD_REQUEST`, `NOT_FOUND` and `ENROLLMENT_ALREADY_REMOVED`.","plan.list":"List this tenant's plans with their current version's trigger and enforcement, cursor-paged. `tenantRead`. Refuses `BAD_REQUEST` for a cursor this read did not return.","plan.get":"Get one plan with its current version's content, open application and trigger-binding need. `tenantRead`. Refuses `NOT_FOUND` when this tenant has no such plan, `PLAN_STEP_EVIDENCE_REQUIREMENT_MISSING` when a stored step carries no `evidenceRequirement`, and `WORK_CLAUSE_CODE_INVALID` when the stored subject criteria or a step's evidence requirement carries a Work clause type that does not satisfy Work type code grammar.",frameworkCreate:"Mint a new content-tier Framework. Refuses `FRAMEWORK_CODE_TAKEN` when the publisher + code already names a framework for this tenant.",requirementCreate:"Create a requirement on a draft FrameworkVersion; a published edition is refused. `tenantWrite`, `edit` authority on `obligations.framework-version`. `key` is required and names the requirement across editions: restate the key a prior edition's requirement carries (read it with `requirement.list`) to continue that requirement; two requirements of one clause share a citation and differ in key. `citation` is required; on a `source_derived` requirement it is the locator of the clause the requirement comes from, exactly as the document numbers it (`Condition 4.2(b)`). It is provenance, never identity. `basis` is required: `source_derived` when `citation` locates a clause of the edition's source, `tenant_authored` otherwise. `action` is the duty the requirement imposes. `applicability` states which subjects the requirement binds and `evidenceRequirement` what evidence satisfies it. Both are requirement trees, where a node is exactly one of `{anyOf: [node, \u2026]}`, `{allOf: [node, \u2026]}`, a clause `{domain, type, match?}`, `{anyEvidence: true}` or `{attestationOnly: true}`. A clause names a subject (in `applicability`, e.g. `{domain: 'assets', type: 'asset', match: {'$facts.basin': 'permian'}}`) or an evidence record (in `evidenceRequirement`) by its `domain` and `type`, and matches one whose facts equal every scalar in `match`; without `match`, any one of that domain and type. `anyEvidence` is met by any evidence entry, and `attestationOnly` by the satisfying call itself with no evidence. A combinator is non-empty and a node carries no other key. A tree is capped at depth 5, 10 children per combinator and 64 nodes: one tree over a cap is refused `CAPS_EXCEEDED` and both trees over one `CAP_REFUSAL_MULTIPLE`, each naming the cap and the node's path. A `work` leaf's `type` and its category and template match codes must satisfy Work's code grammar, or the call refuses `WORK_CLAUSE_CODE_INVALID`. `retentionDuration` (an ISO 8601 duration such as `P7Y`) and `retentionFrom` are set together or not at all. Refuses `REQUIREMENT_KEY_TAKEN` when the edition already holds the key, `BASIS_MISMATCH` for a `source_derived` requirement on a `tenant_authored` edition or with a blank citation, `NOT_FOUND` when this tenant has no such version, `FRAMEWORK_VERSION_NOT_DRAFT` once it is published, and `BAD_REQUEST` when a database-backed requirement constraint such as retention pairing is violated.\n\n`applicability`/`evidenceRequirement` carry `RequirementNodeSchema` (`z.lazy`, D14/R48's `anyOf`/`allOf` tree), which the MCP `inputSchema` carries as local `$defs`.",requirementUpdate:"Revise a requirement on a still-draft FrameworkVersion: its trees, basis, key or citation. `tenantWrite`, `edit` authority on `obligations.requirement`. `applicability` and `evidenceRequirement` are required and replace the saved trees whole, in the grammar and under the caps `requirementCreate` describes, refused `CAPS_EXCEEDED`, `CAP_REFUSAL_MULTIPLE` or `WORK_CLAUSE_CODE_INVALID` the same way. An optional content field set to `null` clears its saved value (`tolerances` to an empty list); `key` and `citation` refuse `null`, since every requirement carries both. An omitted field leaves it as saved. A corrected `citation` keeps the requirement's `key`, so it stays the same requirement. `basis` is required and refuses `BASIS_MISMATCH` as on `requirementCreate`; a restated key the edition already holds refuses `REQUIREMENT_KEY_TAKEN`. Refuses `NOT_FOUND` when this tenant has no such requirement, `FRAMEWORK_VERSION_NOT_DRAFT` once its edition is published, and `BAD_REQUEST` when a database-backed requirement constraint such as retention pairing is violated. Same recursive-schema shape as `requirementCreate`.",frameworkVersionCreate:"Mint a new draft FrameworkVersion under an existing Framework. `tenantWrite`, `edit` authority on `obligations.framework`. The edition starts `draft`: add its requirements with `requirementCreate`, revise them with `requirementUpdate`, and read them back with `requirement.list`. `contentBasis` is required: `source_document` with its `source` when the edition is read from a document, which makes `frameworkPublish` demand the citation attestation, or `tenant_authored` when the tenant writes the content itself; `frameworkVersionSetContentBasis` changes it while the edition is a draft. The edition reaches tenants only through `frameworkPublish`, a `manage` verb authorized from the authenticated principal on every interface; the platform agent bar refuses that authority to an agent principal. Authoring through this verb changes neither who may publish nor what publish requires: the citation gate reads the declared content basis, and neither the calling interface nor the principal that drafted the edition is an input to it. `effectiveFrom`/`effectiveTo` are ISO civil dates bounding the edition's window. Refuses `NOT_FOUND` when `frameworkId` names no Framework this tenant has, and `BAD_REQUEST` when `effectiveTo` precedes `effectiveFrom`. Send `suggestedPlans` empty here: each suggestion's `requirementId` must name a requirement of this edition, which `frameworkPublish` checks, and those ids exist only once `requirementCreate` returns them, so author suggestions with `frameworkVersionSetSuggestedPlans` after that. A `suggestedPlans` list sent here is checked as that verb checks it: refuses `SUGGESTION_TRIGGER_INVALID` when a suggested plan is a schedule with no cadence, carries a cadence outside the RRULE subset, or is any trigger other than `schedule` and carries a cadence, `SUGGESTION_ID_DUPLICATE` when two suggested plans share an `id`, `SUGGESTION_CAPS_EXCEEDED` when a suggestion's `subjectCriteriaTemplate` or `evidenceClause` breaks a requirement-tree cap, `SUBJECT_CRITERIA_INVALID` when a `subjectCriteriaTemplate` is criteria `planCreate` refuses, and `WORK_CLAUSE_CODE_INVALID` when a suggestion's tree carries a `work` clause whose type or match codes break Work's code grammar.\n\n`suggestedPlans[].subjectCriteriaTemplate`/`evidenceClause` carry `RequirementNodeSchema` (`z.lazy`, D14/R48's `anyOf`/`allOf` tree), the recursive tree `requirementCreate` describes, which the MCP `inputSchema` carries as local `$defs`.",frameworkVersionSetSuggestedPlans:"Replace a draft FrameworkVersion's suggested plans with the authored list. A suggestion whose `id` is already stored keeps its stored `authoredBy`; a new one takes the value sent. Send `ai_draft` for a suggestion you drafted; it records provenance and does not gate publish. Each `subjectCriteriaTemplate` is a requirement tree in the subject form `planCreate` describes. Refuses `SUGGESTION_LIST_STALE` when the stored ids differ from `expectedSuggestionIds`, `SUGGESTION_TRIGGER_INVALID` when a suggested plan is a schedule with no cadence, carries a cadence outside the RRULE subset, or is any trigger other than `schedule` and carries a cadence, `SUGGESTION_ID_DUPLICATE` when two suggested plans share an `id`, `SUGGESTION_CAPS_EXCEEDED` when a suggestion's `subjectCriteriaTemplate` or `evidenceClause` breaks a requirement-tree cap, `SUBJECT_CRITERIA_INVALID` when a `subjectCriteriaTemplate` is criteria `planCreate` refuses (a `match` key that is neither a `$facts.` path nor `$asset.assetTypeId` with a lowercase UUID asset type id), `WORK_CLAUSE_CODE_INVALID` when a suggestion's tree carries a `work` clause whose type or match codes break Work's code grammar, `SUGGESTION_REQUIREMENT_UNKNOWN` when a suggestion names no requirement of this version, `NOT_FOUND` when this tenant has no such version, and `FRAMEWORK_VERSION_NOT_DRAFT` once the version is published. Same recursive-schema shape as `frameworkVersionCreate`, and equally reachable from CLI/MCP.",frameworkVersionSetContentBasis:"Change a draft FrameworkVersion's declared content basis. Refuses `NOT_FOUND` when this tenant has no such version, `FRAMEWORK_VERSION_NOT_DRAFT` once it is published, and `BASIS_MISMATCH` when it would leave a `source_derived` requirement on a `tenant_authored` edition.",frameworkPublish:"Publish a draft FrameworkVersion, freezing its requirement tree as the tenant-facing edition. `contentDigest` names the edition content the caller read and publishes: the SHA-256, in lowercase hex, of the JSON of `{ contentBasis, suggestedPlans, requirements }` with object keys sorted at every depth and no whitespace, where `contentBasis` and `suggestedPlans` are the edition's as `framework.get` returns them and `requirements` is every requirement of the edition as `requirement.list` returns it, less `createdAt`, sorted by `requirementId`. `framework.get` returns each edition's `contentDigest` over the same content: read `framework.get` first and keep its `contentDigest`, then read the content you review, so that anything changed after the digest was read refuses the publish. A caller that computes the digest itself computes it over exactly the content it read. Refuses `FRAMEWORK_VERSION_STALE` when the edition as stored no longer matches `contentDigest`, `FRAMEWORK_VERSION_OVERLAP` when its effective window collides with an already-published edition of the same Framework, `CITATION_CHECK_REQUIRED` when the edition's declared content basis is `source_document` and the call does not attest that its source-derived citations were checked against the source (`citationCheckCompleted: true`), and `WORK_CLAUSE_CODE_INVALID` when stored requirement or suggestion content carries a Work clause type that does not satisfy Work type code grammar, `SUGGESTION_REQUIREMENT_UNKNOWN` when a suggested Plan names no requirement of the edition, `NOT_FOUND` when this tenant has no such version, and `FRAMEWORK_VERSION_NOT_DRAFT` when it is already published. The attester recorded is the authenticated principal the call runs under. This `manage` verb is served over CLI/MCP under the same principal authority as every other interface.",frameworkImport:"Import a FrameworkVersion + requirement tree from a published pack. `tenantWrite`, `edit` authority on `obligations.framework`. A retry under an `idempotencyKey` that already committed returns that import's result before any refusal below is judged again. Refuses `NOT_FOUND` when the pack is not offered to this tenant, is outside its reach, or has no such version, `PACK_VERSION_RETIRED` when the version is retired (an item with no version still offered answers `NOT_FOUND`, R160), `PACK_PAYLOAD_INVALID` when the pack item's payload does not parse as a framework payload or a requirement's `applicability` or a suggestion's `subjectCriteriaTemplate` names an `$asset.` key (an asset type is tenant vocabulary, which a pack references none of), `CAP_REFUSAL_MULTIPLE` when any requirement in the payload violates a requirement-tree cap, `RRULE_MALFORMED` or `RRULE_INTERVAL_REQUIRES_BYMONTH` when a requirement's own cadence wording does not translate into this domain's RRULE subset, `FRAMEWORK_CODE_TAKEN` when the pack's publisher+code already names a `framework` row for this tenant, `SUGGESTION_REQUIREMENT_UNKNOWN` when a pack suggestion's `requirementKey` names no requirement key of the pack, `SUGGESTION_ID_DUPLICATE` when two pack suggestions share an `id`, `SUGGESTION_TRIGGER_INVALID` when a pack suggestion is a schedule with no cadence, carries a cadence outside the RRULE subset, or is any trigger other than `schedule` and carries a cadence, `SUGGESTION_CAPS_EXCEEDED` when a pack suggestion's tree breaks a requirement-tree cap, `SUBJECT_CRITERIA_INVALID` when a pack suggestion's `subjectCriteriaTemplate` is criteria `planCreate` refuses, `BASIS_MISMATCH` when a `source_derived` requirement sits on a `tenant_authored` pack edition or has a blank citation, and `WORK_CLAUSE_CODE_INVALID` when a requirement or suggestion tree in the pack carries a Work clause type that does not satisfy Work type code grammar, and `BAD_REQUEST` when `packRef` is not a well-formed pack coordinate, the pack's edition ends before it begins, or a requirement breaks one of its CHECK constraints. Stores the pack's own suggested plans as authored.",programCreate:"Enroll this tenant into a Program against a chosen framework, under a `name` (trimmed, 1\u2013120 characters) and an optional `description` (at most 1000; one that trims to empty is stored as none). The pack triple is supplied for a framework imported from a pack and omitted for one authored in the tenant. Refuses `PIN_REQUIRES_FRAMEWORK` when `pinnedFrameworkVersionId` is supplied without a `frameworkId` (the DB's own pairing CHECK, R103), and `PACK_PIN_INCOMPLETE` when only part of the pack triple is supplied. The pinned edition must be a published edition of `frameworkId`: another framework's edition, or an id this tenant does not have, is refused `PIN_VERSION_NOT_IN_FRAMEWORK`, and a draft is refused `PIN_VERSION_NOT_PUBLISHED`. With no pinned edition, a `frameworkId` this tenant does not have is refused `NOT_FOUND`. An `ownerPrincipal` that is no principal this tenant can use is refused `PRINCIPAL_NOT_ASSIGNABLE`.",programUpdate:"Update a program's own mutable fields (name, description, owner + pack pin) \u2014 never `status`/`archivedAt`, `programArchive`'s alone. An omitted field is left alone; a `description` of `null`, or one that trims to empty, clears it. Refuses `PACK_PIN_INCOMPLETE` when only part of the pack triple is supplied, `PRINCIPAL_NOT_ASSIGNABLE` when `ownerPrincipal` is no principal this tenant can use, and `NOT_FOUND` when this tenant has no such program.",enrollmentCreate:"Enroll a subject (e.g. an Asset) into a program, or a criteria-matched set. Refuses `ENROLLMENT_SCOPE_XOR_VIOLATION` when the explicit-subject triple and `criteria` are both or neither supplied, `WORK_CLAUSE_CODE_INVALID` when `criteria` carries a `work` leaf whose type or codes fail Work's code grammar (checked first), `SUBJECT_CRITERIA_INVALID` when `criteria` is not a requirement tree the determination judge can read (the subject form `planCreate` describes: `{domain: 'assets', type: 'asset'}` clauses with `$facts.`-prefixed `match` keys and `$asset.assetTypeId`), `NOT_FOUND` when this tenant has no such program, and `PRINCIPAL_NOT_ASSIGNABLE` when `enrolledByPrincipal` is no principal this tenant can use.",enrollmentRemove:"Remove a subject's enrollment \u2014 a soft removal: the row survives with `removedAt`/`removalReason` set. Refuses `NOT_FOUND` when this tenant has no such enrollment and `ENROLLMENT_ALREADY_REMOVED` when it was already removed.",enrollmentReplace:"Change an enrollment: record `replacement` as a new enrollment and remove `enrollmentId` with `removalReason`, as one governed act. The removed enrollment keeps its scope, basis, as-of date and enroller, and names its replacement; its governing-zone override carries to the replacement. The program's other enrollments are untouched, and subjects still enrolled keep their admissions. Refuses `ENROLLMENT_SCOPE_XOR_VIOLATION` unless the replacement names exactly one subject or one criteria clause, `WORK_CLAUSE_CODE_INVALID` for a `work` leaf off Work's code grammar, `SUBJECT_CRITERIA_INVALID` for criteria the judge cannot read, `PRINCIPAL_NOT_ASSIGNABLE` for an enroller this tenant cannot use, `NOT_FOUND` when this tenant has no such enrollment, `ENROLLMENT_ALREADY_REMOVED` for a removed one, and `ENROLLMENT_ROUTES_CHANGED` when the program's enrollments are no longer the ones `expectedScopeRevision` names. Refuses `BAD_REQUEST` for an `idempotencyKey` already spent on another enrollment, on another replacement, or by another caller.",enrollmentSetZoneOverride:"Override the resolved governing zone for one enrollment (zone-ladder rung 2, R98). Refuses `ZONE_INVALID` when `zone` names something other than an IANA time zone \u2014 a fixed UTC offset, or a name the platform's zone data does not carry. `zone: null` clears the override instead of setting one and is never validated against that. Refuses `NOT_FOUND` when this tenant has no such enrollment and `ENROLLMENT_ALREADY_REMOVED` when it was removed.",planCreate:"Author a new Plan + its first PlanVersion (a versioned obligation-generation rule). `subjectCriteria` and each step's `evidenceRequirement` are requirement trees in the grammar and under the caps `requirementCreate` describes; an attestation-only step declares `{attestationOnly: true}`. In `subjectCriteria` a clause names the subject by the EntityRef the determination judge compares, `{domain: 'assets', type: 'asset'}` for an Assets asset, and every `match` key is either a `$facts.`-prefixed path into that subject's facts, e.g. `{domain: 'assets', type: 'asset', match: {'$facts.basin': 'permian'}}`, or `$asset.assetTypeId` with a lowercase UUID Assets asset type id, which holds for an asset of that type; a clause naming any other domain or type matches no asset. Refuses `PLAN_CODE_TAKEN` when `(programId, code)` already names a plan for this tenant, and `NOT_FOUND` when `programId` or `source.frameworkVersionId` names nothing this tenant has. On save it refuses `RRULE_MALFORMED` when the schedule is not a well-formed RFC 5545 recur-value, `RRULE_UNSUPPORTED_TERM` when it carries COUNT, UNTIL, DTSTART, BYHOUR, BYMINUTE, BYSECOND, BYWEEKNO, BYYEARDAY or WKST, `RRULE_SUBDAILY_REFUSED` when its frequency is finer than daily, `RRULE_INTERVAL_REQUIRES_BYMONTH` when a daily or weekly cadence sets INTERVAL > 1 or a monthly or yearly one does so without an explicit BYMONTH, `TRIGGER_GAP_BOUNDS_INVALID` when a `periodic_with_gap` cadence sets `minGapDays` above `maxGapDays`, `ANCHOR_NOT_LIVE` when a step anchors on detection or triggerTime outside an event, work or condition plan or on an `event_window` one, `OFFSET_SIGN_INVALID` when a step sets a negative offset on a fixed-point anchor (windowStart, windowEnd, predecessorCompletion, detection or triggerTime), `ZONE_INVALID` when `fallbackZone` is not a valid IANA time zone, `PLAN_STEP_LEAD_DAYS_INVALID` when a step's `leadDays` violates its bounds (0-366, at most 6 entries, strictly descending), `CAPS_EXCEEDED` when `subjectCriteria` or a step's `evidenceRequirement` exceeds a tree cap, `SUBJECT_CRITERIA_INVALID` when a `subjectCriteria` `match` key is neither a fact path the determination judge can read nor `$asset.assetTypeId` with a lowercase UUID asset type id, `WORK_CLAUSE_CODE_INVALID` when `subjectCriteria` or a step's `evidenceRequirement` carries a Work clause type that does not satisfy Work type code grammar, `CALENDAR_NOT_FOUND` and `WORKING_DAY_OFFSET_OUT_OF_RANGE` for a working-day step no calendar walk can answer, `PLAN_STEP_PREDECESSOR_MISSING` for a chain step with no predecessor, `PLAN_STEP_ACTIVATE_WHEN_NOT_CHAINED` for an `activateWhen` off the chain, `PLAN_STEP_INDEX_DUPLICATED` for two steps sharing a `stepIndex`, `PLAN_STEP_FIELD_ANCHOR_NEEDS_NOT_AFTER` for a `predecessorField` step with no `notAfter`, `ANCHOR_CYCLE_IDENTITY_MISSING` for a scheduled `rolling_from_event` step anchored on an asset fact without a `cycleIdentityPath`, and `COVERS_REQUIREMENT_UNKNOWN` when `covers` names a requirement this tenant does not have. The trigger pair is one of `PlanVersionTriggerSchema`'s arms: `schedule` with a cadence or rolling schedule, `event`/`work`/`condition` with `rolling_from_event` or `event_window`, `manual` with none; any other pair fails input validation (`BAD_REQUEST`) and writes nothing.\n\n`subjectCriteria` and each `steps` entry's `evidenceRequirement` both carry `RequirementNodeSchema` (`z.lazy`, D14/R48's `anyOf`/`allOf` tree), which the MCP `inputSchema` carries as local `$defs`.",planRevise:"Author a new PlanVersion revising an existing Plan. `subjectCriteria` and each step's `evidenceRequirement` are requirement trees in the grammar and under the caps `requirementCreate` describes, `subjectCriteria` in the subject form `planCreate` describes. It runs `planCreate`'s save-time validation and inserts no `plan` row, so it never refuses `PLAN_CODE_TAKEN`. Refuses `NOT_FOUND` when `planId` names no plan this tenant has, and `ENFORCEMENT_GATE_NOT_ALLOWED_ON_PUBLISHED_CONTENT` when a plan carrying `source_pack_publisher` is revised to `gate`. On save it refuses `RRULE_MALFORMED` when the schedule is not a well-formed RFC 5545 recur-value, `RRULE_UNSUPPORTED_TERM` when it carries COUNT, UNTIL, DTSTART, BYHOUR, BYMINUTE, BYSECOND, BYWEEKNO, BYYEARDAY or WKST, `RRULE_SUBDAILY_REFUSED` when its frequency is finer than daily, `RRULE_INTERVAL_REQUIRES_BYMONTH` when a daily or weekly cadence sets INTERVAL > 1 or a monthly or yearly one does so without an explicit BYMONTH, `TRIGGER_GAP_BOUNDS_INVALID` when a `periodic_with_gap` cadence sets `minGapDays` above `maxGapDays`, `ANCHOR_NOT_LIVE` when a step anchors on detection or triggerTime outside an event, work or condition plan or on an `event_window` one, `OFFSET_SIGN_INVALID` when a step sets a negative offset on a fixed-point anchor (windowStart, windowEnd, predecessorCompletion, detection or triggerTime), `ZONE_INVALID` when `fallbackZone` is not a valid IANA time zone, `PLAN_STEP_LEAD_DAYS_INVALID` when a step's `leadDays` violates its bounds (0-366, at most 6 entries, strictly descending), `CAPS_EXCEEDED` when `subjectCriteria` or a step's `evidenceRequirement` exceeds a tree cap, `SUBJECT_CRITERIA_INVALID` when a `subjectCriteria` `match` key is neither a fact path the determination judge can read nor `$asset.assetTypeId` with a lowercase UUID asset type id, `WORK_CLAUSE_CODE_INVALID` when `subjectCriteria` or a step's `evidenceRequirement` carries a Work clause type that does not satisfy Work type code grammar, `CALENDAR_NOT_FOUND` and `WORKING_DAY_OFFSET_OUT_OF_RANGE` for a working-day step no calendar walk can answer, `PLAN_STEP_PREDECESSOR_MISSING` for a chain step with no predecessor, `PLAN_STEP_ACTIVATE_WHEN_NOT_CHAINED` for an `activateWhen` off the chain, `PLAN_STEP_INDEX_DUPLICATED` for two steps sharing a `stepIndex`, `PLAN_STEP_FIELD_ANCHOR_NEEDS_NOT_AFTER` for a `predecessorField` step with no `notAfter`, `ANCHOR_CYCLE_IDENTITY_MISSING` for a scheduled `rolling_from_event` step anchored on an asset fact without a `cycleIdentityPath`, and `COVERS_REQUIREMENT_UNKNOWN` when `covers` names a requirement this tenant does not have.",planEnable:"Enable a plan for generation. Refuses `NOT_FOUND` when this tenant has no such plan.",planDisable:"Disable a plan \u2014 stops future generation without deleting history. Refuses `NOT_FOUND` when this tenant has no such plan.",planCloneFromLibrary:"Clone a library (pack-provided) plan's current PlanVersion content into this tenant's own authored Plan + first PlanVersion \u2014 the same `insertPlanVersion` path and `PLAN_CODE_TAKEN` refusal `planCreate` carries, since both mint a fresh plan + version.\n\nThe cloned content is re-validated on save rather than trusted, so every `insertPlanVersion` refusal reaches this verb too. On save it refuses `RRULE_MALFORMED` when the schedule is not a well-formed RFC 5545 recur-value, `RRULE_UNSUPPORTED_TERM` when it carries COUNT, UNTIL, DTSTART, BYHOUR, BYMINUTE, BYSECOND, BYWEEKNO, BYYEARDAY or WKST, `RRULE_SUBDAILY_REFUSED` when its frequency is finer than daily, `RRULE_INTERVAL_REQUIRES_BYMONTH` when a daily or weekly cadence sets INTERVAL > 1 or a monthly or yearly one does so without an explicit BYMONTH, `TRIGGER_GAP_BOUNDS_INVALID` when a `periodic_with_gap` cadence sets `minGapDays` above `maxGapDays`, `ANCHOR_NOT_LIVE` when a step anchors on detection or triggerTime outside an event, work or condition plan or on an `event_window` one, `OFFSET_SIGN_INVALID` when a step sets a negative offset on a fixed-point anchor (windowStart, windowEnd, predecessorCompletion, detection or triggerTime), `ZONE_INVALID` when `fallbackZone` is not a valid IANA time zone, `PLAN_STEP_LEAD_DAYS_INVALID` when a step's `leadDays` violates its bounds (0-366, at most 6 entries, strictly descending), `CAPS_EXCEEDED` when `subjectCriteria` or a step's `evidenceRequirement` exceeds a tree cap, `SUBJECT_CRITERIA_INVALID` when a `subjectCriteria` `match` key is neither a fact path the determination judge can read nor `$asset.assetTypeId` with a lowercase UUID asset type id, `WORK_CLAUSE_CODE_INVALID` when `subjectCriteria` or a step's `evidenceRequirement` carries a Work clause type that does not satisfy Work type code grammar, `CALENDAR_NOT_FOUND` and `WORKING_DAY_OFFSET_OUT_OF_RANGE` for a working-day step no calendar walk can answer, `PLAN_STEP_PREDECESSOR_MISSING` for a chain step with no predecessor, `PLAN_STEP_ACTIVATE_WHEN_NOT_CHAINED` for an `activateWhen` off the chain, `PLAN_STEP_INDEX_DUPLICATED` for two steps sharing a `stepIndex`, `PLAN_STEP_FIELD_ANCHOR_NEEDS_NOT_AFTER` for a `predecessorField` step with no `notAfter`, `ANCHOR_CYCLE_IDENTITY_MISSING` for a scheduled `rolling_from_event` step anchored on an asset fact without a `cycleIdentityPath`, and `COVERS_REQUIREMENT_UNKNOWN` when `covers` names a requirement this tenant does not have. It also refuses `PLAN_STEP_EVIDENCE_REQUIREMENT_MISSING` when a cloned step carries no `evidenceRequirement` at all.\n\n`PLAN_TRIGGER_NOT_RUNNABLE` refuses a source version storing a trigger pair no plan can run on. `ENFORCEMENT_GATE_NOT_ALLOWED_ON_PUBLISHED_CONTENT` refuses a source whose version is `gate` while it carries `source_pack_publisher`, which the clone inherits. `NOT_FOUND` refuses a `libraryPlanRef` naming no plan, or a `programId` naming no program, this tenant has.",programPinVersion:"Pin the program to a specific published FrameworkVersion and/or pack version, recording the release delta as a pending `change_review` row.\n\nRefuses `PIN_TARGET_REQUIRED` when neither half of the new pin is supplied, and `PIN_REQUIRES_FRAMEWORK` when a framework-version pin is asked of a program that names no framework \u2014 the DB's own `program_pinned_version_requires_framework_check`, checked first for a clean refusal rather than a raw constraint hit (the `programCreate` convention). Refuses `PIN_REQUIRES_PACK` when a pack-version pin is asked of a program with no pack provenance, which would leave it carrying part of the pack triple. Refuses `PROGRAM_NOT_ACTIVE` for an archived program, whichever half is pinned. The new edition must be a published edition of the program's framework: another framework's edition, or an id this tenant does not have, is refused `PIN_VERSION_NOT_IN_FRAMEWORK`, and a draft is refused `PIN_VERSION_NOT_PUBLISHED`. A program whose current edition is a draft is refused `PIN_CURRENT_VERSION_NOT_PUBLISHED`, naming that edition, because a review names requirements by key and only a published edition's keys are frozen. A program this tenant does not have is refused `NOT_FOUND`. Every refusal writes nothing: the pin, the `change_review` row and the Record stay unwritten.",programArchive:"Archive a program \u2014 ends its active adoption without deleting history. Refuses `NOT_FOUND` when this tenant has no such program.",applicationCancel:"Cancel an application. Stamps `cancelledAt` regardless of window state (no open/closed guard \u2014 matches `planEnable`/`planDisable`, which refuse only a plan this tenant does not have). A repeat call re-stamps `cancelledAt` with the current time and re-runs the cascade; it is not a no-op. Refuses `NOT_FOUND` when this tenant has no such application.","application.apply":"Apply a plan to its resolved subject set, or preview it.\n\nThe output is discriminated on `mode`: the `applied` arm names the one application the call opened, the `preview` arm carries the version it previewed, the Program scope, the plan's applicability over it, and the occurrence counts of each currently applicable subject. Both arms carry the resolved `governingZone` and the rung that produced it.\n\nRefuses `APPLY_OVERLAP` for an overlapping live application, `ZONE_INVALID` naming the invalid governing-zone rung, `APPLY_WINDOW_INVALID` for an inverted window, and `ESTATE_WIDE_APPLY_REQUIRES_CONFIRMATION` when more subjects are currently applicable than the large-activation confirmation threshold allows unacknowledged. The applied arm refuses `PLAN_VERSION_CHANGED` when `expectedPlanVersionId` is no longer the plan's current version, and `PROGRAM_SCOPE_CHANGED` when `expectedScopeRevision` no longer matches the program's live enrollment routes. Refuses `REQUEST_EXPANSION_OVER_CAP` when the Program-scope candidates or a preview's expanded occurrences exceed what one request may hold \u2014 confirming a large activation (`confirmEstateWide`) does not lift it \u2014 and `WINDOW_BEYOND_HORIZON`, on both arms, for a window reaching more than `EXPANSION_HORIZON_YEARS` past today. The applied arm refuses `ADMISSION_SOURCE_CHANGED` (409, retryable) when the program's enrollments change while it resolves subjects. Refuses `PLAN_STEP_EVIDENCE_REQUIREMENT_MISSING` (409) when a stored plan-version step carries no `evidenceRequirement`, and `WORK_CLAUSE_CODE_INVALID` (409) when a stored work clause type does not satisfy Work type-code grammar. Refuses `NOT_FOUND` when this tenant has no such plan.","application.regenerate":"Move an open application onto its plan's current version \u2014 supersede the future occurrences the new version no longer produces, reopen those an earlier regenerate superseded that it produces again. The next `obligations.generate` tick creates new occurrences under that version.\n\nThe only path that clears an application's derived `stale` read. `planRevise` (`tenantWrite`) never calls it: moving an estate's live duties onto a new version is an administrative act (`tenantAdmin`), and the caller sees `planRevise`'s own preview delta before deciding to take it.\n\nA subject it cannot judge keeps its future occurrences, and a superseded future occurrence the new version produces again is reopened.\n\nRefuses `APPLICATION_NOT_OPEN` when the application is cancelled. Refuses `PLAN_VERSION_NOT_PUBLISHED` when the plan has no current version to move onto. Refuses `PLAN_VERSION_MOVED` when the plan published another version while this call expanded one; nothing is written, and a retry expands the current version. Refuses `REQUEST_EXPANSION_OVER_CAP` when the expansion, or the rows it would write, exceed what one request may hold, before any write. Refuses `PLAN_STEP_UNRESOLVABLE` (409) when the new version's steps do not carry a step an occurrence names, and `PLAN_STEP_EVIDENCE_REQUIREMENT_MISSING` (409) when a stored step carries no `evidenceRequirement`, and `WORK_CLAUSE_CODE_INVALID` (409) when a stored work clause type does not satisfy Work type-code grammar. Refuses `ADMISSION_SOURCE_CHANGED` (409) when the program's enrollments or the application change while it expands; nothing is written, and a retry expands afresh. Refuses `NOT_FOUND` when this tenant has no such application. The result counts every occurrence under the application by disposition.","application.confirmScope":"Confirm that an application applies to the subjects it now applies to, setting its confirmed count to `expectedApplicableCount`. Plan health reports an application whose applicable count grew past both the large-activation threshold and its confirmed count; this verb is the one that clears it. Duties keep generating whether or not anyone confirms.\n\nRefuses `APPLICATION_SCOPE_CHANGED` when the count the determine sweep last measured is not `expectedApplicableCount`, writing nothing; read the plan again and confirm the count it shows. Refuses `NOT_FOUND` when this tenant has no such application.","application.recordEvent":"Record a subject-side event (a detection, a work completion, a condition breach) against the plan's open application, materializing its occurrence(s) inline, using the call's `idempotencyKey` as their identity.\n\nRefuses `APPLICATION_NOT_OPEN` when no uncancelled application of the plan has opened, `APPLICATION_WINDOW_CLOSED` when the open one's window ended before today, `SUBJECT_REF_UNRESOLVED` when `subjectRef` names no single enrolled subject, `PLAN_NOT_EVENT_TRIGGERED` when the pinned version is not an `event`, `work` or `condition` plan storing an event shape \u2014 a `schedule` or `manual` plan, or a version stored with a pair no plan can run on, which `data.reason` names \u2014 and `EVENT_OUTSIDE_WINDOW` when the event's civil date (`triggeredAt`, or today without it) falls before the application's window opens or after it closes, `data.bound` naming the side. `EVENT_INSTANT_MISSING` when a `rolling_from_event` step is anchored on `triggerTime` or `detection` and the call carries no `triggeredAt` or `detectedAt`, refused before anything is expanded. Refuses `SUBJECT_NOT_APPLICABLE` when the resolved subject's plan-applicability determination has settled `not_applicable` or `indeterminate` \u2014 no occurrence materializes and no Record is written for it. `PLAN_STEP_UNRESOLVABLE` (409) and `PLAN_STEP_EVIDENCE_REQUIREMENT_MISSING` (409) when the pinned version's stored steps cannot be read for an occurrence. `DUE_DATE_OUTSIDE_CALENDAR_COVERAGE` (409) when a working-day step's due date falls outside its calendar's coverage. `ADMISSION_SOURCE_CHANGED` (409) when the program's enrollments or the application change while it judges; a retry judges afresh. A refusal rolls the request transaction back and writes no Record. `ANCHOR_UNRESOLVED` and `OCCURRENCE_COLLISION` surface as a `CONFLICT` carrying the code in `data`, the same channel `obligationCreate` uses for them.\n\n`.meta({ agenticSurface: 'excluded', agenticSurfaceReason: 'semantic' })`: semantic, because the verb has no manual use \u2014 a composition flow's verb step calls it when a `CompositionTriggerBinding` matches a Record. The verb remains callable over `/rpc` and `/api`.","determination.override":"Manually override a determination with an administrative reason. Refuses OVERRIDE_REASON_REQUIRED when no reason is supplied, CODELIST_TERM_UNKNOWN for an unknown or retired reason, REASON_CODE_RESERVED for system-only codes, and NOT_FOUND when this tenant has no such determination.","determination.revokeOverride":"Revoke a prior override, preserving its original outcome and inputs while reverting to the computed determination. Refuses NOT_FOUND when this tenant has no such determination, and DETERMINATION_NOT_OVERRIDE when it is not an override.","application.list":"List plan applications with their derived `stale`/`expired` state, cursor-paged. `tenantRead`. Refuses `BAD_REQUEST` for a cursor this read did not return.","determination.list":"List determination history for a subject, plan or application, latest first, cursor-paged. `tenantRead`. Refuses `BAD_REQUEST` for a filter naming no subject, plan or application, or a cursor this read did not return.",deviationDraft:"System-only: draft against an existing obligation. Requires a caller idempotencyKey. Refuses DEVIATION_DRAFT_SYSTEM_ONLY for a non-system principal, NOT_FOUND when this tenant has no such obligation, and BAD_REQUEST when the obligation is not the plan's.\n\n`.meta({ agenticSurface: 'excluded', agenticSurfaceReason: 'semantic' })`: semantic, because the verb has no manual use \u2014 the `obligations.deadlines` sweep and `obligationSatisfy` call it in-process under their system principals, and every wire caller, a flow step included, is refused. The verb remains mounted on `/rpc` and `/api`.",deviationRecord:"Record a deviation directly against an existing obligation. Requires a caller idempotencyKey. `DEVIATION_LIVE_EXISTS` when a live deviation of that kind already exists for the obligation, `NOT_FOUND` when this tenant has no such obligation, and `BAD_REQUEST` when the obligation is not the plan's.",deviationValidate:"Validate a draft, recording its regulatory metadata. Requires a caller idempotencyKey. Refuses NOT_FOUND when this tenant has no such deviation, DEVIATION_STATE_CONFLICT when it is not a draft, and BAD_REQUEST for a blank justification.",deviationVoid:"Void a draft deviation, with a reason code. Requires a caller idempotencyKey. Refuses VOID_REASON_REQUIRED when no reason code is supplied, CODELIST_TERM_UNKNOWN when the supplied reason code is absent or retired in this codelist, and REASON_CODE_RESERVED when it names a system-reserved code a human may not author, NOT_FOUND when this tenant has no such deviation, and DEVIATION_STATE_CONFLICT when it is not a draft.",deviationUpdate:"Update a deviation's own (non-lifecycle) fields. Refuses NOT_FOUND when this tenant has no such deviation, DEVIATION_STATE_CONFLICT when it is not open or under review, and BAD_REQUEST for a blank justification.",deviationReport:"Attach/finalize a deviation's report content. Refuses NOT_FOUND when this tenant has no such deviation, DEVIATION_STATE_CONFLICT when it is not open or under review, and DEVIATION_NOT_REPORTABLE when it was recorded as not reportable.",deviationClose:"Close a deviation, ending its lifecycle. Refuses DEVIATION_NOT_FILED when a reportable deviation has not yet been filed via `deviationReport`, NOT_FOUND when this tenant has no such deviation, and DEVIATION_STATE_CONFLICT when it is not under review or reported.",deviationMarkUnderReview:"Composition-owned open \u2192 under_review transition. Refuses NOT_FOUND when this tenant has no such deviation.\n\n`.meta({ agenticSurface: 'excluded', agenticSurfaceReason: 'semantic' })`: semantic, because the verb has no manual use \u2014 only a composition flow step calls it (R90(c), R272). The verb remains callable over `/rpc` and `/api`.",workLinkKindSet:"Make a Work link kind the current corrective link kind, and add it to the recognized kinds in the same write; no recognized kind is ever removed. `tenantAdmin`: it decides tenant-wide which completed work counts. Requires a caller idempotencyKey. Refuses `WORK_LINK_KIND_UNSUITABLE` when Work has no active kind with that code or the kind does not link to both deviations and obligations, `WORK_LINK_KIND_LIMIT_REACHED` (409) when the kind is new and the tenant already recognizes as many kinds as one Work read accepts (`WORK_LINKED_OBJECTS_RESOLVE_KINDS_MAX`), `LINKED_WORK_INACCESSIBLE` (403) when the caller cannot read Work, `LINKED_WORK_UNAVAILABLE` (503) when Work does not answer, and `BAD_REQUEST` for a malformed code or a key already spent on another kind.",workLinkKindGet:"The tenant's current corrective link kind and every kind it has recognized. `tenantRead`.",obligationCreate:"Directly author an obligation outside plan-driven generation. This manual intake creates one occurrence without a plan application. `PLAN_STEP_UNRESOLVABLE` when the named plan version has no stepIndex 0, `PLAN_STEP_EVIDENCE_REQUIREMENT_MISSING` (409) when a stored step of it carries no `evidenceRequirement`, `WORK_CLAUSE_CODE_INVALID` (409) when a stored work clause type does not satisfy Work type-code grammar, `NOT_FOUND` when this tenant has no such plan version, and `BAD_REQUEST` when the plan version is another plan's.",obligationUpdate:"Update an obligation's own (non-lifecycle) fields \u2014 owner-only. Refuses `NOT_FOUND` when this tenant has no such obligation, and `PRINCIPAL_NOT_ASSIGNABLE` when `ownerPrincipal` names no principal this tenant can use (`null` clears).",obligationCancel:"Cancel an obligation before it is satisfied, with a reason code. `ENDING_REASON_REQUIRED` when no reason is given, `CODELIST_TERM_UNKNOWN` when it names no term in this codelist, `REASON_CODE_RESERVED` when it names a system-reserved code a human may not author, `OBLIGATION_NOT_LIVE` when the obligation is not `OPEN` or `PENDING_REVIEW`, `NOT_FOUND` when this tenant has no such obligation.",obligationExempt:"Mark an obligation exempt, with a reason code. `ENDING_REASON_REQUIRED` when no reason is given, `CODELIST_TERM_UNKNOWN` when it names no term in this codelist, `REASON_CODE_RESERVED` when it names a system-reserved code a human may not author, `OBLIGATION_NOT_LIVE` when the obligation is not `OPEN` or `PENDING_REVIEW`, `NOT_FOUND` when this tenant has no such obligation.",obligationMarkNotApplicable:"Mark an obligation as not applicable to its subject, with a reason code. `ENDING_REASON_REQUIRED` when no reason is given, `CODELIST_TERM_UNKNOWN` when it names no term in this codelist, `REASON_CODE_RESERVED` when it names a system-reserved code a human may not author, `OBLIGATION_NOT_LIVE` when the obligation is not `OPEN` or `PENDING_REVIEW`, `NOT_FOUND` when this tenant has no such obligation, or no determination the supplied `determinationId` names, and `BAD_REQUEST` when that determination is not the obligation's deciding `not_applicable` determination at the call's instant or, for an obligation with no application, is not an override.",obligationSatisfy:"Satisfy an obligation with evidence entries. This verb can run in a composition. Evidence outside the current window is credited to the prior one instead of refusing (`OUT_OF_WINDOW_CREDIT_MOVED` \u2014 behavior, not a hard refusal). The answer names the obligation where the satisfaction was recorded and, as `outcome`, whether that was the named obligation, an earlier occurrence, or retained surplus on the named obligation. `PLAN_STEP_UNRESOLVABLE` when the obligation's materialized evidence requirement is not a valid requirement tree, and `PLAN_STEP_EVIDENCE_REQUIREMENT_MISSING` (409) when a stored step of its plan version carries no `evidenceRequirement`. `OBLIGATION_NOT_LIVE` when the obligation, or the prior window the evidence is credited to, is not `OPEN` or `PENDING_REVIEW` \u2014 an ended or already satisfied obligation is never satisfied again. `NOT_FOUND` when this tenant has no such obligation. `WORK_CLAUSE_CODE_INVALID` (409) when a stored work clause type does not satisfy Work type-code grammar. For Work evidence, `WORK_COMPLETION_NOT_ESTABLISHED` (400) means the reference is not a Work Record or Work says it does not establish a completion, with `evidenceIndex` naming the refused entry's position in `evidence`; `WORK_COMPLETION_INACCESSIBLE` (403) means the caller cannot access the completion; `WORK_COMPLETION_BUDGET_EXCEEDED` (422) means Work could not verify the cited completions within its transaction budget, so cite fewer; and `EVIDENCE_SOURCE_UNAVAILABLE` (503) means the Work source is missing or unavailable, and a retry can succeed. Where the evidence cites a verified Work completion, the act time is Work's, as `ObligationSatisfyInputSchema` describes. `BAD_REQUEST` when an evidence entry's `attested` fields name `ref`, `sourceType`, `verified` or `displayDetails`; when an entry carries its own `verified` block; when the evidence cites more than 500 Work completion references; or when the idempotency key was already used for a different obligation.",obligationSatisfyFromWork:"Offer a Work completion Record to every obligation its completed items link to under a link kind the tenant recognizes, in one transaction. `tenantWrite`, composable: a flow maps `$record.id` from a Work completion. Requires a caller idempotencyKey; a replay answers the first call's summary.\n\nEach obligation is decided on its own: its evidence policy writes an accepted, review-required or surplus satisfaction, on the earlier occurrence of its series when the completion falls before its window (`creditedObligationId`). Surplus retains evidence on the named obligation without changing its status, so a consumer must branch on `outcome` rather than infer review-required from an unchanged `OPEN` status. An `already-satisfied`, `ended`, `duplicate-evidence` or `refused` outcome writes nothing. Those outcomes describe the run's decision, not merely the named row's starting status: early evidence offered to a satisfied or ended named row can still redirect to an earlier open occurrence. The run refuses whole with `NOT_FOUND` for a Record this tenant does not have, `WORK_COMPLETION_INACCESSIBLE` / `LINKED_WORK_INACCESSIBLE` (403) when the caller cannot read Work, `EVIDENCE_SOURCE_UNAVAILABLE` / `LINKED_WORK_UNAVAILABLE` (503) when Work does not answer, `WORK_COMPLETION_BUDGET_EXCEEDED` (422), `LINKED_WORK_NOT_CONFIGURED` (424) when Work lacks the tenant's current link kind, and `BAD_REQUEST` for a key already spent on another Record.",obligationExtend:"Extend an obligation's due window. Requires a tenant administrator. `OBLIGATION_NOT_LIVE` when the obligation is not `OPEN` or `PENDING_REVIEW`, `NOT_FOUND` when this tenant has no such obligation.",satisfactionAccept:"Accept a pending satisfaction. The reviewer is the signed-in caller, not a body field, and `reviewRationale` is required. Refuses `REVIEW_STATE_CONFLICT` when the satisfaction's review state is already terminal (accepted or rejected), and `SURPLUS_EVIDENCE` when the evidence is retained outside this obligation's window. Refuses `OBLIGATION_ENDED` when its obligation is cancelled, exempted, not applicable or superseded \u2014 a superseded occurrence's pending satisfaction is reviewable once a regenerate reopens it. Refuses `PLAN_STEP_EVIDENCE_REQUIREMENT_MISSING` (409) when a stored step of the obligation's plan version carries no `evidenceRequirement`, `WORK_CLAUSE_CODE_INVALID` (409) when a stored work clause type does not satisfy Work type-code grammar, and `NOT_FOUND` when this tenant has no such satisfaction.",satisfactionReject:"Reject a pending satisfaction. `reasonCode` and `reviewRationale` are distinct fields. Refuses `REVIEW_STATE_CONFLICT` when its review state is already terminal, `OBLIGATION_ENDED` when its obligation is cancelled, exempted, not applicable or superseded, `CODELIST_TERM_UNKNOWN` when the reason code names no term in this codelist, `REASON_CODE_RESERVED` when it names a system-reserved code a human may not author, and `NOT_FOUND` when this tenant has no such satisfaction.","obligation.explain":"Explain an obligation's current state: its generating plan version, the citations and determination inputs behind it, its generation trace, and its evidence-retention date, by obligation id. Refuses `NOT_FOUND` for an obligation this tenant does not have. `tenantRead`.","determination.explain":"Explain why a determination resolved the way it did: the plan/subject it was computed for, its inputs and outcome, the facts it consulted with their recorded values, and any human override, by determination id. Refuses `NOT_FOUND` for a determination this tenant does not have. `tenantReadRunner`.","determination.explainMany":"Explain several determinations in one read: `determination.explain`'s payload per id, in request order, the Assets revisions read once per subject. Refuses `NOT_FOUND` for the whole request when any id is not this tenant's, and `BAD_REQUEST` for no ids or more than `DETERMINATION_EXPLAIN_MANY_MAX`. `tenantReadRunner`.","obligation.get":"Fetch one obligation by id \u2014 the same full row `obligation.list` returns; refuses `NOT_FOUND` for an obligation this tenant does not have. Its `hasLinkedWork` is read from Work under the caller's own access: refuses `LINKED_WORK_INACCESSIBLE` (403) for a caller without Work read and `LINKED_WORK_UNAVAILABLE` (503) when Work does not answer, and `LINKED_WORK_NOT_CONFIGURED` (424) when the tenant's Work lacks the corrective link kind. `tenantRead`.","obligation.history":"Fetch an obligation's status-transition history: the committed obligations Records naming it in `effects`, each with the status it moved the obligation to, oldest first, whole (no cursor). `truncated` marks a history whose oldest entries the drain bound dropped. `tenantRead`.","obligation.advisoryVerdict":"Check candidate evidence against this obligation's stored evidence requirement, writing nothing; the out-of-window redirect is not modelled. Refuses `NOT_FOUND`, `OBLIGATION_NOT_LIVE` and `PLAN_STEP_UNRESOLVABLE`. `WORK_CLAUSE_CODE_INVALID` (409) means a stored work clause type does not satisfy Work type-code grammar. For Work evidence, `WORK_COMPLETION_NOT_ESTABLISHED` (400) means the reference is not a Work Record or Work says it does not establish a completion, with `evidenceIndex` naming the refused entry's position in `evidence`; `WORK_COMPLETION_INACCESSIBLE` (403) means the caller cannot access the completion; `WORK_COMPLETION_BUDGET_EXCEEDED` (422) means Work could not verify the cited completions within its transaction budget, so cite fewer; and `EVIDENCE_SOURCE_UNAVAILABLE` (503) means the Work source is missing or unavailable, and a retry can succeed. `BAD_REQUEST` refuses caller-supplied verified facts, reserved attested fields, or more than 500 Work completion refs. `tenantRead`.","obligation.list":"List the obligations this tenant can see, earliest due first, cursor-paged and filterable by status/subject/plan/predecessor obligation and by civil due date (`dueFrom`/`dueTo`, both ends inclusive) or by a window holding the due date, the occurrence's own date or the stored window end (`dueOrOccurrenceWindow`, which takes precedence over `dueFrom`/`dueTo`). Refuses `AS_OF_IN_FUTURE` for an `asOf` no time zone has reached, and `BAD_REQUEST` for a cursor this read did not return. Each row's `hasLinkedWork` is read from Work under the caller's own access: refuses `LINKED_WORK_INACCESSIBLE` (403) for a caller without Work read and `LINKED_WORK_UNAVAILABLE` (503) when Work does not answer, and `LINKED_WORK_NOT_CONFIGURED` (424) when the tenant's Work lacks the corrective link kind. `tenantRead`.","projection.list":"Project a plan's would-be occurrences over a civil window, cursor-paged, writing nothing, with the subjects its enrollments could not decide \u2014 and so did not project \u2014 named on every page (`undecided`). A plan that does not exist or is not visible is refused `NOT_FOUND`; a window wider than `PROJECTION_WINDOW_MAX_DAYS` `PROJECTION_WINDOW_EXCEEDED`; one reaching more than `EXPANSION_HORIZON_YEARS` past today `WINDOW_BEYOND_HORIZON`; an expansion past the request cap `REQUEST_EXPANSION_OVER_CAP`; an unresolvable governing zone `ZONE_INVALID`; and a stored plan step it cannot resolve, or that names no evidence requirement, `PLAN_STEP_UNRESOLVABLE` or `PLAN_STEP_EVIDENCE_REQUIREMENT_MISSING`; `WORK_CLAUSE_CODE_INVALID` (409) for a stored work clause type that does not satisfy Work type-code grammar; a cursor this read did not return `BAD_REQUEST`. `tenantRead`.","deviation.list":"List deviations newest first, cursor-paged, filterable by status and obligation. Refuses `BAD_REQUEST` for a cursor this read did not return. `tenantRead`.","deviation.get":"Fetch one deviation by id \u2014 the same row `deviation.list` returns; refuses `NOT_FOUND` for a deviation this tenant does not have. `tenantRead`.","satisfaction.reviewQueue":"List satisfactions awaiting evidence review on reviewable obligations, oldest first, cursor-paged. Refuses `BAD_REQUEST` for a cursor this read did not return. `tenantRead`.","satisfaction.list":"List one obligation's satisfactions, oldest first, cursor-paged, whatever their `reviewState`. Refuses `BAD_REQUEST` for a cursor this read did not return. `tenantRead`.",creditOverride:"Manually override a computed credit relationship. Rewrites the one 1:1 credit row in place \u2014 never a second row \u2014 recording the reason code and the optional free-text elaboration behind the decision, and keeping the assignment, reason code and detail it replaced as `replaced`. `tenantAdmin`. Requires a caller idempotencyKey. Refuses CREDIT_OVERRIDE_REASON_REQUIRED when no reason code is supplied, CODELIST_TERM_UNKNOWN when the supplied reason code is absent or retired in this codelist, REASON_CODE_RESERVED when it names a system-reserved code a human may not author, CREDIT_REQUIREMENT_MISMATCH when the credit does not carry the requirement the override names, and NOT_FOUND when this tenant has no such credit.",changeReviewDecide:"Decide the listed items of a pending change review. `tenantAdmin`. Requires a caller idempotencyKey.\n\nDecisions are recorded PER ITEM: one call may accept one item and defer a sibling, and a review is decided incrementally across as many calls as the tenant needs. `accept` and `reject` settle an item; `defer` records the tenant's position and HOLDS that item open, so `status` flips to `decided` only once every entry in `affected_items` is accepted or rejected, and a deferred item may be decided by a later call. A suggestion-provenance item is decided the same way, and deciding it regenerates nothing \u2014 revising or retiring the named Plan is that Plan's own verbs' act.\n\nAn accepted or rejected requirement item regenerates every open application of this review's program whose plan covers the requirement the item's `requirementRef` names in either of the review's editions \u2014 by key, or by citation in a review written by a server built before requirement keys: a plan not yet revised still covers the old edition's row, and a requirement the new edition removed has only that row. Each is filed as its own `applicationRegenerate` under the key `<idempotencyKey>/regenerate/<planApplicationId>`; occurrences whose window has opened keep their plan version. An accepted item may add `extendOpenOccurrences` \u2014 the new due date plus the `basis` and `citation` the deadline moved under \u2014 and every live occurrence under those applications due on or after the new edition's effective date and before the new due date is extended through `obligationExtend` under `<idempotencyKey>/extend/<obligationId>`; a duty that fell due under the earlier edition keeps its date and its overdue stamp.\n\nRefuses CHANGE_REVIEW_AFFECTED_ITEMS_UNREADABLE when the review's stored `affected_items` do not parse, CHANGE_REVIEW_ITEM_UNKNOWN when a decision names an item the review does not carry, CHANGE_REVIEW_ITEM_ALREADY_DECIDED when it names one already accepted or rejected, and CHANGE_REVIEW_ITEM_DUPLICATE when one call names the same item twice, CHANGE_REVIEW_EXTEND_REQUIRES_ACCEPT when an extension rides a deferred or rejected item, and CHANGE_REVIEW_EXTEND_OVERLAP when two extensions reach the same open occurrence. Refuses REQUEST_EXPANSION_OVER_CAP when the decision would regenerate more applications, or extend more occurrences, than one request may hold. A child regenerate's APPLICATION_NOT_OPEN, PLAN_VERSION_MOVED, REQUEST_EXPANSION_OVER_CAP, PLAN_STEP_UNRESOLVABLE, PLAN_STEP_EVIDENCE_REQUIREMENT_MISSING and ADMISSION_SOURCE_CHANGED reach this caller as they are and roll the decision back with them, as does a child extension's OBLIGATION_NOT_LIVE when an occurrence it selected ends before the extension locks it. Refuses NOT_FOUND when this tenant has no such review. Refuses WORK_CLAUSE_CODE_INVALID when a stored `work` clause type does not satisfy Work's type-code grammar.\n\nReplaying the idempotency key returns the ORIGINAL receipt, so a key re-sent after the review has moved on answers the `status` its own call produced \u2014 never a fresh read of the row.",frameworkDraftFromDocument:'Start a framework draft from a source document (a permit, regulation or policy), for a person to review and publish. This is the first call of the document workflow; it writes a new framework and one unpublished edition whose content basis is `source_document` with `documentRef` as its source, and no requirements. `tenantWrite`, `edit` authority on `obligations.framework`.\n\nWorkflow:\n 1. Read the whole document yourself. Nothing uploads it; only what you send is kept.\n 2. Call this once: `kind` (`permit` for a permit), `code` (the document\'s own number),\n `title`, `jurisdiction`/`authority` when stated, `editionLabel` (the revision or\n issue it names), `effectiveFrom` (`YYYY-MM-DD`; `effectiveTo` only when it states an\n end), and `documentRef`: `{"kind":"url","url":\u2026}`, or `{"kind":"document","name":\u2026}`\n with the file name you were given when it has no URL.\n 3. For each obligation the document imposes, call `requirementCreate` once with the\n returned `frameworkVersionId` and `basis` `source_derived`: `key` is a name of your\n own for that obligation, unique within the edition (`sec-4.2b-inspect`); `citation`\n is the locator of the clause it comes from, exactly as the document numbers it\n (`Condition 4.2(b)`), never a paraphrase, and several obligations may cite one\n clause under different keys;\n `action` is the verb it demands; the applicability and evidence trees and any\n schedule, retention, tolerances or consequence note come from that clause.\n 4. Correct a requirement with `requirementUpdate`, restating its `basis`; a corrected\n `citation` keeps its `key`. Everything stays editable until publish.\n 5. Nothing written so far is live. A person checks every source-derived citation\n against the source and explicitly confirms the check. The assistant must not set\n `citationCheckCompleted: true` on its own judgement. Publishing is the separate\n `frameworkPublish` `manage` call: read `framework.get` first and keep the edition\'s\n `contentDigest`, then read the requirements with `requirement.list`. An authorized\n caller submits the person\'s attestation and that digest; the call refuses\n `FRAMEWORK_VERSION_STALE` if content changed after the digest was read. It records\n the publishing principal and actual time as the citation check.\n\nExample \u2014 step 2 for a two-condition air permit:\n `{"kind":"permit","code":"AQ-1234-R2","title":"Example Compressor Station Air Permit",\n "authority":"Example State DEQ","editionLabel":"Revision 2","effectiveFrom":"2025-03-01",\n "documentRef":{"kind":"url","url":"https://example.org/permits/aq-1234-r2.pdf"},\n "idempotencyKey":"<a new UUID>"}`\nthen one `requirementCreate` per obligation, each with `basis` `source_derived`, e.g. `key` `cond-5.1-inspect`, `citation` `Condition 5.1`, `action` `inspect`, and `key` `cond-7.3b-report`, `citation` `Condition 7.3(b)`, `action` `report`.\n\nRefuses `FRAMEWORK_CODE_TAKEN` when the code already names a framework this tenant publishes, `BAD_REQUEST` when `effectiveTo` is before `effectiveFrom`, and `KEY_PARAM_MISMATCH` when the key was spent on another draft.',"credit.list":"List credits with each requirement's key and citation, in id order, cursor-paged. Refuses `BAD_REQUEST` for a cursor that does not decode to a row id. `tenantRead`.","changeReview.list":"List change reviews oldest first, cursor-paged, filterable by program and status. Refuses `BAD_REQUEST` for a cursor this read did not return. `tenantRead`.","changeReview.impact":"Count what each requirement item of one change review affects in the register today. Refuses `NOT_FOUND` for a review this tenant does not have. `tenantRead`.","export.auditPack":"Generate a subject's audit pack for a period and return it inline. Refuses `OVER_CAP` for a selection larger than one pack may carry and `AS_OF_IN_FUTURE` for an `asOf` no time zone has reached. `tenantRead`.","posture.summary":"Count the Posture tiles for the tenant, each program and each subject under it. Refuses `OVER_CAP` for an `asOf` over more obligations than one read may reconstruct and `AS_OF_IN_FUTURE` for an `asOf` no time zone has reached. Refuses `WORK_CLAUSE_CODE_INVALID` when a stored `work` clause type does not satisfy Work's type-code grammar. `tenantRead`.","register.sectionCounts":"Count a program's Register sections \u2014 needs-attention, in-progress, recently-satisfied, upcoming and history \u2014 by the predicate the Register itself groups by. In-progress is read from Work under the caller's own access: refuses `LINKED_WORK_INACCESSIBLE` (403) for a caller without Work read and `LINKED_WORK_UNAVAILABLE` (503) when Work does not answer, and `LINKED_WORK_NOT_CONFIGURED` (424) when the tenant's Work lacks the corrective link kind. Refuses `WORK_CLAUSE_CODE_INVALID` when a stored `work` clause type does not satisfy Work's type-code grammar. `tenantRead`."},insights:{metricCreate:"Create a Metric \u2014 enters with a Draft v1.",metricRevise:"Revise a Metric \u2014 mint the next immutable version, Draft.",metricDescribe:"Set or clear a Metric's description, on the metric itself: no version is minted, and the edit files a Record under the caller's key. Needs the same permission as revising a metric.",metricPublish:"Publish a MetricVersion \u2014 Draft\u2192Published, in place; only Published is consumable (F-M3).",metricRetire:"Retire a MetricVersion \u2014 Published\u2192Retired, in place (F-M3).",thresholdRuleCreate:"Create a ThresholdRule \u2014 active immediately; returns the view + freshness disclosure (F-T1).",thresholdRuleRevise:"Revise a ThresholdRule \u2014 edit name/condition/severity in place, full-replace.",thresholdRuleDelete:"Delete a ThresholdRule \u2014 the rule row goes; its RuleEvents survive (F-T5, P14 rider).",metricList:"List every Metric identity visible to the tenant, with its latest-Published ordinal.",metricPaletteList:"The Solution builder's Metrics tab: published metrics only, searched and ordered by name in SQL, at most `METRIC_PALETTE_LIST_CAP` of them, with the count that matched.","datasetUses.list":"The metrics reading an asked dataset. `canSwitch` is the `metricRevise` check, or the `metricPublish` check when a staged draft that IS the switch waits to be published.","datasetUses.switch":"`metricRevise` from the latest PUBLISHED definition with its references to `from` moved to `to` (unpinned), then `metricPublish` \u2014 both as the caller, each filing its Record; a staged draft that is exactly that switch is published instead. A caller who may not publish gets the new version as a draft (`outcome: 'left-as-draft'`). A metric already reading `to` answers `switched`, writing nothing. Refuses NOT_FOUND for an unknown metric (or one with nothing live), CONFLICT `DATASET_USE_MOVED`, `DATASET_USE_DRAFT_IN_PROGRESS`, `DATASET_USE_ATTESTED` and `DATASET_USE_TARGET_MISMATCH`.",metricGet:"Fetch one Metric + all its versions by durable `metricId` (F-M4 detail).",ruleEventList:"RuleEvent history \u2014 by rule or by metric, the PR F drill path (F-T5 read surface). BOUNDED: answers the newest `limit` events (1\u2013500, and 500 when omitted) plus `total`, the uncapped count for that rule or metric. A `total` above `items.length` is the only signal older history exists and is not shown; there is no cursor, so the older events are not reachable here.",thresholdRuleList:"A metric's ThresholdRules \u2014 the read that makes a threshold DRAWABLE.\n\n**A new read surface, and the reason it is one:** the contract carried create/revise/delete and no way to discover a rule, and `MetricViewSchema` does not embed them \u2014 so a widget holding a `MetricId` could not learn there was a threshold at all, which is why no chart drew one even though rules evaluate in the background and raise severity-tagged events. Embedding rules on `MetricViewSchema` was the alternative and was rejected: it widens a read every consumer already parses for the benefit of one, and ties a metric's identity to its watching configuration.\n\nBY METRIC only (`WidgetProps.binding` carries no other identity) and BOUNDED at `THRESHOLD_RULE_PAGE_MAX_ITEMS` with a `total`, mirroring `ruleEventList`'s truncation signal \u2014 a chart silently missing a threshold looks fine, which is exactly why the signal has to exist.",watchList:'The TENANT-WIDE watch surface (QA-F) \u2014 every ThresholdRule the tenant holds, the metric each watches BY NAME, and its per-series held state.\n\n**Why a second rules read.** `thresholdRuleList` answers "what watches THIS metric", which is the question a chart placement asks. The Watchtower board asks "what is this tenant watching, and what is wrong right now" \u2014 and nothing could answer it: the only route was fanning `thresholdRuleList` over `metricList` client-side, which is N+1 requests, N boundaries, and a state count that is wrong while any one is in flight. Widening `thresholdRuleList` instead was rejected on both halves of its shape: its `metricId` would have to become optional (which a lenient parse strips \u2014 the hazard its own `strictObject` docblock argues), and its output would grow a metric-name join plus a per-series query that every chart on every dashboard would pay for and draw nothing from.\n\n**The NAME is for the CAPABILITY, not the entity, and that is deliberate.** Reads here are entity-prefixed (`metricList`/`metricGet`/`ruleEventList`/`thresholdRuleList`) because the domain has three entities and the prefix keeps the flat surface unambiguous. An entity-prefixed name is unavailable and would be wrong here on both counts: `thresholdRuleList` is taken by the read this one is NOT a variant of, and a row is more than a ThresholdRule (it carries another entity\'s name and a grain the rule row does not hold). So it is named for what the module calls the capability \u2014 **watching** \u2014 which is also the route (`/insights/watching`), the tab and the CTA vocabulary. `dimensionValues` is the standing precedent for a read named for the question rather than the entity. Grammar stays inside R5 (`verbNoun`, lowerCamelCase, no preposition) and keeps R1\'s canonical head verb: it IS a list.\n\n**COMPLETE OR REFUSED \u2014 the one place this diverges from its two sibling reads.** `ruleEventList` and `thresholdRuleList` both truncate-and-disclose, which is honest for a chart drawing decoration. This read\'s consumer GROUPS BY STATE AND COUNTS, so a truncated page becomes a confidently wrong number ("3 breaching" when there are forty) rather than a visibly partial picture \u2014 the `DIMENSION_VALUES_TOO_MANY` situation exactly. So it takes that posture: past `WATCH_LIST_MAX_ITEMS` (500) it refuses (`WATCH_LIST_TOO_MANY`, `BAD_REQUEST`) rather than answering a prefix, and therefore carries neither a `limit` nor a `total` \u2014 both describe a page, and this read has none.\n\nNO INPUT, like `metricList`: the scope is the tenant, and the tenant comes from RLS. A read, not a verb: it records nothing.',query:"The widget data path \u2014 a Metric's series over a UTC window (F-E1/F-E5). A `live` metric is compiled to the platform's generic-fold IR and executed client-side; a `verbatim` one is served from its bound promoted version, never recomputed. Returns series carrying their own unit + dimension metadata, with `state: 'empty'` making \"no data in range\" distinct from a failed fetch. A read, not a verb: it records nothing.\n\n`assetScope` narrows the figures to the assets a page's Assets filters name, each dataset by its own asset column, every dataset or none. A kind the metric cannot apply is named in `assetScopeUnapplied` on either arm, and its figures are not narrowed by it; a scope past what one read can carry refuses `ASSET_SCOPE_TOO_LARGE`, and unreadable column tags refuse `ASSET_SCOPE_UNAVAILABLE` \u2014 never a truncated or unfiltered figure. The two drills take the scope the figure applied, and refuse `ASSET_SCOPE_UNSUPPORTED` for one it could not. Past its answer bound it refuses `ANSWER_DEADLINE_EXCEEDED` (422), and the fold it was running is stopped.",metricPreview:"PREVIEW an unsaved definition \u2014 the same figures `query` would serve, for a definition that has not been created yet.\n\nWhy it exists at all: only a PUBLISHED version resolves, so a DRAFT is unreachable through a `MetricRef` \u2014 and preview-before-publish is a hard authoring guardrail, not a convenience. Without this read an author's only way to see what a definition computes is to publish it, which is the reverse of the order that keeps a wrong metric off a dashboard.\n\nA separate procedure rather than a ref-or-definition arm on `query`: widening that input would make every existing consumer's type a union and put an unsaved definition on the path that owns version resolution and the result cache.\n\nA READ, and it writes nothing \u2014 no Record, no version, no cache entry. The fold, the verbatim serve, the units boundaries and the CONSUMER-side promotion gate are the same code `query` walks, so a preview can never answer figures a published metric could not (and can never serve an ungoverned load).\n\nWhy a CUSTOM verb: `get` names the saved-definition read and `query` names folding a SAVED metric's series; evaluating a definition that does not exist yet is neither, and a canonical verb would misdescribe it. Reads here are entity-prefixed across the domain's three entities, so `metricPreview` sits beside `metricList`/`metricGet` rather than coining a second idiom. Past its answer bound it refuses `ANSWER_DEADLINE_EXCEEDED` (422), and the fold it was running is stopped.",metricSupportingRows:"The DRILL-DOWN read behind a chart point / KPI \u2014 a bounded page of the rows a Metric's figure was computed from, over the window the ask names and at the dataset version the Metric's ref resolves to.\n\nIt walks the same resolve \u2192 promotion-gate \u2192 serve path as `query`, and it takes the SAME ask (`ref`/`range`/`grain`/`dimensionFilters`) a widget's query carries, so the rows it opens are selected by exactly the window and the predicates the number on screen was served with \u2014 narrowed to one data point by `members` (the clicked series' dimension members) and `bucket` (the clicked point's period start; a row instant on a verbatim Metric).\n\nBOUNDED, twice: the engine bounds the read \u2014 an aggregated drill with no `members`, while `start + take` \u2264 10,000, reads only its first `start + take` rows plus one count when more match; any other drill refuses `RESULT_TOO_LARGE` past the engine's guardrail rather than truncating \u2014 and `rows: { start, take }` pages what crosses the wire \u2014 default 100, a `take` past 1,000 refused, a `start` past the end an empty page with `totalRows` intact. The result echoes the `source` version it READ at, which is what makes the provenance checkable \u2014 a follow-latest ref (`versionId` absent) re-resolves per read, so a promotion between two reads moves it and the echo is how a caller SEES that. A read, not a verb: it records nothing.\n\nWhy a CUSTOM verb: `get` names the definition detail and `query` names folding the series; opening the rows behind one figure is neither, and reads here are entity-prefixed (`metricList`/`metricGet`/ `metricPreview`), so `metricSupportingRows` sits in the same idiom. Past its answer bound it refuses `ANSWER_DEADLINE_EXCEEDED` (422), and the fold it was running is stopped.",resultRows:"The dataset rows behind a result, saved or not, from the moment a dataset is picked: a time column, window, conditions and a clicked point narrow them, group-by columns first. Promotion-gated like every read here. It never truncates: past its ceiling, min(100,000, 400,000 cells \xF7 the columns read), it answers `too-many` with a reason and the ceiling. A version past 1,000,000 rows, or stating no row count, joined ones included, is answered `too-large` unread; `datasetRows` is `null` when the dataset states no count, or when only a joined one is past the limit. A read; it records nothing. Past its answer bound it refuses `ANSWER_DEADLINE_EXCEEDED` (422), and the fold it was running is stopped.",metricTimeAxisGrain:"The grain a time column's period keys are published at, for the authoring form's grain picker. Resolves the binding through the preview's promotion gate, reads one capped sample of the column, and answers the coarsest period key in it (or `null`) with the `versionId` it read. Advisory: `GRAIN_FINER_THAN_DATA` at query time is the guarantee. A read, at `metricPreview`'s tier; it records nothing. Past its answer bound it refuses `ANSWER_DEADLINE_EXCEEDED` (422), and the fold it was running is stopped.",rollupHierarchies:"The tenant's named hierarchies, for the Group by roll-up picker: read from the published asset directory, promoted versions only. The Unassigned group is left out. A read. Past its answer bound it refuses `ANSWER_DEADLINE_EXCEEDED` (422), and the fold it was running is stopped.",rollupLevels:"One hierarchy's levels, top first: each level's asset type (or `null` when types are mixed), its node count and one example branch. Today's tree, from the published asset directory. A read. Past its answer bound it refuses `ANSWER_DEADLINE_EXCEEDED` (422), and the fold it was running is stopped.",rollupNodeLevels:'The "Calculation nodes" ladder: each level with its node count; refuses `ROLLUP_LEVELS_TOO_MANY` past 64. Past its answer bound it refuses `ANSWER_DEADLINE_EXCEEDED` (422), and the fold it was running is stopped.',dimensionValues:"The DISCOVERY read behind a filter picker \u2014 the distinct values one of a Metric's DECLARED dimensions actually takes, over the metric's resolved (promoted) data and optionally within a UTC window.\n\nIt walks the same resolve \u2192 promotion-gate \u2192 serve path as `query`, so it respects the promotion gate and RLS by construction and never sees a version a query could not. What it answers is different: not the metric's numbers but the values a viewer may filter them BY, so a filter picker's options and the metric-authoring dimension control stop being hand-authored lists that go stale the moment a new facility reports.\n\nBOUNDED and refuse-loudly: past 1,000 distinct values it refuses (`DIMENSION_VALUES_TOO_MANY`) rather than truncating \u2014 a shortened option list is indistinguishable from a complete one, and a viewer would filter on a set they believe is whole. The 1,000 bound is a provisional guardrail. A read, not a verb: it records nothing. Past its answer bound it refuses `ANSWER_DEADLINE_EXCEEDED` (422), and the fold it was running is stopped.",snapshot:"Pin a MetricVersion as an approval-gate subject \u2014 a `tenantRead`, NOT a verb: it writes no Record and judges nothing (B5 \u2014 gates stay composition wiring). The host's mint table is derived from `manifest.reads.snapshotMint`, which names this procedure.","views.create":"Create a saved query. Duplicate name in this tenant's explorer \u2192 CONFLICT.\n\nDECLARED refusals: a duplicate name, a reached tenant cap, or an oversized payload are this domain's own answers \u2014 `createSavedQuery`'s own \u2014 never a transport fault.","views.list":"List the tenant's saved queries \u2014 name-ascending, everyone sees all of them.","views.get":`Read ONE saved query by durable id \u2014 the shared-link read. The refusal is DECLARED: a dead link is this domain's honest "it was deleted", not a transport fault.`,"views.update":"Update a saved query's name and/or payload by id \u2014 ANY tenant member may (communal).\n\nDECLARED refusals: a rename collision, an oversized payload, or the row vanishing between the pre-read and the write (an ordinary communal-mode race \u2014 any tenant member may delete any row) are `updateSavedQuery`'s own answers, never a transport fault. A RENAME-ONLY update returns the row's STORED payload rather than one this call sent (`data` is conditional), so a drifted row answers the same schema-drifted refusal `get`/`list`/`delete` do.","views.delete":"Delete a saved query by id \u2014 ANY tenant member may; its shared links then refuse NOT_FOUND.\n\nDECLARED: the row not existing \u2014 already deleted, or racing a concurrent communal delete \u2014 is `deleteSavedQuery`'s own answer, never a transport fault. The row is parsed BEFORE the delete (`deleteSavedQuery`), so a schema-drifted row refuses rather than deleting."},events:{get:"One event, with its slot values split active/retired and whether this deployment can serve its place. With no place of its own, `inheritedPlace` is `inherited` \u2014 the location of a pinned `ASSET` link's asset at the pinned version, and that asset \u2014 by the `list` projection and tie-break; `unavailable` when an Assets or links read it needs faulted (reported, never thrown); `null` when nothing is inherited. `tenantRead`.\n\nDeclared refusals: NOT_FOUND.",list:"The filtered, paged list the table and the map share, newest first by `start` falling back to `knownDuring`, then `end`; the time window is half-open `[from, to)`. `orderBy` orders the WHOLE filtered set on the server instead \u2014 number, title, type, status (bucket, then label), severity (rank) or that time, either direction, an unknown severity last both ways. A cursor carries the order it was minted under: one sent with another order is BAD_REQUEST (`data.code: EVENTS_LIST_CURSOR_STALE`) \u2014 start again. A `bounds` filter on a PostGIS-less deployment refuses loudly rather than answering an empty map; an inverted or zero-area `bounds` or a garbled cursor is BAD_REQUEST. `linkedAssetId` narrows the page and the facets to the events whose active `ASSET` link names that asset, read on the server through ' reverse read; an asset the reader may not see answers an empty page, and one linked to more events than that read returns is BAD_REQUEST (`data.code: EVENTS_ASSET_FILTER_TOO_LARGE`, `data.bound`). `eventId` narrows to named events \u2014 the asset tab's second step after `links.reverse`. Each row carries at most the first ten of its active `ASSET` links and `assetCount`, the total. The page reads every row's `ASSET` links in one batch, so one event it refuses \u2014 one the reader cannot see, or one holding more links than one read returns \u2014 fails the page with LINK_SUBJECT_UNAVAILABLE or LINK_READ_LIMIT_EXCEEDED, `data {eventId, number}` naming it. `tenantRead`.\n\nDeclared refusals: BAD_REQUEST, SERVICE_UNAVAILABLE, LINK_SUBJECT_UNAVAILABLE, LINK_READ_LIMIT_EXCEEDED.",historyList:"The event's Record trail, newest first \u2014 the platform Records reader filtered to its address; Events keeps no audit table. `tenantRead`.\n\nDeclared refusals: NOT_FOUND, BAD_REQUEST (a garbled cursor).",create:"Raise an event of a Type: a tenant-unique number minted suggest-not-enforce, the creation-default status, and the given or defaulted severity. A person must send a title (BAD_REQUEST with `data.field` `title` otherwise) and at least one time (EVENT_TIME_REQUIRED otherwise). An automation (an agent on its own role, or a step of a composition run) may send neither: an omitted title is the template's title pattern, else the Type's label, and when neither the call nor its links supply a time, `knownDuring` is the moment of the request; the Record's `params.titleDefaulted` and `params.knownDuringDefaulted` say which, and neither is a fill. An automation's `templateId` also supplies the template's field values, under its own `properties` (its own value for a field wins); they are fills, as its own values are, and a template value the Type refuses is refused naming the template's pre-fill. A person's create takes only the template's severity, never its field values. CONFLICT covers three cases: a number collision, which is retryable (`data.number` \u2014 retry mints a fresh one); an exhausted numbering scheme, which is permanent until an admin changes the scheme's prefix or suffix (`numberingConfigSet`) \u2014 `data.scheme`, `data.categoryId`, `data.highWaterNumber` \u2014 and a retry refuses the same way; and a `sourceKey` claimed at the same moment by a write that took no lock, which is retryable (`data.sourceKey` \u2014 the retry answers `existing`). Optional `links` are drawn WITH the event in its one Record, with `propose`'s rules: one refused link refuses the whole create and nothing lands; the refusal keeps its own code and names the link \u2014 the message starts `link <n> of <total> (<type> \u2192 <domain>/<type>/<id>)` and `data.link` is `{index, linkType, object}` \u2014 `<n>` is 1-based and `index` 0-based, both in the caller's order, so `index` is `<n> - 1`. An `ASSET` link is pinned to the asset version in effect at the event's time (send no `objectVersion`; BAD_REQUEST `EVENTS_ASSET_VERSION_GIVEN` otherwise), a link to a work item or an event is pinned to the moment the create draws it, one instant for every such link of the call, a link to an event folded into another refuses LINK_OBJECT_UNAVAILABLE (naming it), and a `DUPLICATE_OF` is drawn only by `merge` (BAD_REQUEST `EVENTS_FOLD_LINK`). An optional `sourceKey` (opaque, trimmed, 1\u2013200 characters) is unique per tenant AND Type across every bucket: when an event of the tenant already holds it under that Type the answer is `existing` with that event's `id` and `number`, nothing is created, and a receipt Record (no effects) is filed under the idempotency key; otherwise the event claims it and the Record's `params.sourceKey` names it. The key is looked up under a per-(tenant, Type, key) lock, so a concurrent second call naming it under that Type waits for the first, then answers `existing` once the first has committed; if the first rolled back, the second creates the event.\n\nDeclared refusals: NOT_FOUND, BAD_REQUEST, CONFLICT, EVENT_TIME_REQUIRED, EVENT_TYPE_UNKNOWN, EVENT_SEVERITY_UNKNOWN, EVENT_CODELIST_TERM_UNKNOWN, EVENT_PLACE_INVALID, SERVICE_UNAVAILABLE, LINK_OBJECT_UNAVAILABLE, LINK_OBJECT_TYPE_NOT_ALLOWED, LINK_CARDINALITY_VIOLATION, LINK_CYCLE, LINK_OBJECT_NO_STANDING, LINK_ALREADY_ACTIVE, LINK_TYPE_RETIRED, LINK_TYPE_UNDECLARED, LINK_VERSION_REQUIRED, LINK_VERSION_NOT_ALLOWED, LINK_PIN_UNRESOLVABLE.",update:"Edit title, times with their pins, place with its pin, severity and slot values. A fill by an automation takes this verb too, fill-only. A folded event refuses `EVENT_FOLDED`; a closed or dismissed one `EVENT_NOT_OPEN`. A write that moves the event's pin time (`start`, else `knownDuring`, else `end`) re-pins every active `ASSET` link to the version effective then, in the same Record: no version at the new time refuses `LINK_PIN_UNRESOLVABLE`; an asset that is deleted or that the caller cannot read keeps its old pin, recorded in `detail.events.repinSkipped[]`. More than 100 active `ASSET` links to re-pin refuses BAD_REQUEST `EVENTS_REPIN_TOO_LARGE` (`data {counted, bound}`) before anything is written \u2014 end the ones no longer needed. A value that would leave the event more values than it holds (values a Type change kept count) refuses BAD_REQUEST `EVENTS_PROPERTIES_TOO_MANY`. CONFLICT when the event's time or `ASSET` links moved while the write was being checked, or its Type changed; `LINK_OBJECT_UNAVAILABLE` only when the asset goes between that check and the redraw.\n\nDeclared refusals: NOT_FOUND, BAD_REQUEST, CONFLICT, EVENT_TIME_REQUIRED, EVENT_FOLDED, EVENT_NOT_OPEN, EVENT_SEVERITY_UNKNOWN, EVENT_CODELIST_TERM_UNKNOWN, EVENT_PLACE_INVALID, SERVICE_UNAVAILABLE, LINK_PIN_UNRESOLVABLE, LINK_OBJECT_UNAVAILABLE.",changeTypePreview:"What changing the event to another Type would do \u2014 a READ, no Record: each value the event holds in a field of its current Type, and each value an earlier change kept (`sources[].kept`: its origin Type and field), with every field of the new Type it fits (`sources[].targets`, the value as it would be stored, converted between units of one quantity; `keepRefused` when it cannot be kept); each kept value that goes back to its origin Type's field (`restored[]`); each fill the new Type's rules would WRITE from the event's existing links, each one whose source could not be read (`cannotRead[]`) and a draw that would not happen and why (`skipped[]`); and the `fingerprint` `changeType` checks. The reading, work-item, subject, asset-version and asset-pin reads it needs run with no transaction held. Refuses as `changeType` would: a folded event `EVENT_FOLDED`, a closed or dismissed one `EVENT_NOT_OPEN`, a retired or unknown Type `EVENT_TYPE_UNKNOWN`, the event's own Type BAD_REQUEST (`data.code: EVENTS_CHANGE_TYPE_SAME`), more active links than one change reads BAD_REQUEST (`data.code: EVENTS_CHANGE_TYPE_TOO_LARGE`, `data {bound}`). `tenantReadRunner`.\n\nDeclared refusals: NOT_FOUND, BAD_REQUEST, EVENT_FOLDED, EVENT_NOT_OPEN, EVENT_TYPE_UNKNOWN.",changeType:"Change a proposed or open event's Type in place: the number, links, comments, times, severity and status stay; each mapped value (a kept one too) moves onto its field of the new Type (a measurement converted), every other value of the old Type is kept \u2014 read back under the event view's `keptValues`, by its origin Type and field code \u2014 and a kept value whose origin the new Type is goes back to its field when it fits; the fills the preview listed are applied or skipped as decided; the template pointer is cleared; a `sourceKey` stays claimed under the Type it was sent with. A person only: not composable. Policy: required fields of the new Type left blank (`requireSlots`) and a missing reason (`reasonOnTypeChange`, a check word only this verb's `EventChangeTypeResult` carries) warn and can be overridden (`warned`, nothing written). Refuses a folded event `EVENT_FOLDED`, a closed or dismissed one `EVENT_NOT_OPEN`, a retired or unknown Type `EVENT_TYPE_UNKNOWN`; BAD_REQUEST for the event's own Type (`EVENTS_CHANGE_TYPE_SAME`), a mapping or value that does not fit (`EVENTS_CHANGE_TYPE_MAPPING`, `data.issues` \u2014 more values than an event holds too), fill decisions that are not the preview's (`EVENTS_CHANGE_TYPE_FILL_DECISIONS`), more links than one change reads (`EVENTS_CHANGE_TYPE_TOO_LARGE`), more `ASSET` links than one change of its time re-pins (`EVENTS_REPIN_TOO_LARGE`), fills that would leave the event more values than it holds, kept ones included (`EVENTS_PROPERTIES_TOO_MANY`); CONFLICT when what the preview showed has changed (`EVENTS_CHANGE_TYPE_PREVIEW_STALE`: read the preview again), another change of the event's Type committed first (`EVENTS_EVENT_TYPE_CHANGED`), or the event or a Type moved while the write was being checked. A time fill that moves the pin time re-pins the `ASSET` links as `update` does.\n\nDeclared refusals: NOT_FOUND, BAD_REQUEST, CONFLICT, EVENT_FOLDED, EVENT_NOT_OPEN, EVENT_TYPE_UNKNOWN, EVENT_CODELIST_TERM_UNKNOWN, LINK_PIN_UNRESOLVABLE, LINK_OBJECT_UNAVAILABLE.",transition:"Status \u2192 status, from an open, closed or dismissed event to any live open, closed or dismissed status \u2014 `closed` \u2192 `repaired` is one move. Both `statusCode` and `bucket` are written from the status's own bucket; the optional note lives in the Record and is projected only when the move lands terminal (landing open clears it). Into or out of `candidate` refuses `EVENT_CANDIDATE_TRANSITION`; a folded event, `EVENT_FOLDED`. CONFLICT when the event moved while the write was being checked, or when a close's `requireLinkTypesToClose` newly fails on the locked policy re-check.\n\nDeclared refusals: NOT_FOUND, BAD_REQUEST, CONFLICT, EVENT_FOLDED, EVENT_STATUS_UNKNOWN, EVENT_STATUS_RETIRED, EVENT_CANDIDATE_TRANSITION.",accept:'`candidate` \u2192 an open status, by a person or an automation; omitted \u2192 the tenant\'s creation default, and CONFLICT when the tenant has none. A non-candidate refuses `EVENT_NOT_CANDIDATE`; a named status outside `open`, BAD_REQUEST with `data.code = "EVENTS_TARGET_BUCKET"`.\n\nDeclared refusals: NOT_FOUND, BAD_REQUEST, CONFLICT, EVENT_FOLDED, EVENT_STATUS_UNKNOWN, EVENT_STATUS_RETIRED, EVENT_NOT_CANDIDATE.',dismiss:'`candidate` or `open` \u2192 the named dismissed status, any live one the tenant has; `statusCode` is required. A named status outside `dismissed` refuses BAD_REQUEST with `data.code = "EVENTS_TARGET_BUCKET"`. A terminal event refuses `EVENT_NOT_OPEN` \u2014 reopen it first.\n\nDeclared refusals: NOT_FOUND, BAD_REQUEST, CONFLICT, EVENT_FOLDED, EVENT_STATUS_UNKNOWN, EVENT_STATUS_RETIRED, EVENT_NOT_OPEN.',reopen:'`closed` or `dismissed` \u2192 an open status; omitted \u2192 the tenant\'s creation default, and CONFLICT when the tenant has none. A named status outside `open` refuses BAD_REQUEST with `data.code = "EVENTS_TARGET_BUCKET"`. It clears the terminal note, and on a folded event the same Record clears the fold and ends its `DUPLICATE_OF` link. The one write a folded event takes. An event already open refuses CONFLICT.\n\nDeclared refusals: NOT_FOUND, BAD_REQUEST, CONFLICT, EVENT_STATUS_UNKNOWN, EVENT_STATUS_RETIRED.',linkList:"The event's own links, forward \u2014 active by default, `includeEnded` for history. `tenantRead`; what the reader may see is decided as `links.forward` decides it. `nextCursor` is an offset: a caller walking pages dedupes by `linkId`. A cursor this read did not issue refuses BAD_REQUEST `EVENTS_LINK_CURSOR`.\n\nDeclared refusals: NOT_FOUND, BAD_REQUEST.",linkedEvents:"Which events link THIS object, and with which role \u2014 the reverse of `linkList`: every link Events drew whose object is `object`, ACTIVE by default, `includeEnded` for ended ones too (each with its `effectiveTo`), `linkType` for one role. Events' links only \u2014 another domain's links at the same object never appear. `tenantRead`; what the reader may see is decided as `links.reverse` decides it (a link whose event the reader may not see is left out, never refused; a reader whose roles do not reach the events domain gets the \"nothing links\" answer). ONE page, newest link first, at most 200 (`MAX_LINK_READ_TAKE`), with no paging: `count` is the page's, never a total, and `truncated` says older links exist; `first` is the event of the newest VISIBLE item on that page \u2014 `null` with `truncated: true` when every row on the page was unreadable, even if visible links exist past it (see `EventLinkedEventsOutputSchema`). `statusLabel` is `null` when the tenant holds no status row for the code \u2014 show `statusCode`. An object nothing links answers `{first: null, items: [], count: 0, truncated: false}`. A `linkType` no slice of the tenant declares refuses `LINK_TYPE_UNDECLARED` (422, `data {kind:'type'}`), whoever reads; one declared only by ANOTHER slice (Media's `EVIDENCE`, say) is accepted and answers that empty shape \u2014 no event link holds it. Published:.\n\nDeclared refusals: BAD_REQUEST (the input fails its schema), FORBIDDEN (the `tenantRead` tier: no `tenant:member`), LINK_TYPE_UNDECLARED \u2014 declared so a classifying caller (a flow's read step) reads each as a refusal, never an outage (Work's `linkedWorkResolve` precedent).",linkedEventsComplete:"`linkedEvents`' complete-or-refuse sibling \u2014 the read a flow's read contract can declare (Events' `readContracts` entry), never `linkedEvents` itself. The SAME input; it answers EVERY event linking `object` as the caller, or refuses EVENT_READ_INCOMPLETE \u2014 one message for every case, neither a count nor which case. No privileged path: the host ports, as given; the reverse page's `withheld` refuses through `requireNoneWithheld`. The answer is `{first, items, count}`, no `truncated` (`EventLinkedEventsCompleteOutputSchema`); nothing linked answers `{first: null, items: [], count: 0}`. Inside a tenant Events has no per-event visibility today (RLS only), so in practice it refuses on the page bound.\n\nDeclared refusals: BAD_REQUEST, FORBIDDEN, LINK_TYPE_UNDECLARED (all as `linkedEvents`), EVENT_READ_INCOMPLETE \u2014 declared so a flow reads it as a refusal, never an outage.",linkDraw:"Draw one link from the event. An `ASSET` link is pinned to the asset version effective at the event's pin time, which Events resolves (send no `objectVersion`; BAD_REQUEST `EVENTS_ASSET_VERSION_GIVEN` otherwise), and points at an asset only (LINK_OBJECT_TYPE_NOT_ALLOWED otherwise). Every evidence type is pinned: a draw to a dataset version (or an asset as evidence) names its `objectVersion` (LINK_VERSION_REQUIRED otherwise), while a draw to a work item, an event or an observation declaration names none \u2014 Events pins it to the moment it draws the link, the database's statement time (BAD_REQUEST `EVENTS_EVIDENCE_VERSION_GIVEN` when one is sent \u2014 before a `CUSTOM_*` type's own refusal, so a version named on an undeclared, retired or disallowed `CUSTOM_*` type to a work item or an event answers that). Evidence outside the event's window is drawn anyway, never refused. `DUPLICATE_OF` is drawn only by `merge` (BAD_REQUEST `EVENTS_FOLD_LINK`). The draw may fill the event's place or times, recorded in the Record's `detail.events.fills[]`; a fill that moves the pin time re-pins the `ASSET` links as `update` does, refusing BAD_REQUEST `EVENTS_REPIN_TOO_LARGE` past 100 of them. A soft-deleted asset refuses LINK_OBJECT_UNAVAILABLE, whatever the event's time, and so does a link to an event folded into another (naming it \u2014 link that event instead). CONFLICT when the event's time or `ASSET` links moved while the draw was being checked.\n\nA draw to a dataset version under an evidence type may cite observation READINGS of that version: each is an evidence record beside the link, written in the same Record. BAD_REQUEST `EVENTS_CITATION_OBJECT` on any other link, `EVENTS_CITATION_VERSION_MISMATCH` for a ref naming another version than `objectVersion`, `EVENTS_CITATION_REPEATED` for a reading named twice, `EVENTS_CITATION_REF_TOO_LARGE` for a ref over its size bounds (an identity value or `basis` over 512 characters, more than 16 identity columns, or over 4 KB of JSON), `EVENTS_CITATION_OMITTED_ALONE` for an `omittedCount` with no readings beside it. To cite a reading on a link the event already holds, use `citeReadings`. A draw to an observation DECLARATION (`{observations, declaration, <declarationId>}`) may cite readings that FOLLOW the sensor instead: each of that declaration (`EVENTS_CITATION_DECLARATION_MISMATCH` otherwise), and resolved to the sensor's latest reading whenever it is read. A pinned ref on a declaration, or a following one on a version, is `EVENTS_CITATION_OBJECT`; a draw to a declaration with no following refs is `EVENTS_CITATION_DECLARATION_NEEDS_REFS` (that link only carries them). A follow of a REPLACED declaration is drawn onto the current one of its chain (the link's object and each ref); of a RETIRED one, `EVENTS_CITATION_DECLARATION_RETIRED`. The Record keeps each following reading as it resolved when drawn (`detail.events.latestAtCite`).\n\nDeclared refusals: NOT_FOUND, BAD_REQUEST, CONFLICT, EVENT_FOLDED, LINK_OBJECT_UNAVAILABLE, LINK_OBJECT_TYPE_NOT_ALLOWED, LINK_CARDINALITY_VIOLATION, LINK_CYCLE, LINK_OBJECT_NO_STANDING, LINK_ALREADY_ACTIVE, LINK_TYPE_RETIRED, LINK_TYPE_UNDECLARED, LINK_VERSION_REQUIRED, LINK_VERSION_NOT_ALLOWED, LINK_PIN_UNRESOLVABLE.",linkEnd:`End a link this event drew \u2014 stamped, never deleted. Ending an ended link is the recorded no-op; a link the event did not draw (another event's, or one where this event is the object) is NOT_FOUND. The event's place is left as it is, even when it was filled from that link. Every observation reading the link cited is ended with it.
195
195
 
196
196
  Declared refusals: NOT_FOUND, BAD_REQUEST, CONFLICT, EVENT_FOLDED.`,citeReadings:"Cite observation READINGS as evidence: one or more `ObservationRef`s (Observations' published reference, at most 50) of ONE dataset version, under ONE evidence type. The link points at the version (`{datasets, dataset-version, <datasetId>}`, `objectVersion` the version id \u2014 optional on the wire, since a declaration takes none, but REQUIRED here: a dataset-version cite without one is `EVENTS_CITATION_VERSION_MISMATCH`), never at a reading: the event's ACTIVE link of that type to that dataset is reused when it has one, else drawn (`linkDrawn` says which), and each reading becomes an evidence record beside it \u2014 all in ONE `events.citeReadings` Record. Who may cite is who may draw the link: `linkDraw`'s tier and check.\n\nFOLLOWING: readings that follow the sensor (`ObservationFollowingRef`, no version, no result time) are cited the same way on the observation's DECLARATION (`{observations, declaration, <declarationId>}`), with NO `objectVersion` \u2014 Events pins that link to the moment it draws it (BAD_REQUEST `EVENTS_EVIDENCE_VERSION_GIVEN` when one is sent) \u2014 each ref of that declaration (`EVENTS_CITATION_DECLARATION_MISMATCH` otherwise). `citationList` answers each with the sensor's LATEST promoted reading and `latest`. A REPLACED declaration's follow is drawn onto the current one of its chain (the link's object and each ref name it); the Record keeps each following reading as it resolved when cited (`detail.events.latestAtCite`; one that could not be resolved says `notResolvable`, and is still cited).\n\nBAD_REQUEST `EVENTS_CITATION_OBJECT` \u2014 not an evidence type, not a dataset version or a declaration, or a ref of the other form (a following one on a version, a pinned one on a declaration); `EVENTS_CITATION_VERSION_MISMATCH` \u2014 a ref naming another version than `objectVersion`, or than the active link's pin (`data.linkId`; end that link first, or cite the reading in its version); `EVENTS_CITATION_REPEATED` \u2014 a reading named twice; `EVENTS_CITATION_REF_TOO_LARGE` \u2014 a ref over its size bounds (an identity value or `basis` over 512 characters, more than 16 identity columns, or over 4 KB of JSON); `EVENTS_CITATION_DECLARATION_RETIRED` \u2014 a follow of a declaration retired with no replacement it carries to: \"This declaration is retired, so it won't get new readings. Pin a reading instead.\" CONFLICT `EVENTS_CITATION_DUPLICATE` \u2014 the link already carries the reading (`data.citationId`). Plus every refusal of drawing the link. Nothing is written on any refusal.\n\nDeclared refusals: NOT_FOUND, BAD_REQUEST, CONFLICT, EVENT_FOLDED, LINK_OBJECT_UNAVAILABLE, LINK_OBJECT_TYPE_NOT_ALLOWED, LINK_CARDINALITY_VIOLATION, LINK_CYCLE, LINK_OBJECT_NO_STANDING, LINK_ALREADY_ACTIVE, LINK_TYPE_RETIRED, LINK_TYPE_UNDECLARED, LINK_VERSION_REQUIRED, LINK_VERSION_NOT_ALLOWED, LINK_PIN_UNRESOLVABLE.",citationRemove:"Stop citing ONE reading: its evidence record is ended (stamped, never deleted), and when it was the link's last live reading the link is ended too, in the same Record (`linkEnded`). Removing an ended citation is the recorded no-op; a citation this event does not hold is NOT_FOUND. Who may remove is who may end the link: `linkEnd`'s tier and check.\n\nDeclared refusals: NOT_FOUND, BAD_REQUEST, CONFLICT, EVENT_FOLDED.",citationList:"The event's cited readings, oldest first \u2014 live ones, `includeEnded` for every one \u2014 each with what `observations.resolve` answers for its ref AS THE READER: `resolved`, `refused` (Observations' code and a plain sentence, and nothing of the ref), or `unavailable` when the resolve read itself failed. A page is at most 50, one resolve call; `nextCursor` continues it. `tenantReadRunner` (the `tenantRead` claim; the resolve runs with no transaction held). A cursor this read did not issue refuses BAD_REQUEST `EVENTS_CITATION_CURSOR`, one past 10,000 citations `EVENTS_CITATION_CURSOR_TOO_DEEP`.\n\nDeclared refusals: NOT_FOUND, BAD_REQUEST.",merge:"Fold duplicates into a survivor in ONE Record: every active link on each duplicate is ended there and drawn on the survivor (an `ASSET` link re-pinned at the survivor's time), a link the survivor already holds is skipped and returned, a link pointing at the survivor or at another duplicate of the merge is dropped and returned (as is the survivor's own link at a duplicate, which is ended), each duplicate gains a `DUPLICATE_OF` to the survivor and is dismissed with its fold set. A link whose object the caller may not link to now (deleted, or not visible) or whose tenant type was retired is NOT moved: it stays on the duplicate and is returned (`object-unavailable` / `type-retired`). An active link ANOTHER event drew to a duplicate, of any type, moves too, redrawn from that event at the survivor (`movedFromOtherEvents` counts them; one that event already holds at the survivor is skipped `already-held` with its `subject`; one whose subject is itself folded is skipped `subject-folded` and stays); an earlier fold's `DUPLICATE_OF` stays. Before anything is written, a link to a duplicate whose subject this caller cannot see refuses LINK_READ_INCOMPLETE (no count, no ids), and one whose subject is another domain's record refuses BAD_REQUEST `EVENTS_MERGE_LINKS_NOT_MOVABLE` (`data {domains: {domain, count}[]}`): only that domain moves its links \u2014 end them there, or choose that duplicate as the survivor; one of a tenant type retired since it was drawn refuses BAD_REQUEST `EVENTS_MERGE_LINK_TYPE_RETIRED` (`data {types: {code, count}[]}`) \u2014 end those links or re-activate the type; and a domain whose link types may point at an event (derived from the tenant's link types) that this caller's link reach does not cover refuses BAD_REQUEST `EVENTS_MERGE_LINKS_UNREACHABLE` (`data {domains}`), since links there could be neither read nor reported. Every `sourceKey` a duplicate holds moves to the survivor, named by key in `sourceKeysMoved`, so a later call naming it answers the survivor. All or nothing otherwise: a CONTAINS redraw closing a loop refuses the whole merge (a second parent too \u2014 defensive for the duplicate's own CONTAINS, ended first; real for a parent's at a duplicate while another parent holds the survivor), as does an asset with no version at the survivor's time (LINK_PIN_UNRESOLVABLE, naming the recourse). The survivor must be open or closed and no duplicate already folded (EVENT_MERGE_PRECONDITION, `data.reason`); CONFLICT when the survivor's time or a duplicate's `ASSET` links moved while the merge was being checked, or a new event linked a duplicate meanwhile, or no dismissed status is live; EVENT_STATUS_RETIRED / EVENT_STATUS_UNKNOWN when the chosen dismissed status went meanwhile. More than 125 active links across the duplicates \u2014 theirs and those other events drew to them \u2014 refuses BAD_REQUEST `EVENTS_MERGE_TOO_LARGE` (`data {counted, bound, largestDuplicate}`) before anything is written \u2014 past the 10 000 links the reverse read takes, too, naming the over-limit duplicate: when one duplicate alone holds more, choose it as the survivor instead (a survivor's own links do not move); otherwise merge fewer duplicates at a time. More than 100 live observation readings cited on the moving links refuses BAD_REQUEST `EVENTS_CITATION_TOO_MANY` (`data {counted, bound}`) the same way, before any link ends. A merge may extend a fold chain: a duplicate that already has events folded into it is folded in turn, and they stay folded into it. A survivor holding more than 10 000 active links of its own refuses LINK_READ_LIMIT_EXCEEDED (the platform's exhaustive-read ceiling).\n\nDeclared refusals: NOT_FOUND, BAD_REQUEST, CONFLICT, EVENT_MERGE_PRECONDITION, EVENT_STATUS_RETIRED, EVENT_STATUS_UNKNOWN, LINK_CARDINALITY_VIOLATION, LINK_CYCLE, LINK_TYPE_RETIRED, LINK_OBJECT_UNAVAILABLE, LINK_PIN_UNRESOLVABLE, LINK_READ_INCOMPLETE, LINK_READ_LIMIT_EXCEEDED.",propose:"The automation's verb: one `candidate` of a Type with its links and slot values, atomically \u2014 one refused link refuses the whole call and nothing lands. A link's refusal keeps its own code and names the link: the message starts `link <n> of <total> (<type> \u2192 <domain>/<type>/<id>)` and `data.link` is `{index, linkType, object}` (0-based `index` beside the message's 1-based `<n>`, the caller's order); a fault is never named. An `ASSET` link is pinned to the asset version in effect at the proposed time (send no `objectVersion`; BAD_REQUEST `EVENTS_ASSET_VERSION_GIVEN` otherwise), a link to a work item or an event is pinned to the moment the proposal draws it, one instant for every such link of the call (send no `objectVersion`; BAD_REQUEST `EVENTS_EVIDENCE_VERSION_GIVEN` otherwise), a link to an event folded into another refuses LINK_OBJECT_UNAVAILABLE (naming it), and a `DUPLICATE_OF` is drawn only by `merge` (BAD_REQUEST `EVENTS_FOLD_LINK`). With no time given or filled, `knownDuring` is the proposal's own time. An optional `place` is `create`'s: an automation's is a fill and a person's is set, and either way an `ASSET` link's place fill is then skipped `set` in the Record's fills; EVENT_PLACE_INVALID when the geometry is not valid (e.g. self-intersecting) or over the 10,000-position cap \u2014 a malformed shape, or a coordinate array past 20,000 elements, is BAD_REQUEST at the wire instead; SERVICE_UNAVAILABLE with `data.code` EVENT_GEOMETRY_UNAVAILABLE on a deployment without PostGIS \u2014 both before any link is pinned and with nothing written. An automation is never warned; a person with an unmet policy check gets `warned` and nothing is written, and proceeds with `overridePolicy: true`. CONFLICT when the tenant has no live status in the candidate bucket (an admin must create one), or the Type or that status changed while the proposal was being checked (retry). ONE `events.propose` Record; the store stamps `viaFlowRun`. Composable at `tenantWrite`. A retried key answers the first call's receipt. An optional `sourceKey` \u2014 the recipe's opaque dedupe handle, trimmed, 1\u2013200 characters, unique per tenant AND Type across every bucket \u2014 answers `existing` {id, number} when an event of the tenant already holds it under that Type, creating nothing and filing a receipt Record (no effects) under the idempotency key, so a flow step ends a success; the key is looked up under a per-(tenant, Type, key) lock, so a concurrent second call naming it under that Type waits for the first, then answers `existing` once the first has committed; if the first rolled back, the second creates the event. CONFLICT with `data.sourceKey` if the key is claimed at the same moment by a write that took no lock \u2014 retry to answer `existing`. An optional `templateId` is `create`'s: NOT_FOUND when the tenant has no such template, BAD_REQUEST when it belongs to another event type, CONFLICT when it is retired; it is stored on the event, its slot values are the caller's \u2014 under any the caller sends for the same slot, and an automation's are fills in the Record's fills \u2014 and its severity and title pattern stand where the call names none. No `templateId` \u2192 no template applied.\n\nDeclared refusals: NOT_FOUND, BAD_REQUEST, CONFLICT, EVENT_TYPE_UNKNOWN, EVENT_SEVERITY_UNKNOWN, EVENT_CODELIST_TERM_UNKNOWN, EVENT_PLACE_INVALID, SERVICE_UNAVAILABLE, LINK_OBJECT_UNAVAILABLE, LINK_OBJECT_TYPE_NOT_ALLOWED, LINK_CARDINALITY_VIOLATION, LINK_CYCLE, LINK_OBJECT_NO_STANDING, LINK_ALREADY_ACTIVE, LINK_TYPE_RETIRED, LINK_TYPE_UNDECLARED, LINK_VERSION_REQUIRED, LINK_VERSION_NOT_ALLOWED, LINK_PIN_UNRESOLVABLE.",commentList:"The event's comments, oldest first (`createdAt`, then id), paged; a folded event's stay readable. `tenantRead`.\n\nDeclared refusals: NOT_FOUND, BAD_REQUEST (a garbled cursor).",commentAdd:`Append a comment, authored by the caller \u2014 there is no verb to edit or delete one, and the store refuses a raw write. One Record per comment.
197
197