@sensorup/sustudio 42.25.1 → 42.25.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/sustudio.mjs +4 -4
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.25.1"),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.25.2"),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
|
|
|
@@ -438,13 +438,13 @@ over SSH, in a container and in a headless shell, with nothing pasted back and n
|
|
|
438
438
|
port opened. Approve only a code that matches the one printed here.
|
|
439
439
|
If you interrupt this command after approving, the session it opened was never saved
|
|
440
440
|
here; nothing in Studio lists it for you to end, so it expires on its own after 8 hours.
|
|
441
|
-
`).action(flags=>runMapped(async()=>{let name2=selectedProfileName();if(flags.baseUrl!==void 0){let baseUrl=flags.baseUrl;typedAddressProfile(baseUrl,name2,reason=>{throw new CliInputError(`the Studio address given cannot be used: ${reason}`)}),asCliInput(()=>upsertLoginProfile({name:name2,baseUrl}))}let active=profileOf();if(active.auth.mode!=="login")throw new CliInputError(`profile "${active.name}" is ${active.auth.mode} \u2014 it has nothing to log in to. Create a login profile with: ${INVOCATION} login --profile <name> --base-url <origin>`);let confirmed;try{confirmed=await deviceLogin({profile:active,write,open:openBrowser})}catch(error62){if(error62 instanceof DeviceLoginError){writeError(stringifyRedacted({error:error62.message})),process.exitCode=1;return}throw error62}write(stringifyRedacted({...whoamiReport(active),confirmed:{subject:confirmed.subject,tenant:confirmed.tenant}},2))})),program3.command("logout").description("revoke this session\u2019s renewal chain server-side, then delete its cached credential").action(()=>runMapped(async()=>{let active;try{active=profileOf()}catch(error62){let missing=missingProfileOf(error62);if(missing===void 0)throw error62;let cached2=cachedSignInOf(missing.profileName);if(cached2 instanceof CredentialCacheError){if(missing instanceof UnknownProfileError)throw unknownNameUnreadableCache(missing,cached2);write(stringifyRedacted({profile:missing.profileName,removed:deleteCredential(missing.profileName),revoked:!1,detail:UNREADABLE_CACHE_DELETED},2));return}if(cached2!==void 0)active=cachedSignInProfile(missing.profileName,cached2);else if(missing instanceof NoStudioAddressError){write(stringifyRedacted({profile:missing.profileName,removed:!1,revoked:!1,detail:"nothing to remove \u2014 no Studio address is configured and nothing is cached"},2));return}else throw error62}let{removed,revoked}=await revokeThenDeleteCredential(active);write(stringifyRedacted(logoutReport(active,removed,revoked),2))})),program3.command("whoami").description("the active profile, its auth mode, and (login mode) session state").option("--check","also ask the server whether it accepts the session, renewing it first if it is expiring").action(flags=>runMapped(async()=>{let active;try{active=profileOf()}catch(error62){let missing=missingProfileOf(error62);if(missing===void 0)throw error62;let cached2=cachedSignInOf(missing.profileName);if(cached2 instanceof CredentialCacheError&&missing instanceof UnknownProfileError)throw unknownNameUnreadableCache(missing,cached2);if(cached2!==void 0&&!(cached2 instanceof CredentialCacheError))active=cachedSignInProfile(missing.profileName,cached2);else{if(!(missing instanceof NoStudioAddressError))throw error62;let noAddress=missing;write(stringifyRedacted({profile:noAddress.profileName,...cached2===void 0?{session:"none",detail:"no Studio address is configured"}:{session:"unreadable",detail:cached2.message},hint:`run: ${noAddress.command}`,build:artifactBuildReport({})},2));return}}if(flags.check!==!0||active.auth.mode!=="login"){write(stringifyRedacted(whoamiReport(active),2));return}let server=await checkSessionWithServer(active);write(stringifyRedacted({...whoamiReport(active),server},2))})),program3}var VERB_SEGMENT_PATTERN=/^[a-zA-Z][a-zA-Z0-9]*$/,DOMAIN_VERB_PATTERN=/^[a-z][a-z0-9-]*\.[a-zA-Z][a-zA-Z0-9]*$/,QUALIFIED_ACTION_PATTERN=/^[a-z][a-z0-9-]*(\.[a-zA-Z][a-zA-Z0-9]*)+$/,DOMAIN_VIEW_ACTION_PATTERN=/^[a-z][a-z0-9-]*:view$/,CONTRACT_PROCEDURE_PATTERN=/^[a-zA-Z][a-zA-Z0-9]*(\.[a-zA-Z][a-zA-Z0-9]*)*$/,JOB_FIELD_PATTERN=/^[A-Za-z_][A-Za-z0-9_-]*$/,RESOURCE_KIND_PATTERN=/^[a-z][a-z0-9-]*\.[a-z][a-z0-9_-]*$/;var LINK_TYPE_CODE_PATTERN=/^[A-Za-z][A-Za-z0-9_-]*$/,LINK_TENANT_TYPE_CODE_PREFIX="CUSTOM_",LINK_MODULE_NAME_PATTERN=/^[a-z][a-z0-9-]*$/,LINK_RECORD_TYPE_PATTERN=/^[a-z][a-z0-9_-]*$/,LINK_PINNINGS=["pinned","following"],LINK_ENFORCEMENT_CLASSES=["structural","fold","display-only"],LINK_CARDINALITY_SIDES=["subject","object"],LINK_CONSTRAINT_KEYS=["cardinality","acyclic"],LinkObjectTypeSchema=external_exports.strictObject({domain:external_exports.string().regex(LINK_MODULE_NAME_PATTERN),type:external_exports.string().regex(LINK_RECORD_TYPE_PATTERN)}),LinkCardinalityConstraintSchema=external_exports.strictObject({side:external_exports.enum(LINK_CARDINALITY_SIDES),max:external_exports.literal(1)}),LinkTypeConstraintsSchema=external_exports.strictObject({cardinality:LinkCardinalityConstraintSchema.optional(),acyclic:external_exports.literal(!0).optional()},{error:issue2=>issue2.code==="unrecognized_keys"?`unknown link constraint key(s) ${issue2.keys.map(key=>`"${key}"`).join(", ")} \u2014 the closed vocabulary is ${LINK_CONSTRAINT_KEYS.join(", ")}`:void 0}).refine(constraints=>constraints.cardinality!==void 0||constraints.acyclic,{message:`constraints declares nothing \u2014 name at least one of ${LINK_CONSTRAINT_KEYS.join(", ")}, or omit it on a non-structural type`,when:payload=>payload.issues.length===0}),LinkTypeDeclarationSchema=external_exports.strictObject({code:external_exports.string().regex(LINK_TYPE_CODE_PATTERN),name:external_exports.string().min(1),inverseName:external_exports.string().min(1),allowedObjects:external_exports.array(LinkObjectTypeSchema),pinning:external_exports.enum(LINK_PINNINGS).optional(),enforcementClass:external_exports.enum(LINK_ENFORCEMENT_CLASSES),constraints:LinkTypeConstraintsSchema.optional(),system:external_exports.literal(!0,{error:"a declared link type is shipped \u2014 system is true or omitted; a tenant-added type is created by linkTypes.create, never declared"}).optional()}).superRefine((declaration,ctx)=>{declaration.code.startsWith(LINK_TENANT_TYPE_CODE_PREFIX)&&ctx.addIssue({code:"custom",path:["code"],message:`link type "${declaration.code}" takes the "${LINK_TENANT_TYPE_CODE_PREFIX}" prefix, which is reserved for tenant-added types \u2014 a shipped code may not begin with it`}),declaration.allowedObjects.length===0&&ctx.addIssue({code:"custom",path:["allowedObjects"],message:`link type "${declaration.code}" allows no objects \u2014 allowedObjects must name at least one {domain, type}`}),declaration.enforcementClass==="structural"&&declaration.constraints===void 0&&ctx.addIssue({code:"custom",path:["constraints"],message:`link type "${declaration.code}" is structural but declares no constraints`}),declaration.enforcementClass!=="structural"&&declaration.constraints!==void 0&&ctx.addIssue({code:"custom",path:["constraints"],message:`link type "${declaration.code}" is ${declaration.enforcementClass} but declares constraints \u2014 a constraint is only legal on a structural type`})}),LinkTypesManifestFacetSchema=external_exports.array(LinkTypeDeclarationSchema).superRefine((declarations,ctx)=>{let seen=new Set;declarations.forEach((declaration,index)=>{seen.has(declaration.code)&&ctx.addIssue({code:"custom",path:[index,"code"],message:`link type "${declaration.code}" is declared twice \u2014 a code is unique within its slice`}),seen.add(declaration.code)})}),LinkableStandingSchema=external_exports.union([external_exports.literal("on-create"),external_exports.strictObject({promotedBy:external_exports.string().regex(DOMAIN_VERB_PATTERN)})]),LinkableDeclarationSchema=external_exports.strictObject({type:external_exports.string().regex(LINK_RECORD_TYPE_PATTERN),standing:LinkableStandingSchema}),LinkableManifestFacetSchema=external_exports.array(LinkableDeclarationSchema).superRefine((declarations,ctx)=>{let seen=new Set;declarations.forEach((declaration,index)=>{seen.has(declaration.type)&&ctx.addIssue({code:"custom",path:[index,"type"],message:`record type "${declaration.type}" is declared linkable twice`}),seen.add(declaration.type)})});var ReadContractDeclarationSchema=external_exports.strictObject({name:external_exports.string().regex(VERB_SEGMENT_PATTERN,"read contract name must match the verb-segment grammar"),version:external_exports.number().int().positive(),procedurePath:external_exports.string().regex(CONTRACT_PROCEDURE_PATTERN),title:external_exports.string().trim().min(1).max(120).optional(),description:external_exports.string().trim().min(1).max(500).optional(),composable:external_exports.boolean(),answers:external_exports.literal("complete"),viewPermission:external_exports.string().refine(action=>DOMAIN_VERB_PATTERN.test(action)||DOMAIN_VIEW_ACTION_PATTERN.test(action),'viewPermission must be "<domain>.<verb>" or "<domain>:view"').optional()}),ReadContractsManifestFacetSchema=external_exports.array(ReadContractDeclarationSchema);var RECIPE_NAME_PATTERN=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,RECIPE_MAP_MAX=64;var RECIPE_PARAMETER_MAX=64,RECIPE_STEP_MAX=128,VALUE_PATH_PATTERN=/^[A-Za-z_][A-Za-z0-9_-]*(?:\.[A-Za-z_][A-Za-z0-9_-]*)*$/,ParameterName=external_exports.string().regex(VERB_SEGMENT_PATTERN),ParameterWords={title:external_exports.string().min(1).max(80),help:external_exports.string().min(1).max(400).optional()},Optional={optional:external_exports.literal(!0).optional()},RecipeEntityHintSchema=external_exports.strictObject({domain:external_exports.string().min(1),type:external_exports.string().min(1),pickerResource:external_exports.string().min(1).optional(),scopedBy:external_exports.record(external_exports.string().min(1),ParameterName).optional(),pinsTo:external_exports.strictObject({picker:external_exports.string().min(1)}).optional()}),StringParameterSchema=external_exports.strictObject({type:external_exports.literal("string"),...ParameterWords,...Optional,segment:external_exports.literal(!0).optional(),maxLength:external_exports.int().min(1).max(4096).optional()}),NumberParameterSchema=external_exports.strictObject({type:external_exports.literal("number"),...ParameterWords,...Optional,integer:external_exports.literal(!0).optional(),min:external_exports.number().optional(),max:external_exports.number().optional()}),BooleanParameterSchema=external_exports.strictObject({type:external_exports.literal("boolean"),...ParameterWords,...Optional}),EntityParameterSchema=external_exports.strictObject({type:external_exports.literal("entity"),...ParameterWords,...Optional,hint:RecipeEntityHintSchema}),RecipeValueParameterSchema=external_exports.discriminatedUnion("type",[StringParameterSchema,NumberParameterSchema,BooleanParameterSchema,EntityParameterSchema]),MapParameterSchema=external_exports.strictObject({type:external_exports.literal("map"),...ParameterWords,of:RecipeValueParameterSchema,min:external_exports.int().min(0).max(RECIPE_MAP_MAX).optional(),max:external_exports.int().min(1).max(RECIPE_MAP_MAX),keyTitle:external_exports.string().min(1).max(80)}).refine(map2=>(map2.min??0)<=map2.max,{message:"min must not exceed max"}),RecipeParameterSchema=external_exports.discriminatedUnion("type",[StringParameterSchema,NumberParameterSchema,BooleanParameterSchema,EntityParameterSchema,MapParameterSchema]),RecipeParamRefSchema=external_exports.strictObject({param:ParameterName,path:external_exports.string().regex(VALUE_PATH_PATTERN).optional()}),EntryPath=external_exports.union([external_exports.literal(""),external_exports.string().regex(VALUE_PATH_PATTERN)]),RecipeEntryRefSchema=external_exports.strictObject({entry:EntryPath}),RecipeEachEntryRefSchema=external_exports.strictObject({each:ParameterName,entry:EntryPath}),ScalarLeafSchema=external_exports.union([external_exports.string(),external_exports.number(),external_exports.boolean(),external_exports.null()]),RecipeLeafSchema=external_exports.union([ScalarLeafSchema,RecipeParamRefSchema,RecipeEntryRefSchema,RecipeEachEntryRefSchema]),RecipeVerbStepTemplateSchema=external_exports.strictObject({id:external_exports.string().min(1).max(200),type:external_exports.literal("verb").optional(),each:ParameterName.optional(),verb:external_exports.string().regex(DOMAIN_VERB_PATTERN),args:external_exports.record(external_exports.string().min(1),RecipeLeafSchema)}),DurationSchema=external_exports.strictObject({amount:external_exports.number(),unit:external_exports.string().min(1)}),BranchGateTemplateSchema=external_exports.strictObject({kind:external_exports.literal("branch"),config:external_exports.strictObject({cases:external_exports.array(external_exports.strictObject({when:external_exports.strictObject({field:external_exports.string().min(1),op:external_exports.string().min(1),value:external_exports.union([RecipeLeafSchema,external_exports.array(RecipeLeafSchema).min(1)])}),next:external_exports.string().min(1)})).min(1),otherwise:external_exports.union([external_exports.strictObject({next:external_exports.string().min(1)}),external_exports.strictObject({end:external_exports.literal(!0)})]),merge:external_exports.string().min(1)})}),JobGateTemplateSchema=external_exports.strictObject({kind:external_exports.literal("job"),config:external_exports.strictObject({startedBy:external_exports.string().min(1),giveUpAfter:DurationSchema.optional()})}),DelayGateTemplateSchema=external_exports.strictObject({kind:external_exports.literal("delay"),config:external_exports.strictObject({duration:DurationSchema})}),RecipeGateStepTemplateSchema=external_exports.strictObject({id:external_exports.string().min(1).max(200),type:external_exports.literal("gate"),gate:external_exports.discriminatedUnion("kind",[BranchGateTemplateSchema,JobGateTemplateSchema,DelayGateTemplateSchema])}),RecipeStepTemplateSchema=external_exports.union([RecipeVerbStepTemplateSchema,RecipeGateStepTemplateSchema]),RecipeDefinitionTemplateSchema=external_exports.strictObject({compensation:external_exports.string().min(1),inputSchema:external_exports.strictObject({fields:external_exports.record(external_exports.string().min(1),external_exports.record(external_exports.string(),external_exports.unknown()))}).optional(),steps:external_exports.array(RecipeStepTemplateSchema).min(1).max(RECIPE_STEP_MAX)}),MappingLeafSchema=external_exports.union([ScalarLeafSchema,RecipeParamRefSchema]),RecipeMappingValueSchema=external_exports.union([MappingLeafSchema,external_exports.record(external_exports.string().min(1),MappingLeafSchema)]),RecipeBindingTemplateSchema=external_exports.strictObject({recordAction:external_exports.string().regex(DOMAIN_VERB_PATTERN),match:external_exports.record(external_exports.string().min(1),MappingLeafSchema).optional(),inputMapping:external_exports.record(external_exports.string().min(1),RecipeMappingValueSchema)}),RecipeDeclarationSchema=external_exports.strictObject({name:external_exports.string().max(64).regex(RECIPE_NAME_PATTERN),title:external_exports.string().min(1).max(80),description:external_exports.string().min(1).max(400),parameters:external_exports.record(ParameterName,RecipeParameterSchema).refine(parameters=>Object.keys(parameters).length<=RECIPE_PARAMETER_MAX,{message:`a recipe declares at most ${String(RECIPE_PARAMETER_MAX)} parameters`}),definition:RecipeDefinitionTemplateSchema,binding:RecipeBindingTemplateSchema.optional()}),RecipesManifestFacetSchema=external_exports.array(RecipeDeclarationSchema);var LabelWordsSchema=external_exports.strictObject({singular:external_exports.string().min(1).max(60),plural:external_exports.string().min(1).max(60)}),SignOffLabelSchema=LabelWordsSchema.extend({short:LabelWordsSchema.optional()}).strict(),SignOffStepDeclarationSchema=external_exports.strictObject({id:external_exports.string().regex(VERB_SEGMENT_PATTERN),verb:external_exports.string().regex(VERB_SEGMENT_PATTERN),subjectIdArg:external_exports.string().regex(VERB_SEGMENT_PATTERN),factsArg:external_exports.string().regex(VERB_SEGMENT_PATTERN).optional(),factRecordArg:external_exports.string().regex(VERB_SEGMENT_PATTERN).optional()}),NewerRunSchema=external_exports.enum(["supersede","keep"]),SignOffStepsDeclarationSchema=external_exports.strictObject({inputField:external_exports.string().regex(VERB_SEGMENT_PATTERN),before:external_exports.array(SignOffStepDeclarationSchema).max(4),after:external_exports.array(SignOffStepDeclarationSchema).max(4),newerRun:NewerRunSchema.optional(),ownerHost:external_exports.strictObject({host:external_exports.strictObject({domain:external_exports.string().min(1),type:external_exports.string().min(1)}),slot:external_exports.string().min(1),label:external_exports.string().min(1).max(60)}).optional()}),FACT_PATH_PATTERN=/^[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)+$/,SignOffKindFactSchema=external_exports.strictObject({name:external_exports.string().regex(VERB_SEGMENT_PATTERN),label:external_exports.string().min(1).max(60),path:external_exports.string().regex(FACT_PATH_PATTERN)}),SIGN_OFF_FACTS_MAX=16,SignOffKindFactsSchema=external_exports.array(SignOffKindFactSchema).min(1).max(SIGN_OFF_FACTS_MAX).refine(facts=>new Set(facts.map(fact=>fact.name)).size===facts.length,{message:"each fact name appears once"}),EntityKindFields={domain:external_exports.string().min(1),type:external_exports.string().min(1)},SignOffFactSubjectSchema=external_exports.strictObject({...EntityKindFields,idPath:external_exports.string().min(1),versionPath:external_exports.string().min(1).optional()}),SignOffFactScopeSchema=external_exports.strictObject({path:external_exports.string().min(1),...EntityKindFields,pickerResource:external_exports.string().min(1).optional()}),SignOffFactSchema=external_exports.strictObject({label:external_exports.string().min(1).max(80),subjects:external_exports.array(SignOffFactSubjectSchema).min(1).max(4),scopes:external_exports.array(SignOffFactScopeSchema).max(8)});var asSchema=value2=>value2 instanceof external_exports.ZodType?value2:void 0;function unwrapOnce(schema){if(schema instanceof external_exports.ZodOptional||schema instanceof external_exports.ZodNullable||schema instanceof external_exports.ZodDefault||schema instanceof external_exports.ZodPrefault||schema instanceof external_exports.ZodCatch||schema instanceof external_exports.ZodReadonly||schema instanceof external_exports.ZodLazy)return asSchema(schema.unwrap())}function unwrapSchema(schema){let current=schema;for(let depth=0;depth<32;depth+=1){let next=unwrapOnce(current);if(next===void 0)return current;current=next}return current}function shapeOf(schema){let unwrapped=unwrapSchema(schema);if(!(unwrapped instanceof external_exports.ZodObject))return;let shape=unwrapped.shape,entries=Object.entries(shape).flatMap(([key,value2])=>{let field=asSchema(value2);return field===void 0?[]:[[key,field]]});return Object.fromEntries(entries)}function unionOptionsOf(schema){let unwrapped=unwrapSchema(schema);return unwrapped instanceof external_exports.ZodUnion?unwrapped.def.options.flatMap(option=>{let branch=asSchema(option);return branch===void 0?[]:[branch]}):void 0}function literalValuesOf(schema){let unwrapped=unwrapSchema(schema);if(unwrapped instanceof external_exports.ZodEnum)return unwrapped.options.filter(value2=>typeof value2=="string");if(unwrapped instanceof external_exports.ZodLiteral)return[...unwrapped.values].filter(value2=>typeof value2=="string");let branches=unionOptionsOf(unwrapped);if(branches!==void 0){let perBranch=branches.map(branch=>literalValuesOf(branch));return perBranch.some(values2=>values2===void 0)?void 0:perBranch.flatMap(values2=>values2??[])}}function indexedElements(schema){let collect=values2=>{let elements2=values2.flatMap(value2=>{let element=asSchema(value2);return element===void 0?[]:[element]});return elements2.length===0?void 0:elements2};if(schema instanceof external_exports.ZodArray)return collect([schema.element]);if(schema instanceof external_exports.ZodSet)return collect([schema.def.valueType]);if(schema instanceof external_exports.ZodMap)return collect([schema.def.valueType]);if(schema instanceof external_exports.ZodTuple){let items=schema.def.items;return collect([...items,schema.def.rest])}}function keyedMembers(schema){if(schema instanceof external_exports.ZodObject)return Object.entries(shapeOf(schema)??{});if(schema instanceof external_exports.ZodRecord){let value2=asSchema(schema.def.valueType);return value2===void 0?[]:[["*",value2]]}return schema instanceof external_exports.ZodUnion?(unionOptionsOf(schema)??[]).map(branch=>["",branch]):schema instanceof external_exports.ZodIntersection?[asSchema(schema.def.left),asSchema(schema.def.right)].flatMap(side=>side===void 0?[]:[["",side]]):[]}function recordKeysAreNameable(schema){let keyType=asSchema(schema.def.keyType);if(keyType===void 0)return!1;let literals=literalValuesOf(keyType);return literals!==void 0?literals.length>0&&literals.every(value2=>JOB_FIELD_PATTERN.test(value2)):(unwrapSchema(keyType).def.checks??[]).some(check2=>regexOf(check2)===patternIdentity(JOB_FIELD_PATTERN))}var patternIdentity=pattern=>`${pattern.source}/${pattern.flags}`;function regexOf(check2){let inner=check2===null||typeof check2!="object"?void 0:Reflect.get(check2,"_zod"),def=inner===null||typeof inner!="object"?void 0:Reflect.get(inner,"def"),pattern=def===null||typeof def!="object"?void 0:Reflect.get(def,"pattern");return pattern instanceof RegExp?patternIdentity(pattern):void 0}var join4=(path3,segment)=>segment===""?path3:path3===""?segment:`${path3}.${segment}`,MAX_DETAIL_DEPTH=24;function firstNamedPath(schema,depth){if(depth>=MAX_DETAIL_DEPTH)return"";let unwrapped=unwrapSchema(schema);for(let[segment,member]of keyedMembers(unwrapped))return join4(segment,firstNamedPath(member,depth+1));return""}function unwalkableCompletionDetailPath(schema){let visit2=(current,path3,depth)=>{if(depth>=MAX_DETAIL_DEPTH)return;let unwrapped=unwrapSchema(current);if(unwrapped instanceof external_exports.ZodRecord&&!recordKeysAreNameable(unwrapped))return join4(path3,"*");let elements2=indexedElements(unwrapped);if(elements2!==void 0){for(let element of elements2){let inner=unwrapSchema(element);if(keyedMembers(inner).length===0&&indexedElements(inner)===void 0)continue;let beneath=firstNamedPath(element,depth+1);return`${path3}[]${beneath===""?"":`.${beneath}`}`}return}for(let[segment,member]of keyedMembers(unwrapped)){let found=visit2(member,join4(path3,segment),depth+1);if(found!==void 0)return found}};return visit2(schema,"",0)}var StartsJobSchema=external_exports.strictObject({handleField:external_exports.string().regex(JOB_FIELD_PATTERN,"handleField must be a walkable field name"),completionAction:external_exports.string().regex(DOMAIN_VERB_PATTERN,"completionAction must be <domain>.<verb>"),status:external_exports.string().regex(CONTRACT_PROCEDURE_PATTERN,"status must be a contract path"),completionDetail:external_exports.custom(value2=>value2 instanceof external_exports.ZodType,{message:"completionDetail must be a zod schema"}),cancel:external_exports.string().regex(VERB_SEGMENT_PATTERN,"cancel must be a verb name").optional(),panel:external_exports.string().min(1).optional(),waitOnly:external_exports.literal(!0).optional()}).superRefine((declaration,ctx)=>{let unwalkable=unwalkableCompletionDetailPath(declaration.completionDetail);unwalkable!==void 0&&ctx.addIssue({code:"custom",path:["completionDetail"],message:`completionDetail holds "${unwalkable}" \u2014 no dot expression can walk it (O7): an array between its root and a leaf, or a record whose key schema lets a key be anything. Publish a KEYED PROJECTION of those members instead, keyed by their own declared name, and seal that shape`})});var JOB_STATE_WORDS=Object.freeze({pending:"running",queued:"running",running:"running",completed:"completed",failed:"failed"}),TERMINAL_STATE_WORDS=Object.entries(JOB_STATE_WORDS).flatMap(([word,engine])=>engine==="running"?[]:[word]);var VERB_GRADES=["G0","G1","G2","G3"],VerbGradeSchema=external_exports.enum(VERB_GRADES),VerbDialSchema=external_exports.object({target:VerbGradeSchema,enforced:VerbGradeSchema}).refine(dial=>VERB_GRADES.indexOf(dial.enforced)<=VERB_GRADES.indexOf(dial.target),{message:"verb dial: enforced grade must be \u2264 target grade"}),REFUSAL_CODE_PATTERN=/^[A-Z][A-Z0-9_]*$/,VerbDeclarationSchema=external_exports.object({name:external_exports.string().regex(VERB_SEGMENT_PATTERN,"verb name must match the verb-segment grammar"),version:external_exports.number().int().positive(),title:external_exports.string().trim().min(1).max(120).optional(),description:external_exports.string().trim().min(1).max(500).optional(),dial:VerbDialSchema.optional(),procedurePath:external_exports.string().regex(CONTRACT_PROCEDURE_PATTERN).optional(),composable:external_exports.boolean(),startsJob:StartsJobSchema.optional(),needsJobsWaited:external_exports.literal(!0).optional(),signOffFact:SignOffFactSchema.optional(),personFacingRefusals:external_exports.array(external_exports.string().regex(REFUSAL_CODE_PATTERN,"a refusal code is SCREAMING_SNAKE_CASE")).min(1).refine(codes=>new Set(codes).size===codes.length,"refusal codes are listed once").optional()}),AUTHZ_AUTHORITIES=["view","edit","manage"],PLATFORM_RESOURCE_KIND_PREFIX="platform.",AUTHZ_TENANT_ROOT_KIND=`${PLATFORM_RESOURCE_KIND_PREFIX}tenant`,ScopingModeSchema=external_exports.discriminatedUnion("mode",[external_exports.object({mode:external_exports.literal("hierarchical")}),external_exports.object({mode:external_exports.literal("derived-via-link"),refColumn:external_exports.string().min(1)}),external_exports.object({mode:external_exports.literal("tenant-wide")})]),AuthzResourceTypeSchema=external_exports.object({name:external_exports.string().regex(RESOURCE_KIND_PATTERN),scoping:ScopingModeSchema,attributes:external_exports.array(external_exports.string())}),PROCEDURE_PATH_PATTERN=/^[a-zA-Z][a-zA-Z0-9]*(\.[a-zA-Z][a-zA-Z0-9]*)+$/,AuthzVerbSchema=external_exports.object({verb:external_exports.string().regex(VERB_SEGMENT_PATTERN),requiredAuthority:external_exports.enum(AUTHZ_AUTHORITIES),targetResourceType:external_exports.string().min(1),procedurePath:external_exports.string().regex(PROCEDURE_PATH_PATTERN).optional(),reachesBelowTenant:external_exports.boolean().optional()}),AuthzDeclarationSchema=external_exports.object({resourceTypes:external_exports.array(AuthzResourceTypeSchema),verbs:external_exports.array(AuthzVerbSchema),noTenantWriteSurface:external_exports.literal(!0).optional(),noGovernedVerb:external_exports.array(external_exports.object({procedurePath:external_exports.string().regex(PROCEDURE_PATH_PATTERN),reason:external_exports.string().min(1)})).optional()}).refine(declaration=>declaration.noTenantWriteSurface!==!0||declaration.verbs.length===0,{message:"noTenantWriteSurface claims the module mounts nothing on a tenant write tier, but authz.verbs declares authority verbs",path:["noTenantWriteSurface"]}),SnapshotMintDeclarationSchema=external_exports.strictObject({procedurePath:external_exports.string().regex(CONTRACT_PROCEDURE_PATTERN),kindLabels:external_exports.record(external_exports.string().min(1),SignOffLabelSchema).optional(),signOffSteps:external_exports.record(external_exports.string().min(1),SignOffStepsDeclarationSchema).optional(),signOffFacts:external_exports.record(external_exports.string().min(1),SignOffKindFactsSchema).optional()}),DomainReadsSchema=external_exports.strictObject({snapshotMint:SnapshotMintDeclarationSchema.optional()}),CodelistTermDefaultSchema=external_exports.strictObject({code:external_exports.string().min(1),label:external_exports.string().min(1),description:external_exports.string().optional(),system:external_exports.boolean().optional()}),CodelistDeclarationSchema=external_exports.strictObject({codelist:external_exports.string().min(1),defaultTerms:external_exports.array(CodelistTermDefaultSchema)}),CodelistsManifestFacetSchema=external_exports.strictObject({codelists:external_exports.array(CodelistDeclarationSchema)}),AgentGuidanceSourceSchema=external_exports.discriminatedUnion("kind",[external_exports.strictObject({kind:external_exports.literal("repoFile"),text:external_exports.string().min(1)}),external_exports.strictObject({kind:external_exports.literal("generated"),text:external_exports.string().min(1)})]),AgentGuidanceResourceSchema=external_exports.strictObject({uri:external_exports.string().min(1),name:external_exports.string().min(1),description:external_exports.string().min(1),mimeType:external_exports.string().min(1),source:AgentGuidanceSourceSchema}),AgentGuidancePromptArgumentSchema=external_exports.strictObject({name:external_exports.string().min(1),description:external_exports.string().min(1),required:external_exports.boolean().optional()}),AgentGuidancePromptSchema=external_exports.strictObject({name:external_exports.string().min(1),description:external_exports.string().min(1),arguments:external_exports.array(AgentGuidancePromptArgumentSchema),template:external_exports.string().min(1)}),AgentGuidanceManifestFacetSchema=external_exports.strictObject({scheme:external_exports.string().regex(/^[a-z][a-z0-9+.-]*$/u),resources:external_exports.array(AgentGuidanceResourceSchema),prompts:external_exports.array(AgentGuidancePromptSchema)}),DomainManifestSchema=external_exports.object({name:external_exports.string().min(1),plane:external_exports.literal("resource"),events:external_exports.array(external_exports.string()),routerKey:external_exports.string().min(1),verbs:external_exports.array(VerbDeclarationSchema).optional(),reads:DomainReadsSchema.optional(),readContracts:ReadContractsManifestFacetSchema.optional(),authz:AuthzDeclarationSchema,codelists:CodelistsManifestFacetSchema.optional(),agentGuidance:AgentGuidanceManifestFacetSchema.optional(),linkTypes:LinkTypesManifestFacetSchema.optional(),linkable:LinkableManifestFacetSchema.optional(),recipes:RecipesManifestFacetSchema.optional()});var PlatformManifestSchema=external_exports.object({name:external_exports.string().min(1),plane:external_exports.literal("platform"),events:external_exports.array(external_exports.string()),routerKey:external_exports.string().min(1),verbs:external_exports.array(VerbDeclarationSchema).optional(),authz:AuthzDeclarationSchema,codelists:CodelistsManifestFacetSchema.optional(),agentGuidance:AgentGuidanceManifestFacetSchema.optional(),linkTypes:LinkTypesManifestFacetSchema.optional(),linkable:LinkableManifestFacetSchema.optional()});var IdempotencyKeySchema=external_exports.string().min(1).describe("Client-minted replay key for this governed write \u2014 YOU generate it (a UUID is fine), the server never does. REPLAY SEMANTICS: once a call has COMPLETED, reusing its key returns that original receipt without re-executing. A call refused before its change applied filed no receipt, so the same key is free to run again \u2014 but a refusal that says the change landed, or may have landed, outside this server means exactly that: re-read before re-sending. Mint a NEW key whenever you change the inputs; reuse one only to safely re-send the identical intent, e.g. after a network timeout."),RecordIdSchema=external_exports.string().min(1).brand(),EntityRefSchema=external_exports.object({domain:external_exports.string().min(1),type:external_exports.string().min(1),id:external_exports.string().min(1),version:external_exports.string().min(1).optional()});var EntitySnapshotRefSchema=external_exports.object({domain:external_exports.string().min(1),type:external_exports.string().min(1),id:external_exports.string().min(1),snapshot:external_exports.string().min(1).describe("Opaque snapshot identity minted by the owning domain \u2014 get it from that domain's own `snapshot` procedure. Never construct or parse one: the same value always means the same content, and any change to the entity yields a new value.")}),ENTITY_REF_MAX_KIND_CHARS=64,ENTITY_REF_MAX_IDENTITY_CHARS=200,RecordIdInputSchema=RecordIdSchema.max(ENTITY_REF_MAX_IDENTITY_CHARS),EntityRefInputSchema=EntityRefSchema.extend({domain:EntityRefSchema.shape.domain.max(ENTITY_REF_MAX_KIND_CHARS),type:EntityRefSchema.shape.type.max(ENTITY_REF_MAX_KIND_CHARS),id:EntityRefSchema.shape.id.max(ENTITY_REF_MAX_IDENTITY_CHARS),version:EntityRefSchema.shape.version.unwrap().max(ENTITY_REF_MAX_IDENTITY_CHARS).optional()}),EntitySnapshotRefInputSchema=EntitySnapshotRefSchema.extend({domain:EntitySnapshotRefSchema.shape.domain.max(ENTITY_REF_MAX_KIND_CHARS),type:EntitySnapshotRefSchema.shape.type.max(ENTITY_REF_MAX_KIND_CHARS),id:EntitySnapshotRefSchema.shape.id.max(ENTITY_REF_MAX_IDENTITY_CHARS),snapshot:EntitySnapshotRefSchema.shape.snapshot.max(ENTITY_REF_MAX_IDENTITY_CHARS)}),ActionRefSchema=external_exports.object({name:external_exports.string().regex(QUALIFIED_ACTION_PATTERN,"action name must be dot-qualified"),version:external_exports.number().int().positive()}),ActorSchema=external_exports.object({principal:external_exports.string().min(1),onBehalfOf:external_exports.string().min(1).optional(),viaFlowRun:external_exports.string().min(1).optional(),originFlowRun:external_exports.string().min(1).optional()}),WriteActorSchema=ActorSchema.omit({viaFlowRun:!0,originFlowRun:!0}),RecordStatusSchema=external_exports.enum(["in-flight","committed","failed"]),ActionRecordSchema=external_exports.object({id:RecordIdSchema,tenantId:external_exports.string().min(1),action:ActionRefSchema,actor:ActorSchema,time:external_exports.iso.datetime(),params:external_exports.unknown(),effects:external_exports.array(EntityRefSchema),reads:external_exports.array(EntityRefSchema),status:RecordStatusSchema,committedAt:external_exports.iso.datetime().optional(),idempotencyKey:IdempotencyKeySchema,detail:external_exports.unknown().optional()}),FlowRunOutcomeSchema=external_exports.enum(["completed","completed-with-account","ended-at-branch","ended-at-gate"]),FlowRunRecordSchema=ActionRecordSchema.extend({definition:external_exports.object({name:external_exports.string().min(1),version:external_exports.number().int().positive()}),steps:external_exports.array(RecordIdSchema),outcome:FlowRunOutcomeSchema.optional()}),WriteRecordInputSchema=ActionRecordSchema.omit({id:!0,tenantId:!0,time:!0,status:!0}).extend({actor:WriteActorSchema}),VerbEnvelopeInputSchema=WriteRecordInputSchema.omit({effects:!0,detail:!0});var ReactionSchema=external_exports.object({type:external_exports.literal("toast"),message:external_exports.string().min(1).optional()}).strict(),ActionBindingExprSchema=external_exports.discriminatedUnion("source",[external_exports.object({source:external_exports.literal("literal"),value:external_exports.unknown()}).strict(),external_exports.object({source:external_exports.literal("subject"),as:external_exports.enum(["identity","id"])}).strict(),external_exports.object({source:external_exports.literal("selection"),channel:external_exports.string().min(1)}).strict(),external_exports.object({source:external_exports.literal("prompt"),label:external_exports.string().min(1).max(200).optional(),help:external_exports.string().min(1).max(500).optional()}).strict()]),ActionSchema=external_exports.object({definition:external_exports.string().min(1),label:external_exports.string().min(1),confirmLabel:external_exports.string().min(1).optional(),input:external_exports.record(external_exports.string().min(1),ActionBindingExprSchema),onCommitted:ReactionSchema,onFailed:ReactionSchema,onParked:ReactionSchema.optional()}).strict();var ACTION_SLOT_MARKER="forge:actionSlot",MAX_ACTIONS_PER_SLOT=20;function actionSlot(opts){return external_exports.array(ActionSchema).max(MAX_ACTIONS_PER_SLOT).meta({[ACTION_SLOT_MARKER]:{subject:opts.subject}})}function peelDeclarationWrappers(schema){let candidate=schema;for(;candidate instanceof external_exports.ZodOptional||candidate instanceof external_exports.ZodDefault||candidate instanceof external_exports.ZodNullable||candidate instanceof external_exports.ZodReadonly||candidate instanceof external_exports.ZodCatch||candidate instanceof external_exports.ZodPrefault;)candidate=candidate.unwrap();return candidate}var CHANNEL_PAYLOAD_TYPES=["string","number","boolean","ref","entity-ref"],ChannelDeclarationSchema=external_exports.object({name:external_exports.string().min(1),payload:external_exports.enum(CHANNEL_PAYLOAD_TYPES),scope:external_exports.enum(["page","solution"])}).strict(),MAX_CHANNELS_PER_PAGE=20,MAX_CHANNELS_PER_SOLUTION=20;var NON_BLANK_TRIMMED_RE=/^\S(.*\S)?(?![\s\S])/,CONFIG_VERSION_RE=/^[1-9][0-9]*$/;var PICK_KINDS=["dimension.member","geo.within","assets.set"],PickKindSchema=external_exports.enum(PICK_KINDS),PICK_ASSET_SET_MAX=200,MAX_PICK_RENDITIONS=3,MAX_PICK_LABEL_LENGTH=60,MAX_PICK_RING_POSITIONS=1e3,MAX_PICK_PART_CHARS=200;var PickPositionSchema=external_exports.tuple([external_exports.number().min(-180).max(180),external_exports.number().min(-90).max(90)]),isClosedRing=ring=>{let first=ring[0],last=ring.at(-1);return first!==void 0&&last!==void 0&&first[0]===last[0]&&first[1]===last[1]},PickPolygonSchema=external_exports.strictObject({type:external_exports.literal("Polygon"),coordinates:external_exports.array(external_exports.array(PickPositionSchema).min(4).max(MAX_PICK_RING_POSITIONS).refine(isClosedRing,"a ring is closed: its first position equals its last")).min(1).max(1)}),PickEntityRefSchema=external_exports.strictObject({domain:external_exports.string().min(1).max(64),type:external_exports.string().min(1).max(64)}),PickRenditionSchema=external_exports.discriminatedUnion("kind",[external_exports.strictObject({kind:external_exports.literal("dimension.member"),dimension:external_exports.string().min(1).max(MAX_PICK_PART_CHARS),value:external_exports.string().max(MAX_PICK_PART_CHARS),refersTo:PickEntityRefSchema.optional()}),external_exports.strictObject({kind:external_exports.literal("geo.within"),geometry:PickPolygonSchema}),external_exports.strictObject({kind:external_exports.literal("assets.set"),assetIds:external_exports.array(external_exports.string().min(1).max(MAX_PICK_PART_CHARS)).max(PICK_ASSET_SET_MAX)})]),PagePickSchema=external_exports.strictObject({sourceInstanceId:external_exports.string().min(1),label:external_exports.string().max(MAX_PICK_LABEL_LENGTH).regex(NON_BLANK_TRIMMED_RE),renditions:external_exports.array(PickRenditionSchema).max(MAX_PICK_RENDITIONS),omitted:external_exports.array(external_exports.strictObject({kind:PickKindSchema,total:external_exports.number().int().min(1)})).max(MAX_PICK_RENDITIONS).refine(entries=>new Set(entries.map(e=>e.kind)).size===entries.length,"an omitted kind is listed once").optional()}).refine(pick2=>pick2.renditions.length>0||(pick2.omitted?.length??0)>0,"a pick with no renditions records what it omitted");var KIND_PART_MAX_CHARS=64,kindPart=label=>external_exports.string().min(1).max(KIND_PART_MAX_CHARS).regex(/^[^/]+$/,`a record kind's ${label} may not contain "/"`),RecordKindSchema=external_exports.object({domain:kindPart("domain"),type:kindPart("type")}).strict(),ROW_CLICKS=["blade","page","none"],ROW_CLICK_MESSAGE=`rowClick is "blade" (open the row in a blade), "page" (go to its record page), "none" (rows do nothing) or { publish: '<channel>' } (publish the row's reference on that channel)`,RowClickSchema=external_exports.union([external_exports.enum(ROW_CLICKS),external_exports.object({publish:external_exports.string().min(1,ROW_CLICK_MESSAGE)},{error:issue2=>issue2.code==="unrecognized_keys"?ROW_CLICK_MESSAGE:void 0}).strict()],{error:ROW_CLICK_MESSAGE}),MAX_SOLUTION_BLADES=20,MAX_BLADE_TABS=6,MAX_BLADE_TAB_LABEL_LENGTH=40,BLADE_TAB_BINDS=["record","subject"];var SolutionBladeTabSectionSchema=external_exports.object({componentName:external_exports.string().min(1).describe(`A registered binds "entity" component that can bind this kind; a component appears at most once across a blade entry's tabs and sections.`),config:external_exports.unknown().optional(),configVersion:external_exports.string().regex(CONFIG_VERSION_RE)}).strict(),SolutionBladeTabSchema=external_exports.object({label:external_exports.string().min(1).max(MAX_BLADE_TAB_LABEL_LENGTH).regex(NON_BLANK_TRIMMED_RE).describe(`The tab's heading \u2014 non-blank, no leading or trailing whitespace, at most ${String(MAX_BLADE_TAB_LABEL_LENGTH)} characters, unique within the blade and never "Details".`),componentName:external_exports.string().min(1).describe(`A registered binds "entity" component that can bind this kind; a component appears at most once across a blade entry's tabs and sections.`),config:external_exports.unknown().optional(),configVersion:external_exports.string().regex(CONFIG_VERSION_RE),bind:external_exports.enum(BLADE_TAB_BINDS).optional().describe('What the tab shows: "record" (the record on screen; the default) or "subject" (the record that one is about, at its pin). "subject" only on a kind whose records have one; a subject the component cannot show hides the tab.'),sections:external_exports.array(SolutionBladeTabSectionSchema).max(50).optional().describe("Further components shown under the tab's own, in this order, each bound as the tab is. A section whose component cannot bind that record is hidden; the tab stays.")}).strict(),SolutionBladeSchema=external_exports.object({entity:RecordKindSchema,view:external_exports.literal("details",{error:`a blade shows the module's Details view \u2014 "details" is the only view there is`}),tabs:external_exports.array(SolutionBladeTabSchema).max(MAX_BLADE_TABS).optional().describe("Catalog widgets placed as further tabs on this kind's record view, after Details and the modules' own tabs, each bound to the record on screen.")}).strict();var MAX_SOLUTION_FILTERS=10,MAX_FILTER_DIMENSION_LENGTH=255,MAX_FILTER_ID_LENGTH=MAX_FILTER_DIMENSION_LENGTH,MAX_FILTER_PAGES=100,FilterIdSchema=external_exports.string().min(1).max(MAX_FILTER_ID_LENGTH).regex(NON_BLANK_TRIMMED_RE,{error:"a filter id must be non-blank with no leading or trailing whitespace"}),FilterDimensionColumnSchema=external_exports.string().min(1).max(MAX_FILTER_DIMENSION_LENGTH).regex(NON_BLANK_TRIMMED_RE,{error:"dimension must be a non-blank column name without leading or trailing whitespace"}),DAY_PATTERN=String.raw`\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])`;var RANGE_KEY=new RegExp(String.raw`^(${DAY_PATTERN})\.\.(${DAY_PATTERN})$`),periodKeyRange=key=>{let match=RANGE_KEY.exec(key);return match?.[1]===void 0||match[2]===void 0?void 0:{start:match[1],end:match[2]}},PeriodKeySchema=external_exports.string().regex(new RegExp(String.raw`^(\d{4}(-(0[1-9]|1[0-2])|-Q[1-4])?|${DAY_PATTERN}\.\.${DAY_PATTERN})$`),{error:"a period key is a year (2026), a quarter (2026-Q3), a month (2026-09) or a range of days (2026-03-15..2026-04-14)"}),PERIOD_GRAINS=["month","quarter","year"],PeriodGrainSchema=external_exports.enum(PERIOD_GRAINS),PeriodDefaultSchema=external_exports.union([external_exports.strictObject({policy:external_exports.literal("currentPeriod"),grain:PeriodGrainSchema}),external_exports.strictObject({policy:external_exports.literal("lastClosedPeriod"),grain:PeriodGrainSchema}),external_exports.strictObject({policy:external_exports.literal("fixed"),key:PeriodKeySchema})]),PeriodWindowSchema=external_exports.strictObject({from:external_exports.iso.datetime(),to:external_exports.iso.datetime()}),KIND_SEGMENT=external_exports.string().regex(/^[a-z0-9-]+$/),PublishedFilterKindSchema=external_exports.templateLiteral([KIND_SEGMENT,".",KIND_SEGMENT]),FilterLabelSchema=external_exports.string().min(1).describe("What the viewer reads above the control. Absent = the kind's own label."),FilterPagesSchema=external_exports.array(external_exports.string().min(1)).max(MAX_FILTER_PAGES).describe("Ids of the pages that show this filter, top-level or child. Absent = every page; empty = no page. A page that does not show a filter is not narrowed by it."),PeriodSolutionFilterSchema=external_exports.strictObject({id:FilterIdSchema,kind:external_exports.literal("period"),label:FilterLabelSchema.optional(),pages:FilterPagesSchema.optional(),default:PeriodDefaultSchema.optional().describe("The period a page opens on: the current month, quarter or year, the last closed one, or a fixed key. Absent = any time.")}),FILTER_OPTIONS_WIRE_MAX=1e3,DimensionSolutionFilterSchema=external_exports.strictObject({id:FilterIdSchema,kind:external_exports.literal("dimension"),label:FilterLabelSchema.optional(),pages:FilterPagesSchema.optional(),dimension:FilterDimensionColumnSchema,options:external_exports.array(external_exports.string().min(1)).optional().describe("The values the control offers \u2014 exactly what the author typed.")}),PublishedSolutionFilterSchema=external_exports.strictObject({id:FilterIdSchema,kind:PublishedFilterKindSchema,label:FilterLabelSchema.optional(),pages:FilterPagesSchema.optional()}),SolutionFilterSchema=external_exports.union([PeriodSolutionFilterSchema,DimensionSolutionFilterSchema,PublishedSolutionFilterSchema]),SolutionFilterInputSchema=external_exports.union([PeriodSolutionFilterSchema,DimensionSolutionFilterSchema.extend({options:external_exports.array(external_exports.string().min(1)).max(FILTER_OPTIONS_WIRE_MAX).optional().describe("The values the control offers \u2014 exactly what the author typed.")}),PublishedSolutionFilterSchema]);var PageDateRangeSchema=external_exports.strictObject({label:FilterLabelSchema.optional(),default:PeriodWindowSchema.optional().describe("The range the page opens on. Absent = any time.")});var ROW_SOURCE_MAX_LIMIT=200,MAX_ROW_SOURCE_COLUMNS=100,MAX_ROW_SOURCE_FILTERS=50,MAX_ROW_SOURCE_OPTIONS=100,MAX_ROW_SOURCE_FILTER_TERMS=50,MAX_ROW_SOURCE_IN_VALUES=100,MAX_FIELD_KEY_LENGTH=64,MAX_CURSOR_LENGTH=2048,MAX_LABEL_LENGTH=120,MAX_DESCRIPTION_LENGTH=500,MAX_TEXT_VALUE_LENGTH=1e3,RowSourceIdSchema=PublishedFilterKindSchema.refine(id=>id.length<=MAX_LABEL_LENGTH,`a row source id is at most ${MAX_LABEL_LENGTH} characters`);var LabelSchema=external_exports.string().max(MAX_LABEL_LENGTH).regex(NON_BLANK_TRIMMED_RE),FieldKeySchema=external_exports.string().max(MAX_FIELD_KEY_LENGTH).regex(/^[A-Za-z][A-Za-z0-9_]*$/,'a column or filter key is letters, digits and "_"'),ROW_SOURCE_COLUMN_TYPES=["text","number","date","datetime","boolean","enum","entity"],RowSourceColumnSchema=external_exports.strictObject({key:FieldKeySchema,label:LabelSchema,type:external_exports.enum(ROW_SOURCE_COLUMN_TYPES),unit:LabelSchema.optional(),sortable:external_exports.boolean(),shownByDefault:external_exports.boolean()}),ROW_SOURCE_FILTER_VALUE_TYPES=["text","number","boolean","date","enum","entity"],ROW_SOURCE_FILTER_OPERATORS=["eq","in","contains","gte","lte"],OPERATORS_FOR={text:["eq","in","contains"],number:["eq","in","gte","lte"],boolean:["eq"],date:["eq","gte","lte"],enum:["eq","in"],entity:["eq","in"]},RowSourceFilterSchema=external_exports.strictObject({key:FieldKeySchema,label:LabelSchema,valueType:external_exports.enum(ROW_SOURCE_FILTER_VALUE_TYPES),operators:external_exports.array(external_exports.enum(ROW_SOURCE_FILTER_OPERATORS)).min(1),options:external_exports.array(external_exports.strictObject({value:external_exports.string().min(1).max(MAX_LABEL_LENGTH),label:LabelSchema})).min(1).max(MAX_ROW_SOURCE_OPTIONS).optional(),kind:RecordKindSchema.optional()}),RowSourceOrderBySchema=external_exports.strictObject({field:external_exports.string().min(1).max(MAX_FIELD_KEY_LENGTH),direction:external_exports.enum(["asc","desc"])}),duplicates=values2=>{let seen=new Set,repeated2=new Set;for(let v of values2)(seen.has(v)?repeated2:seen).add(v);return[...repeated2]},RowSourcePageScopeSchema=external_exports.strictObject({period:external_exports.boolean().optional(),dateRange:external_exports.boolean().optional(),dimensions:external_exports.boolean().optional(),facets:external_exports.array(PublishedFilterKindSchema).optional(),picks:external_exports.array(PickKindSchema).max(PICK_KINDS.length).refine(kinds=>duplicates(kinds).length===0,"a pick kind is listed once").optional(),resolves:external_exports.array(PickEntityRefSchema).optional()}),RowSourceDescriptionSchema=external_exports.object({id:RowSourceIdSchema,label:LabelSchema,description:external_exports.string().regex(NON_BLANK_TRIMMED_RE).max(MAX_DESCRIPTION_LENGTH),bindsTo:RecordKindSchema.optional(),rowKind:RecordKindSchema.optional(),pageScope:RowSourcePageScopeSchema.optional(),columns:external_exports.array(RowSourceColumnSchema).min(1).max(MAX_ROW_SOURCE_COLUMNS),filters:external_exports.array(RowSourceFilterSchema).max(MAX_ROW_SOURCE_FILTERS),defaultSort:RowSourceOrderBySchema,limit:external_exports.strictObject({default:external_exports.number().int().min(1),max:external_exports.number().int().min(1).max(ROW_SOURCE_MAX_LIMIT)}),pending:external_exports.strictObject({reason:external_exports.string().regex(NON_BLANK_TRIMMED_RE).max(MAX_DESCRIPTION_LENGTH)}).optional()}).superRefine((source,ctx)=>{let problem=message=>ctx.addIssue({code:"custom",message});for(let key of duplicates(source.columns.map(column2=>column2.key)))problem(`declares column key "${key}" twice`);source.columns.find(column2=>column2.key===source.defaultSort.field)?.sortable!==!0&&problem(`default sort "${source.defaultSort.field}" is not a sortable column`);for(let key of duplicates(source.filters.map(filter=>filter.key)))problem(`declares filter key "${key}" twice`);for(let filter of source.filters){filter.valueType==="enum"&&filter.options===void 0&&problem(`enum filter "${filter.key}" lists no options`),filter.valueType!=="enum"&&filter.options!==void 0&&problem(`filter "${filter.key}" is not an enum and cannot list options`),filter.valueType==="entity"&&filter.kind===void 0&&problem(`entity filter "${filter.key}" names no kind`),filter.valueType!=="entity"&&filter.kind!==void 0&&problem(`filter "${filter.key}" is not an entity and cannot name a kind`);for(let op of duplicates(filter.operators))problem(`filter "${filter.key}" offers "${op}" twice`);for(let value2 of duplicates((filter.options??[]).map(o=>o.value)))problem(`enum filter "${filter.key}" lists option "${value2}" twice`);for(let op of new Set(filter.operators))OPERATORS_FOR[filter.valueType].includes(op)||problem(`filter "${filter.key}" offers "${op}", which a ${filter.valueType} cannot take`)}source.limit.default>source.limit.max&&problem(`default limit ${source.limit.default} exceeds its maximum ${source.limit.max}`)}),RowSourceRowSchema=external_exports.strictObject({id:external_exports.string().min(1),values:external_exports.record(external_exports.string(),external_exports.unknown())}),RowSourcePickableSchema=external_exports.union([external_exports.strictObject({assetIds:external_exports.array(external_exports.string().min(1).max(MAX_PICK_PART_CHARS)).max(PICK_ASSET_SET_MAX).refine(ids=>duplicates(ids).length===0,"an asset id is listed once")}),external_exports.strictObject({total:external_exports.number().int().gt(PICK_ASSET_SET_MAX)})]),RowSourcePageSchema=external_exports.strictObject({rows:external_exports.array(RowSourceRowSchema).max(ROW_SOURCE_MAX_LIMIT),nextCursor:external_exports.string().min(1).max(MAX_CURSOR_LENGTH).nullable(),unappliedPicks:external_exports.array(PickKindSchema).max(PICK_KINDS.length).refine(kinds=>duplicates(kinds).length===0,"a pick kind is listed once").optional(),pickable:RowSourcePickableSchema.optional()}),FilterTermScalarSchema=external_exports.union([external_exports.string().max(MAX_TEXT_VALUE_LENGTH),external_exports.number(),external_exports.boolean()]),FilterTermSchema=external_exports.strictObject({key:external_exports.string().max(MAX_FIELD_KEY_LENGTH),op:external_exports.enum(ROW_SOURCE_FILTER_OPERATORS),value:external_exports.union([FilterTermScalarSchema,external_exports.array(FilterTermScalarSchema).max(MAX_ROW_SOURCE_IN_VALUES)])});var RowSourceRequestSchema=external_exports.strictObject({boundId:external_exports.string().min(1).max(MAX_LABEL_LENGTH).optional(),filter:external_exports.array(FilterTermSchema).max(MAX_ROW_SOURCE_FILTER_TERMS).default([]),orderBy:RowSourceOrderBySchema.optional(),cursor:external_exports.string().min(1).max(MAX_CURSOR_LENGTH).optional(),limit:external_exports.number().int().min(1).max(ROW_SOURCE_MAX_LIMIT).optional()});var CHANNEL_REF_MARKER="forge:channelRef";function channelRef(opts){return external_exports.string().min(1).meta({[CHANNEL_REF_MARKER]:{payload:opts.payload}})}var HOST_ONLY_MARKER="forge:hostOnly";function hostOnly(schema){if(peelDeclarationWrappers(schema)!==schema)throw new Error("hostOnly wraps the base type, before .optional() \u2014 write hostOnly(z.boolean()).optional(), not hostOnly(z.boolean().optional())");if(schema.meta()?.id!==void 0)throw new Error("hostOnly refuses a schema with a meta id \u2014 a reused id is emitted once and $ref-ed, so its markers would not count true; declare a fresh schema per key");return schema.meta({[HOST_ONLY_MARKER]:!0})}var MAX_DRILL_TARGET_LABEL_LENGTH=80,DrillTargetSchema=external_exports.object({page:external_exports.string().min(1).describe("Id of the page this block opens."),label:external_exports.string().min(1).max(MAX_DRILL_TARGET_LABEL_LENGTH).regex(NON_BLANK_TRIMMED_RE).optional().describe(`Hover text and accessible name for the block's open-page control \u2014 the same trim and non-blank check as a placement title, at most ${String(MAX_DRILL_TARGET_LABEL_LENGTH)} code points. Absent = "Open <target page name>".`)}).strict(),CONTAINER_DRILL_TARGET_MESSAGE="a layout container has no content of its own to drill from \u2014 set the drill target on the blocks inside it";var STATUS_SLOT_MARKER="forge:statusSlot",StatusSlotFillSchema=external_exports.object({componentName:external_exports.string().min(1).describe("A registered component that declares rowStatus and can bind the host\u2019s row kind."),config:external_exports.unknown().optional(),configVersion:external_exports.string().regex(CONFIG_VERSION_RE)}).strict();function statusSlot(){return StatusSlotFillSchema.meta({[STATUS_SLOT_MARKER]:!0})}var COMPONENT_BINDS=["none","collection","entity"],COMPONENT_GRAINS=["page","widget"];var PageLayoutSchema=external_exports.object({fullBleed:external_exports.boolean().default(!1),mode:external_exports.never({error:'layout.mode is a manifest v1 key and this manifest declares schemaVersion 2 \u2014 every page is the 12-column grid now; remove "mode" and use layout.fullBleed to select chromeless rendering'}).optional()}),GRID_MAX_COLS=12,GRID_MAX_ROWS=12,SpacingScaleSchema=external_exports.enum(["sm","default","lg"]),LayoutSchema=external_exports.object({spanCol:external_exports.number().int().min(1).max(GRID_MAX_COLS).optional(),spanRow:external_exports.number().int().min(1).max(GRID_MAX_ROWS).optional(),grow:external_exports.boolean().optional(),padding:SpacingScaleSchema.optional()});var SolutionIdSchema=external_exports.string().min(1).brand(),PageIdSchema=external_exports.string().min(1).brand(),InstanceIdSchema=external_exports.string().min(1).brand(),SOLUTION_SLUG_RE=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,SolutionSlugSchema=external_exports.string().regex(SOLUTION_SLUG_RE).brand(),PageSlugSchema=external_exports.string().regex(SOLUTION_SLUG_RE).brand();var SolutionItemBindingSchema=external_exports.union([external_exports.object({resourceId:external_exports.string().regex(/\S/).optional()}).strict(),external_exports.object({entity:external_exports.object({domain:external_exports.string().min(1),type:external_exports.string().min(1),id:external_exports.string().regex(/\S/),version:external_exports.string().min(1).optional(),snapshot:external_exports.string().regex(/\S/).optional().describe("Opaque snapshot identity minted by the owning domain \u2014 get it from that domain's own `snapshot` procedure. Never construct or parse one: the same value always means the same content, and any change to the entity yields a new value.")}).strict()}).strict(),external_exports.object({selectionChannel:external_exports.string().min(1)}).strict()]);var MAX_ITEM_TITLE_LENGTH=120,SolutionLeafItemSchema=external_exports.object({instanceId:external_exports.string().min(1),componentName:external_exports.string().min(1),title:external_exports.string().min(1).max(MAX_ITEM_TITLE_LENGTH).regex(NON_BLANK_TRIMMED_RE).optional().describe("Author-set heading for this placement \u2014 non-blank, no leading or trailing whitespace. Absent = the runtime page renders no heading and the builder canvas falls back to the component id."),configVersion:external_exports.string().regex(CONFIG_VERSION_RE),config:external_exports.unknown(),binding:SolutionItemBindingSchema,layout:LayoutSchema.optional(),span:external_exports.never({error:"span is a manifest v1 key and this manifest declares schemaVersion 2 \u2014 use layout.spanCol / layout.spanRow instead ({ w, h } becomes { spanCol: w, spanRow: h })"}).optional(),items:external_exports.never().optional(),ignoredFilters:external_exports.array(FilterIdSchema).max(MAX_SOLUTION_FILTERS).optional().describe("Solution filter ids this block does NOT follow. Absent = follow every filter shown on the page that the component can honour."),ignoredPicks:external_exports.array(PickKindSchema).min(1).max(PICK_KINDS.length).refine(kinds=>new Set(kinds).size===kinds.length,{message:"ignoredPicks must not repeat a pick kind"}).optional().describe("Pick kinds this block does NOT follow. Non-empty and without repeats; absent is the only way to follow every pick kind the component declares in pageScope.picks."),mutedPicks:external_exports.literal(!0).optional().describe("True stops this placement publishing picks and click-filters to other blocks. Absent = publish every kind declared by the component."),rowClick:RowClickSchema.optional().describe("What clicking one of this block's rows does: 'blade' opens the record in a blade over the page, 'page' goes to the Solution's record page for its kind, 'none' leaves rows unclickable, { publish: '<channel>' } publishes the clicked row's reference on that entity-ref channel. Absent = 'blade'."),drillTarget:DrillTargetSchema.optional().describe("Another page of this Solution the block opens from its open-page control, keeping the Solution filters and period. Not on a layout container. Absent = the block opens no page.")}),SolutionItemSchema=SolutionLeafItemSchema.extend({items:external_exports.array(SolutionLeafItemSchema).max(50).optional()}).superRefine((item,context)=>{item.items!==void 0&&item.drillTarget!==void 0&&context.addIssue({code:"custom",path:["drillTarget"],message:CONTAINER_DRILL_TARGET_MESSAGE})});var SolutionPageFieldsSchema=external_exports.looseObject({id:PageIdSchema,slug:PageSlugSchema,name:external_exports.string().min(1),order:external_exports.number().int().nonnegative(),layout:PageLayoutSchema,items:external_exports.array(SolutionItemSchema).max(50),path:external_exports.string().min(1).optional(),icon:external_exports.string().min(1).optional(),requiresCapability:external_exports.string().min(1).optional(),separatorBefore:external_exports.boolean().optional(),channels:external_exports.array(ChannelDeclarationSchema).max(MAX_CHANNELS_PER_PAGE).optional(),record:RecordKindSchema.optional().describe("Makes this page the Solution's record page for one kind: a reference to such a record opens here, at /s/<solution>/<page>/<id>. One page per kind, and only a page with no children."),hideFromNav:external_exports.boolean().optional().describe("Leaves this page out of the Solution's menu. A record page still opens from a reference to one of its records; any other page must be reached by a drill target chain from a page in the menu. A hidden record page starts no chain: nothing in the Solution leads to its own address. Not on a group."),filters:external_exports.never({error:"page filters moved to the Solution \u2014 declare them in the manifest's root `filters` and list this page's id in each filter's `pages`; a date range only this page offers goes in the page's `dateRange`"}).optional(),dateRange:PageDateRangeSchema.optional().describe("A date range this page alone offers its viewers, not kept across pages. Absent = none.")}),SolutionLeafPageSchema=SolutionPageFieldsSchema.extend({children:external_exports.never().optional()}),SolutionPageSchema=SolutionPageFieldsSchema.extend({children:external_exports.array(SolutionLeafPageSchema).max(50).optional()});var SolutionManifestSchema=external_exports.object({schemaVersion:external_exports.string().regex(CONFIG_VERSION_RE),pages:external_exports.array(SolutionPageSchema).max(50),channels:external_exports.array(ChannelDeclarationSchema).max(MAX_CHANNELS_PER_SOLUTION).optional(),filters:external_exports.array(SolutionFilterSchema).max(MAX_SOLUTION_FILTERS).optional().describe("Solution-wide filters: declared once, shown on the pages each one lists, kept as a viewer moves between pages."),blades:external_exports.array(SolutionBladeSchema).max(MAX_SOLUTION_BLADES).optional().describe("How each record kind's record view shows, in a blade and on its record page, one entry per kind: the module's Details view, then the modules' own tabs, then the entry's tabs. Absent for a kind = the module's Details view and the modules' own tabs.")}).meta({examples:[{schemaVersion:"2",filters:[{id:"period",kind:"period",label:"Period",default:{policy:"currentPeriod",grain:"month"}},{id:"site",kind:"assets.subtree",label:"Assets",pages:["page-overview"]}],pages:[{id:"page-overview",slug:"overview",name:"Overview",order:0,layout:{},items:[{instanceId:"item-1",componentName:"asset-count",configVersion:"1",config:{label:"assets tracked"},binding:{},layout:{spanCol:4,spanRow:2}}]},{id:"page-details",slug:"details",name:"Details",order:1,layout:{},items:[{instanceId:"item-2",componentName:"layout-grid",configVersion:"1",config:{columns:2,gap:"default"},binding:{},items:[{instanceId:"item-2a",componentName:"dataset-count",configVersion:"1",config:{},binding:{},layout:{spanCol:1}},{instanceId:"item-2b",componentName:"asset-count",configVersion:"1",config:{label:"assets tracked"},binding:{},layout:{spanCol:1}}]}]},{id:"page-admin",slug:"admin",name:"Admin",order:2,layout:{fullBleed:!0},path:"/admin",icon:"settings",requiresCapability:"tenant:admin",items:[{instanceId:"item-3",componentName:"asset-manager",configVersion:"1",config:{},binding:{}}]}]}]});var approvalTemplateVersionConfigSchema=external_exports.object({variant:external_exports.enum(["full","name","stages","summary","label"]).default("full").describe("full (default): stages and rules cards. name: the linked name and version, inline. stages: one short line per stage. summary: only its name and stage count, on one line. label: the bare template name as plain text, no link and no participant lookup.")});var approvalRequestConfigSchema=external_exports.object({templateVersionId:external_exports.string().regex(external_exports.regexes.uuid(),"Expected a template version id").optional().describe("Show only sign-offs raised under this approval template version. Unset shows any. Bound to a record, or answering a table row\u2019s status, it picks that record\u2019s standing request among this version\u2019s only."),subjectChannel:channelRef({payload:"entity-ref"}).optional().describe("Publish this sign-off's subject ref \u2014 opaque, whole, never decoded here \u2014 onto this declared page channel on load and on change, for another placement bound `{ selectionChannel }` to follow. Unset publishes nothing.")});var APPROVAL_DETAIL_DEFAULT_LAYOUT={spanCol:6,spanRow:6},approvalDetailComponentContract={name:"approval-detail",binds:"entity",bindsToResource:"approval-request",entity:{domain:"approval",type:"approval"},configVersion:"1",configSchema:external_exports.object({}),description:"One approval in full: what is being signed off, the decision, the workflow, comments and history.",grain:"widget",viewer:!0,recordSubject:!0,defaultLayout:APPROVAL_DETAIL_DEFAULT_LAYOUT},APPROVAL_ROW_KIND={domain:"approval",type:"approval"},approvalQueueComponentContract={name:"approval-queue",binds:"collection",bindsToResource:"approval",configVersion:"1",configSchema:external_exports.object({}),description:"Approval inbox and full list. Selecting a row opens the approval in a side-blade the component owns, or in the Solution\u2019s blade where it configures one for approvals, so it never navigates away. A link to the templates admin appears only where the frame offers that page.",grain:"page",rowKind:APPROVAL_ROW_KIND},approvalQueueShowcaseComponentContract={name:"approval-queue-showcase",binds:"collection",bindsToResource:"approval",configVersion:"1",configSchema:external_exports.object({}),description:"Approval queue grouped by the kind of thing being approved, each row carrying the subject, its headline figure and the variance against the owning domain\u2019s own basis. A subject whose domain publishes no figure shows its name, approvers and status only. Selecting a row opens the approval in a side-blade the component owns, or in the Solution\u2019s blade where it configures one for approvals, so it never navigates away.",grain:"page",rowKind:APPROVAL_ROW_KIND},approvalTemplatesComponentContract={name:"approval-templates",binds:"none",configVersion:"1",configSchema:external_exports.object({}),description:"Approval template admin: the reusable sign-off templates approvals are requested against. Creating a template works in any frame (a self-contained dialog); opening a row appears only where the frame offers a destination.",grain:"page"},approvalRecentForSubjectsConfigSchema=external_exports.object({subjects:external_exports.array(external_exports.discriminatedUnion("kind",[external_exports.object({kind:external_exports.literal("entity"),domain:external_exports.string().min(1),type:external_exports.string().min(1),id:external_exports.string().min(1)})])).optional().describe("The subjects whose sign-offs to list, most recent subject first."),limit:external_exports.number().int().min(1).max(20).optional().describe("How many sign-offs to show. Defaults to five.")});var ApprovalIdSchema=external_exports.string().min(1).brand(),ApprovalRefSchema=external_exports.object({approvalId:ApprovalIdSchema}),PartyRefSchema=external_exports.string().min(1).brand(),ApprovalSubjectSchema=EntitySnapshotRefSchema,ApprovalSubjectEntitySchema=ApprovalSubjectSchema.omit({snapshot:!0}),ApprovalStatusSchema=external_exports.enum(["in-progress","approved","rejected","cancelled"]),ApprovalStatusProjectionSchema=external_exports.object({approvalId:ApprovalIdSchema,subject:ApprovalSubjectSchema,status:ApprovalStatusSchema}),EntityApprovalSchema=ApprovalStatusProjectionSchema.extend({requestedBy:PartyRefSchema,createdAt:external_exports.iso.datetime(),originFlowRun:external_exports.string().min(1).optional()}),SubjectHasOpenRequestDataSchema=external_exports.object({code:external_exports.literal("SUBJECT_HAS_OPEN_REQUEST"),standing:external_exports.object({approvalId:ApprovalIdSchema,templateVersionId:external_exports.string(),requestedBy:PartyRefSchema}).nullable()}),SubjectSnapshotRejectedDataSchema=external_exports.object({code:external_exports.literal("SUBJECT_SNAPSHOT_REJECTED"),rejected:external_exports.object({approvalId:ApprovalIdSchema,templateVersionId:external_exports.string()})}),RequestRefusalDataSchema=external_exports.discriminatedUnion("code",[SubjectHasOpenRequestDataSchema,SubjectSnapshotRejectedDataSchema]),LIST_BY_SUBJECTS_MAX=200;var PATH_SEGMENT=/^[A-Za-z_][A-Za-z0-9_-]*$/;var PROTOTYPE_SEGMENTS=["__proto__","constructor","prototype"];function isArgumentPathSegment(segment){return PATH_SEGMENT.test(segment)&&!PROTOTYPE_SEGMENTS.includes(segment)}var FLOW_INPUT_LIST_MAX=200,LIST_ELEMENT_KINDS=["string","number","boolean","principal"],PrincipalRefSchema=external_exports.strictObject({kind:external_exports.enum(["user","group","role"]),id:external_exports.string().min(1).max(ENTITY_REF_MAX_IDENTITY_CHARS)}),StoredPrincipalRefSchema=external_exports.strictObject({...PrincipalRefSchema.shape,id:external_exports.string().min(1)});var ListInputFieldSchema=external_exports.object({type:external_exports.literal("list"),element:external_exports.enum(LIST_ELEMENT_KINDS),max:external_exports.number().int().positive().max(FLOW_INPUT_LIST_MAX,`a list input holds at most ${String(FLOW_INPUT_LIST_MAX)} elements (the platform ceiling)`),optional:external_exports.literal(!0).optional()}).strict(),PrincipalInputFieldSchema=external_exports.object({type:external_exports.literal("principal"),nullable:external_exports.literal(!0),optional:external_exports.literal(!0).optional()}).strict(),PRINCIPAL_SHAPE="a principal {kind: user|group|role, id}";var NULLABLE_PRINCIPAL_SHAPE=`${PRINCIPAL_SHAPE} or null`;var FLOW_INPUT_CHOICES_MAX=50,FLOW_INPUT_CHOICE_MAX_CHARS=200,FLOW_INPUT_STRING_MAX_LENGTH=1e4,VISIBLE_CHARACTER=/[^\s\p{Cf}\u034F\uFE00-\uFE0F\u3164\uFFA0\u2800]/u;var lengthBound=which=>external_exports.number().int().min(1,`${which} is at least 1 \u2014 leave it out for no bound`).max(FLOW_INPUT_STRING_MAX_LENGTH,`${which} is at most ${String(FLOW_INPUT_STRING_MAX_LENGTH)} (the platform ceiling)`),StringInputFieldSchema=external_exports.object({type:external_exports.literal("string"),optional:external_exports.literal(!0).optional(),choices:external_exports.array(external_exports.string().min(1).max(FLOW_INPUT_CHOICE_MAX_CHARS,`a choice is at most ${String(FLOW_INPUT_CHOICE_MAX_CHARS)} characters (the platform ceiling)`).regex(VISIBLE_CHARACTER,"a choice cannot be blank")).min(1).max(FLOW_INPUT_CHOICES_MAX,`a string input offers at most ${String(FLOW_INPUT_CHOICES_MAX)} choices (the platform ceiling)`).optional().describe("The only values accepted, matched exactly. Not together with a length."),minLength:lengthBound("minLength").optional().describe("Fewest characters, not counting leading and trailing white space."),maxLength:lengthBound("maxLength").optional().describe("Most characters, not counting leading and trailing white space.")}).strict();var InputFieldSchema=external_exports.discriminatedUnion("type",[StringInputFieldSchema,external_exports.object({type:external_exports.literal("number"),optional:external_exports.literal(!0).optional()}).strict(),external_exports.object({type:external_exports.literal("boolean"),optional:external_exports.literal(!0).optional()}).strict(),external_exports.object({type:external_exports.literal("ref"),kind:external_exports.string().min(1).describe("The resource kind this reference names, carried FOR CONSUMERS (a surface needs to know what to offer). DOCUMENTARY in v1: the platform checks only that the value is version-pinned, never that it refers to a resource of this kind."),optional:external_exports.literal(!0).optional()}).strict(),external_exports.object({type:external_exports.literal("entity-ref"),optional:external_exports.literal(!0).optional()}).strict(),ListInputFieldSchema,PrincipalInputFieldSchema]),EntityIdentitySchema=external_exports.strictObject(EntityRefInputSchema.shape).describe("An unpinned entity identity the gate subject port mints: {domain, type, id, version?}"),StoredEntityIdentitySchema=external_exports.strictObject(EntityRefSchema.shape),CompositionInputContractSchema=external_exports.object({fields:external_exports.record(external_exports.string().min(1).regex(PATH_SEGMENT,"a declared field name must be bindable as $input.<name> \u2014 a bare identifier (letter or underscore, then letters/digits/underscores/hyphens)"),InputFieldSchema),startingRecord:external_exports.string().regex(PATH_SEGMENT).optional()}).strict().superRefine((contract,ctx)=>{if(contract.startingRecord===void 0)return;let field=Object.hasOwn(contract.fields,contract.startingRecord)?contract.fields[contract.startingRecord]:void 0;(field?.type!=="string"||field.optional!==!0)&&ctx.addIssue({code:"custom",path:["startingRecord"],message:`startingRecord "${contract.startingRecord}" must name a declared optional string field`})});var RunStateSchema=external_exports.enum(["running","parked","done"]),TransitionKindSchema=external_exports.enum(["started","parked","resumed","routed","anchored","reclaimed","sealed"]),ApprovalAwaitingSchema=external_exports.object({kind:external_exports.literal("approval"),ref:external_exports.string().min(1),subject:EntitySnapshotRefSchema.optional(),until:external_exports.iso.datetime().optional(),replaced:external_exports.string().min(1).optional()}).strict(),DelayAwaitingSchema=external_exports.object({kind:external_exports.literal("delay"),until:external_exports.iso.datetime()}).strict(),JobAwaitingSchema=external_exports.object({kind:external_exports.literal("job"),verb:external_exports.string().regex(DOMAIN_VERB_PATTERN,'verb must be "<domain>.<verbName>"'),handle:external_exports.string().min(1),until:external_exports.iso.datetime()}).strict(),FindingsAwaitingSchema=external_exports.object({kind:external_exports.literal("findings"),until:external_exports.iso.datetime()}).strict(),AwaitingSchema=external_exports.discriminatedUnion("kind",[ApprovalAwaitingSchema,DelayAwaitingSchema,JobAwaitingSchema,FindingsAwaitingSchema]),ParkedAtStepSchema=external_exports.string().min(1),DueModeSchema=external_exports.enum(["wake","give-up"]),AttemptSchema=external_exports.number().int().min(1).brand(),DefinitionVersionSchema=external_exports.number().int().min(1).max(2147483647).brand(),DefinitionVersionNumberSchema=external_exports.number().int().min(1).max(2147483647);var ExpressionSchema=external_exports.string().min(1),STEP_ID_PATTERN=/^[^/#]+$/u,STEP_ID_MESSAGE='step id must not contain the key delimiters "/" or "#"',StepIdSchema=external_exports.string().min(1).regex(STEP_ID_PATTERN,STEP_ID_MESSAGE).refine(id=>id!=="__proto__",'a step cannot be named "__proto__"; choose another name'),refuseRepeats=label=>(entries,context)=>{let seen=new Set;for(let entry of entries)seen.has(entry)&&context.addIssue({code:"custom",message:`${label} lists "${entry}" twice`}),seen.add(entry)},CompensationPolicySchema=external_exports.enum(["keep-and-account"]),DefinitionAvailabilitySchema=external_exports.enum(["active","retired"]),TemporalModeSchema=external_exports.enum(["action-time","period-time"]),VersionRuleSchema=external_exports.enum(["current","period-effective"]);var GateSubjectBindingSchema=external_exports.string().min(1).regex(/^\$(steps|input)\./u,"a gate subject must be a $steps.* lookup, or $input.* for a declared entity-ref field"),GateExclusionBindingSchema=external_exports.string().min(1).regex(/^\$steps\./u,"a gate exclusion basis must be a $steps.* lookup \u2014 it names who may NOT approve, so it must be a value the flow itself produced, never input (R1/P3; G6/Q1)"),GateDurationSchema=external_exports.object({amount:external_exports.number().int().min(1),unit:external_exports.enum(["minutes","hours","days"])}).strict().describe("At least 5 minutes and at most 30 days, checked at save and at load."),StandingRequestPolicySchema=external_exports.enum(["stand-down","supersede"]),GateApprovalConfigSchema=external_exports.object({templateVersionId:external_exports.string().min(1),subjectSource:GateSubjectBindingSchema,excludedPartiesSource:GateExclusionBindingSchema.optional(),temporalMode:TemporalModeSchema,versionRule:VersionRuleSchema,giveUpAfter:GateDurationSchema.optional(),onStandingRequest:StandingRequestPolicySchema.optional()}).strict(),ApprovalGateSchema=external_exports.object({kind:external_exports.literal("approval"),config:GateApprovalConfigSchema}).strict(),BranchTargetSchema=StepIdSchema,BranchOperatorSchema=external_exports.enum(["equals","not-equals","greater","greater-or-equal","less","less-or-equal","is-one-of","is-type"]);var BranchConditionSchema=external_exports.object({field:ExpressionSchema,op:BranchOperatorSchema,value:external_exports.union([ExpressionSchema,external_exports.array(ExpressionSchema).min(1)])}).strict(),BranchAllGroupSchema=external_exports.object({all:external_exports.array(BranchConditionSchema).min(2)}).strict(),BranchAnyGroupSchema=external_exports.object({any:external_exports.array(BranchConditionSchema).min(2)}).strict(),BranchWhenSchema=external_exports.union([BranchConditionSchema,BranchAllGroupSchema,BranchAnyGroupSchema]),BranchArmEndSchema=external_exports.object({end:external_exports.literal(!0)}).strict(),BranchCaseSchema=external_exports.object({when:BranchWhenSchema,next:BranchTargetSchema,then:BranchArmEndSchema.optional()}).strict(),BranchOtherwiseSchema=external_exports.union([external_exports.object({next:BranchTargetSchema,then:BranchArmEndSchema.optional()}).strict(),external_exports.object({end:external_exports.literal(!0)}).strict()]),GateBranchConfigSchema=external_exports.object({cases:external_exports.array(BranchCaseSchema).min(1),otherwise:BranchOtherwiseSchema,merge:BranchTargetSchema}).strict(),BranchGateSchema=external_exports.object({kind:external_exports.literal("branch"),config:GateBranchConfigSchema}).strict(),GateDelayConfigSchema=external_exports.object({duration:GateDurationSchema}).strict(),DelayGateSchema=external_exports.object({kind:external_exports.literal("delay"),config:GateDelayConfigSchema}).strict(),GateJobConfigSchema=external_exports.object({startedBy:StepIdSchema,giveUpAfter:GateDurationSchema.optional()}).strict(),JobGateSchema=external_exports.object({kind:external_exports.literal("job"),config:GateJobConfigSchema}).strict(),findingsFromList=max2=>{let sources=external_exports.array(StepIdSchema).min(1);return(max2===void 0?sources:sources.max(max2)).superRefine(refuseRepeats("findingsFrom"))},GateFindingsConfigSchema=external_exports.object({findingsFrom:findingsFromList(),giveUpAfter:GateDurationSchema.optional(),ownerWorkType:external_exports.string().min(1)}).strict(),FindingsGateSchema=external_exports.object({kind:external_exports.literal("findings"),config:GateFindingsConfigSchema}).strict(),GateSchema=external_exports.discriminatedUnion("kind",[ApprovalGateSchema,BranchGateSchema,DelayGateSchema,JobGateSchema,FindingsGateSchema]);var absentPaths=max2=>{let paths=external_exports.array(external_exports.string().refine(path3=>path3.split(".").every(isArgumentPathSegment),`an absent path is a dotted argument path: every segment a plain name, never ${PROTOTYPE_SEGMENTS.join(", ")}`)).min(1);return(max2===void 0?paths:paths.max(max2)).superRefine(refuseRepeats("absent"))},AbsentPathsSchema=absentPaths(),VerbStepSchema=external_exports.object({id:StepIdSchema,type:external_exports.literal("verb").optional(),verb:external_exports.string().regex(DOMAIN_VERB_PATTERN,'verb must be "<domain>.<verbName>"'),args:external_exports.record(external_exports.string().min(1),ExpressionSchema),title:external_exports.string().trim().min(1).max(120).optional(),absent:AbsentPathsSchema.optional(),version:DefinitionVersionNumberSchema.optional(),forEach:ExpressionSchema.optional()}).strict(),GateStepSchema=external_exports.object({id:StepIdSchema,type:external_exports.literal("gate"),gate:GateSchema,title:external_exports.string().trim().min(1).max(120).optional()}).strict(),READ_ANSWER_MAX_BYTES=256*1024,READ_STEP_MAX_BYTES=1024*1024;var ReadStepSchema=external_exports.object({id:StepIdSchema,type:external_exports.literal("read"),read:external_exports.string().regex(DOMAIN_VERB_PATTERN,'read must be "<domain>.<readName>"'),version:external_exports.number().int().positive(),args:external_exports.record(external_exports.string().min(1),ExpressionSchema),title:external_exports.string().trim().min(1).max(120).optional(),forEach:ExpressionSchema.optional()}).strict(),CompositionStepSchema=external_exports.union([VerbStepSchema,GateStepSchema,ReadStepSchema]);function isApprovalGateStep(step){return step.type==="gate"&&step.gate.kind==="approval"}var WriteCompositionDefinitionSchema=external_exports.object({name:external_exports.string().min(1),version:DefinitionVersionNumberSchema,compensation:CompensationPolicySchema,steps:external_exports.array(CompositionStepSchema).min(1),inputSchema:CompositionInputContractSchema.optional(),title:external_exports.string().trim().min(1).max(200).optional(),description:external_exports.string().trim().min(1).max(2e3).optional()}).strict();var ATTEMPT_MARKER="#attempt-",RUN_KEY_ATTEMPT_PATTERN=new RegExp(`^[\\s\\S]+${ATTEMPT_MARKER}[1-9]\\d*$`,"u");var BaseRunKeySchema=external_exports.string().min(1).brand(),RunKeySchema=external_exports.string().min(1).brand();var MS_PER_UNIT={minutes:6e4,hours:36e5,days:864e5},WAIT_FLOOR_MS=5*MS_PER_UNIT.minutes,WAIT_CEILING_MS=30*MS_PER_UNIT.days;var FINDING_MATCH_KEY_MAX_LENGTH=256,FINDING_COUNT_MAX=2147483647,FindingHandlingSchema=external_exports.enum(["exclude","carry"]),FINDING_FAMILY_MAX_LENGTH=128,FINDING_ROWS_REF_MAX_LENGTH=2048,FamilySchema=external_exports.string().max(FINDING_FAMILY_MAX_LENGTH).regex(RESOURCE_KIND_PATTERN,'a finding family is "<module>.<name>"'),FindingSchema=external_exports.strictObject({family:FamilySchema,count:external_exports.number().int().min(1).max(FINDING_COUNT_MAX),rowsRef:external_exports.string().min(1).max(FINDING_ROWS_REF_MAX_LENGTH),matchKey:external_exports.string().min(1).max(FINDING_MATCH_KEY_MAX_LENGTH).nullable(),handling:FindingHandlingSchema}),AcceptedFindingOutcomeSchema=external_exports.enum(["accept","send-to-owner"]),AcceptedFindingSchema=external_exports.strictObject({family:FindingSchema.shape.family,matchKey:FindingSchema.shape.matchKey,handling:FindingSchema.shape.handling,count:FindingSchema.shape.count,outcome:AcceptedFindingOutcomeSchema,decisionId:external_exports.string().min(1),recordRef:external_exports.string().min(1),decidedAt:external_exports.iso.datetime()});var ENDS_AFTER_ARM=Object.freeze({endsRun:!0});var ANY_VALUE_LEAF=Object.freeze({}),NO_VALUE_LEAF=Object.freeze({not:Object.freeze({})});var GateGiveUpSchema=external_exports.object({step:external_exports.string().min(1),reason:external_exports.literal("gave-up"),limit:external_exports.iso.datetime(),overdueMs:external_exports.number().int().nonnegative(),verb:external_exports.string().min(1).optional(),unreadable:external_exports.string().min(1).optional().catch(void 0),gate:external_exports.literal("findings").optional(),openFindings:external_exports.array(external_exports.strictObject({family:FindingSchema.shape.family,matchKey:FindingSchema.shape.matchKey,count:FindingSchema.shape.count})).optional()});var EmptyForEachDetailSchema=external_exports.object({emptyForEachSteps:external_exports.array(external_exports.string().min(1))});var BranchRoutingSchema=external_exports.object({step:external_exports.string().min(1),selected:external_exports.string().min(1).nullable(),divergedFrom:external_exports.string().min(1).nullable().optional(),unevaluatable:external_exports.string().optional(),ends:external_exports.literal(!0).optional(),wroteAnchor:external_exports.literal(!0).optional(),evaluated:external_exports.array(external_exports.object({held:external_exports.boolean(),member:external_exports.number().int().nonnegative().optional()})).optional()});var GateEndedSchema=external_exports.discriminatedUnion("endedBecause",[external_exports.object({gate:external_exports.string().min(1),endedBecause:external_exports.literal("standing-request"),standing:external_exports.array(external_exports.object({approvalRef:external_exports.string().min(1).optional(),requestedBy:external_exports.string().min(1).optional()})).readonly()}),external_exports.object({gate:external_exports.string().min(1),endedBecause:external_exports.literal("superseded"),approvalRef:external_exports.string().min(1),supersededBy:external_exports.string().min(1)}),external_exports.object({gate:external_exports.string().min(1),endedBecause:external_exports.literal("withdraw-refused"),approvalRef:external_exports.string().min(1),requestedBy:external_exports.string().min(1),error:external_exports.string()})]);var StepRefusalSchema=external_exports.object({code:external_exports.string().min(1),message:external_exports.string().trim().min(1)}),RefusalCarrierSchema=external_exports.object({refusal:StepRefusalSchema});var SealSchema=external_exports.object({step:external_exports.string().min(1).optional().catch(void 0),error:external_exports.string().optional().catch(void 0),gate:external_exports.unknown().optional()}),GateSchema2=external_exports.object({status:external_exports.string().optional().catch(void 0),reason:external_exports.string().optional().catch(void 0),error:external_exports.string().optional().catch(void 0),verb:external_exports.string().optional().catch(void 0),unreadable:external_exports.string().optional().catch(void 0),refusalCode:external_exports.string().optional().catch(void 0)}),RUN_FAILURE_REASON_MAX=500;var StepDetailSchema=external_exports.object({step:external_exports.string().min(1)}),RoutedDetailSchema=StepDetailSchema.extend({selected:external_exports.string().min(1).nullable()});var PublishedAwaitingMembers={approval:ApprovalAwaitingSchema.extend({ref:external_exports.string().min(1).nullable()}),delay:DelayAwaitingSchema,job:JobAwaitingSchema.extend({panel:external_exports.string().min(1).nullable()}),findings:FindingsAwaitingSchema},PublishedAwaitingSchema=external_exports.discriminatedUnion("kind",[PublishedAwaitingMembers.approval,PublishedAwaitingMembers.delay,PublishedAwaitingMembers.job,PublishedAwaitingMembers.findings]),RunTransitionSchema=external_exports.object({kind:TransitionKindSchema,causeRecordRef:external_exports.string().min(1).nullable(),at:external_exports.iso.datetime(),detail:external_exports.unknown().optional()}),RunFailureSchema=external_exports.object({step:external_exports.string().min(1).nullable(),cause:external_exports.enum(["failed","refused","rejected","cancelled","gave-up","errored"]),reason:external_exports.string().min(1).max(RUN_FAILURE_REASON_MAX).optional()}),runStatusCommonShape={flowRunRecordId:RecordIdSchema,definition:external_exports.object({name:external_exports.string().min(1),version:DefinitionVersionNumberSchema}),attempt:AttemptSchema.optional(),record:external_exports.object({status:RecordStatusSchema,outcome:FlowRunOutcomeSchema.optional()}),failure:RunFailureSchema.nullable(),trail:external_exports.array(RunTransitionSchema)},RunStatusSchema=external_exports.discriminatedUnion("state",[external_exports.object({...runStatusCommonShape,state:external_exports.literal("parked"),parkedAtStep:ParkedAtStepSchema,awaiting:PublishedAwaitingSchema}),external_exports.object({...runStatusCommonShape,state:RunStateSchema.exclude(["parked"]),parkedAtStep:external_exports.null(),awaiting:external_exports.null()})]),RunSummarySchema=external_exports.object({state:RunStateSchema,record:external_exports.object({status:RecordStatusSchema,outcome:FlowRunOutcomeSchema.optional()}),updatedAt:external_exports.iso.datetime().optional()}),DefinitionDescriptionSchema=external_exports.object({name:external_exports.string().min(1),version:DefinitionVersionNumberSchema,title:external_exports.string().min(1).optional(),description:external_exports.string().min(1).optional(),inputSchema:CompositionInputContractSchema.optional(),steps:external_exports.array(CompositionStepSchema).min(1),availability:DefinitionAvailabilitySchema}),runListItemCommonShape={flowRunRecordId:RecordIdSchema,definition:external_exports.object({name:external_exports.string().min(1),version:DefinitionVersionNumberSchema}),attempt:AttemptSchema.optional(),record:external_exports.object({status:RecordStatusSchema,outcome:FlowRunOutcomeSchema.optional()}),failure:RunFailureSchema.nullable(),createdAt:external_exports.iso.datetime(),updatedAt:external_exports.iso.datetime()},RunListItemSchema=external_exports.discriminatedUnion("state",[external_exports.object({...runListItemCommonShape,state:external_exports.literal("parked"),parkedAtStep:ParkedAtStepSchema,awaiting:PublishedAwaitingSchema}),external_exports.object({...runListItemCommonShape,state:RunStateSchema.exclude(["parked"]),parkedAtStep:external_exports.null(),awaiting:external_exports.null()})]),RunsPageSchema=external_exports.object({items:external_exports.array(RunListItemSchema),cursor:external_exports.string().min(1).optional(),unreadableCount:external_exports.number().int().nonnegative()}),RunRecordStepSchema=external_exports.object({id:external_exports.string().min(1),item:external_exports.string().min(1).optional(),nested:external_exports.boolean()}),RunRecordSchema=ActionRecordSchema.extend({step:RunRecordStepSchema.nullable()}),RunRecordsPageSchema=external_exports.object({items:external_exports.array(RunRecordSchema),cursor:external_exports.string().min(1).optional()});var ApplyResultSchema=external_exports.discriminatedUnion("kind",[external_exports.object({kind:external_exports.literal("sealed"),record:FlowRunRecordSchema}),external_exports.object({kind:external_exports.literal("parked"),flowRunRecordId:external_exports.string().min(1),parkedAtStep:external_exports.string().min(1),awaiting:AwaitingSchema})]);var TriggerBindingSchema=external_exports.object({name:external_exports.string().min(1),version:DefinitionVersionNumberSchema,enabled:external_exports.boolean(),recordAction:external_exports.string().regex(DOMAIN_VERB_PATTERN),match:external_exports.unknown().optional(),definition:external_exports.object({name:external_exports.string().min(1),version:DefinitionVersionNumberSchema}),inputMapping:external_exports.unknown()}).strict();var TriggerBindingPauseCauseSchema=external_exports.enum(["circuit-open"]),TriggerClaimStatusSchema=external_exports.enum(["pending","started","failed","skipped"]),TriggerClaimReasonSchema=external_exports.enum(["mapping-unresolved","apply-failed","definition-retired","input-refused","binding-unreadable","record-unreadable","binding-missing","record-missing","self-triggered","chain-too-long","circuit-open","rule-paused","unknown","previous-run-in-flight","waiting-for-run","verb-changed"]),INPUT_ISSUE_CODES={"not-an-object":"not-an-object","missing-required":"missing-required","undeclared-field":"undeclared-field","wrong-type":"wrong-type","list-too-long":"list-too-long","list-element-wrong-type":"list-element-wrong-type","not-a-choice":"not-a-choice","string-too-short":"string-too-short","string-too-long":"string-too-long","number-not-finite":"number-not-finite","ref-unpinned":"ref-unpinned","entity-ref-shape":"entity-ref-shape","nested-unpinned-ref":"nested-unpinned-ref"},TriggerClaimInputIssueSchema=external_exports.object({code:external_exports.enum(INPUT_ISSUE_CODES),field:external_exports.string().min(1).nullable()}).strict(),TriggerMappingMissSchema=external_exports.discriminatedUnion("effect",[external_exports.object({effect:external_exports.literal("left-out"),field:external_exports.string(),path:external_exports.string().min(1)}).strict(),external_exports.object({effect:external_exports.literal("skips"),field:external_exports.string().nullable(),path:external_exports.string().min(1)}).strict()]),TriggerClaimSchema=external_exports.object({id:external_exports.string().min(1),recordId:external_exports.string().min(1),bindingName:external_exports.string().min(1),bindingVersion:DefinitionVersionNumberSchema,status:TriggerClaimStatusSchema,attempts:external_exports.number().int().positive(),flowRunRecordId:RecordIdSchema.nullable(),run:RunSummarySchema.nullable(),reason:TriggerClaimReasonSchema.nullable(),inputIssue:TriggerClaimInputIssueSchema.nullable(),mappingMisses:external_exports.array(TriggerMappingMissSchema).min(1).nullable(),claimedAt:external_exports.iso.datetime(),updatedAt:external_exports.iso.datetime()}).strict();var RECORD_ROOTS=["params","detail","effects","actor"],SCALAR_LEAVES=["id","committedAt"];var ROOT_LIST=[...SCALAR_LEAVES,...RECORD_ROOTS].map(root=>`$record.${root}`).join(", ");var DEFINITION_STEPS_WIRE_MAX=400,STEP_ARGS_WIRE_MAX=500,STEP_ABSENT_WIRE_MAX=500,BRANCH_CASES_WIRE_MAX=200,BRANCH_GROUP_WIRE_MAX=100,BRANCH_VALUE_LIST_WIRE_MAX=1e3,INPUT_FIELDS_WIRE_MAX=500,DEFINITION_CONFIG_WIRE_MAX=1e3,WIRE_BOUNDED_RECORDS=[],boundedRecord=(key,value2,max2)=>{let schema=external_exports.record(key,value2).refine(record2=>Object.keys(record2).length<=max2,{message:`at most ${String(max2)} entries`});return WIRE_BOUNDED_RECORDS.push([schema,max2]),schema},BranchConditionInputSchema=BranchConditionSchema.extend({value:external_exports.union([ExpressionSchema,external_exports.array(ExpressionSchema).min(1).max(BRANCH_VALUE_LIST_WIRE_MAX)])}),BranchWhenInputSchema=external_exports.union([BranchConditionInputSchema,BranchAllGroupSchema.extend({all:external_exports.array(BranchConditionInputSchema).min(2).max(BRANCH_GROUP_WIRE_MAX)}),BranchAnyGroupSchema.extend({any:external_exports.array(BranchConditionInputSchema).min(2).max(BRANCH_GROUP_WIRE_MAX)})]),GateBranchConfigInputSchema=GateBranchConfigSchema.extend({cases:external_exports.array(BranchCaseSchema.extend({when:BranchWhenInputSchema})).min(1).max(BRANCH_CASES_WIRE_MAX)}),GateFindingsConfigInputSchema=GateFindingsConfigSchema.extend({findingsFrom:findingsFromList(DEFINITION_STEPS_WIRE_MAX)}),GateInputSchema=external_exports.discriminatedUnion("kind",[ApprovalGateSchema,BranchGateSchema.extend({config:GateBranchConfigInputSchema}),DelayGateSchema,JobGateSchema,FindingsGateSchema.extend({config:GateFindingsConfigInputSchema})]),CompositionStepInputSchema=external_exports.union([VerbStepSchema.extend({args:boundedRecord(external_exports.string().min(1),ExpressionSchema,STEP_ARGS_WIRE_MAX),absent:absentPaths(STEP_ABSENT_WIRE_MAX).optional()}),GateStepSchema.extend({gate:GateInputSchema}),ReadStepSchema.extend({args:boundedRecord(external_exports.string().min(1),ExpressionSchema,STEP_ARGS_WIRE_MAX)})]),CompositionInputContractInputSchema=CompositionInputContractSchema.safeExtend({fields:boundedRecord(CompositionInputContractSchema.shape.fields.keyType,CompositionInputContractSchema.shape.fields.valueType,INPUT_FIELDS_WIRE_MAX)});var ApprovalNotifiedSchema=external_exports.array(PrincipalRefSchema),ApprovalNotificationFactsSchema=external_exports.object({notified:ApprovalNotifiedSchema,requester:PrincipalRefSchema,subjectPath:external_exports.string().min(1),stageOpened:external_exports.literal(!0).optional()}),ApprovalCancelFactsSchema=external_exports.object({notified:ApprovalNotifiedSchema,requester:PrincipalRefSchema,subjectPath:external_exports.string().min(1),superseded:external_exports.boolean()});var ApprovalSubjectInputSchema=EntitySnapshotRefInputSchema,ApprovalSubjectEntityInputSchema=ApprovalSubjectInputSchema.omit({snapshot:!0}),PARTY_REF_NOT_AN_EMAIL="a party is a principal id (jwt.sub), never an email \u2014 B8",PRINCIPAL_ID_PATTERN=/^[^@]*$/,NewPartyRefSchema=external_exports.string().min(1).regex(PRINCIPAL_ID_PATTERN,PARTY_REF_NOT_AN_EMAIL).brand(),AvailabilitySchema=external_exports.enum(["draft","published","retired"]),SegregationConfigSchema=external_exports.object({selfApproval:external_exports.boolean().default(!1),crossStep:external_exports.boolean().default(!1)}),CancelAuthoritySchema=external_exports.object({allowRequester:external_exports.boolean().default(!0),allowTenantAdmin:external_exports.boolean().default(!0),additionalPrincipals:external_exports.array(PartyRefSchema).default([])}),STAGE_NAME_MAX_LENGTH=80,StageSpecSchema=external_exports.object({name:external_exports.string().trim().min(1).max(STAGE_NAME_MAX_LENGTH).optional(),parties:external_exports.array(PartyRefSchema).min(1),m:external_exports.number().int().min(1)}).refine(stage=>stage.m<=stage.parties.length,{message:"threshold M must not exceed the number of named approvers N (1 <= M <= N; M1 named-principals floor)",path:["m"]}).refine(stage=>new Set(stage.parties).size===stage.parties.length,{message:"a step names each approver at most once",path:["parties"]});var TemplateContentSchema=external_exports.object({name:external_exports.string().min(1),stages:external_exports.array(StageSpecSchema).min(1),segregation:SegregationConfigSchema.prefault({}),cancelAuthority:CancelAuthoritySchema.prefault({}),singleOpenRequestPerSubject:external_exports.boolean().default(!1)}),TEMPLATE_STAGES_MAX=50,TEMPLATE_PARTIES_MAX=200,NewStageSpecSchema=StageSpecSchema.safeExtend({parties:external_exports.array(NewPartyRefSchema).min(1).max(TEMPLATE_PARTIES_MAX)}),NewCancelAuthoritySchema=CancelAuthoritySchema.safeExtend({additionalPrincipals:external_exports.array(NewPartyRefSchema).max(TEMPLATE_PARTIES_MAX).default([])}),NewTemplateContentSchema=TemplateContentSchema.safeExtend({stages:external_exports.array(NewStageSpecSchema).min(1).max(TEMPLATE_STAGES_MAX),cancelAuthority:NewCancelAuthoritySchema.prefault({})}),ResolvedStageSchema=external_exports.object({stageIndex:external_exports.number().int().min(0),voters:external_exports.array(external_exports.string().min(1)),n:external_exports.number().int().min(0),m:external_exports.number().int().min(1)}).refine(stage=>stage.n===stage.voters.length,{message:"frozen N must equal the resolved voter count",path:["n"]}).refine(stage=>stage.m<=stage.n,{message:"threshold M cannot exceed the frozen resolved N (F3 owns the loud service error)",path:["m"]}).refine(stage=>new Set(stage.voters).size===stage.voters.length,{message:"a resolved voter set contains each principal at most once",path:["voters"]}),ResolutionSnapshotSchema=external_exports.object({stages:external_exports.array(ResolvedStageSchema).min(1),excludedParties:external_exports.array(external_exports.string().min(1)).default([])}).refine(snapshot=>snapshot.stages.every((stage,index)=>stage.stageIndex===index),{message:"step indexes must be contiguous from 0 (the engine addresses steps by position)",path:["stages"]}),VoteOutcomeSchema=external_exports.enum(["approve","reject"]),TemplateVersionViewSchema=external_exports.object({templateId:external_exports.string().min(1),versionId:external_exports.string().min(1),version:external_exports.number().int().min(1),availability:AvailabilitySchema,content:TemplateContentSchema,createdAt:external_exports.iso.datetime(),updatedAt:external_exports.iso.datetime()}),TemplateVersionLookupSchema=TemplateVersionViewSchema.nullable(),TemplateSummarySchema=external_exports.object({templateId:external_exports.string().min(1),name:external_exports.string().min(1),latestVersion:external_exports.number().int().min(1),latestVersionId:external_exports.string().min(1),availability:AvailabilitySchema}),TemplateDetailSchema=external_exports.object({templateId:external_exports.string().min(1),versions:external_exports.array(TemplateVersionViewSchema).min(1)}),RowIdSchema=external_exports.uuid(),GetApprovalInputSchema=external_exports.object({approvalId:RowIdSchema}),GetTemplateInputSchema=external_exports.object({templateId:RowIdSchema}),ListBySubjectInputSchema=external_exports.object({subject:ApprovalSubjectInputSchema,templateVersionId:RowIdSchema.optional()}),ListBySubjectsInputSchema=external_exports.object({subjects:external_exports.array(ApprovalSubjectInputSchema).min(1).max(LIST_BY_SUBJECTS_MAX),templateVersionId:RowIdSchema.optional()}),ListByEntitiesInputSchema=external_exports.object({entities:external_exports.array(ApprovalSubjectEntityInputSchema).min(1).max(LIST_BY_SUBJECTS_MAX),templateVersionId:RowIdSchema.optional(),sameTemplateAs:RowIdSchema.optional()}),TemplateVersionRefInputSchema=external_exports.object({templateVersionId:RowIdSchema}),TemplateVersionPublishedSchema=external_exports.object({published:external_exports.boolean()}),TemplateCreateInputSchema=external_exports.object({content:NewTemplateContentSchema,idempotencyKey:IdempotencyKeySchema}),TemplateReviseInputSchema=external_exports.object({templateId:RowIdSchema,content:NewTemplateContentSchema,idempotencyKey:IdempotencyKeySchema}),TemplatePublishInputSchema=external_exports.object({templateVersionId:RowIdSchema,idempotencyKey:IdempotencyKeySchema}),TemplateRetireInputSchema=external_exports.object({templateVersionId:RowIdSchema,idempotencyKey:IdempotencyKeySchema}),EXCLUDED_PARTIES_MAX=200;var RequestApprovalInputSchema=external_exports.object({templateVersionId:RowIdSchema,subject:ApprovalSubjectInputSchema,excludedParties:external_exports.array(NewPartyRefSchema).max(EXCLUDED_PARTIES_MAX).default([]),idempotencyKey:IdempotencyKeySchema}),ApprovalViewSchema=external_exports.object({approvalId:external_exports.string().min(1),subject:ApprovalSubjectSchema,templateVersionId:external_exports.string().min(1),status:ApprovalStatusSchema,currentStage:external_exports.number().int().min(0),requesterId:external_exports.string().min(1),resolution:ResolutionSnapshotSchema,createdAt:external_exports.iso.datetime(),updatedAt:external_exports.iso.datetime(),originFlowRun:external_exports.string().min(1).optional()}),ApprovalDetailSchema=ApprovalViewSchema.extend({requestedAt:external_exports.iso.datetime().optional()}),ApprovalRecordDetailSchema=ApprovalViewSchema.extend(ApprovalNotificationFactsSchema.shape),ApprovalCancelRecordDetailSchema=ApprovalViewSchema.extend(ApprovalCancelFactsSchema.shape),AUDIT_TEXT_MAX_LENGTH=2e3,AuditTextSchema=external_exports.string().trim().min(1).max(AUDIT_TEXT_MAX_LENGTH),ApproveInputSchema=external_exports.object({approvalId:RowIdSchema,onBehalfOf:external_exports.string().min(1).optional(),note:AuditTextSchema.optional(),idempotencyKey:IdempotencyKeySchema}),RejectInputSchema=external_exports.object({approvalId:RowIdSchema,reason:AuditTextSchema,onBehalfOf:external_exports.string().min(1).optional(),idempotencyKey:IdempotencyKeySchema}),CancelInputSchema=external_exports.object({approvalId:RowIdSchema,reason:AuditTextSchema,idempotencyKey:IdempotencyKeySchema}),CommentInputSchema=external_exports.object({approvalId:RowIdSchema,text:AuditTextSchema,idempotencyKey:IdempotencyKeySchema}),DelegateInputSchema=external_exports.object({approvalId:RowIdSchema,toPrincipal:external_exports.string().min(1).regex(PRINCIPAL_ID_PATTERN,PARTY_REF_NOT_AN_EMAIL),idempotencyKey:IdempotencyKeySchema}),RemindInputSchema=external_exports.object({approvalId:RowIdSchema,idempotencyKey:IdempotencyKeySchema}),RemindResultSchema=external_exports.object({approvalId:RowIdSchema,notified:ApprovalNotifiedSchema.min(1),remindedAt:external_exports.iso.datetime()}),ApprovalActivityVerbSchema=external_exports.enum(["request","approve","reject","cancel","comment","delegate","remind"]),ApprovalActivityEntrySchema=external_exports.object({recordId:external_exports.string().min(1),verb:ApprovalActivityVerbSchema,principal:external_exports.string().min(1),onBehalfOf:external_exports.string().min(1).optional(),time:external_exports.iso.datetime(),reason:external_exports.string().optional(),text:external_exports.string().optional(),toPrincipal:external_exports.string().optional(),notified:external_exports.array(external_exports.string()).optional()}),ApprovalActivityPageSchema=external_exports.object({items:external_exports.array(ApprovalActivityEntrySchema),truncated:external_exports.boolean()}),StageProgressSchema=external_exports.object({index:external_exports.number().int().min(0),m:external_exports.number().int().min(1),n:external_exports.number().int().min(0)}),InboxStageSchema=external_exports.object({index:external_exports.number().int().min(0),m:external_exports.number().int().min(1),name:external_exports.string().min(1).max(STAGE_NAME_MAX_LENGTH).optional(),voters:external_exports.array(external_exports.string().min(1)).min(1)}),InboxRowSchema=external_exports.object({approvalId:external_exports.string().min(1),subject:ApprovalSubjectSchema,status:ApprovalStatusSchema,requesterId:external_exports.string().min(1),templateName:external_exports.string().min(1),templateVersion:external_exports.number().int().min(1),updatedAt:external_exports.iso.datetime(),currentStage:StageProgressSchema,stages:external_exports.array(InboxStageSchema).min(1)}),InboxPageSchema=external_exports.object({items:external_exports.array(InboxRowSchema),total:external_exports.number().int().min(0)}),ApprovalListRowSchema=InboxRowSchema,ApprovalStatusCountsSchema=external_exports.object({inProgress:external_exports.number().int().min(0),approved:external_exports.number().int().min(0),rejected:external_exports.number().int().min(0),cancelled:external_exports.number().int().min(0)}),ApprovalListPageSchema=external_exports.object({items:external_exports.array(ApprovalListRowSchema),total:external_exports.number().int().min(0),counts:ApprovalStatusCountsSchema}),ListApprovalsInputSchema=external_exports.object({status:ApprovalStatusSchema.optional()});var ApprovalStatusPageSchema=external_exports.object({items:external_exports.array(ApprovalStatusProjectionSchema),total:external_exports.number().int().min(0)}),ApprovalsBySubjectPageSchema=external_exports.object({items:external_exports.array(external_exports.object({subject:ApprovalSubjectSchema,approvals:external_exports.array(ApprovalStatusProjectionSchema)})),total:external_exports.number().int().min(0)}),ApprovalsByEntityPageSchema=external_exports.object({items:external_exports.array(external_exports.object({entity:ApprovalSubjectEntitySchema,approvals:external_exports.array(EntityApprovalSchema)})),total:external_exports.number().int().min(0)}),TemplateSummaryPageSchema=external_exports.object({items:external_exports.array(TemplateSummarySchema),total:external_exports.number().int().min(0)}),approvalContract=oc.router({getStatus:oc.input(GetApprovalInputSchema).output(ApprovalStatusProjectionSchema),listBySubject:oc.input(ListBySubjectInputSchema).output(ApprovalStatusPageSchema),listBySubjects:oc.input(ListBySubjectsInputSchema).output(ApprovalsBySubjectPageSchema),listByEntities:oc.input(ListByEntitiesInputSchema).output(ApprovalsByEntityPageSchema),isTemplateVersionPublished:oc.input(TemplateVersionRefInputSchema).output(TemplateVersionPublishedSchema),getDetail:oc.input(GetApprovalInputSchema).output(ApprovalDetailSchema),getActivity:oc.input(GetApprovalInputSchema).output(ApprovalActivityPageSchema).meta({agenticSurface:"excluded",agenticSurfaceReason:"semantic"}),inbox:oc.output(InboxPageSchema),listApprovals:oc.input(ListApprovalsInputSchema).output(ApprovalListPageSchema),listTemplates:oc.output(TemplateSummaryPageSchema),getTemplate:oc.input(GetTemplateInputSchema).output(TemplateDetailSchema),getTemplateVersion:oc.input(TemplateVersionRefInputSchema).output(TemplateVersionLookupSchema),request:oc.input(RequestApprovalInputSchema).output(ApprovalViewSchema).errors({BAD_REQUEST:{data:RequestRefusalDataSchema}}),approve:oc.input(ApproveInputSchema).output(ApprovalViewSchema),reject:oc.input(RejectInputSchema).output(ApprovalViewSchema),cancel:oc.input(CancelInputSchema).output(ApprovalViewSchema),comment:oc.input(CommentInputSchema).output(ApprovalViewSchema),delegate:oc.input(DelegateInputSchema).output(ApprovalViewSchema),remind:oc.input(RemindInputSchema).output(RemindResultSchema),templateCreate:oc.input(TemplateCreateInputSchema).output(TemplateVersionViewSchema),templateRevise:oc.input(TemplateReviseInputSchema).output(TemplateVersionViewSchema),templatePublish:oc.input(TemplatePublishInputSchema).output(TemplateVersionViewSchema),templateRetire:oc.input(TemplateRetireInputSchema).output(TemplateVersionViewSchema)});var AssetIdSchema=external_exports.string().min(1).brand().describe("The asset's DURABLE identity \u2014 stable across every version of the asset. This is the id every write and every graph call takes (get / update / delete / setLocation / relationships / subtree). It is NOT the `id` an asset read returns: that one is the VERSION-ROW id, which changes on every edit and is output-only. When a create returns both, keep `assetId`.");var AccessUpdateStateSchema=external_exports.enum(["current","updating","failed"]),AccessUpdateJobIdSchema=external_exports.uuid().brand(),AccessUpdateJobStateSchema=external_exports.enum(["PENDING","RUNNING","COMPLETED","FAILED"]);var AccessStatusInputSchema=external_exports.strictObject({assetId:AssetIdSchema}),AccessUpdateJobSummarySchema=external_exports.strictObject({jobId:AccessUpdateJobIdSchema,state:AccessUpdateJobStateSchema,nodesDone:external_exports.number().int().nonnegative(),failureDetail:external_exports.string().optional()}),AccessStatusSchema=external_exports.strictObject({state:AccessUpdateStateSchema,job:AccessUpdateJobSummarySchema.optional(),failureDetail:external_exports.string().optional()}),RerunAccessUpdateResultSchema=external_exports.strictObject({reopened:external_exports.boolean(),job:AccessUpdateJobSummarySchema.optional()}),ACCESS_UPDATE_RUNNER_UNAVAILABLE="ACCESS_UPDATE_RUNNER_UNAVAILABLE",AccessUpdateRunnerUnavailableDataSchema=external_exports.object({code:external_exports.literal(ACCESS_UPDATE_RUNNER_UNAVAILABLE)});var WIRE_BOUNDED_RECORDS2=[],wireBoundedRecord=(key,value2,max2)=>{let schema=external_exports.record(key,value2).refine(record2=>Object.keys(record2).length<=max2,{message:`at most ${String(max2)} entries`});return WIRE_BOUNDED_RECORDS2.push({schema,max:max2}),schema},wireRecordPublished=({max:max2})=>({maxProperties:max2});var DatasetColumnSchema=external_exports.object({name:external_exports.string().min(1),type:external_exports.string().min(1)});var NUMERIC_STRING_PATTERN="^-?[0-9]+(\\.[0-9]+)?([eE][+-]?[0-9]+)?$",NUMERIC_STRING_RE=new RegExp(NUMERIC_STRING_PATTERN);var LIVE_OWNER_DOMAIN_PATTERN=/^[a-z][a-z0-9_]*$/;var SdpConnectorKindSchema=external_exports.string().min(1).max(64).regex(/^[a-z][a-z0-9-]*$/,'connector kind is a lowercase slug (e.g. "delta-share")'),SdpConnectionRefSchema=external_exports.object({connectionId:external_exports.string().min(1)}),SdpConnectionProfileSchema=external_exports.object({connectorKind:SdpConnectorKindSchema,name:external_exports.string().min(1),endpointUrl:external_exports.string().min(1),config:external_exports.record(external_exports.string(),external_exports.unknown()).default({}),secretArn:external_exports.string().min(1).optional(),credential:external_exports.string().min(1).optional()}),ConfigureSdpConnectionInputSchema=external_exports.object({name:external_exports.string().min(1).optional(),endpointUrl:external_exports.string().min(1).optional(),config:external_exports.record(external_exports.string(),external_exports.unknown()).optional(),secretArn:external_exports.string().min(1).nullable().optional()}).refine(changes=>Object.values(changes).some(value2=>value2!==void 0),{message:"a configure must change at least one field"}),SdpConnectionSchema=SdpConnectionRefSchema.extend(SdpConnectionProfileSchema.shape),SDP_CONNECTION_PROBE_FAILURES=["unreachable","unauthorized","protocol_mismatch","timeout"],SdpConnectionProbeFailureSchema=external_exports.enum(SDP_CONNECTION_PROBE_FAILURES),TestSdpConnectionInputSchema=external_exports.union([external_exports.object({connection:SdpConnectionRefSchema}),external_exports.object({draft:SdpConnectionProfileSchema})]),SdpConnectionTestResultSchema=external_exports.discriminatedUnion("ok",[external_exports.object({ok:external_exports.literal(!0),durationMs:external_exports.number().int().nonnegative()}),external_exports.object({ok:external_exports.literal(!1),failure:SdpConnectionProbeFailureSchema,reason:external_exports.string().min(1),durationMs:external_exports.number().int().nonnegative()})]),MAX_SDP_LISTING_DEPTH=8,SdpListingPathSchema=external_exports.array(external_exports.string().min(1)).max(MAX_SDP_LISTING_DEPTH),browsePathSchema=external_exports.array(external_exports.string().min(1)).max(MAX_SDP_LISTING_DEPTH-1),SdpListingEntrySchema=external_exports.object({name:external_exports.string().min(1),path:SdpListingPathSchema,kind:external_exports.enum(["container","dataset"]),readable:external_exports.boolean().optional()}),MAX_SDP_LISTING_ENTRIES=1e3,BrowseSdpListingsInputSchema=external_exports.object({path:browsePathSchema.default([])}),SdpConnectionListingSchema=external_exports.object({path:browsePathSchema,entries:external_exports.array(SdpListingEntrySchema).max(MAX_SDP_LISTING_ENTRIES)});var CATALOG_SLUG_PATTERN=/^[a-z][a-z0-9_-]{0,62}[a-z0-9]$/;var CATALOG_CONCEPT_REF_PATTERN=/^[a-z][a-z0-9_-]{0,62}[a-z0-9]\/[a-z][a-z0-9_-]{0,62}[a-z0-9]$/,CATALOG_QUDT_UNIT_PATTERN=/^[a-z][a-z0-9]*:[A-Za-z0-9][A-Za-z0-9._-]*$/;var SDP_FIELD_ANNOTATION_COLUMN_MAX=255,SDP_FIELD_ANNOTATION_URI_MAX=2048,ABSOLUTE_IRI=/^[A-Za-z][A-Za-z0-9+.-]*:\S+$/,UNSAFE_URI_SCHEMES=new Set(["javascript","data","vbscript"]),hasC0Control=value2=>{for(let index=0;index<value2.length;index+=1)if(value2.charCodeAt(index)<32)return!0;return!1},SdpFieldAnnotationColumnSchema=external_exports.string().min(1).max(SDP_FIELD_ANNOTATION_COLUMN_MAX).refine(column2=>!column2.includes("/"),"a column name cannot contain '/'").refine(column2=>column2!=="."&&column2!=="..","a column name cannot be . or ..").refine(column2=>!hasC0Control(column2),"a column name cannot hold control characters"),SdpFieldAnnotationUriSchema=external_exports.string().min(1).max(SDP_FIELD_ANNOTATION_URI_MAX).regex(ABSOLUTE_IRI,"must be an absolute IRI, e.g. 'https://schema.org/value'").refine(uri2=>!hasC0Control(uri2),"a uri cannot hold control characters").refine(uri2=>!UNSAFE_URI_SCHEMES.has((uri2.split(":",1)[0]??"").toLowerCase()),"the javascript, data and vbscript schemes are refused");var UnreceiptedIdempotencyKeySchema=external_exports.string().min(1).describe("Client-minted key for this write \u2014 YOU generate it (a UUID is fine), the server never does. NOT A REPLAY KEY, unlike the receipted governed writes: this call files no Record, so nothing is stored under this key and a reused one is never replayed \u2014 the call simply executes again. Mint a fresh key per attempt, and treat a re-send after a timeout as a second write rather than a safe retry.");var ExternalIdSystemSchema=external_exports.string().min(1).max(64),ExternalIdValueSchema=external_exports.string().min(1).max(512);var AssetExternalIdSchema=external_exports.object({get assetId(){return AssetIdSchema},system:ExternalIdSystemSchema,value:ExternalIdValueSchema}),AssetSystemIdSchema=external_exports.string().min(1).brand(),ExternalIdFormatSchema=external_exports.strictObject({pattern:external_exports.string().min(1).max(200).optional(),minLength:external_exports.number().int().min(1).max(1e3).optional(),maxLength:external_exports.number().int().min(1).max(1e3).optional()}),AssetSystemTermSchema=external_exports.string().regex(CATALOG_CONCEPT_REF_PATTERN,"a term is 'scheme/slug'"),AssetSystemSchema=external_exports.object({id:AssetSystemIdSchema,key:ExternalIdSystemSchema,displayLabel:external_exports.string().min(1).max(64),idFormat:ExternalIdFormatSchema.nullable(),term:AssetSystemTermSchema.nullable().default(null),createdAt:external_exports.iso.datetime(),updatedAt:external_exports.iso.datetime()}),CreateAssetSystemInputSchema=external_exports.strictObject({idempotencyKey:UnreceiptedIdempotencyKeySchema,key:ExternalIdSystemSchema,displayLabel:external_exports.string().min(1).max(64),idFormat:ExternalIdFormatSchema.optional(),term:AssetSystemTermSchema.optional()}),RawCreateAssetSystemInputSchema=CreateAssetSystemInputSchema.omit({idempotencyKey:!0}),GetAssetSystemInputSchema=external_exports.strictObject({id:AssetSystemIdSchema}),ListAssetSystemsInputSchema=external_exports.strictObject({}),UpdateAssetSystemInputSchema=external_exports.strictObject({idempotencyKey:UnreceiptedIdempotencyKeySchema,id:AssetSystemIdSchema,displayLabel:external_exports.string().min(1).max(64).optional(),idFormat:ExternalIdFormatSchema.nullable().optional(),term:AssetSystemTermSchema.nullable().optional()}),DeleteAssetSystemInputSchema=external_exports.strictObject({idempotencyKey:UnreceiptedIdempotencyKeySchema,id:AssetSystemIdSchema}),ExternalIdBindingIdSchema=external_exports.string().min(1).brand(),ExternalIdBindingSchema=external_exports.object({bindingId:ExternalIdBindingIdSchema,get assetId(){return AssetIdSchema},system:ExternalIdSystemSchema,value:ExternalIdValueSchema,effectiveFrom:external_exports.iso.datetime(),effectiveTo:external_exports.iso.datetime().nullable()}),BindExternalIdInputSchema=external_exports.strictObject({get assetId(){return AssetIdSchema},system:ExternalIdSystemSchema,value:ExternalIdValueSchema}),UnbindExternalIdInputSchema=external_exports.strictObject({bindingId:ExternalIdBindingIdSchema}),GovernedBindExternalIdInputSchema=BindExternalIdInputSchema.extend({idempotencyKey:IdempotencyKeySchema}),GovernedUnbindExternalIdInputSchema=UnbindExternalIdInputSchema.extend({idempotencyKey:IdempotencyKeySchema}),ListAssetExternalIdsInputSchema=external_exports.strictObject({get assetId(){return AssetIdSchema}}),ResolveExternalIdInputSchema=external_exports.strictObject({system:ExternalIdSystemSchema,value:ExternalIdValueSchema}),ExternalIdDirectoryInputSchema=external_exports.strictObject({system:ExternalIdSystemSchema,cursor:external_exports.string().min(1).optional(),limit:external_exports.number().int().min(1).max(1e4).optional(),asOf:external_exports.iso.datetime().optional()}),ExternalIdDirectoryEntrySchema=external_exports.object({value:ExternalIdValueSchema,get assetId(){return AssetIdSchema}}),ExternalIdDirectoryOutputSchema=external_exports.object({items:external_exports.array(ExternalIdDirectoryEntrySchema),nextCursor:external_exports.string().nullable()}),BULK_BIND_EXTERNAL_ID_MAX_ROWS=100,BulkBindExternalIdItemSchema=external_exports.strictObject({get assetId(){return AssetIdSchema},system:ExternalIdSystemSchema,value:ExternalIdValueSchema}),BulkBindExternalIdInputSchema=external_exports.strictObject({bindings:external_exports.array(BulkBindExternalIdItemSchema).min(1).max(BULK_BIND_EXTERNAL_ID_MAX_ROWS),idempotencyKey:IdempotencyKeySchema}),BulkBindExternalIdErrorCodeSchema=external_exports.enum(["asset-not-found","invalid-value","already-bound"]),BulkBindExternalIdRowResultSchema=external_exports.discriminatedUnion("status",[external_exports.object({get assetId(){return AssetIdSchema},system:ExternalIdSystemSchema,value:ExternalIdValueSchema,status:external_exports.literal("bound"),bindingId:ExternalIdBindingIdSchema}),external_exports.object({get assetId(){return AssetIdSchema},system:ExternalIdSystemSchema,value:ExternalIdValueSchema,status:external_exports.literal("refused"),error:external_exports.object({code:BulkBindExternalIdErrorCodeSchema,message:external_exports.string().min(1),get holdingAssetId(){return AssetIdSchema.optional()}})})]),BulkBindExternalIdOutputSchema=external_exports.object({summary:external_exports.object({requested:external_exports.number().int().min(0),bound:external_exports.number().int().min(0),reasserted:external_exports.number().int().min(0),refused:external_exports.number().int().min(0)}),results:external_exports.array(BulkBindExternalIdRowResultSchema)});var ASSET_SEARCH_MAX=512,ASSET_SEARCH_PREFIX_MIN_LENGTH=3;var SearchCapReachedSchema=external_exports.enum(["names","checked","ids"]);var AssetSearchSchema=external_exports.string().min(1).max(ASSET_SEARCH_MAX).regex(/^[^\u0000]*$/,"search cannot contain a NUL character").describe(`The search box: an asset matches when its NAME contains this text (any case) OR it holds a current external ID, in any system, that STARTS WITH this text ignoring case (${String(ASSET_SEARCH_PREFIX_MIN_LENGTH)} characters or more; \`equipment_1055\` finds \`EQUIPMENT_105558\`; never the middle of an ID, no numeric coercion). An external ID typed whole and exactly is always found, at any length. The text is trimmed and both sides are literal, so \`%\`, \`_\` and \`\\\` are ordinary characters. Unlike \`nameContains\`, which is name-only, this also finds an asset by an external ID.`);var AssetLifecycleStatusSchema=external_exports.enum(["PRE_PRODUCTION","ACTIVE","INACTIVE","SHUT_IN","DECOMMISSIONED"]),LifecycleMoveSchema=external_exports.strictObject({from:AssetLifecycleStatusSchema,to:AssetLifecycleStatusSchema}),LifecycleGateBindingSchema=LifecycleMoveSchema.extend({approvalTemplateVersionId:external_exports.uuid()}),LifecycleRuleSchema=LifecycleMoveSchema.extend({gated:external_exports.boolean(),approvalTemplateVersionId:external_exports.uuid().optional()}),LifecycleRulesSchema=external_exports.strictObject({moves:external_exports.array(LifecycleRuleSchema).max(25)}),LifecyclePolicyOverlaySchema=external_exports.strictObject({disabledMoves:external_exports.array(LifecycleMoveSchema).max(25),addedGates:external_exports.array(LifecycleGateBindingSchema).max(25)}),EMPTY_LIFECYCLE_OVERLAY=Object.freeze({disabledMoves:[],addedGates:[]}),EffectiveMoveSchema=LifecycleRuleSchema,EffectiveLifecyclePolicySchema=external_exports.object({moves:external_exports.array(EffectiveMoveSchema)}).brand(),LifecyclePolicyViewSchema=external_exports.object({rules:LifecycleRulesSchema.nullable(),overlay:LifecyclePolicyOverlaySchema.nullable(),effective:EffectiveLifecyclePolicySchema.nullable()}),SaveLifecycleRulesInputSchema=external_exports.strictObject({rules:LifecycleRulesSchema,idempotencyKey:IdempotencyKeySchema}),SaveLifecyclePolicyInputSchema=external_exports.strictObject({overlay:LifecyclePolicyOverlaySchema,idempotencyKey:IdempotencyKeySchema});var AssetSummarySchema=external_exports.object({total:external_exports.number().int().min(0),byLifecycleStatus:external_exports.record(AssetLifecycleStatusSchema,external_exports.number().int().min(0)),atLeast:external_exports.literal(!0).optional(),capReached:SearchCapReachedSchema.optional()});var LongitudeSchema=external_exports.number().min(-180).max(180),LatitudeSchema=external_exports.number().min(-90).max(90),GeoJsonPositionSchema=external_exports.tuple([LongitudeSchema,LatitudeSchema]),GEOJSON_ARRAY_WIRE_MAX=2e6,bounded=(element,min,max2)=>{let list=external_exports.array(element).min(min);return max2===void 0?list:list.max(max2)},ringOf=max2=>bounded(GeoJsonPositionSchema,4,max2),buildPolygonSchema=(max2,ringMax=max2)=>external_exports.strictObject({type:external_exports.literal("Polygon"),coordinates:bounded(ringOf(ringMax),1,max2)}),buildGeometrySchema=max2=>{let ring=ringOf(max2);return external_exports.discriminatedUnion("type",[external_exports.strictObject({type:external_exports.literal("Point"),coordinates:GeoJsonPositionSchema}),external_exports.strictObject({type:external_exports.literal("LineString"),coordinates:bounded(GeoJsonPositionSchema,2,max2)}),buildPolygonSchema(max2),external_exports.strictObject({type:external_exports.literal("MultiPoint"),coordinates:bounded(GeoJsonPositionSchema,1,max2)}),external_exports.strictObject({type:external_exports.literal("MultiLineString"),coordinates:bounded(bounded(GeoJsonPositionSchema,2,max2),1,max2)}),external_exports.strictObject({type:external_exports.literal("MultiPolygon"),coordinates:bounded(bounded(ring,1,max2),1,max2)})])},GeoJsonGeometrySchema=buildGeometrySchema(void 0),GeoJsonGeometryInputSchema=buildGeometrySchema(GEOJSON_ARRAY_WIRE_MAX),WITHIN_POLYGON_MAX_VERTICES=1e3,GeoJsonPolygonSchema=buildPolygonSchema(GEOJSON_ARRAY_WIRE_MAX,WITHIN_POLYGON_MAX_VERTICES);var HierarchyRelationshipTypeSchema=external_exports.enum(["CONTAINS","PART_OF","REPORTS_TO","BELONGS_TO"]).describe("Edge type to walk, read subject\u2192object (`CONTAINS`: subject contains object). Only the four HIERARCHICAL types are walkable \u2014 the storage-only `FLOWS_TO` / `CONNECTED_TO` are rejected here, though `relationships.create`/`listFor` accept them.");var HIERARCHY_ID_SHAPE=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,HierarchyIdSchema=external_exports.string().regex(HIERARCHY_ID_SHAPE,"must be a uuid").brand().describe("The named tree an edge lives in \u2014 `hierarchy.id`, stable for the tree's lifetime."),HIERARCHY_NAME_MAX=120,HierarchyNameSchema=external_exports.string().trim().min(1,"a hierarchy name cannot be blank").max(HIERARCHY_NAME_MAX).describe("The tree's operator-facing name, UNIQUE PER TENANT. Compositions reference a hierarchy by this name and the import resolves-or-creates on it, so the name is the durable ref an operator types \u2014 not an internal code.");var HierarchySchema=external_exports.object({id:HierarchyIdSchema,name:HierarchyNameSchema,createdAt:external_exports.iso.datetime()}),CreateHierarchyInputSchema=external_exports.strictObject({idempotencyKey:UnreceiptedIdempotencyKeySchema,name:HierarchyNameSchema}),ListHierarchiesInputSchema=external_exports.strictObject({}),HierarchyEdgeCountSchema=external_exports.object({relationshipType:HierarchyRelationshipTypeSchema,edgeCount:external_exports.number().int().min(1)}),HierarchyListItemSchema=HierarchySchema.extend({edgeCounts:external_exports.array(HierarchyEdgeCountSchema).optional()}),ListHierarchiesOutputSchema=external_exports.array(HierarchyListItemSchema),HierarchyScopeSchema=external_exports.discriminatedUnion("by",[external_exports.object({by:external_exports.literal("hierarchy"),get hierarchyId(){return HierarchyIdSchema}}),external_exports.object({by:external_exports.literal("unassigned")})]).describe('REQUIRED \u2014 which tree to walk. `{by:"hierarchy", hierarchyId}` walks that named tree; `{by:"unassigned"}` walks the edges that predate hierarchies (the only bucket where a child may have more than one parent). There is no "all trees" option: the union of two trees is not a tree.');var AssetForestSchema=external_exports.strictObject({hierarchy:HierarchyScopeSchema,relationshipType:HierarchyRelationshipTypeSchema});var UNDER_ASSET_IDS_MAX=50,AssetBranchScopeSchema=external_exports.strictObject({forest:AssetForestSchema,assetIds:external_exports.array(AssetIdSchema).min(1).max(UNDER_ASSET_IDS_MAX)}),UNDER_ASSET_IDS_DESCRIPTION="Show only assets in the branch of ANY of these items: each item AND everything under it, walked in ONE tree (`forest.hierarchy`) by one relationship type, so a set of items is an OR. Node-inclusive: the item itself is in its own branch. 1 to 50 items. There is no size cap on a branch, which is walked to a depth of 64 as `subtreeOf` is: one too large for the request's time budget is refused with `TX_BUDGET_OVERRUN`, never truncated. An id that is not a UUID is dropped (an all-malformed set matches nothing, never everything); an id with no edge in the tree matches itself alone. ANDs with every other filter. Read-only: bulk writes and export do not take it. `subtreeOf` is the capped (10,000), single-item form kept for existing callers; this key has no cap.";var AssetCategoryIdSchema=external_exports.string().min(1).brand(),ASSET_TYPE_ENTITY_HINT={entity:{domain:"assets",type:"asset-type"}},ASSET_ENTITY_HINT={entity:{domain:"assets",type:"asset"},pickerResource:"assets"},AssetTypeIdSchema=external_exports.string().min(1).brand().meta(ASSET_TYPE_ENTITY_HINT),AssetCategorySchema=external_exports.object({id:AssetCategoryIdSchema,key:external_exports.string().min(1),displayName:external_exports.string().min(1),createdAt:external_exports.iso.datetime(),updatedAt:external_exports.iso.datetime()}),CreateAssetCategoryInputSchema=external_exports.strictObject({idempotencyKey:UnreceiptedIdempotencyKeySchema,key:external_exports.string().min(1),displayName:external_exports.string().min(1)}),RawCreateAssetCategoryInputSchema=CreateAssetCategoryInputSchema.omit({idempotencyKey:!0}),GetAssetCategoryInputSchema=external_exports.strictObject({id:AssetCategoryIdSchema}),UpdateAssetCategoryInputSchema=external_exports.strictObject({idempotencyKey:UnreceiptedIdempotencyKeySchema,id:AssetCategoryIdSchema,displayName:external_exports.string().min(1)}),ListAssetCategoriesInputSchema=external_exports.strictObject({}),DeleteAssetCategoryInputSchema=external_exports.strictObject({idempotencyKey:UnreceiptedIdempotencyKeySchema,id:AssetCategoryIdSchema}),AssetTypeSchema=external_exports.object({id:AssetTypeIdSchema,key:external_exports.string().min(1),displayName:external_exports.string().min(1),categoryId:AssetCategoryIdSchema,createdAt:external_exports.iso.datetime(),updatedAt:external_exports.iso.datetime()}),CreateAssetTypeInputSchema=external_exports.strictObject({idempotencyKey:UnreceiptedIdempotencyKeySchema,key:external_exports.string().min(1),displayName:external_exports.string().min(1),categoryId:AssetCategoryIdSchema}),RawCreateAssetTypeInputSchema=CreateAssetTypeInputSchema.omit({idempotencyKey:!0}),GetAssetTypeInputSchema=external_exports.strictObject({id:AssetTypeIdSchema}),UpdateAssetTypeInputSchema=external_exports.strictObject({idempotencyKey:UnreceiptedIdempotencyKeySchema,id:AssetTypeIdSchema,displayName:external_exports.string().min(1)}),ListAssetTypesInputSchema=external_exports.strictObject({categoryId:AssetCategoryIdSchema.optional()}),DeleteAssetTypeInputSchema=external_exports.strictObject({idempotencyKey:UnreceiptedIdempotencyKeySchema,id:AssetTypeIdSchema});var ASSETS_SUBTREE_FILTER_KIND="assets.subtree",ASSETS_TYPE_FILTER_KIND="assets.type",AssetSubtreeScopeSchema=external_exports.strictObject({forest:AssetForestSchema,assetId:AssetIdSchema}).describe("The asset `assetId` AND everything under it, walked in ONE tree (`forest.hierarchy`) by one relationship type. Node-inclusive. An asset reachable only through another tree is not in it."),AssetSubtreeFilterValueSchema=external_exports.union([AssetSubtreeScopeSchema,AssetBranchScopeSchema]),AssetTypeFilterValueSchema=external_exports.strictObject({assetTypeIds:external_exports.array(AssetTypeIdSchema).min(1).max(50)});var AsOfSchema=external_exports.iso.datetime().describe("Point-in-time instant to resolve as-of (half-open effectiveFrom <= asOf < effectiveTo). UTC, Z-only \u2014 a numeric offset (+HH:MM) is rejected; the OpenAPI date-time format cannot express Z-only, so this note is where the constraint lives. Absent \u2192 the current state."),KnownAtSchema=external_exports.iso.datetime().refine(value2=>Date.parse(value2)<=Date.now(),{message:"A known-at instant cannot be in the future."}).describe("Replay an as-of read as known at this instant: only dated values recorded at or before it and not retired by it are merged; version rows are read as stored. UTC, Z-only. Never in the future, and only with asOf. Absent \u2192 now."),EffectiveFromSchema=external_exports.iso.datetime({precision:3}).describe("Instant the change took effect (the successor version opens here). UTC, Z-only \u2014 a numeric offset (+HH:MM) is rejected \u2014 and pinned to MILLISECOND precision. Must be after the current version\u2019s effectiveFrom and not in the future. Absent \u2192 the instant the request is applied."),EffectiveToSchema=external_exports.iso.datetime({precision:3}).describe("Instant the interval closed (the row stops being in force here). UTC, Z-only \u2014 a numeric offset (+HH:MM) is rejected \u2014 and pinned to MILLISECOND precision. Must be after the row\u2019s own effectiveFrom and not in the future. Absent \u2192 the instant the request is applied (or, on a create, the edge stays open)."),InitialEffectiveFromSchema=external_exports.iso.datetime({precision:3}).describe("Instant this asset first existed \u2014 its FIRST version opens here, so a reporting window that closes before it resolves the asset as not-yet-created. UTC, Z-only \u2014 a numeric offset (+HH:MM) is rejected \u2014 and pinned to MILLISECOND precision. Must NOT be in the future; there is no lower bound (a first version has no predecessor to invert). Absent \u2192 the instant the request is applied, byte-identically to a create that predates this field.");var RelationshipNeighborsInputSchema=external_exports.strictObject({get assetId(){return AssetIdSchema},get relationshipType(){return HierarchyRelationshipTypeSchema},hierarchy:HierarchyScopeSchema,get asOf(){return AsOfSchema.optional()}}),RelationshipRootsInputSchema=external_exports.strictObject({get relationshipType(){return HierarchyRelationshipTypeSchema},hierarchy:HierarchyScopeSchema,get asOf(){return AsOfSchema.optional()},offset:external_exports.number().int().min(0).optional(),get limit(){return external_exports.number().int().min(1).max(QUALITY_PAGE_LIMIT_MAX).optional()}}),HIERARCHY_MAX_DEPTH=64,AssetSubtreeInputSchema=external_exports.strictObject({get assetId(){return AssetIdSchema},get relationshipType(){return HierarchyRelationshipTypeSchema},hierarchy:HierarchyScopeSchema,get asOf(){return AsOfSchema.optional()},maxDepth:external_exports.number().int().min(1).max(HIERARCHY_MAX_DEPTH).describe("REQUIRED \u2014 how many edges deep to walk (1\u201364). There is no default: omitting it is a validation error, not an unbounded walk. Depth 1 = immediate neighbours only.")}),AssetAncestorsInputSchema=external_exports.strictObject({get assetId(){return AssetIdSchema},get relationshipType(){return HierarchyRelationshipTypeSchema},hierarchy:HierarchyScopeSchema,get asOf(){return AsOfSchema.optional()},maxDepth:external_exports.number().int().min(1).max(HIERARCHY_MAX_DEPTH).describe("REQUIRED \u2014 how many edges deep to walk (1\u201364). There is no default: omitting it is a validation error, not an unbounded walk. Depth 1 = immediate neighbours only.")}),SubtreeNodeSchema=external_exports.object({get assetId(){return AssetIdSchema},name:external_exports.string().min(1),get assetTypeId(){return AssetTypeIdSchema},lifecycleStatus:AssetLifecycleStatusSchema}),HierarchyBrowseNodeSchema=SubtreeNodeSchema.extend({hasChildren:external_exports.boolean()});var RelationshipRootsCountSchema=external_exports.discriminatedUnion("kind",[external_exports.object({kind:external_exports.literal("exact"),total:external_exports.number().int().min(0)}),external_exports.object({kind:external_exports.literal("atLeast"),total:external_exports.number().int().min(0)})]),RelationshipRootsOutputSchema=external_exports.object({items:external_exports.array(HierarchyBrowseNodeSchema),count:RelationshipRootsCountSchema}),RelationshipHasChildrenInputSchema=external_exports.strictObject({get assetIds(){return external_exports.array(AssetIdSchema).min(1).max(ASSET_IDS_MAX_PER_PAGE)},get relationshipType(){return HierarchyRelationshipTypeSchema},hierarchy:HierarchyScopeSchema,get asOf(){return AsOfSchema.optional()}}),RelationshipHasChildrenOutputSchema=external_exports.array(external_exports.object({get assetId(){return AssetIdSchema},hasChildren:external_exports.boolean()})),AssetSubtreeOutputSchema=external_exports.array(external_exports.object({node:SubtreeNodeSchema,depth:external_exports.number().int().min(0),get parentAssetId(){return AssetIdSchema.nullable()}})),AssetAncestorsOutputSchema=external_exports.array(external_exports.object({node:SubtreeNodeSchema,depth:external_exports.number().int().min(0),get childAssetId(){return AssetIdSchema.nullable()}})),RelationshipAncestorsManyInputSchema=external_exports.strictObject({get assetIds(){return external_exports.array(AssetIdSchema).min(1).max(ASSET_IDS_MAX_PER_PAGE)},get relationshipType(){return HierarchyRelationshipTypeSchema},hierarchy:HierarchyScopeSchema,get asOf(){return AsOfSchema.optional()},maxDepth:external_exports.number().int().min(1).max(HIERARCHY_MAX_DEPTH).describe("REQUIRED \u2014 how many edges deep to walk above each asset (1\u201364). There is no default: omitting it is a validation error, not an unbounded walk.")}),RelationshipAncestorsManyOutputSchema=external_exports.array(external_exports.object({get assetId(){return AssetIdSchema},ancestors:AssetAncestorsOutputSchema})),UNDER_COUNT_IDS_MAX=50,DescendantCountsInputSchema=external_exports.strictObject({get forest(){return AssetForestSchema},get assetIds(){return external_exports.array(AssetIdSchema).min(1).max(UNDER_COUNT_IDS_MAX)},get asOf(){return AsOfSchema.optional()}}),DescendantCountsOutputSchema=external_exports.array(external_exports.object({get assetId(){return AssetIdSchema},count:external_exports.number().int().min(0)}));var AssetDescendantsInputSchema=external_exports.strictObject({get assetId(){return AssetIdSchema},get relationshipType(){return HierarchyRelationshipTypeSchema},hierarchy:HierarchyScopeSchema,get asOf(){return AsOfSchema.optional()},maxDepth:external_exports.number().int().min(1).max(HIERARCHY_MAX_DEPTH).describe("REQUIRED \u2014 how many edges deep to walk (1\u201364). There is no default: omitting it is a validation error, not an unbounded walk. Depth 1 = immediate neighbours only."),get assetTypeIds(){return external_exports.array(AssetTypeIdSchema).min(1).max(50).optional()}}),DescendantNodeSchema=external_exports.object({get assetId(){return AssetIdSchema},get assetTypeId(){return AssetTypeIdSchema},lifecycleStatus:AssetLifecycleStatusSchema,depth:external_exports.number().int().min(0),current:external_exports.boolean()}),AssetDescendantsOutputSchema=external_exports.object({root:external_exports.object({get assetId(){return AssetIdSchema},name:external_exports.string().min(1)}),nodes:external_exports.array(DescendantNodeSchema),reachedCount:external_exports.number().int().min(0).optional(),maxDepthReached:external_exports.number().int().min(0).optional()});var DESCENDANT_GEOMETRY_MAX_ITEMS=1e3,DESCENDANT_GEOMETRY_HIERARCHY_TYPES_WIRE_MAX=16,DescendantGeometryInputSchema=external_exports.strictObject({get assetId(){return AssetIdSchema},get hierarchyTypes(){return external_exports.array(HierarchyRelationshipTypeSchema).min(1).max(DESCENDANT_GEOMETRY_HIERARCHY_TYPES_WIRE_MAX).optional()},limit:external_exports.number().int().min(1).max(DESCENDANT_GEOMETRY_MAX_ITEMS).optional()}),LocatedDescendantSchema=SubtreeNodeSchema.extend({geometry:GeoJsonGeometrySchema}),DescendantGeometryOutputSchema=external_exports.object({items:external_exports.array(LocatedDescendantSchema),total:external_exports.number().int().min(0)});var CONDITIONS_MAX=10,CONDITION_VALUE_MAX=512,DISTINCT_VALUES_LIMIT_MAX=20,ConditionScalarSchema=external_exports.union([external_exports.string().max(CONDITION_VALUE_MAX),external_exports.number(),external_exports.boolean()]),ConditionFieldSchema=external_exports.string().regex(/^(asset:(name|type|category|status)|prop:[\s\S]{1,64}|ext:(\*|[\s\S]{1,64}))$/).describe("A condition field: `asset:name`, `asset:type`, `asset:category`, `asset:status`, `prop:<property code>`, `ext:<external-ID system key>` or `ext:*` (any system)."),ConditionRowSchema=external_exports.discriminatedUnion("op",[external_exports.strictObject({field:ConditionFieldSchema,op:external_exports.literal("is"),value:ConditionScalarSchema}),external_exports.strictObject({field:ConditionFieldSchema,op:external_exports.literal("isNot"),value:ConditionScalarSchema}),external_exports.strictObject({field:ConditionFieldSchema,op:external_exports.literal("contains"),value:external_exports.string().min(1).max(CONDITION_VALUE_MAX)}),external_exports.strictObject({field:ConditionFieldSchema,op:external_exports.literal("gt"),value:external_exports.number()}),external_exports.strictObject({field:ConditionFieldSchema,op:external_exports.literal("lt"),value:external_exports.number()}),external_exports.strictObject({field:ConditionFieldSchema,op:external_exports.literal("isEmpty")}),external_exports.strictObject({field:ConditionFieldSchema,op:external_exports.literal("isNotEmpty")})]),AssetConditionsSchema=external_exports.strictObject({match:external_exports.enum(["all","any"]),rows:external_exports.array(ConditionRowSchema).min(1).max(CONDITIONS_MAX)}).describe('Operator conditions, 1 to 10 rows of { field, op, value }, combined by `match` (`all` or `any`). `any` applies only among these rows: every facet, `nameContains`, `propertyFilters` and the id sets still combine with And. Fields: `asset:name`, `asset:type` (a type id), `asset:category` (a category id), `asset:status`, `prop:<code>`, `ext:<system>` or `ext:*`. Operators: `is`, `isNot`, `contains`, `gt`, `lt`, `isEmpty`, `isNotEmpty`. `is` on `asset:name` and `prop:` ignores case and coerces numbers ("42" matches 42); on `ext:`, `asset:type`, `asset:category` and `asset:status` it is exact. `isNot` is its complement and includes assets without the property. `contains` is a literal, case-insensitive substring of the value text. `gt` / `lt` compare numbers and numeric strings. Empty means absent, "" or a stored JSON null. Unlike `propertyFilters` (exact, JSON-typed `equals` / `oneOf` / `noneOf`), these rules are loose by design. A property or external-ID condition alone reads every asset and may be refused with TX_BUDGET_OVERRUN: narrow by a type or category first. A field, operator and value that do not fit is refused with INVALID_CONDITION naming the row.'),INVALID_CONDITION="INVALID_CONDITION",InvalidConditionReasonSchema=external_exports.enum(["operator-not-allowed","value-not-allowed","invalid-status","invalid-text","prefix-required","values-not-allowed"]),InvalidConditionDataSchema=external_exports.object({code:external_exports.literal(INVALID_CONDITION),reason:InvalidConditionReasonSchema,index:external_exports.number().int().min(0).optional(),field:external_exports.string().optional(),op:external_exports.string().optional()});var PropertyCodeSchema=external_exports.string().min(1).max(64),PropertyScalarSchema=external_exports.union([external_exports.string(),external_exports.number(),external_exports.boolean()]),PropertyValuesSchema=external_exports.record(PropertyCodeSchema,PropertyScalarSchema),PROPERTY_VALUES_WIRE_MAX=1e3,PropertyValuesInputSchema=wireBoundedRecord(PropertyCodeSchema,PropertyScalarSchema,PROPERTY_VALUES_WIRE_MAX),PROPERTY_FILTER_MAX=10,PROPERTY_FILTER_VALUES_MAX=20,PROPERTY_FILTER_VALUE_TEXT_MAX=CONDITION_VALUE_MAX,PropertyFilterListValueSchema=external_exports.union([external_exports.string().max(PROPERTY_FILTER_VALUE_TEXT_MAX).regex(/^[^\u0000\ud800-\udfff]*$/u,"a value cannot hold a NUL character or an unpaired surrogate"),external_exports.number(),external_exports.boolean()]),PropertyFilterValuesSchema=external_exports.array(PropertyFilterListValueSchema).min(1).max(PROPERTY_FILTER_VALUES_MAX),AssetPropertyEqualsSchema=external_exports.strictObject({code:PropertyCodeSchema,equals:PropertyScalarSchema}),AssetPropertyOneOfSchema=external_exports.strictObject({code:PropertyCodeSchema,oneOf:PropertyFilterValuesSchema}),AssetPropertyNoneOfSchema=external_exports.strictObject({code:PropertyCodeSchema,noneOf:PropertyFilterValuesSchema}),AssetPropertyPredicateSchema=external_exports.union([AssetPropertyEqualsSchema,AssetPropertyOneOfSchema,AssetPropertyNoneOfSchema]),AssetPropertyFilterSchema=external_exports.array(AssetPropertyPredicateSchema).min(1).max(PROPERTY_FILTER_MAX).describe(`Narrow to assets whose static properties hold these values \u2014 one entry per property \`code\`, ANDed. Each entry is exactly one of \`{code, equals}\`, \`{code, oneOf: [..]}\` (any of the values) or \`{code, noneOf: [..]}\` (none of them; an asset without the property is kept). A list holds 1 to ${String(PROPERTY_FILTER_VALUES_MAX)} values; an empty list is refused. Equality is JSON-typed and exact: the number 42 does NOT match a stored "42", and "Sold" does not match "SOLD". For \`equals\` and \`oneOf\`, a code no asset carries matches nothing; for \`noneOf\` it keeps every asset. Resolved against the version effective at \`asOf\` when that is supplied, so a past-instant page and its \`total\` describe the same population. This is the EXACT form, kept as an alias: the looser operator filter is \`conditions\`, whose \`is\` ignores case and coerces numbers.`),AssetPropertyEqualsFilterSchema=external_exports.array(AssetPropertyEqualsSchema).min(1).max(PROPERTY_FILTER_MAX).describe('Narrow to assets whose static properties hold exactly these values \u2014 one `{code, equals}` entry per property, ANDed, JSON-typed (42 does NOT match a stored "42"). A bulk write takes `equals` only; `oneOf` / `noneOf` are refused here.');var DUPLICATE_ASSETS_PAGE_SIZE_MAX=100,DUPLICATE_ASSETS_SEARCH_MAX=200,DUPLICATE_ASSETS_GROUP_MEMBERS_MAX=50,DUPLICATE_ASSETS_MIN_MEMBERS_DEFAULT=2,DuplicateEvidenceKindSchema=external_exports.enum(["SAME_SYSTEM","DIFFERENT_SYSTEMS","TOO_LITTLE_EVIDENCE"]),DuplicateAssetsSortSchema=external_exports.enum(["MEMBERS_DESC","NAME","TYPE"]),DuplicateMatchedBySchema=external_exports.discriminatedUnion("kind",[external_exports.object({kind:external_exports.literal("NAME")}),external_exports.object({kind:external_exports.literal("PROPERTY"),code:PropertyCodeSchema})]),MatchPropertyCodeSchema=PropertyCodeSchema.regex(/^[^\u0000\ud800-\udfff]*$/u,"a property code cannot hold a NUL character or an unpaired surrogate"),DuplicateAssetsInputSchema=external_exports.strictObject({search:external_exports.string().trim().min(1).max(DUPLICATE_ASSETS_SEARCH_MAX).optional(),assetType:AssetTypeIdSchema.optional(),lifecycle:AssetLifecycleStatusSchema.optional(),externalIdSystem:ExternalIdSystemSchema.optional(),minMembers:external_exports.number().int().min(DUPLICATE_ASSETS_MIN_MEMBERS_DEFAULT).optional(),evidence:DuplicateEvidenceKindSchema.optional(),sort:DuplicateAssetsSortSchema.optional(),page:external_exports.number().int().min(1).optional(),pageSize:external_exports.number().int().min(1).max(DUPLICATE_ASSETS_PAGE_SIZE_MAX).optional(),matchProperty:MatchPropertyCodeSchema.optional()}),DuplicateAssetMemberSchema=SubtreeNodeSchema.extend({externalIdSystems:external_exports.array(ExternalIdSystemSchema),matchedValue:external_exports.string().optional()}),DuplicateAssetGroupSchema=external_exports.object({nameKey:external_exports.string(),name:external_exports.string().min(1),matchedBy:DuplicateMatchedBySchema,sharedValue:external_exports.string().min(1),evidence:DuplicateEvidenceKindSchema,memberCount:external_exports.number().int().min(2),members:external_exports.array(DuplicateAssetMemberSchema).min(2).max(DUPLICATE_ASSETS_GROUP_MEMBERS_MAX)}).refine(group=>group.members.length===Math.min(group.memberCount,DUPLICATE_ASSETS_GROUP_MEMBERS_MAX),{message:"members must be the group\u2019s first members up to the cap",path:["members"]}),DuplicateAssetsReportSchema=external_exports.object({total:external_exports.number().int().min(0),groups:external_exports.array(DuplicateAssetGroupSchema)});var EdgeWriteDeadlockDataSchema=external_exports.object({reason:external_exports.literal("deadlock")});var DATED_STATUS_CODE="@status";var TemplateDefinitionIssueSchema=external_exports.strictObject({code:external_exports.string().min(1),message:external_exports.string().min(1)});var RESERVED_STATUS_CODE_MESSAGE=`property code "${DATED_STATUS_CODE}" is reserved for the asset's status`;var RECEIVED_VALUE_MAX_LENGTH=120,PropertyValueIssueSchema=external_exports.strictObject({code:external_exports.string().min(1),message:external_exports.string().min(1),expected:external_exports.string().min(1).optional(),received:external_exports.string().min(1).optional(),receivedValue:external_exports.string().max(RECEIVED_VALUE_MAX_LENGTH+1).optional()});var DatedLinkReasonSchema=external_exports.enum(["already-holds","kept-recorded","multiple-parents"]),DatedLinkEndSchema=external_exports.enum(["until","next-change","current-link","open"]),InstantSchema=external_exports.iso.datetime({precision:6}),DatedLinkStretchSchema=external_exports.strictObject({from:InstantSchema,until:InstantSchema.nullable(),parentAssetIds:external_exports.array(AssetIdSchema)}),DatedLinkKeptSchema=DatedLinkStretchSchema.extend({reason:DatedLinkReasonSchema}),DatedLinkReplacedSchema=external_exports.strictObject({relationshipId:external_exports.uuid(),parentAssetId:AssetIdSchema,from:InstantSchema,until:InstantSchema}),DatedLinkResultSchema=external_exports.strictObject({verdict:external_exports.enum(["written","unchanged"]),reason:DatedLinkReasonSchema.optional(),from:InstantSchema,until:InstantSchema.nullable(),endsAt:DatedLinkEndSchema,written:external_exports.array(DatedLinkStretchSchema),replaced:external_exports.array(DatedLinkReplacedSchema),kept:external_exports.array(DatedLinkKeptSchema),startMoved:external_exports.boolean().optional()}),LIST_PARENT_LINKS_PAGE_MAX=500;var ListParentLinksInputSchema=external_exports.strictObject({assetId:AssetIdSchema,hierarchy:HierarchyScopeSchema,limit:external_exports.number().int().min(1).max(LIST_PARENT_LINKS_PAGE_MAX).optional(),cursor:external_exports.string().min(1).max(512).optional()}),PARENT_LINK_REPLACED_MAX=20,ParentLinkReplacedSchema=external_exports.strictObject({parentAssetId:AssetIdSchema,from:external_exports.iso.datetime(),until:external_exports.iso.datetime()}),ParentLinkRowSchema=external_exports.strictObject({id:external_exports.uuid(),relationshipId:external_exports.uuid(),relationshipType:HierarchyRelationshipTypeSchema,parentAssetId:AssetIdSchema,effectiveFrom:external_exports.iso.datetime(),effectiveTo:external_exports.iso.datetime().nullable(),recordedAt:external_exports.iso.datetime().nullable(),recordId:external_exports.uuid().nullable(),statedBy:external_exports.strictObject({principal:external_exports.string(),onBehalfOf:external_exports.string().optional()}).nullable(),statedAt:external_exports.iso.datetime().nullable(),replaced:external_exports.array(ParentLinkReplacedSchema).max(PARENT_LINK_REPLACED_MAX),replacedTotal:external_exports.number().int().min(0)}),ListParentLinksOutputSchema=external_exports.strictObject({items:external_exports.array(ParentLinkRowSchema),nextCursor:external_exports.string().nullable()}),DatedLinkDryRunSchema=external_exports.strictObject({dryRun:external_exports.literal(!0),dated:DatedLinkResultSchema}),DATED_CREATE_FIELDS={replaceRecorded:external_exports.boolean().optional(),dryRun:external_exports.boolean().optional()},previewsADatedLink=input2=>input2.dryRun!==!0||input2.effectiveFrom!==void 0&&(input2.relationshipType===void 0||HierarchyRelationshipTypeSchema.safeParse(input2.relationshipType).success),DATED_DRY_RUN_ISSUE={message:"A dry run needs an effectiveFrom and a hierarchy relationship type.",path:["dryRun"]};var DATED_VALUES_MAX_ITEMS=1e3,DatedValueCodeSchema=external_exports.string().min(1).max(64),DatedValueScalarSchema=external_exports.union([external_exports.string(),external_exports.number(),external_exports.boolean()]).nullable(),DatedInstantSchema=external_exports.iso.datetime({precision:3}).describe("UTC instant, Z-only, millisecond precision. Never in the future."),DatedValueItemSchema=external_exports.strictObject({assetId:AssetIdSchema,code:DatedValueCodeSchema,value:DatedValueScalarSchema,from:DatedInstantSchema,until:external_exports.union([DatedInstantSchema,external_exports.literal("today")]).optional()}),SetDatedValuesInputSchema=external_exports.strictObject({items:external_exports.array(DatedValueItemSchema).min(1).max(DATED_VALUES_MAX_ITEMS),idempotencyKey:IdempotencyKeySchema,dryRun:external_exports.boolean().optional(),replaceRecorded:external_exports.boolean().optional()});var DatedValueVerdictSchema=external_exports.enum(["written","unchanged","refused"]),DatedValueReasonSchema=external_exports.enum(["already-holds","outside-asset-life","kept-recorded","future-date","invalid-range","unknown-property","invalid-value","asset-fails-template","unknown-asset","lifecycle-transition","lifecycle-gated-transition"]),DatedValueEndSchema=external_exports.enum(["next-change","deletion","today","until"]),DatedValueReplacedSchema=external_exports.strictObject({value:DatedValueScalarSchema,from:external_exports.iso.datetime(),until:external_exports.iso.datetime(),covered:external_exports.boolean()}),DatedStatusMoveSchema=external_exports.strictObject({from:AssetLifecycleStatusSchema,to:AssetLifecycleStatusSchema,at:external_exports.iso.datetime()}),DatedValueItemResultSchema=external_exports.strictObject({assetId:AssetIdSchema,code:DatedValueCodeSchema,verdict:DatedValueVerdictSchema,reason:DatedValueReasonSchema.optional(),from:external_exports.iso.datetime().optional(),until:external_exports.iso.datetime().optional(),endsAt:DatedValueEndSchema.optional(),startMoved:external_exports.boolean().optional(),replaced:external_exports.array(DatedValueReplacedSchema),kept:external_exports.array(DatedValueReplacedSchema),todayChanged:external_exports.boolean(),issues:external_exports.array(PropertyValueIssueSchema).optional(),move:DatedStatusMoveSchema.optional()}),SetDatedValuesOutputSchema=external_exports.strictObject({dryRun:external_exports.boolean(),results:external_exports.array(DatedValueItemResultSchema)}),AppliedDatedValueIdsSchema=external_exports.record(DatedValueCodeSchema,external_exports.uuid()),LIST_DATED_VALUES_PAGE_MAX=500;var ListDatedValuesInputSchema=external_exports.strictObject({assetId:AssetIdSchema,limit:external_exports.number().int().min(1).max(LIST_DATED_VALUES_PAGE_MAX).optional(),cursor:external_exports.string().min(1).max(512).optional()}),DatedValueStatedBySchema=external_exports.strictObject({principal:external_exports.string(),onBehalfOf:external_exports.string().optional()}),DatedValueRowSchema=external_exports.strictObject({id:external_exports.uuid(),code:DatedValueCodeSchema,value:DatedValueScalarSchema,replacedValue:DatedValueScalarSchema,replacedCovered:external_exports.boolean(),effectiveFrom:external_exports.iso.datetime(),effectiveTo:external_exports.iso.datetime(),recordedAt:external_exports.iso.datetime(),recordedTo:external_exports.iso.datetime().nullable(),recordId:external_exports.uuid(),statedBy:DatedValueStatedBySchema.nullable(),statedAt:external_exports.iso.datetime().nullable()}),ListDatedValuesOutputSchema=external_exports.strictObject({items:external_exports.array(DatedValueRowSchema),nextCursor:external_exports.string().nullable()}),DATED_VALUE_CHANGES_MAX_WINDOWS=200,DATED_VALUE_CHANGES_MAX_CODES=200,DATED_VALUE_CHANGES_MAX_ASSET_IDS=2e5,DATED_VALUE_CHANGES_MAX_TREES=200,DATED_VALUE_CHANGES_PAGE_MAX=1e3;var DatedValueChangeWindowSchema=external_exports.strictObject({from:AsOfSchema,to:AsOfSchema,knownAt:AsOfSchema}),ListDatedValueChangesInputSchema=external_exports.strictObject({codes:external_exports.array(DatedValueCodeSchema).min(1).max(DATED_VALUE_CHANGES_MAX_CODES),windows:external_exports.array(DatedValueChangeWindowSchema).min(1).max(DATED_VALUE_CHANGES_MAX_WINDOWS),assetIds:external_exports.array(AssetIdSchema).min(1).max(DATED_VALUE_CHANGES_MAX_ASSET_IDS).optional(),trees:external_exports.array(HierarchyScopeSchema).min(1).max(DATED_VALUE_CHANGES_MAX_TREES).optional(),limit:external_exports.number().int().min(1).max(DATED_VALUE_CHANGES_PAGE_MAX).optional(),cursor:external_exports.string().min(1).max(512).optional()}),DatedValueChangeSchema=external_exports.strictObject({kind:external_exports.literal("dated-value").default("dated-value"),id:external_exports.uuid(),assetId:AssetIdSchema,code:DatedValueCodeSchema,value:DatedValueScalarSchema,effectiveFrom:external_exports.iso.datetime(),effectiveTo:external_exports.iso.datetime(),recordedAt:external_exports.iso.datetime(),recordedTo:external_exports.iso.datetime().nullable(),windows:external_exports.array(external_exports.number().int().min(0)).min(1)}),DatedLinkChangeSchema=external_exports.strictObject({kind:external_exports.literal("link"),change:external_exports.enum(["recorded","retired","closed"]),id:external_exports.uuid(),relationshipId:external_exports.uuid(),relationshipType:external_exports.string(),childAssetId:AssetIdSchema,parentAssetId:AssetIdSchema,hierarchyId:external_exports.uuid().nullable(),effectiveFrom:external_exports.iso.datetime(),effectiveTo:external_exports.iso.datetime().nullable(),windows:external_exports.array(external_exports.number().int().min(0)).min(1)}),VersionChangeSchema=external_exports.strictObject({kind:external_exports.literal("version"),id:external_exports.uuid(),assetId:AssetIdSchema,codes:external_exports.array(DatedValueCodeSchema).min(1),effectiveFrom:external_exports.iso.datetime(),effectiveTo:external_exports.iso.datetime().nullable(),writtenAt:external_exports.iso.datetime(),windows:external_exports.array(external_exports.number().int().min(0)).min(1)}),DatedValueChangesItemSchema=external_exports.discriminatedUnion("kind",[DatedValueChangeSchema,VersionChangeSchema,DatedLinkChangeSchema]),ListDatedValueChangesOutputSchema=external_exports.strictObject({items:external_exports.array(DatedValueChangesItemSchema),nextCursor:external_exports.string().nullable()});var RevertDatedValuesInputSchema=external_exports.strictObject({importId:external_exports.uuid(),idempotencyKey:IdempotencyKeySchema}),RevertSkippedSchema=external_exports.strictObject({assetId:AssetIdSchema,code:DatedValueCodeSchema,from:external_exports.iso.datetime(),until:external_exports.iso.datetime()}),RevertDatedValuesOutputSchema=external_exports.strictObject({importId:external_exports.uuid(),retired:external_exports.number().int().nonnegative(),restored:external_exports.number().int().nonnegative(),skipped:external_exports.number().int().nonnegative(),skippedSample:external_exports.array(RevertSkippedSchema).max(20)});var ProjectedEffectiveFromSchema=external_exports.discriminatedUnion("from",[external_exports.object({from:external_exports.literal("column"),column:external_exports.string().min(1)}),external_exports.object({from:external_exports.literal("constant"),value:InitialEffectiveFromSchema}),external_exports.object({from:external_exports.literal("asset-start")})]).describe("WHEN each row takes effect. ABSENT: at the moment of the write. A `constant` applies one instant to every row (UTC, Z-only, millisecond precision). A `column` is read per row and must hold an ISO-8601 UTC calendar date `YYYY-MM-DD` (midnight UTC) or a full instant `YYYY-MM-DDTHH:MM:SS[.sss]Z`; anything else, a blank cell, a future date or a date that does not exist fails its row `template-validation`. `asset-start` dates each matched row from its asset's start (its first version's date) and a created asset from the import. A CREATED asset first exists at this instant, and so do its placement edges. A MATCHED row dated after the asset's current version is an ordinary dated update. A matched row dated at or before it is BACK-DATED: its property values are set over `[its date, the next row for that asset with a value for that column, or now)`, filling stretches with no value, writing nothing where the value already holds, and keeping a different recorded value unless `replaceRecorded` or `replaceColumns` says otherwise; a blank cell states nothing, and only the values a row writes are validated. Its name, status and location changes apply today. In a dated mode a file may carry several contiguous rows for one asset (its history), processed oldest first; a later non-contiguous row or a second row on the same date fails `identity-conflict`, and a history over the row bound fails `history-too-long`."),ProjectedReplaceFields={replaceRecorded:external_exports.boolean().optional().describe("Back-dated rows only: `true` replaces a different recorded value over the row's range with the file's value (\"Use the file's values\"). Absent or `false`: recorded values are kept and counted."),replaceColumns:external_exports.array(external_exports.string().min(1)).max(1e3).optional().describe("Back-dated rows only: the dataset columns whose different recorded values are replaced, the per-column form of `replaceRecorded`.")},RefusedValueSchema=external_exports.object({code:external_exports.string().min(1),message:external_exports.string().min(1)}),BackDatedRowFields={backDated:external_exports.literal(!0).optional(),valuesKept:external_exports.number().int().positive().optional(),refusedValues:external_exports.array(RefusedValueSchema).optional(),appliedToday:external_exports.literal(!0).optional()},DatedImportCountFields={backDated:external_exports.number().int().positive().optional(),valuesDated:external_exports.number().int().positive().optional(),valuesKept:external_exports.number().int().positive().optional(),valuesRefused:external_exports.number().int().positive().optional(),statusesDated:external_exports.number().int().positive().optional(),statusesKept:external_exports.number().int().positive().optional(),statusesRefused:external_exports.number().int().positive().optional(),parentsDated:external_exports.number().int().positive().optional(),parentsKept:external_exports.number().int().positive().optional(),parentsRefused:external_exports.number().int().positive().optional(),appliedToday:external_exports.number().int().positive().optional()},DatedImportPreviewFields={willBackDate:external_exports.number().int().nonnegative().optional(),matchedColumnDifferences:external_exports.number().int().nonnegative().optional()};var AssetDistinctValuesInputSchema=external_exports.strictObject({field:ConditionFieldSchema,get filter(){return AssetListFilterSchema.describe("The rest of the list filter the suggestions are over, verbatim (asOf included).")},prefix:external_exports.string().min(1).max(CONDITION_VALUE_MAX).optional().describe('Only values of a group where ANY member spelling starts with this, ignoring case, taken literally (`%`, `_` and `\\` match themselves). The returned `value` is the most common spelling of that group, so it may not start with the prefix itself (members `42` and `"42.0"`, prefix `42.`, returns `42`). REQUIRED for `asset:name` and `ext:` fields, which hold about one value per asset.'),limit:external_exports.number().int().min(1).max(DISTINCT_VALUES_LIMIT_MAX).optional().describe("How many values to return, 1 to 20; defaults to 20. There is no next page."),values:PropertyFilterValuesSchema.optional().describe('Count exactly these values instead of suggesting: JSON-typed and case-exact, the `propertyFilters` equality (42 is not "42", "Sold" is not "SOLD"). A `prop:` field only, with no `prefix`; refused INVALID_CONDITION `values-not-allowed` otherwise. Each listed value some selected asset holds comes back once, as listed, in list order; a value no selected asset holds is absent. `limit` does not apply. With a `search` that reached one of its caps, each count is a floor and says so (`countAtLeast`, `capReached`).')}),AssetDistinctValueSchema=external_exports.strictObject({value:ConditionScalarSchema,count:external_exports.number().int().min(1),countAtLeast:external_exports.literal(!0).optional(),capReached:SearchCapReachedSchema.optional()}),AssetDistinctValuesOutputSchema=external_exports.array(AssetDistinctValueSchema);var QUALITY_SCAN_TIMEOUT_REASON="timeout",QUALITY_SCAN_BUSY_REASON="busy",QualityScanRefusalDataSchema=external_exports.object({reason:external_exports.enum([QUALITY_SCAN_TIMEOUT_REASON,QUALITY_SCAN_BUSY_REASON])}),UnparentedScopeSchema=external_exports.strictObject({by:external_exports.literal("hierarchy"),hierarchyId:HierarchyIdSchema,relationshipType:HierarchyRelationshipTypeSchema});var ReadTxBudgetOverrunDataSchema=external_exports.object({budgetMs:external_exports.number().int().positive()}),LONG_READ_BUSY_REASON="long-read-busy",LongReadBusyDataSchema=external_exports.object({reason:external_exports.literal(LONG_READ_BUSY_REASON)}),RUNNER_ONLY_REASON="runner-only",NO_LONG_READ_REASON="no-long-read",RunnerOnlyDataSchema=external_exports.object({reason:external_exports.literal(RUNNER_ONLY_REASON)}),NoLongReadDataSchema=external_exports.object({reason:external_exports.literal(NO_LONG_READ_REASON)});var OBSERVED_PROPERTY_CATALOG_ENTRIES=[{observedProperty:"pressure",uom:"kPa"},{observedProperty:"temperature",uom:"degC"},{observedProperty:"flow_rate",uom:"m3/h"}];var ReturnResultsSchema=external_exports.enum(["all","failures","summary"]).describe("How much of the per-row `results` array to return on THIS call. `summary` (the counts object) rides on the wire in EVERY mode \u2014 this controls `results` alone. `all` (default) returns every row; `failures` returns only rows that did not succeed; `summary` returns no rows at all. Response-shaping only: the persisted governance Record keeps the FULL results array regardless, so a later replay of the same idempotencyKey can still return every row.");var MoveManyItemSchema=external_exports.strictObject({get assetId(){return AssetIdSchema},get fromParentAssetId(){return AssetIdSchema.nullable()}}),MOVE_MANY_MAX_ITEMS=100,MoveManyInputSchema=external_exports.strictObject({get relationshipType(){return HierarchyRelationshipTypeSchema},get targetAssetId(){return AssetIdSchema},items:external_exports.array(MoveManyItemSchema).min(1).max(MOVE_MANY_MAX_ITEMS),hierarchy:HierarchyScopeSchema.optional(),idempotencyKey:IdempotencyKeySchema,returnResults:ReturnResultsSchema.optional()}),MoveManyRefusalReasonSchema=external_exports.enum(["self-parent","asset-not-found","already-under-target","edge-changed","would-cycle"]),MoveManyItemResultSchema=external_exports.discriminatedUnion("status",[external_exports.strictObject({get assetId(){return AssetIdSchema},status:external_exports.literal("moved"),get relationshipId(){return AssetRelationshipIdSchema}}),external_exports.strictObject({get assetId(){return AssetIdSchema},status:external_exports.literal("attached"),get relationshipId(){return AssetRelationshipIdSchema}}),external_exports.strictObject({get assetId(){return AssetIdSchema},status:external_exports.literal("refused"),reason:MoveManyRefusalReasonSchema})]),MoveManyOutputSchema=external_exports.object({summary:external_exports.object({requested:external_exports.number().int().min(0),moved:external_exports.number().int().min(0),attached:external_exports.number().int().min(0),refused:external_exports.number().int().min(0)}),results:external_exports.array(MoveManyItemResultSchema)}),MoveManyResponseSchema=MoveManyOutputSchema.extend({accessUpdate:AccessUpdateStateSchema});var AssetSortFieldSchema=external_exports.enum(["name","lifecycleStatus","effectiveFrom"]),SortDirectionSchema=external_exports.enum(["asc","desc"]),AssetOrderBySchema=external_exports.strictObject({field:AssetSortFieldSchema,direction:SortDirectionSchema});var ASSETS_LIST_ROW_SOURCE_ID="assets.list",LIFECYCLE_OPTION_LABEL={PRE_PRODUCTION:"Pre-production",ACTIVE:"Active",INACTIVE:"Inactive",SHUT_IN:"Shut in",DECOMMISSIONED:"Decommissioned"},assetsListRowSource={id:ASSETS_LIST_ROW_SOURCE_ID,label:"Assets",description:"Every current asset in the tenant, with its category, type, lifecycle status and last update.",rowKind:{domain:"assets",type:"asset"},pageScope:{facets:[ASSETS_SUBTREE_FILTER_KIND,ASSETS_TYPE_FILTER_KIND]},columns:[{key:"name",label:"Name",type:"text",sortable:!0,shownByDefault:!0},{key:"category",label:"Category",type:"text",sortable:!1,shownByDefault:!0},{key:"type",label:"Type",type:"text",sortable:!1,shownByDefault:!0},{key:"lifecycle",label:"Lifecycle",type:"enum",sortable:!0,shownByDefault:!0},{key:"updated",label:"Last updated",type:"datetime",sortable:!0,shownByDefault:!0}],filters:[{key:"name",label:"Name",valueType:"text",operators:["contains"]},{key:"lifecycleStatus",label:"Lifecycle",valueType:"enum",operators:["eq","in"],options:AssetLifecycleStatusSchema.options.map(status=>({value:status,label:LIFECYCLE_OPTION_LABEL[status]}))},{key:"categoryId",label:"Category",valueType:"text",operators:["eq","in"]},{key:"assetTypeId",label:"Type",valueType:"text",operators:["eq","in"]},{key:"subtree",label:"Under asset (<tree>~<relationshipType>~<assetId>)",valueType:"text",operators:["eq"]}],defaultSort:{field:"name",direction:"asc"},limit:{default:20,max:200}};var ASSET_EXTERNAL_ID_DATASET_NAME="asset_external_id",ASSET_CURRENT_DATASET_NAME="asset_current",ASSET_CURRENT_PARENT_DATASET_NAME="asset_current_parent",ASSET_HIERARCHY_DATASET_NAME="asset_hierarchy";var ASSET_DIRECTORY_COLUMN_TYPES={[ASSET_EXTERNAL_ID_DATASET_NAME]:{asset_id:"VARCHAR",system:"VARCHAR",external_id:"VARCHAR",valid_from:"TIMESTAMPTZ",valid_to:"TIMESTAMPTZ",is_current:"BOOLEAN",as_of:"TIMESTAMPTZ"},[ASSET_CURRENT_DATASET_NAME]:{asset_id:"VARCHAR",asset_code:"VARCHAR",kind:"VARCHAR",name:"VARCHAR",parent_id:"VARCHAR",as_of:"TIMESTAMPTZ",location_wkt:"VARCHAR",location_type:"VARCHAR",latitude:"DOUBLE",longitude:"DOUBLE",location_from:"VARCHAR",kind_id:"VARCHAR"},[ASSET_CURRENT_PARENT_DATASET_NAME]:{asset_id:"VARCHAR",hierarchy_id:"VARCHAR",parent_id:"VARCHAR",as_of:"TIMESTAMPTZ",relationship_type:"VARCHAR"},[ASSET_HIERARCHY_DATASET_NAME]:{hierarchy_id:"VARCHAR",name:"VARCHAR",created_at:"TIMESTAMPTZ",as_of:"TIMESTAMPTZ"}},ASSET_DIRECTORY_COLUMN_ENTITIES={[ASSET_EXTERNAL_ID_DATASET_NAME]:{asset_id:ASSET_ENTITY_HINT},[ASSET_CURRENT_DATASET_NAME]:{asset_id:ASSET_ENTITY_HINT,parent_id:ASSET_ENTITY_HINT,location_from:ASSET_ENTITY_HINT,kind_id:ASSET_TYPE_ENTITY_HINT},[ASSET_CURRENT_PARENT_DATASET_NAME]:{asset_id:ASSET_ENTITY_HINT,parent_id:ASSET_ENTITY_HINT},[ASSET_HIERARCHY_DATASET_NAME]:{}};var ASSET_DIRECTORY_TYPED_COLUMNS={[ASSET_EXTERNAL_ID_DATASET_NAME]:["asset_id","system","external_id"],[ASSET_CURRENT_DATASET_NAME]:["asset_id"],[ASSET_CURRENT_PARENT_DATASET_NAME]:["asset_id"],[ASSET_HIERARCHY_DATASET_NAME]:[]};var DIRECTORY_SCHEDULE_MIN_INTERVAL_SECONDS=3600,DirectoryScheduleSchema=external_exports.object({intervalSeconds:external_exports.number().int().min(DIRECTORY_SCHEDULE_MIN_INTERVAL_SECONDS).nullable()}),DirectoryScheduleReadSchema=DirectoryScheduleSchema.nullable(),SetDirectoryScheduleInputSchema=external_exports.strictObject({intervalSeconds:external_exports.number().int().min(DIRECTORY_SCHEDULE_MIN_INTERVAL_SECONDS).nullable(),idempotencyKey:IdempotencyKeySchema});var DatasetColumnTypeSchema=external_exports.enum(["STRING","NUMBER","BOOLEAN"]),DatasetCellValueSchema=external_exports.union([external_exports.string(),external_exports.number(),external_exports.boolean(),external_exports.null()]);var COLUMN_MAP_WIRE_MAX=8192,SOURCE_TRANSFORMATION_RUN_INPUTS_MAX=128,SOURCE_TRANSFORMATION_RUN_PARAMS_MAX=200,SOURCE_TRANSFORMATION_OUTPUTS_MAX=64,SOURCE_TRANSFORMATION_OUTPUT_COLUMN_TYPES_MAX=COLUMN_MAP_WIRE_MAX,QUALITY_CHECKS_TABLES_WIRE_MAX=128,DESCRIBE_EXPECTED_KEYWORDS_MAX=1e3,WIRE_BOUNDED_RECORDS3=[];function boundedRecord2(key,value2,max2,noun,published4={}){let bounded4=external_exports.record(key,value2).refine(candidate=>Object.keys(candidate).length<=max2,{message:`name at most ${String(max2)} ${noun}`}),schema=published4.description===void 0?bounded4:bounded4.describe(published4.description);return WIRE_BOUNDED_RECORDS3.push({schema,max:max2,...published4.min===void 0?{}:{min:published4.min}}),schema}var DatasetColumnEntitySchema=external_exports.object({entity:external_exports.object({domain:external_exports.string().min(1).max(64),type:external_exports.string().min(1).max(64)}),pickerResource:external_exports.string().min(1).max(64).optional()}).describe('What the values of this column are the ids of, e.g. `{"entity": {"domain": "assets", "type": "asset"}, "pickerResource": "assets"}` for a column of asset ids.'),ASSET_COLUMN_ENTITY={entity:{domain:"assets",type:"asset"}},DatasetColumnEntitiesSchema=external_exports.record(external_exports.string().min(1),DatasetColumnEntitySchema),DatasetColumnEntitiesPatchSchema=boundedRecord2(external_exports.string().min(1),DatasetColumnEntitySchema.nullable(),COLUMN_MAP_WIRE_MAX,"column tags",{description:"Tag or untag columns, by column name: a tag sets it, `null` removes it, and columns not named keep theirs. Only a kind of thing Studio can show by name is accepted."}),DatasetColumnEntitiesWireSchema=boundedRecord2(external_exports.string().min(1),DatasetColumnEntitySchema,COLUMN_MAP_WIRE_MAX,"column tags"),COLUMN_ENTITIES_DESCRIPTION='Tag columns with what their values are the ids of, by column name (e.g. `{"site_id": {"entity": {"domain": "assets", "type": "asset"}}}`). The tag belongs to the dataset, so later versions keep it: a later land that omits this keeps every tag, and one that sends it sets the named columns and leaves the rest. A name that is not a column of the landed data is refused.',columnEntitiesWireFacet={columnEntities:DatasetColumnEntitiesWireSchema.optional().describe(COLUMN_ENTITIES_DESCRIPTION)},columnEntitiesFacet={columnEntities:DatasetColumnEntitiesSchema.optional().describe(COLUMN_ENTITIES_DESCRIPTION)};var DatasetColumnSchema2=external_exports.object({name:external_exports.string().min(1),type:DatasetColumnTypeSchema,refersTo:DatasetColumnEntitySchema.optional(),wholeNumbers:external_exports.literal(!0).optional()}),DatasetRowSchema=external_exports.record(external_exports.string(),DatasetCellValueSchema);var DATASET_LABEL_MAX_LENGTH=200,NO_CONTROL_CHARACTERS=/^[^\p{Cc}]*$/u,SHOWS_SOMETHING=/[^\s\p{Cf}\u115F\u1160\u2800\u3164\uFFA0]/u,DatasetLabelSchema=external_exports.string().trim().min(1).max(DATASET_LABEL_MAX_LENGTH).regex(NO_CONTROL_CHARACTERS,{message:"A label cannot hold control characters."}).regex(SHOWS_SOMETHING,{message:"A label needs at least one character that shows."}).describe("The readable name shown for the dataset. It never changes how the dataset is found."),labelFacet={label:DatasetLabelSchema.optional().describe('The readable name to show for this dataset, e.g. "Results \xB7 GHG \xB7 2025 \xB7 Totals". Set only when the dataset has no label yet, so a label a person chose is never overwritten. The dataset is still found by `name`.')};var datasetReadabilityFields={label:external_exports.string().min(1).optional(),category:external_exports.string().min(1).optional(),dataOwner:external_exports.string().min(1).optional()};var DATASET_ENTITY_HINT={entity:{domain:"datasets",type:"dataset"},pickerResource:"datasets",pinsTo:{path:"versionId",picker:"dataset-version"}},DatasetIdSchema=external_exports.string().min(1).brand().meta(DATASET_ENTITY_HINT),DatasetVersionIdSchema=external_exports.string().min(1).brand(),DatasetRefSchema=external_exports.object({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema.optional()}).describe("How every consumer addresses a dataset. `versionId` absent = whatever load is current; present = pin that exact load in single-version reads (`versionStatus`/`read`/`getLiveDefinition`), which is what makes a read reproducible; the `versions` history read ignores `versionId` and lists every load. A consumer wanting the latest PROMOTED load computes it from `versions`' `promotedAt`. PROMOTE-BEFORE-CONSUME gates governed CONSUMPTION, not reading: `datasets.read` and composition validation resolve an unpromoted version by design, so a successful read proves nothing about promotion. What refuses one is a governed consumer that turns dataset rows into domain state \u2014 `assets.composition.createMany` and the source-transformation inputs. The pipeline is land \u2192 promote \u2192 consume. Check a version's state with `datasets.versionStatus`; resolve a human name to a ref with `datasets.resolveName`.");var DATASET_REPLACED_CODE="DATASET_REPLACED";var RUN_CONNECTED_SYNCHRONOUS_UNSUPPORTED_CODE="RUN_CONNECTED_SYNCHRONOUS_UNSUPPORTED",DatasetReplacedBySchema=external_exports.object({get datasetId(){return DatasetIdSchema},name:external_exports.string().min(1),label:external_exports.string().min(1).optional()});var FORGE_DATASET_SLUG_PATTERN=/^[a-z0-9]+(?:-[a-z0-9]+)*(?:\/[a-z0-9]+(?:-[a-z0-9]+)*)*$/,SDP_CATALOG_SLUG_PATTERN=/^[a-z][a-z0-9_-]{0,62}[a-z0-9]$/,datasetSlugArm=pattern=>external_exports.string().min(1).max(200).regex(pattern),DatasetSlugSchema=external_exports.union([datasetSlugArm(FORGE_DATASET_SLUG_PATTERN),datasetSlugArm(SDP_CATALOG_SLUG_PATTERN)]).brand();var VERSION_PRODUCER_STATES=["failed","in-flight","abandoned"],DatasetVersionProducerSchema=external_exports.object({kind:external_exports.literal("corrections-apply"),applyRecordId:external_exports.string().min(1),state:external_exports.enum(VERSION_PRODUCER_STATES)});var ANALYTICS_MAX_PROFILE_COLUMNS=50;var ANALYTICS_MAX_TOP_VALUES=100;var ANALYTICS_MAX_HISTOGRAM_BUCKETS=100;var ANALYTICS_MAX_GROUP_LIMIT=1e3;var ANALYTICS_CURSOR_MAX_LENGTH=16384,ANALYTICS_MAX_SERIES=20;var DatasetProfileInputSchema=DatasetRefSchema.extend({columns:external_exports.array(external_exports.string().min(1)).min(1).max(ANALYTICS_MAX_PROFILE_COLUMNS).optional(),topValues:external_exports.number().int().min(1).max(ANALYTICS_MAX_TOP_VALUES).optional(),buckets:external_exports.number().int().min(1).max(ANALYTICS_MAX_HISTOGRAM_BUCKETS).optional()}),DatasetTemporalGrammarSchema=external_exports.enum(["iso-datetime","iso-date","year-month","year"]),DatasetColumnTemporalSchema=external_exports.object({grammar:DatasetTemporalGrammarSchema,min:external_exports.string().min(1),max:external_exports.string().min(1),minInstant:external_exports.iso.datetime(),maxInstant:external_exports.iso.datetime(),rangeDays:external_exports.number().int().nonnegative()}),DatasetTopValueSchema=external_exports.object({value:external_exports.string(),count:external_exports.number().int().nonnegative()}),DatasetHistogramBucketSchema=external_exports.object({bucketMin:external_exports.number(),bucketMax:external_exports.number(),count:external_exports.number().int().nonnegative()}),columnProfileBase={name:external_exports.string().min(1),rows:external_exports.number().int().nonnegative(),nonNull:external_exports.number().int().nonnegative(),nulls:external_exports.number().int().nonnegative(),blanks:external_exports.number().int().nonnegative(),distinct:external_exports.number().int().nonnegative()},DatasetStringColumnProfileSchema=external_exports.object({...columnProfileBase,type:external_exports.literal("STRING"),minLength:external_exports.number().int().nonnegative().nullable(),maxLength:external_exports.number().int().nonnegative().nullable(),topValues:external_exports.array(DatasetTopValueSchema),topValuesTruncated:external_exports.boolean(),temporal:DatasetColumnTemporalSchema.optional()}),DatasetNumberColumnProfileSchema=external_exports.object({...columnProfileBase,type:external_exports.literal("NUMBER"),numericKind:external_exports.enum(["integer","decimal"]).nullable(),min:external_exports.string().nullable(),max:external_exports.string().nullable(),mean:external_exports.string().nullable(),stddev:external_exports.string().nullable(),sum:external_exports.string().nullable(),p25:external_exports.string().nullable(),median:external_exports.string().nullable(),p75:external_exports.string().nullable(),quantilesExact:external_exports.boolean(),histogram:external_exports.array(DatasetHistogramBucketSchema)}),DatasetBooleanColumnProfileSchema=external_exports.object({...columnProfileBase,type:external_exports.literal("BOOLEAN"),trueCount:external_exports.number().int().nonnegative(),falseCount:external_exports.number().int().nonnegative()}),DatasetColumnProfileSchema=external_exports.discriminatedUnion("type",[DatasetStringColumnProfileSchema,DatasetNumberColumnProfileSchema,DatasetBooleanColumnProfileSchema]),DatasetProfileSchema=external_exports.object({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,producedBy:DatasetVersionProducerSchema.optional(),totalRows:external_exports.number().int().nonnegative(),totalColumns:external_exports.number().int().nonnegative(),columnsTruncated:external_exports.boolean(),columns:external_exports.array(DatasetColumnProfileSchema)}),DatasetMeasureAggSchema=external_exports.enum(["sum","avg","min","max"]),DatasetMeasureSchema=external_exports.discriminatedUnion("kind",[external_exports.object({kind:external_exports.literal("count")}),external_exports.object({kind:external_exports.literal("column"),column:external_exports.string().min(1),agg:DatasetMeasureAggSchema,castAs:external_exports.literal("number").optional()})]),DatasetAggregateInputSchema=DatasetRefSchema.extend({dimension:external_exports.string().min(1),measure:DatasetMeasureSchema,splitBy:external_exports.string().min(1).optional(),limit:external_exports.number().int().min(1).max(ANALYTICS_MAX_GROUP_LIMIT).optional(),cursor:external_exports.string().min(1).max(ANALYTICS_CURSOR_MAX_LENGTH).optional()}),DatasetMeasureStatsSchema=external_exports.object({sum:external_exports.string().nullable(),min:external_exports.string().nullable(),max:external_exports.string().nullable(),avg:external_exports.string().nullable()}),DatasetAggregateRowSchema=external_exports.object({dimension:external_exports.string().nullable(),series:external_exports.string().nullable().optional(),value:external_exports.string().nullable(),rowCount:external_exports.number().int().nonnegative(),stats:DatasetMeasureStatsSchema.nullable(),uncastCount:external_exports.number().int().nonnegative().optional()}),DatasetAggregateSchema=external_exports.object({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,producedBy:DatasetVersionProducerSchema.optional(),rows:external_exports.array(DatasetAggregateRowSchema),groupCount:external_exports.number().int().nonnegative(),seriesCount:external_exports.number().int().nonnegative(),truncated:external_exports.boolean(),omittedGroupCount:external_exports.number().int().nonnegative(),omittedSeriesCount:external_exports.number().int().nonnegative(),totalRows:external_exports.number().int().nonnegative(),nextCursor:external_exports.string().nullable(),uncastCellCount:external_exports.number().int().nonnegative().optional()}),DatasetSeriesBucketSchema=external_exports.enum(["day","month","quarter","year"]);var DatasetSeriesInputSchema=DatasetRefSchema.extend({timeColumn:external_exports.string().min(1),measure:DatasetMeasureSchema,bucket:DatasetSeriesBucketSchema,splitBy:external_exports.string().min(1).optional(),splitValues:external_exports.array(external_exports.string()).min(1).max(ANALYTICS_MAX_SERIES).optional()}),DatasetSeriesPointSchema=external_exports.object({t:external_exports.iso.datetime(),value:external_exports.string().nullable(),rowCount:external_exports.number().int().nonnegative()}),DatasetSeriesStatsSchema=external_exports.object({min:external_exports.string().nullable(),max:external_exports.string().nullable(),avg:external_exports.string().nullable(),first:external_exports.string().nullable(),last:external_exports.string().nullable(),lastT:external_exports.iso.datetime().nullable()}),DatasetSeriesEntrySchema=external_exports.object({key:external_exports.string().nullable().optional(),points:external_exports.array(DatasetSeriesPointSchema),stats:DatasetSeriesStatsSchema.nullable()}),DatasetSeriesSchema=external_exports.object({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,producedBy:DatasetVersionProducerSchema.optional(),timeColumn:external_exports.string().min(1),grammar:DatasetTemporalGrammarSchema,bucket:DatasetSeriesBucketSchema,bucketRequested:DatasetSeriesBucketSchema,bucketAdjusted:external_exports.boolean(),zeroFilled:external_exports.boolean(),series:external_exports.array(DatasetSeriesEntrySchema),droppedBucketCount:external_exports.number().int().nonnegative().optional(),totalRows:external_exports.number().int().nonnegative()});var DatasetStatusSchema=external_exports.enum(["active","paused","archived"]),DatasetMaturitySchema=external_exports.enum(["experimental","active","deprecated"]);var DatasetLifecycleReasonSchema=external_exports.string().min(1).max(500),ChangeDatasetStatusInputSchema=external_exports.strictObject({datasetId:external_exports.string().min(1).meta(DATASET_ENTITY_HINT),status:DatasetStatusSchema,reason:DatasetLifecycleReasonSchema.optional(),idempotencyKey:IdempotencyKeySchema}),ChangeDatasetMaturityInputSchema=external_exports.strictObject({datasetId:external_exports.string().min(1),maturity:DatasetMaturitySchema,reason:DatasetLifecycleReasonSchema.optional(),idempotencyKey:IdempotencyKeySchema});var DATASET_DESCRIPTION_MAX_LENGTH=2e3,DATASET_NOTES_MAX_LENGTH=4e3,DATASET_THEMES_MAX=100,DATASET_KEYWORD_MAX_LENGTH=64,DATASET_KEYWORDS_MAX=32,DATASET_GRAINS=["annual","quarterly","monthly","weekly","daily","hourly","irregular","unknown"],DatasetGrainSchema=external_exports.enum(DATASET_GRAINS),DATASET_TABLE_ROLES=["fact","dimension","relation"],DatasetTableRoleSchema=external_exports.enum(DATASET_TABLE_ROLES),DatasetTimeCoveredSchema=external_exports.strictObject({start:external_exports.iso.datetime({offset:!0}).nullable(),end:external_exports.iso.datetime({offset:!0}).nullable()}),DatasetTimeCoveredReadSchema=external_exports.object({start:external_exports.iso.datetime().nullable(),end:external_exports.iso.datetime().nullable()}),DATASET_DESCRIBE_FIELDS=["description","notes","keywords","themes","grain","timeCovered","tableRole"],DatasetDescribeFieldSchema=external_exports.enum(DATASET_DESCRIBE_FIELDS),DescribeDatasetExpectedSchema=external_exports.strictObject({description:external_exports.string().nullable().optional(),notes:external_exports.string().nullable().optional(),keywords:external_exports.array(external_exports.string()).max(DESCRIBE_EXPECTED_KEYWORDS_MAX).nullable().optional(),themes:external_exports.array(external_exports.string()).nullable().optional(),grain:DatasetGrainSchema.nullable().optional(),timeCovered:external_exports.strictObject({start:external_exports.string().nullable(),end:external_exports.string().nullable()}).nullable().optional(),tableRole:DatasetTableRoleSchema.nullable().optional(),versionId:external_exports.string().min(1).nullable()}),DescribeDatasetInputSchema=external_exports.strictObject({datasetId:external_exports.string().min(1),description:external_exports.string().min(1).max(DATASET_DESCRIPTION_MAX_LENGTH).nullable().optional().describe("Prose a reader needs to decide whether this dataset answers their question."),notes:external_exports.string().min(1).max(DATASET_NOTES_MAX_LENGTH).nullable().optional().describe("What a naive reading of this data gets wrong \u2014 a unit that is not what the column name suggests, timestamps that are really reporting periods, rows that double-count."),keywords:external_exports.array(external_exports.string().min(1).max(DATASET_KEYWORD_MAX_LENGTH)).max(DATASET_KEYWORDS_MAX).nullable().optional().describe("Search terms a reader would plausibly type looking for this dataset."),themes:external_exports.array(external_exports.string().regex(CATALOG_CONCEPT_REF_PATTERN,"a theme is 'scheme/slug'")).max(DATASET_THEMES_MAX).nullable().optional().describe("What this dataset is about, as terms from the tenant's own vocabulary, each 'scheme/slug'. Pick them with datasets.vocabulary.list \u2014 a term that is not there is refused, never created."),grain:DatasetGrainSchema.nullable().optional().describe("How often the data underneath changes. Derive it from how far apart the timestamps actually are, never from how precise they look: a yearly total stamped with a midnight timestamp is annual, not daily."),timeCovered:DatasetTimeCoveredSchema.nullable().optional().describe("The window the rows cover; either bound may be null for an open end."),tableRole:DatasetTableRoleSchema.nullable().optional().describe("What one row IS: a measurement (fact), a thing (dimension), or a link (relation)."),get expected(){return DescribeDatasetExpectedSchema.describe('What you believe each field you are about to write holds RIGHT NOW, so a value somebody edited since you read it is refused instead of overwritten. Every field this call writes must appear here; use null for "believed empty", which is a real assertion and not a default. Add versionId to state which load you read \u2014 the receipt then names the evidence you actually had. Beliefs about description, notes, keywords and themes are judged against the shared data platform, which owns them; the rest are judged against this server. Themes compare as a set. A wrong belief refuses the WHOLE call and names every field that moved, so one round trip builds the corrective retry.')},reason:DatasetLifecycleReasonSchema.optional(),get idempotencyKey(){return IdempotencyKeySchema}}),DescribeCandidatesInputSchema=DatasetRefSchema.extend({}),DatasetTimeCoveredCandidateSchema=external_exports.object({column:external_exports.string().min(1),start:external_exports.iso.datetime(),end:external_exports.iso.datetime(),evidence:external_exports.object({grammar:DatasetTemporalGrammarSchema,minValue:external_exports.string(),maxValue:external_exports.string(),rows:external_exports.number().int().nonnegative(),nonNull:external_exports.number().int().nonnegative()})}),DATASET_GRAIN_BASES=["grammar","spacing"],DatasetGrainBasisSchema=external_exports.enum(DATASET_GRAIN_BASES),DatasetGrainCandidateSchema=external_exports.object({column:external_exports.string().min(1),grain:DatasetGrainSchema,evidence:external_exports.object({basis:DatasetGrainBasisSchema,grammar:DatasetTemporalGrammarSchema,distinctValues:external_exports.number().int().nonnegative(),spanDays:external_exports.number().int().nonnegative(),averageSpacingDays:external_exports.number().nonnegative().nullable()})}),DatasetKeyFieldCandidateSchema=external_exports.object({column:external_exports.string().min(1),evidence:external_exports.object({rows:external_exports.number().int().nonnegative(),nonNull:external_exports.number().int().nonnegative(),distinct:external_exports.number().int().nonnegative()})}),DatasetDescribeCandidatesSchema=external_exports.object({get datasetId(){return DatasetIdSchema},get versionId(){return DatasetVersionIdSchema},rowCount:external_exports.number().int().nonnegative(),totalColumns:external_exports.number().int().nonnegative(),columnsProfiled:external_exports.number().int().nonnegative(),columnsTruncated:external_exports.boolean(),timeCovered:external_exports.array(DatasetTimeCoveredCandidateSchema),grain:external_exports.array(DatasetGrainCandidateSchema),keyFields:external_exports.array(DatasetKeyFieldCandidateSchema)});var REJECTED_CONFIG_SOURCE="`config.path` is not accepted by `datasets.inspectUpload`: this is a read-tier verb where the caller supplies the bytes, so admitting a server-filesystem path would widen it into a (confined) file-read primitive. Send the file inline as `content` (csv/json text) or `contentBase64` (any format); for a file too large to send inline, stage it with `datasets.beginUpload` and inspect the `uploadRef` it issues \u2014 that channel IS accepted here and is the one to reach for. Or use `datasets.land`, which does take `config.path`.",INSPECT_SHEET_DESCRIPTION='Which worksheet to inspect, for `format: "xlsx"` only \u2014 supplying it with any other format is refused. Omitted = the first NON-EMPTY sheet, in workbook order. ONE sheet is PARSED per call, but the response lists every sheet in the workbook, so a picker can show them all and inspect another by naming it here. A name that is not in the workbook is refused, listing the sheets that are. Nothing is landed either way \u2014 this verb persists nothing.\n\nWITH `uploadRef` IT DOES NOTHING: a staged xlsx cannot be inspected through a ref at all, so the whole call is refused (that refusal names your two options), and with every other format supplying `sheet` is the refused mistake above. To choose a worksheet, inspect a sample of the workbook INLINE as `contentBase64` to read its sheet list, then pass the sheet you picked to `datasets.land` together with your ref.',INSPECT_CONTENT_DESCRIPTION="The file itself, as inline UTF-8 TEXT. csv and json only \u2014 a UTF-8 string cannot carry arbitrary bytes losslessly, so xlsx/parquet are refused on this channel and must use `contentBase64`. Exactly one of `content` / `contentBase64` / `uploadRef` may be supplied. `config.path` is NOT a channel here (see `config`) \u2014 the caller supplies the bytes; use `datasets.land` for a file the server already holds.",INSPECT_CONTENT_BASE64_DESCRIPTION="The file itself, as inline BASE64 bytes. Works for EVERY format, and is the only channel here for the binary ones (xlsx, parquet). The size cap is checked on the base64 length BEFORE decoding, so an over-cap upload is refused without ever being allocated. Exactly one of `content` / `contentBase64` / `uploadRef` may be supplied. `config.path` is NOT a channel here (see `config`) \u2014 use `datasets.land` for a file the server already holds.",INSPECT_COLUMN_TYPES_DESCRIPTION='Declare a column\'s type and PREVIEW what that declaration would do, by column name (e.g. `{"asset_tag": "STRING"}`) \u2014 the same map `datasets.land` takes, checked by the same rule against the same full pass over every value. TWO DIFFERENCES from the land, both because this verb persists nothing: a declared NUMBER/BOOLEAN the values cannot carry is REPORTED in `castReport` (how many values fail, and a few of them) rather than refusing the call, and the previewed `columns` then keep the INFERRED type \u2014 so the preview never shows a type the land would refuse to declare. A name that is not a column of the source is still REFUSED, exactly as on `land`: a silently dropped declaration is how a caller ends up believing a column is text when it landed NUMBER. Not accepted on the `objectRef` arm, where the engine reads a bounded sample rather than every value and no honest count exists.',INSPECT_UPLOAD_REF_DESCRIPTION="A sealed staged-upload handle from `completeUpload` \u2014 how a file you STAGED gets PREVIEWED before it is landed (and, for a csv, how a file too large to send inline gets previewed at all). This is the channel to reach for whenever you staged the bytes: inspecting a ref is what lets you choose a `keyColumn` from real columns, and `keyColumn` is fixed AT land and cannot be changed afterwards.\n\nRecipe: `beginUpload` \u2192 `appendUploadChunk` \xD7 N \u2192 `completeUpload` (issues this ref) \u2192 `inspectUpload` with the ref \u2192 `land` with the SAME ref plus the `keyColumn` you chose. The ref must be SEALED, not yet captured into custody, and yours \u2014 each failure is refused by name, exactly as on `land`.\n\nA READ NEVER RELEASES: inspecting does NOT release or consume the slot, so the same ref is still there to `land` afterwards (and still counts toward your open-slot cap until you `abortUpload` it). It also does not EXTEND the slot: unlike `land`, a preview leaves the expiry where it was, because this is a read-tier call and cannot write to the slot at all. So inspect and then land without a long pause between them; if the slot expires in between, the land is refused and you re-stage. In the same vein, a preview does not hold the slot against a concurrent reclaim \u2014 if it expires mid-read you get a named, retryable refusal, never damaged data.\n\nWhich formats, and how big: csv is read INCREMENTALLY, so a staged csv far larger than the inline channels can carry previews fine (up to the streamed bound). json/geojson/parquet are read WHOLE, exactly as `land` reads them \u2014 so those are bound by the same 10 MiB whole-read cap as an inline body, and a staged one over that is refused by size. A staged XLSX is REFUSED outright \u2014 preview a small sample of the workbook inline instead. Exactly one of `content` / `contentBase64` / `uploadRef` may be supplied.";var CAPTURE_POLICY_CLASSES=["interactive","bulk"],CapturePolicyClassSchema=external_exports.enum(CAPTURE_POLICY_CLASSES),CONTENT_ENCODINGS=["identity","gzip"],ContentEncodingSchema=external_exports.enum(CONTENT_ENCODINGS),INTERACTIVE_MAX_CAPTURE_BYTES=1024*1024*1024,BULK_MAX_CAPTURE_BYTES=2*1024*1024*1024;var CaptureSourceIdSchema=external_exports.string().min(1).brand(),CaptureSourceViewSchema=external_exports.object({sourceId:external_exports.string().min(1),displayName:external_exports.string().min(1),policyClass:CapturePolicyClassSchema,maxBytes:external_exports.number().int().positive(),contentEncoding:ContentEncodingSchema,registeredAt:external_exports.iso.datetime().optional(),recordId:external_exports.string().min(1).optional()});var SourceKeySchema=external_exports.string().min(1).max(64).regex(/^[a-z][a-z0-9-]*$/,"source key must be kebab-case starting with a letter"),registrationFields={key:SourceKeySchema,displayName:external_exports.string().min(1).max(200),maxBytes:external_exports.number().int().positive(),idempotencyKey:IdempotencyKeySchema},RegisterSourceInputSchema=external_exports.discriminatedUnion("policyClass",[external_exports.strictObject({...registrationFields,policyClass:external_exports.literal("interactive"),contentEncoding:external_exports.literal("identity").default("identity")}),external_exports.strictObject({...registrationFields,policyClass:external_exports.literal("bulk"),contentEncoding:ContentEncodingSchema.default("identity")})]);var OBJECT_REF_PREFIX="obr_",OBJECT_REF_HEX_LENGTH=32,ObjectRefSchema=external_exports.string().regex(new RegExp(`^${OBJECT_REF_PREFIX}[0-9a-f]{${OBJECT_REF_HEX_LENGTH}}$`),"not an ObjectRef (obr_ + 32 hex characters)").brand();var ResolvedObjectSchema=external_exports.object({uri:external_exports.string().min(1),captureId:external_exports.string().min(1),sizeBytes:external_exports.number().int().nonnegative(),contentType:external_exports.string().min(1),contentEncoding:external_exports.enum(["identity","gzip"]),policyClass:CapturePolicyClassSchema});var CaptureIdSchema=external_exports.uuid().brand(),CAPTURE_STATES=["PENDING","COMPLETED","EXPIRED"],CaptureStateSchema=external_exports.enum(CAPTURE_STATES),CHECKSUM_VERIFICATION_GRADES=["STORE_VERIFIED"],ChecksumVerificationGradeSchema=external_exports.enum(CHECKSUM_VERIFICATION_GRADES),QUARANTINE_WINDOW_MS=1440*60*1e3,Sha256Base64Schema=external_exports.string().regex(/^[A-Za-z0-9+/]{43}=$/,"not a base64-encoded sha256 digest");var BeginCaptureInputSchema=external_exports.strictObject({sourceId:external_exports.string().min(1).optional(),filename:external_exports.string().min(1).max(1024),contentType:external_exports.string().min(1).max(255),sizeBytes:external_exports.number().int().positive(),sha256:Sha256Base64Schema,contentEncoding:ContentEncodingSchema.default("identity"),idempotencyKey:IdempotencyKeySchema}),WriteGrantSchema=external_exports.object({url:external_exports.url(),method:external_exports.literal("PUT"),headers:external_exports.record(external_exports.string(),external_exports.string()),expiresAt:external_exports.iso.datetime()}),CaptureViewSchema=external_exports.object({captureId:CaptureIdSchema,objectRef:ObjectRefSchema,sourceId:external_exports.string().min(1),policyClass:CapturePolicyClassSchema,state:CaptureStateSchema,filename:external_exports.string().min(1),contentType:external_exports.string().min(1),contentEncoding:ContentEncodingSchema,sizeBytes:external_exports.number().int().nonnegative(),declaredSha256:Sha256Base64Schema,verificationGrade:ChecksumVerificationGradeSchema.optional(),capturedBy:external_exports.string().min(1),expiresAt:external_exports.iso.datetime(),completedAt:external_exports.iso.datetime().optional(),createdAt:external_exports.iso.datetime(),recordId:external_exports.string().min(1).optional()}),BeginCaptureResultSchema=external_exports.object({capture:CaptureViewSchema,grants:external_exports.array(WriteGrantSchema)}),CompleteCaptureInputSchema=external_exports.strictObject({captureId:CaptureIdSchema,idempotencyKey:IdempotencyKeySchema}),GetCaptureInputSchema=external_exports.strictObject({captureId:CaptureIdSchema});var CONNECTOR_KINDS=["delta-sharing","snowflake"],ConnectorKindSchema=external_exports.enum(CONNECTOR_KINDS,{error:`connectorKind must be one of: ${CONNECTOR_KINDS.join(", ")} \u2014 the SDP catalog's own data_service_type slug. "delta-share" is the retired spelling and is refused.`});var SNOWFLAKE_ACCOUNT_URL_HINT="Must look like https://<account>.snowflakecomputing.com (<org>-<account> or an account locator) \u2014 lower-case, the account\u2019s own URL, with no path, port or login in it.";var SNOWFLAKE_ACCOUNT_URL_RE=/^https:\/\/[a-z0-9]+(-[a-z0-9]+)*\.snowflakecomputing\.com\/?$/,trimSnowflakeAccountUrlSlash=url2=>url2.endsWith("/")?url2.slice(0,-1):url2,SnowflakeAccountUrlSchema=external_exports.string().min(1).max(2048).regex(SNOWFLAKE_ACCOUNT_URL_RE,SNOWFLAKE_ACCOUNT_URL_HINT).transform(trimSnowflakeAccountUrlSlash),ConnectionIdSchema=external_exports.string().min(1).max(200).brand(),ConnectionRefSchema=external_exports.object({connectionId:ConnectionIdSchema}),TITLE_REQUIRED_HINT="Enter a name for this connection.";var ENDPOINT_URL_HINT="Must be an https:// URL, with no username or password in the URL itself.",SECRET_ARN_HINT="Must be a Secrets Manager ARN (arn:aws:secretsmanager:\u2026).";var MAX_CONNECTION_TITLE_LENGTH=200,ConnectionTitleSchema=external_exports.string().min(1).max(MAX_CONNECTION_TITLE_LENGTH).regex(/\S/,TITLE_REQUIRED_HINT),HTTPS_URL_RE=/^https:\/\/(?![^/?#]*@)[^\s/?#]+[^\s]*$/,ConnectionEndpointUrlSchema=external_exports.string().min(1).max(2048).regex(HTTPS_URL_RE,ENDPOINT_URL_HINT),SECRET_ARN_RE=/^arn:aws:secretsmanager:[a-z0-9-]{1,32}:[0-9]{12}:secret:[A-Za-z0-9/_+=.@-]{1,512}$/,CredentialReferenceSchema=external_exports.string().min(1).max(2048).regex(SECRET_ARN_RE,SECRET_ARN_HINT),CreateConnectionInputSchema=external_exports.strictObject({connectorKind:ConnectorKindSchema,title:ConnectionTitleSchema,endpointUrl:ConnectionEndpointUrlSchema,secretArn:CredentialReferenceSchema.optional(),idempotencyKey:IdempotencyKeySchema}),ConfigureConnectionInputSchema=external_exports.strictObject({connectionId:ConnectionIdSchema,title:ConnectionTitleSchema.optional(),endpointUrl:ConnectionEndpointUrlSchema.optional(),secretArn:CredentialReferenceSchema.optional(),idempotencyKey:IdempotencyKeySchema});var ConnectionDeclarationSchema=external_exports.object({connectionId:ConnectionIdSchema,title:external_exports.string().min(1),connectorKind:external_exports.string().min(1),endpointUrl:external_exports.string().min(1),credentialConfigured:external_exports.boolean()}),TestConnectionInputSchema=external_exports.strictObject({connectionId:ConnectionIdSchema}),RetireConnectionInputSchema=external_exports.strictObject({connectionId:ConnectionIdSchema,idempotencyKey:IdempotencyKeySchema}),ConnectionRetirementSchema=external_exports.object({connectionId:ConnectionIdSchema,title:external_exports.string().min(1),connectorKind:external_exports.string().min(1)}),CONNECTION_PROBE_FAILURES=SDP_CONNECTION_PROBE_FAILURES,ConnectionProbeFailureSchema=external_exports.enum(CONNECTION_PROBE_FAILURES),ConnectionTestResultSchema=external_exports.discriminatedUnion("ok",[external_exports.object({ok:external_exports.literal(!0),durationMs:external_exports.number().int().nonnegative(),message:external_exports.string().min(1)}),external_exports.object({ok:external_exports.literal(!1),failure:ConnectionProbeFailureSchema,durationMs:external_exports.number().int().nonnegative(),message:external_exports.string().min(1),hint:external_exports.string().min(1)})]),MAX_CONNECTION_BROWSE_DEPTH=MAX_SDP_LISTING_DEPTH-1,BrowsePathSchema=external_exports.array(external_exports.string().min(1).max(512)).max(MAX_CONNECTION_BROWSE_DEPTH),ListConnectionContentsInputSchema=external_exports.strictObject({connectionId:ConnectionIdSchema,path:BrowsePathSchema.default([])}),ConnectionContentEntrySchema=external_exports.object({name:external_exports.string().min(1).max(512),path:external_exports.array(external_exports.string().min(1).max(512)).min(1),kind:external_exports.enum(["container","dataset"]),readable:external_exports.boolean()}),ConnectionContentsSchema=external_exports.object({path:BrowsePathSchema,entries:external_exports.array(ConnectionContentEntrySchema)});var ConnectionSourceSchema=external_exports.object({connectionId:ConnectionIdSchema,serviceSlug:external_exports.string().min(1),connectorKind:external_exports.string().min(1),endpointUrl:external_exports.string().min(1),secretArn:external_exports.string().min(1).optional()}),ResolveConnectionSourceInputSchema=external_exports.strictObject({connectionRef:ConnectionRefSchema});var SNOWFLAKE_IDENTIFIER_RE=/^[A-Za-z_][A-Za-z0-9_$]{0,254}$/,SNOWFLAKE_USER_RE=/^[A-Za-z0-9_][A-Za-z0-9_.@$-]{0,254}$/,SNOWFLAKE_IDENTIFIER_HINT="Use the plain Snowflake name \u2014 letters, digits, _ and $, starting with a letter or _, with no quotes.",SNOWFLAKE_USER_HINT="Use the Snowflake user name as it appears in Snowflake, with no quotes.";var MAX_SNOWFLAKE_KEY_PEM_LENGTH=16384,SnowflakeUserSchema=external_exports.string().regex(SNOWFLAKE_USER_RE,SNOWFLAKE_USER_HINT),SnowflakeIdentifierSchema=external_exports.string().regex(SNOWFLAKE_IDENTIFIER_RE,SNOWFLAKE_IDENTIFIER_HINT),SnowflakeKeyOptionsSchema=external_exports.strictObject({user:SnowflakeUserSchema,warehouse:SnowflakeIdentifierSchema,database:SnowflakeIdentifierSchema,role:SnowflakeIdentifierSchema.optional()}),SetSnowflakeKeyInputSchema=external_exports.strictObject({connectionId:ConnectionIdSchema,privateKeyPem:external_exports.string().min(1).max(MAX_SNOWFLAKE_KEY_PEM_LENGTH),passphrase:external_exports.string().min(1).max(1024).optional(),...SnowflakeKeyOptionsSchema.shape,idempotencyKey:IdempotencyKeySchema}),GetSnowflakeKeyInputSchema=external_exports.strictObject({connectionId:ConnectionIdSchema}),SnowflakeKeyStateSchema=external_exports.strictObject({connectionId:ConnectionIdSchema,keyOnFile:external_exports.boolean(),attached:external_exports.boolean().optional(),enabled:external_exports.boolean().optional(),options:SnowflakeKeyOptionsSchema.optional(),lastRefreshError:external_exports.string().optional()});var RawDataLandedDetailSchema=external_exports.strictObject({objectRef:ObjectRefSchema,captureId:external_exports.uuid(),sourceId:external_exports.string().min(1),policyClass:CapturePolicyClassSchema,checksumSha256:Sha256Base64Schema,verificationGrade:ChecksumVerificationGradeSchema,sizeBytes:external_exports.number().int().nonnegative(),contentType:external_exports.string().min(1),contentEncoding:ContentEncodingSchema,filename:external_exports.string().min(1),capturedBy:external_exports.string().min(1)});var STREAMABLE_LAND_FORMATS=Object.freeze(["csv","xlsx"]),MAX_LAND_BASE64_CHARS=Math.ceil(10485760/3)*4+8,LAND_BYTE_CAP_REFUSAL=`this file is over the ${String(10485760/(1024*1024))} MiB limit on landed content, which is the largest file this path reads whole \u2014 it is the number beginUpload reports as landMaxBytes. datasets.startImportJob does NOT lift it: running in the background changes WHEN an import happens, never how much of a file a whole-file read has to hold. A CSV or XLSX staged through datasets.beginUpload IS read incrementally and accepts up to ${String(50331648/(1024*1024))} MiB \u2014 so if this file is one of those, stage it instead of sending it inline and it will land whole. For every other format, and for anything sent inline, this is the limit. This is a size limit, not a time limit, so waiting or retrying will not change it. Splitting the file is the only option, and it is the right one HERE even though the smaller-import guidance warns against it \u2014 that warning applies when a background import can take the whole file, which at this size it cannot. Be aware of the cost it was warning about: each piece lands as its own dataset, so the key-column diff that makes a re-import update rows rather than duplicate them works only within each piece, not across them. Split on a boundary that keeps related rows together.`,STREAMED_LAND_CAP_REFUSAL=`this file is over the ${String(50331648/(1024*1024))} MiB limit for a streamed import, which is the largest source this platform accepts in ANY format \u2014 csv and xlsx are read incrementally and therefore accept more than every other format, and this file is past even that. Staging it again will not help: it is already on the channel that accepts the most, and datasets.startImportJob refuses the same size at accept rather than handing back a job that cannot finish. This is a size limit, not a time limit, so waiting or retrying will not change it. Splitting the file is the only option, and it is the right one HERE even though the smaller-import guidance warns against it \u2014 that warning applies when one import can take the whole file, which at this size it cannot. Be aware of the cost it was warning about: each piece lands as its own dataset, so the key-column diff that makes a re-import update rows rather than duplicate them works only within each piece, not across them. Split on a boundary that keeps related rows together.`;var MAX_STAGED_UPLOAD_BYTES=100*1024*1024,STAGED_UPLOAD_CHUNK_BYTES=512*1024,MAX_STAGED_CHUNK_BASE64_CHARS=Math.ceil(STAGED_UPLOAD_CHUNK_BYTES/3)*4+8,BASE64_CHUNK_PATTERN=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,MAX_UPLOAD_FILENAME_CHARS=255,STAGED_UPLOAD_IDEMPOTENCY_KEY_MAX_LENGTH=200,StagedUploadIdempotencyKeySchema=IdempotencyKeySchema.max(STAGED_UPLOAD_IDEMPOTENCY_KEY_MAX_LENGTH);var MAX_OPEN_UPLOAD_SLOTS_PER_TENANT_PRINCIPAL=8,OPEN_SLOT_CAP_REFUSAL=`you are holding ${String(MAX_OPEN_UPLOAD_SLOTS_PER_TENANT_PRINCIPAL)} open upload slots, which is the most one principal may hold at once (MAX_OPEN_UPLOAD_SLOTS_PER_TENANT_PRINCIPAL) \u2014 so this beginUpload is refused until one is released. RELEASE ONE WITH datasets.abortUpload, naming its uploadId. That is the remedy even when every one of your uploads SUCCEEDED: landing a ref does not release its slot (deliberately \u2014 the same uploadRef can be landed more than once until it expires), so a slot you have already imported is still counted here and only you know that you are done with it. Call datasets.abortUpload after your FINAL land of each ref. Completing an upload does NOT free its slot; a completed-but-unimported slot is exactly what this cap counts. Waiting also works, unlike the size limits: every slot expires on its own, and the next beginUpload reclaims your expired ones \u2014 so this refusal lifts by itself, and splitting or shrinking your file will not change it.`,UploadIdSchema=external_exports.uuid().brand(),UploadRefSchema=external_exports.uuid().brand(),BeginUploadInputSchema=external_exports.object({filename:external_exports.string().min(1).max(MAX_UPLOAD_FILENAME_CHARS),idempotencyKey:StagedUploadIdempotencyKeySchema}).strict(),BeginUploadResultSchema=external_exports.object({uploadId:UploadIdSchema,chunkSizeBytes:external_exports.number().int().positive(),maxBytes:external_exports.number().int().positive(),landMaxBytes:external_exports.number().int().positive().describe("The cap the `land` consumption arm enforces on a ref whose format is read WHOLE (json, geojson, parquet). A slot may STORE up to `maxBytes`, but a staged file of one of those formats may be at most `landMaxBytes`. Always <= `maxBytes`. For a format in `streamableFormats` the binding number is `streamedLandMaxBytes` instead."),streamedLandMaxBytes:external_exports.number().int().positive().describe("The cap for a ref whose format is read INCREMENTALLY \u2014 the formats listed in `streamableFormats`. Larger than `landMaxBytes`, because a streamed land never holds the file: its memory is a function of batch size, not file size. Always <= `maxBytes`."),streamableFormats:external_exports.array(external_exports.string().min(1)).describe("The land formats read incrementally, and therefore bounded by `streamedLandMaxBytes` rather than `landMaxBytes`. Sent as a LIST rather than resolved server-side because `beginUpload` is told a filename, not a format \u2014 the format is a `land` argument the caller has not made yet, and guessing it from an extension here would advertise a bound the land might not honour. A client that knows which format it will pass can pick the right bound before staging a byte."),expiresAt:external_exports.iso.datetime()}),AppendUploadChunkInputSchema=external_exports.object({uploadId:UploadIdSchema,sequence:external_exports.number().int().min(0),contentBase64:external_exports.string().min(4).max(MAX_STAGED_CHUNK_BASE64_CHARS).regex(BASE64_CHUNK_PATTERN,"contentBase64 must be canonical base64 of at least one byte")}).strict(),AppendUploadChunkResultSchema=external_exports.object({nextSequence:external_exports.number().int().min(0),receivedBytes:external_exports.number().int().min(0)}),CompleteUploadInputSchema=external_exports.object({uploadId:UploadIdSchema,sha256:external_exports.string().regex(/^[0-9a-f]{64}$/,"sha256 must be lowercase hex")}).strict(),CompleteUploadResultSchema=external_exports.object({uploadRef:UploadRefSchema,sha256:external_exports.string().min(1),byteSize:external_exports.number().int().min(0)}),AbortUploadInputSchema=external_exports.object({uploadId:UploadIdSchema.describe("The slot to release. PASS YOUR `uploadRef` HERE if that is what you are holding \u2014 a ref and the id it came from are the same value (the brands mark the lifecycle stage, not a different identifier), so a caller who only ever saw the ref needs nothing else. Releasing is how you end a SUCCESSFUL staged upload as well as an abandoned one: landing never releases the slot, and an unreleased slot counts against your open-slot cap until it expires. Idempotent \u2014 releasing an already-released slot succeeds with `released: false`. It frees staged BYTES only, and never touches anything you landed.")}).strict(),AbortUploadResultSchema=external_exports.object({released:external_exports.boolean()});var inlineTextSource={content:external_exports.string().min(1).max(10485760,LAND_BYTE_CAP_REFUSAL).describe("The file itself, as inline UTF-8 TEXT. csv and json only \u2014 a UTF-8 string cannot carry arbitrary bytes losslessly, so xlsx/parquet are refused on this channel and must use `contentBase64`, `config.path` or `uploadRef`. Best for small files a client already holds in memory. Exactly one of `content` / `contentBase64` / `config.path` / `uploadRef` may be supplied.")},inlineBase64Source={contentBase64:external_exports.string().min(1).max(MAX_LAND_BASE64_CHARS,LAND_BYTE_CAP_REFUSAL).describe("The file itself, as inline BASE64 bytes. Works for EVERY format, and is the only inline channel for the binary ones (xlsx, parquet). The size cap is checked on the base64 length BEFORE decoding, so an over-cap upload is refused without ever being allocated. A file too large to emit in one call goes through the staged-upload protocol instead (`beginUpload` \u2192 `appendUploadChunk` \u2192 `completeUpload`) and lands via `uploadRef`. Exactly one of `content` / `contentBase64` / `config.path` / `uploadRef` may be supplied.")},confinedFileSource={config:external_exports.object({path:external_exports.string().min(1).describe("A file the SERVER can already see, named relative to its configured ingest directory. This is the channel for LARGE loads \u2014 the inline channels cap at `MAX_LAND_CONTENT_BYTES`, while a csv supplied this way is landed by STREAMING it and is not bound by that cap at all (other formats are still parsed whole, so they keep the cap). Deliver the file into the ingest directory by whatever means the deployment provides, then name it here.\n\nCONFINED: the path is resolved against the ingest directory and refused if it escapes \u2014 `../` traversal, and an in-directory symlink pointing out, are both rejected before any read. An absolute path is accepted only when it lands inside that directory; it is not a way to read anywhere on the host.\n\nIt takes a PLAIN FILE (`.csv`, `.xlsx`, \u2026) \u2014 not an archive. The zip-shaped artifact intake is a different seam entirely (`registerSourceArtifact` + a source transformation); nothing about `land` unpacks anything.")}).strict().describe("The server-side file channel. Its only member is `path`. Exactly one of `content` / `contentBase64` / `config.path` / `uploadRef` may be supplied. A client that cannot write the server filesystem should stage bytes with the upload protocol and land via `uploadRef` instead.")},uploadRefSource={uploadRef:UploadRefSchema.describe("A sealed staged-upload handle from `completeUpload` \u2014 the byte channel for an agent or any client that cannot write the server filesystem and cannot emit a whole file inline. Recipe: `beginUpload` (returns the chunk size to use) \u2192 `appendUploadChunk` \xD7 N \u2192 `completeUpload` (verifies your declared sha-256 and issues this ref) \u2192 `land` with the ref plus the usual `format`/`sheet`/`keyColumn` facets. The staged bytes are read whole, so the inline land cap applies (`MAX_LAND_CONTENT_BYTES`); the ref must be SEALED, not yet captured into custody, and yours \u2014 each failure is refused by name. Landing does NOT release the ref (the same bytes can be landed again until the slot expires), and reading slides the slot TTL forward. Exactly one of `content` / `contentBase64` / `config.path` / `uploadRef` / `objectRef` may be supplied.")},csvDialectFacet={csvDialect:external_exports.strictObject({delimiter:external_exports.string().length(1).optional().describe("Field separator. Omitted = `,`. Exactly one character."),quote:external_exports.string().length(1).optional().describe('Quoting character. Omitted = `"`. Exactly one character.'),escape:external_exports.string().length(1).optional().describe('Escape character INSIDE a quoted field. Omitted = `"` (RFC4180 doubling). Set it to `\\` for a Spark/Hadoop-style export, which escapes an embedded quote as `\\"` rather than `""` \u2014 that export then lands AS DELIVERED, with no pre-translation.'),header:external_exports.boolean().optional().describe("Does the first record name the columns? Omitted = true. `false` is refused today: a headerless land has no column names to declare a version with.")}).optional().describe('CSV parse dialect for `format: "csv"` on the `objectRef` channel. Omitted = RFC4180 (`,` / `"` / doubled-quote escaping), which is what every other land channel parses unconditionally. The dialect is DECLARED, never sniffed \u2014 auto-detection samples only the head of the file and mistypes exactly the large files this channel exists for.')},objectRefSource={objectRef:ObjectRefSchema.describe("An opaque handle to an object captured through the Integrations capture seam (`integrations.beginCapture` \u2192 a direct-to-bucket PUT \u2192 `integrations.completeCapture`). This is the channel for LARGE loads: the server never reads the bytes \u2014 it resolves the ref server-side and the query engine reads the object directly from object storage \u2014 so no inline or streamed byte cap applies. What bounds it is the capture SOURCE CLASS's own size policy, and that bound already bit at `beginCapture`, before the object existed.\n\nACCEPTED ONLY BY `datasets.startImportJob` (mode `land`), which returns a job handle to poll. `datasets.land` refuses this channel at every size \u2014 landing by reference is always a background job, so the channel has exactly one execution shape.\n\nThe ref must name a capture of YOUR tenant that sealed COMPLETED. A ref belonging to another tenant is NOT_FOUND, indistinguishable from one that never existed; a capture still PENDING and a capture that EXPIRED are refused by name. The ref is opaque \u2014 it carries no bucket, no key and no URL, and nothing resolves one to a browser. Exactly one of `content` / `contentBase64` / `config.path` / `uploadRef` / `objectRef` may be supplied.")};var DatasetFormatSchema=external_exports.enum(["csv","json","geojson","xlsx","parquet"]),LoadStrategySchema=external_exports.enum(["full-refresh"]),LAND_IDEMPOTENCY_KEY_MAX_LENGTH=200,LandIdempotencyKeySchema=IdempotencyKeySchema.max(LAND_IDEMPOTENCY_KEY_MAX_LENGTH).describe("REQUIRED client-minted replay key for this load \u2014 YOU generate it (a UUID is fine), the server never does; omitting it is refused before anything lands. Once a load has COMPLETED, re-sending the same key returns that original DatasetRef and lands nothing \u2014 which is how a caller whose socket died retries a multi-GB load without landing a second copy. A load still IN FLIGHT under the key is refused CONFLICT (data.code LAND_IN_FLIGHT) rather than started again: wait for it, and if it never finishes, CALL datasets.get AND READ currentVersionId before minting a new key \u2014 a load can be complete and current with only its receipt left unsealed, and a new key would land the whole thing a second time. currentVersionId is the field that answers: it flips LAST, whereas a datasets.versions row already exists while the load is still streaming. A load that RAN and FAILED is the different case: its seal frees the base key, so re-sending that key starts a second real load \u2014 unless that failure seal ALSO failed, which leaves the Record in flight and the key claimed. A process that DIED without sealing either way leaves the key claimed indefinitely; nothing sweeps it. On BOTH the replay and in-flight paths the server compares the name, the parse facets, the key column and a digest of the source against what the key recorded, and refuses CONFLICT (data.code LAND_IDEMPOTENCY_KEY_REUSED, listing the differing fields) if they differ \u2014 so mint a new key whenever you change the inputs, including when you change them mid-load. WHAT THE SOURCE DIGEST COVERS depends on the channel: inline content/contentBase64 digests the payload STRING you sent, tagged with the channel \u2014 so the same file re-sent on the OTHER inline channel is refused rather than replayed \u2014 but a config.path source digests the PATH STRING and never reads the file. So replacing the staged file at the same path and re-sending the key REPLAYS \u2014 success is reported for bytes the server never read. Changed the file, kept the path? Mint a new key. An uploadRef source digests the REF, which is safe where the path is not: a ref names bytes sealed against their sha-256 at completeUpload and immutable thereafter, so the ref identifies the bytes transitively. Resuming a partially-streamed load is not something YOU can ask for: an in-flight key is refused, never continued. An import job is the one exception \u2014 it continues its own interrupted load on the next sweep, so a large import survives a deployment \u2014 but that rests on the job row remembering what it opened, which nothing on the wire can supply. So this refusal is unchanged for a direct caller. WHAT TO MINT: a key that is stable across a RE-SEND of one intent and different for a different intent \u2014 a UUID held for the lifetime of the attempt, or a digest of the inputs. A key minted fresh per attempt is accepted and files a Record, but protects nothing."),IMPORT_JOB_TRANSFORM_IDEMPOTENCY_KEY_MAX_LENGTH=512,IMPORT_JOB_KEY_DESCRIPTION="REQUIRED client-minted replay key for this background import \u2014 YOU generate it (a UUID is fine), the server never does. It is the JOB row\u2019s replay identity: re-sending the same key with the same request re-reads YOUR OWN JOB \u2014 and re-runs it if that job FAILED \u2014 rather than starting a second import. It is also what the underlying verb files its own Record under once the job runs, and what THIS verb files its own accept receipt under. Re-sending a key whose accept receipt names a DIFFERENT mode, or a different derived run key, is REFUSED (BAD_REQUEST, data.code KEY_PARAM_MISMATCH) rather than answered from the other request. Mint a NEW key whenever you change the request; reuse one only to re-send the identical intent. ",ImportJobTransformIdempotencyKeySchema=IdempotencyKeySchema.max(IMPORT_JOB_TRANSFORM_IDEMPOTENCY_KEY_MAX_LENGTH).describe(IMPORT_JOB_KEY_DESCRIPTION+'On mode "transform" the server appends `#attempt-1` when your key does not already carry an `#attempt-<n>` segment, so a key minted with `composeTransformRunKey` is used verbatim and a plain one still becomes a well-formed run key. Up to 512 characters \u2014 wider than mode "land" allows, because a composition runner mints this arm\u2019s key from the definition name and the step id, neither of which is length-bounded.'),ImportJobLandIdempotencyKeySchema=LandIdempotencyKeySchema.describe(IMPORT_JOB_KEY_DESCRIPTION+'On mode "land" the key is what the land files its Record under, VERBATIM, and a key beginning with the literal `transform:` or `declared:` is REFUSED (BAD_REQUEST, data.code LAND_KEY_RESERVED_PREFIX) \u2014 those prefixes name the other two arms\u2019 own job namespaces. Up to 200 characters, the SAME bound the synchronous datasets.land takes, so one minted key is legal at both doors however large the file turns out to be.'),ImportJobDeclaredIdempotencyKeySchema=IdempotencyKeySchema.max(IMPORT_JOB_TRANSFORM_IDEMPOTENCY_KEY_MAX_LENGTH).describe(IMPORT_JOB_KEY_DESCRIPTION+'On mode "declared" the key is what the declared transformation run files its Record under, VERBATIM \u2014 no attempt suffix is appended, because that run verb takes a plain caller-minted key and resolves a re-send against a still-running run by RESUMING it rather than starting a second one. Up to 512 characters, the same bound mode "transform" takes, because a composition runner mints this arm\u2019s key too.'),DatasetProvenanceSchema=external_exports.enum(["legacy","sdp","live"]);var DatasetSdpOriginSchema=external_exports.enum(["walkup_declare","replica_connection","transformation_output","catalog_adoption","studio_reference"]),UploadVersionsUnavailableReasonSchema=external_exports.enum(["awaiting-first-landing","connection-delivered"]);var parseFacets={format:DatasetFormatSchema.optional().describe("Which parser reads the bytes. Omitted = `csv` (back-compat, not a sniff \u2014 the format is never guessed from the filename or the content). The declared format is checked against the bytes' magic and a mismatch is refused by name, so a mislabelled file fails loudly rather than landing as garbage."),sheet:external_exports.string().min(1).optional().describe('Which worksheet to land, for `format: "xlsx"` only \u2014 supplying it with any other format is refused. Omitted = the first NON-EMPTY sheet, in workbook order. ONE sheet lands per call; the others are not landed, so a multi-sheet workbook takes one `land` per sheet. A name that is not in the workbook is refused, listing the sheets that are.')},keyColumnFacet={keyColumn:external_exports.string().min(1).optional().describe("The source column holding each row's identity \u2014 copied into `row_key` and used as the join for the load-to-load diff and for asset provenance. It ALWAYS lands as STRING whatever it holds, so a numeric-looking key keeps its exact source text and cannot be reshaped by type inference. Set on the FIRST load and fixed thereafter: a re-land of an established dataset may omit it (the stored value applies) but cannot change it.\n\nSEPARATE from an asset import's own row key. Assets decide the identity they stamp on each created asset in their projection (`keyColumn` / `keyColumns`), and the two settings do not feed each other: this one is not defaulted from that one, that one is not defaulted from this one, and neither is required for the other to work. They are worth pointing at the SAME column when the published rowKey-to-assetId directory has to join back to this dataset's `row_key` \u2014 that join is by rendered text, so a multi-column asset key can never match it.")},COLUMN_TYPES_DESCRIPTION='Declare a column\'s type instead of letting it be inferred, by column name (e.g. `{"asset_tag": "STRING"}`). Reach for it when a column of digits is really an IDENTIFIER: it would otherwise land NUMBER and be ineligible as an external-ID value. Quoting the field in CSV does NOT force text. Undeclared columns are still inferred. Declaring STRING always works. Declaring NUMBER or BOOLEAN applies only where EVERY value ALREADY carries that type \u2014 this land never rewrites a value to fit, so it is refused naming the first value that does not: in csv, `007` is not the number `7`; in json/xlsx/parquet, a value the source supplied as TEXT is not a number just because it looks like one. A name that is not a column of the source is refused rather than ignored.',columnTypesFacet={columnTypes:external_exports.record(external_exports.string().min(1),DatasetColumnTypeSchema).optional().describe(COLUMN_TYPES_DESCRIPTION)},columnTypesWireFacet={columnTypes:boundedRecord2(external_exports.string().min(1),DatasetColumnTypeSchema,COLUMN_MAP_WIRE_MAX,"column types").optional().describe(COLUMN_TYPES_DESCRIPTION)},createOnlyFacet={createOnly:external_exports.literal(!0).optional().describe('Refuse rather than join: this land is a FIRST load, so a name any dataset already holds is a CONFLICT (`LAND_NAME_TAKEN`) and nothing is created. Omit it \u2014 the default \u2014 to keep the ordinary behaviour, where the same `name` re-lands as a new full-refresh version of the dataset that holds it. Reach for it when the caller means "create", not "load again": a wizard minting a dataset from a file cannot otherwise tell a deliberate re-land from a name typo. A `raw` shell whose first load never succeeded is NOT taken \u2014 it holds no data to join and its name can never be freed, so retrying that load under the same name stays possible.')},LoopbackLandProducerSchema=external_exports.enum(["calculation-result","report","scenario-forecast"]),idempotencyKeyFacet={idempotencyKey:LandIdempotencyKeySchema},inlineTextLand=external_exports.object({name:external_exports.string().min(1),...keyColumnFacet,...columnTypesFacet,...columnEntitiesFacet,...labelFacet,...createOnlyFacet,...parseFacets,...inlineTextSource}).strict(),inlineBase64Land=external_exports.object({name:external_exports.string().min(1),...keyColumnFacet,...columnTypesFacet,...columnEntitiesFacet,...labelFacet,...createOnlyFacet,...parseFacets,...inlineBase64Source}).strict(),confinedFileLand=external_exports.object({name:external_exports.string().min(1),...keyColumnFacet,...columnTypesFacet,...columnEntitiesFacet,...labelFacet,...createOnlyFacet,...parseFacets,...confinedFileSource}).strict(),uploadRefLand=external_exports.object({name:external_exports.string().min(1),...keyColumnFacet,...columnTypesFacet,...columnEntitiesFacet,...labelFacet,...createOnlyFacet,...parseFacets,...uploadRefSource}).strict(),objectRefLand=external_exports.object({name:external_exports.string().min(1),...keyColumnFacet,...columnTypesFacet,...columnEntitiesFacet,...labelFacet,...createOnlyFacet,...parseFacets,...csvDialectFacet,...objectRefSource}).strict(),RawLandInputSchema=external_exports.union([inlineTextLand,inlineBase64Land,confinedFileLand,uploadRefLand,objectRefLand]),LandInputSchema=external_exports.union([inlineTextLand.extend(idempotencyKeyFacet),inlineBase64Land.extend(idempotencyKeyFacet),confinedFileLand.extend(idempotencyKeyFacet),uploadRefLand.extend(idempotencyKeyFacet),objectRefLand.extend(idempotencyKeyFacet)]),columnMapWireFacets={...columnTypesWireFacet,...columnEntitiesWireFacet},RawLandWireInputSchema=external_exports.union([inlineTextLand.extend(columnMapWireFacets),inlineBase64Land.extend(columnMapWireFacets),confinedFileLand.extend(columnMapWireFacets),uploadRefLand.extend(columnMapWireFacets),objectRefLand.extend(columnMapWireFacets)]),LandWireInputSchema=external_exports.union([inlineTextLand.extend(columnMapWireFacets).extend(idempotencyKeyFacet),inlineBase64Land.extend(columnMapWireFacets).extend(idempotencyKeyFacet),confinedFileLand.extend(columnMapWireFacets).extend(idempotencyKeyFacet),uploadRefLand.extend(columnMapWireFacets).extend(idempotencyKeyFacet),objectRefLand.extend(columnMapWireFacets).extend(idempotencyKeyFacet)]);var LandRawInputSchema=external_exports.union([inlineTextLand.extend({loadStrategy:LoadStrategySchema}),inlineBase64Land.extend({loadStrategy:LoadStrategySchema}),confinedFileLand.extend({loadStrategy:LoadStrategySchema}),uploadRefLand.extend({loadStrategy:LoadStrategySchema}),objectRefLand.extend({loadStrategy:LoadStrategySchema})]);var DatasetReadColumnNameSchema=external_exports.string().min(1).max(200),NO_CONTROL_CHARS=/^[^\p{Cc}]+$/u,FilterValueSchema=external_exports.string().min(1).max(256).regex(NO_CONTROL_CHARS,"a filter value may not contain control characters");var COMPARE_FILTER_MEMBERS=[external_exports.object({column:DatasetReadColumnNameSchema,op:external_exports.literal("gt"),value:FilterValueSchema}).strict(),external_exports.object({column:DatasetReadColumnNameSchema,op:external_exports.literal("lt"),value:FilterValueSchema}).strict(),external_exports.object({column:DatasetReadColumnNameSchema,op:external_exports.literal("between"),from:FilterValueSchema,to:FilterValueSchema}).strict()],EMPTY_FILTER_MEMBER=external_exports.object({column:DatasetReadColumnNameSchema,op:external_exports.literal("isEmpty")}).strict();var DatasetReadFilterSchema=external_exports.discriminatedUnion("op",[external_exports.object({column:DatasetReadColumnNameSchema,op:external_exports.literal("equals"),value:FilterValueSchema}).strict(),external_exports.object({column:DatasetReadColumnNameSchema,op:external_exports.literal("contains"),value:FilterValueSchema}).strict(),external_exports.object({column:DatasetReadColumnNameSchema,op:external_exports.literal("in"),values:external_exports.array(FilterValueSchema).max(5e5)}).strict(),...COMPARE_FILTER_MEMBERS,EMPTY_FILTER_MEMBER]),DatasetReadRangeSchema=external_exports.object({column:DatasetReadColumnNameSchema,from:external_exports.iso.datetime({offset:!0}).optional().describe("The first instant in range (inclusive): RFC 3339 with `Z` or an offset (seconds required)."),to:external_exports.iso.datetime({offset:!0}).optional().describe("The first instant past the range (exclusive): RFC 3339 with `Z` or an offset (seconds required).")}).strict().describe("Keep rows whose DATE or TIMESTAMP WITH TIME ZONE column falls in the half-open instant range from <= column < to, either end optional. NULL is never in range. At most six fraction digits; from after to is refused."),DatasetReadOrderBySchema=external_exports.object({column:DatasetReadColumnNameSchema,direction:external_exports.enum(["asc","desc"])}).strict();var RecipeResultSchema=external_exports.object({datasetId:DatasetIdSchema,name:external_exports.string().min(1),keyColumn:external_exports.string().min(1).nullable()}),RecipeSourcePinSchema=external_exports.object({versionId:DatasetVersionIdSchema,loadNumber:external_exports.number().int().positive().nullable(),promotedAt:external_exports.iso.datetime().nullable(),newerLoadCount:external_exports.number().int().nonnegative().nullable(),newestPromoted:external_exports.object({versionId:DatasetVersionIdSchema,loadNumber:external_exports.number().int().positive()}).nullable()});var EngineWaitSchema=external_exports.strictObject({since:external_exports.iso.datetime(),gaveUpAfterMs:external_exports.number().int().positive(),asOf:external_exports.iso.datetime()}).describe("The job is waiting for another large job on the same server to finish. `since` is when it started waiting; past `gaveUpAfterMs` it stops waiting and fails retryably, having changed nothing."),EngineBusySchema=external_exports.strictObject({gaveUpAfterMs:external_exports.number().int().positive().optional()}).describe("The job never started: another large job on the same server held the engine for the whole of its wait \u2014 `gaveUpAfterMs`, when the bound was recorded. Nothing was changed, and starting it again can succeed."),TRANSFORMATION_RUN_PHASES=["waiting-for-engine","exporting-inputs","running-sql","saving-outputs"],TransformationRunPhaseSchema=external_exports.enum(TRANSFORMATION_RUN_PHASES),TransformationRunInputProgressSchema=external_exports.strictObject({slot:external_exports.string().min(1),tilesDone:external_exports.number().int().nonnegative(),tilesTotal:external_exports.number().int().nonnegative().optional()}),TransformationRunStepSchema=external_exports.strictObject({phase:TransformationRunPhaseSchema,startedAt:external_exports.iso.datetime()}),TransformationRunPhaseDetailSchema=external_exports.strictObject({steps:external_exports.array(TransformationRunStepSchema).min(1),input:TransformationRunInputProgressSchema.optional()}),TransformationRunProgressSchema=TransformationRunPhaseDetailSchema.extend({phase:TransformationRunPhaseSchema,asOf:external_exports.iso.datetime(),lastActivityAt:external_exports.iso.datetime(),leaseExpiresAt:external_exports.iso.datetime().optional()});var ContentLocationSchema=external_exports.enum(["platform","external"]),EXTERNAL_URI_RE=/^https?:\/\/\S+$/i,ExternalContentUriSchema=external_exports.string().regex(EXTERNAL_URI_RE);var DUCKDB_ENGINE_VERSIONS=["1.5","2.0"],DuckdbEngineVersionSchema=external_exports.enum(DUCKDB_ENGINE_VERSIONS);var ZERO_ROW_OUTPUT_WARNING="zero-row-output",ZeroRowOutputWarningSchema=external_exports.object({kind:external_exports.literal(ZERO_ROW_OUTPUT_WARNING),output:external_exports.string().min(1),inputRows:external_exports.record(external_exports.string(),external_exports.number().int().nonnegative())}),OUTPUT_HELD_WARNING="output-held",OutputHeldWarningSchema=external_exports.object({kind:external_exports.literal(OUTPUT_HELD_WARNING),output:external_exports.string().min(1),datasetId:external_exports.string().min(1),versionId:external_exports.string().min(1)}),TransformationRunWarningSchema=external_exports.discriminatedUnion("kind",[ZeroRowOutputWarningSchema,OutputHeldWarningSchema]),TransformationRunWarningsSchema=external_exports.array(TransformationRunWarningSchema);var TRANSFORMATION_OUTPUT_KEY_PATTERN=JOB_FIELD_PATTERN,TRANSFORMATION_OUTPUT_KEY_MESSAGE="use a bare identifier a gate expression can address (letters, digits, `_`, `-`; no spaces or dots, and it must START with a letter or `_`)";var TransformationOutputEntityRefSchema=EntityRefSchema.extend({domain:external_exports.literal("datasets"),type:external_exports.literal("dataset-version"),version:external_exports.string().min(1)}),TransformationRunCompletionOutputSchema=external_exports.object({datasetId:external_exports.string().min(1).meta(DATASET_ENTITY_HINT),versionId:external_exports.string().min(1),ref:TransformationOutputEntityRefSchema.meta({entity:{domain:"datasets",type:"dataset-version"}})}),TransformationRunCompletionDetailSchema=external_exports.object({outputsByName:external_exports.record(external_exports.string().regex(TRANSFORMATION_OUTPUT_KEY_PATTERN,TRANSFORMATION_OUTPUT_KEY_MESSAGE),TransformationRunCompletionOutputSchema)});var TransformationDefinitionRefSchema=external_exports.discriminatedUnion("kind",[external_exports.strictObject({kind:external_exports.literal("transformation"),transformationId:external_exports.string().min(1),version:external_exports.number().int().positive()}),external_exports.strictObject({kind:external_exports.literal("spec"),specId:external_exports.string().min(1),version:external_exports.number().int().positive()})]);var TransformationEngineSchema=external_exports.enum(["duckdb-sql","declarative-steps"]);var BaseTransformRunKeySchema=external_exports.string().min(1).brand(),TransformRunKeySchema=external_exports.string().min(1).brand(),TransformRunKeyInputSchema=TransformRunKeySchema.regex(/#attempt-[1-9][0-9]*(?:\/|(?![\s\S]))/,"a transform run key must be attempt-scoped \u2014 mint it as `<base>#attempt-<n>` with `composeTransformRunKey`; a base key would be handed the FIRST run's Record and execute nothing").describe("Client-minted replay key \u2014 REQUIRED, and ATTEMPT-SCOPED. Mint it as `<base>#attempt-<n>` (`composeTransformRunKey`), one base per run intent and a new attempt each time you deliberately run again; a key carrying no `#attempt-<n>` segment is REFUSED at validation. Once a run has COMMITTED, reusing its key replays it: you get the original `DatasetRef` back and nothing executes a second time. A key whose run is still IN FLIGHT is refused CONFLICT `TRANSFORM_IN_FLIGHT` naming the run, never resumed \u2014 wait for it to settle rather than starting a second one. (A background import that is restarted DOES continue its own run, because the job row can name the Record as its own; a wire caller cannot, so it is refused.) A run that RAN and sealed FAILED consumed the key and uniquified it at seal, which frees the base key \u2014 so re-sending it after a failure starts a SECOND REAL RUN. To run the same spec again on purpose, bump the attempt. On both same-key paths the server compares what YOU SENT against what the record pinned \u2014 the spec id, the engine those two select, and the spec version IF YOU SENT ONE \u2014 and refuses CONFLICT if anything differs, so a key never silently answers for inputs you did not send. It does NOT compare anything the server resolved for itself: not the source version, and not the spec version when you omitted it (the server takes the latest). So neither a source that re-lands nor a spec that gains a version between your two calls turns a replay into a refusal, and a restarted background run still executes against the source version AND the spec version its Record names."),TransformAttemptSchema=external_exports.number().int().min(1).brand();var DEFAULT_UNSEALED_RECORD_TTL_MS=3600*1e3,UNSEALED_RECORD_CEILING_MS=1440*60*1e3,PinnedDatasetVersionRefSchema=external_exports.strictObject({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema});var SOURCE_ARTIFACT_ENTITY_HINT={entity:{domain:"datasets",type:"source-artifact"}},SourceArtifactIdSchema=external_exports.string().min(1).brand().meta(SOURCE_ARTIFACT_ENTITY_HINT),SourceTransformationIdSchema=external_exports.string().min(1).brand().meta({entity:{domain:"datasets",type:"source-transformation"}}),CitationSchema=external_exports.object({title:external_exports.string().trim().min(1),url:external_exports.string().trim().min(1)}),SourceArtifactSchema=external_exports.object({id:SourceArtifactIdSchema,filename:external_exports.string().min(1),byteSize:external_exports.number().int().nonnegative(),sha256:external_exports.string().regex(/^[0-9a-f]{64}$/),contentType:external_exports.string().min(1),originNote:external_exports.string().min(1),uploadedBy:external_exports.string().min(1),createdAt:external_exports.iso.datetime(),contentLocation:ContentLocationSchema.default("platform"),externalUri:ExternalContentUriSchema.optional()}),RegisterSourceArtifactInputSchema=external_exports.object({filename:external_exports.string().min(1),contentType:external_exports.string().min(1),originNote:external_exports.string().min(1),config:external_exports.object({path:external_exports.string().min(1)}),idempotencyKey:IdempotencyKeySchema}),RegisterSourceArtifactResultSchema=external_exports.object({artifact:SourceArtifactSchema,created:external_exports.boolean()}),TransformationMethodSchema=external_exports.enum(["duckdb-sql"]),SourceTransformationParamSchema=external_exports.object({type:external_exports.enum(["boolean","number","string"]),default:external_exports.union([external_exports.boolean(),external_exports.number(),external_exports.string()])}),TransformationInputFormatSchema=external_exports.enum(["csv","parquet"]),TransformationInputDescriptorSchema=external_exports.discriminatedUnion("kind",[external_exports.object({kind:external_exports.literal("artifact"),name:external_exports.string().min(1)}),external_exports.object({kind:external_exports.literal("dataset-version"),name:external_exports.string().min(1),format:TransformationInputFormatSchema.optional().describe("The file the slot is materialized as: `csv` (the default) exposes `<name>_csv`; `parquet` writes the version with its engine column types and exposes `<name>_parquet`. A Parquet slot reads only a connected dataset.")}),external_exports.object({kind:external_exports.literal("asset-mapping"),name:external_exports.string().min(1)}),external_exports.object({kind:external_exports.literal("identity-directory"),name:external_exports.string().min(1),system:external_exports.string().min(1)})]),DatasetVersionInputBindingSchema=external_exports.object({kind:external_exports.literal("dataset-version"),datasetId:external_exports.string().min(1).meta(DATASET_ENTITY_HINT),versionId:external_exports.string().min(1)}),TransformationInputBindingSchema=external_exports.discriminatedUnion("kind",[external_exports.object({kind:external_exports.literal("artifact"),artifactId:SourceArtifactIdSchema}),DatasetVersionInputBindingSchema,external_exports.object({kind:external_exports.literal("asset-mapping"),sourceDatasetId:external_exports.string().min(1).meta(DATASET_ENTITY_HINT)}),external_exports.strictObject({kind:external_exports.literal("identity-directory")})]),OBJECT_FORM_COLUMN_TYPES_DESCRIBE='Declare a column\'s type instead of letting it be inferred, by column name (e.g. `{"asset_tag": "STRING"}`). Reach for it when a column of digits is really an IDENTIFIER. Declaring STRING always holds. Declaring NUMBER or BOOLEAN is checked, and WHERE plus HOW depends on the output-storage election. On the `legacy` election the pins are applied at the output\'s own land with the same checked coercion a direct land makes \u2014 refused naming the first VALUE that does not already carry the type (in csv, `007` is not the number `7`). On the `connected` election the pins are written into the source read config the movement reader consumes, and a NUMBER/BOOLEAN pin is refused BEFORE delivery when a delivered value does not read as that type, naming the column and a value (a NUMBER refuses a leading zero, `007`; a BOOLEAN takes true, false, t, f, yes or no, in any case). A column of clean integers that was text passes there. A name that is not a column of the source is refused at the land. A `connected` output may instead pin a DuckDB type \u2014 VARCHAR, BIGINT, DOUBLE or TIMESTAMPTZ \u2014 which movement reads the column as; it is refused BEFORE delivery when a delivered value does not read as that type (BIGINT takes only integers as written, TIMESTAMPTZ only a time ending in Z or a numeric offset; named zones are refused), naming the column and the value. An empty column holds any of them. BOOLEAN is the land pin above on both elections. The `legacy` election refuses a DuckDB type.',SourceTransformationOutputColumnTypeSchema=external_exports.enum(["STRING","NUMBER","BOOLEAN","VARCHAR","BIGINT","DOUBLE","TIMESTAMPTZ"]);var SOURCE_TRANSFORMATION_OUTPUT_FORMATS=["csv","parquet"],SourceTransformationOutputFormatSchema=external_exports.enum(SOURCE_TRANSFORMATION_OUTPUT_FORMATS),SourceTransformationOutputKindSchema=external_exports.enum(["raw","result"]),SourceTransformationObjectOutputSchema=external_exports.strictObject({dataset:external_exports.string().min(1),columnTypes:external_exports.record(external_exports.string().min(1),SourceTransformationOutputColumnTypeSchema).optional().describe(OBJECT_FORM_COLUMN_TYPES_DESCRIBE),datasetId:DatasetIdSchema.optional().describe("Land each run of this output as a new version of this existing dataset, found by its id rather than by `dataset`, so it keeps receiving versions after a rename. A run whose id names no dataset it can land into fails, naming the output."),ownerDomain:external_exports.string().min(1).max(48).regex(LIVE_OWNER_DOMAIN_PATTERN).optional().describe("Not settable: a create carrying it is refused. Only the platform stamps a dataset s owner."),kind:SourceTransformationOutputKindSchema.optional().describe("The landed dataset's lineage kind, stamped on every landing. Absent means `raw`."),format:SourceTransformationOutputFormatSchema.optional().describe("The file the declaration writes for this output: `parquet` writes `<output>.parquet`, typed by the declaration itself; `csv` (LEGACY) writes `<output>.csv`. Omitted at create, it is the output's stored format when an append keeps the output, else `parquet` on connected storage \u2014 `csv` on legacy storage, or when the output pins columnTypes. A stored output with no format is `csv`. A create electing legacy storage, or pinning columnTypes, on a parquet output is refused RUN_OUTPUT_FORMAT_UNLANDABLE. A create or run whose SQL writes the other format fails RUN_OUTPUT_FILE_FORMAT_MISMATCH. Before anything is delivered, a parquet output with a nested or unknown column type fails RUN_OUTPUT_COLUMN_TYPE_UNSUPPORTED, and one holding NaN or infinity in a DOUBLE/FLOAT column fails RUN_OUTPUT_NON_FINITE_VALUE.")}),SourceTransformationOutputSchema=external_exports.union([external_exports.string().min(1),SourceTransformationObjectOutputSchema]),SourceTransformationOutputInputSchema=external_exports.union([external_exports.string().min(1),SourceTransformationObjectOutputSchema.extend({columnTypes:boundedRecord2(external_exports.string().min(1),SourceTransformationOutputColumnTypeSchema,SOURCE_TRANSFORMATION_OUTPUT_COLUMN_TYPES_MAX,"column types").optional().describe(OBJECT_FORM_COLUMN_TYPES_DESCRIBE)})]),SourceTransformationOutputsSchema=external_exports.record(external_exports.string().min(1),SourceTransformationOutputSchema);var SourceTransformationOutputsInputSchema=boundedRecord2(external_exports.string().regex(TRANSFORMATION_OUTPUT_KEY_PATTERN,TRANSFORMATION_OUTPUT_KEY_MESSAGE),SourceTransformationOutputInputSchema,SOURCE_TRANSFORMATION_OUTPUTS_MAX,"outputs");var OutputStorageSchema=external_exports.enum(["legacy","connected"]);var SourceTransformationSchema=external_exports.object({id:external_exports.string().min(1),transformationId:SourceTransformationIdSchema,version:external_exports.number().int().min(1),name:external_exports.string().min(1),method:TransformationMethodSchema,engineVersion:external_exports.string().min(1),sql:external_exports.string().min(1),paramsSchema:external_exports.record(external_exports.string().min(1),SourceTransformationParamSchema),inputs:external_exports.array(TransformationInputDescriptorSchema).min(1),outputs:SourceTransformationOutputsSchema,outputStorage:OutputStorageSchema.default("legacy"),citations:external_exports.array(CitationSchema),createdBy:external_exports.string().min(1),createdAt:external_exports.iso.datetime()}),SOURCE_TRANSFORMATION_INPUTS_MAX=64,SOURCE_TRANSFORMATION_CITATIONS_MAX=50,SOURCE_TRANSFORMATION_PARAMS_MAX=100,SourceTransformationParamsInputSchema=boundedRecord2(external_exports.string().min(1),SourceTransformationParamSchema,SOURCE_TRANSFORMATION_PARAMS_MAX,"parameters"),CreateSourceTransformationInputSchema=external_exports.object({transformationId:SourceTransformationIdSchema.optional(),name:external_exports.string().min(1),method:TransformationMethodSchema,engineVersion:external_exports.string().min(1),sql:external_exports.string().min(1),paramsSchema:SourceTransformationParamsInputSchema,inputs:external_exports.array(TransformationInputDescriptorSchema).min(1).max(SOURCE_TRANSFORMATION_INPUTS_MAX),outputs:SourceTransformationOutputsInputSchema,outputStorage:OutputStorageSchema.optional(),citations:external_exports.array(CitationSchema).max(SOURCE_TRANSFORMATION_CITATIONS_MAX).default([]),idempotencyKey:IdempotencyKeySchema}),CallerMintedKeySchema=IdempotencyKeySchema.describe("Client-minted replay key \u2014 REQUIRED. Mint ONE per intent (a UUID is fine) and reuse it only to re-send that identical intent. Once a call has COMPLETED, reusing its key returns the original receipt without re-executing; a call that was REFUSED consumed nothing, so the same key is free to run again. A run that RAN and sealed FAILED is neither: it consumed the key and uniquified it at seal (`<your key>#failed-<id>`), which frees the base key \u2014 so re-sending it after a failure starts a SECOND REAL RUN, never a replay. Recover from the receipt named by `data.runRecordId` instead. `runDeclaredTransformation` adds a third state, because it opens and seals across two transactions: a key whose run is still IN FLIGHT resumes that run rather than starting a second one. On BOTH of those paths the server compares your request against what the record holds \u2014 the declaration version, one digest per bound slot, and the resolved params \u2014 and refuses CONFLICT if anything differs, so a key never silently answers for inputs you did not send; mint a new key to run changed inputs. The values NOT compared are the as-of timestamps of asset-mapping and identity-directory slots: those subjects are temporal, so the stamp is taken per attempt and only the directory / system the slot names is matched. The key LIMITS but does not PREVENT double execution: two callers sending it at the same instant can both pass the in-flight check, so re-send sequentially, never in parallel.");var RUN_ENGINE_BUSY="RUN_ENGINE_BUSY",RUN_ENGINE_MISMATCH="RUN_ENGINE_MISMATCH",DIRECTORY_SLOT_UNAVAILABLE="DIRECTORY_SLOT_UNAVAILABLE",RunSourceTransformationInputSchema=external_exports.object({transformationId:SourceTransformationIdSchema,version:external_exports.number().int().min(1),inputs:external_exports.record(external_exports.string(),TransformationInputBindingSchema).default({}),params:external_exports.record(external_exports.string(),external_exports.union([external_exports.boolean(),external_exports.number(),external_exports.string()])).default({}),idempotencyKey:CallerMintedKeySchema}),DeclaredParamValueSchema=external_exports.union([external_exports.boolean(),external_exports.number(),external_exports.string()]),RunSourceTransformationWireInputSchema=RunSourceTransformationInputSchema.extend({inputs:boundedRecord2(external_exports.string(),TransformationInputBindingSchema,SOURCE_TRANSFORMATION_RUN_INPUTS_MAX,"input bindings").default({}),params:boundedRecord2(external_exports.string(),DeclaredParamValueSchema,SOURCE_TRANSFORMATION_RUN_PARAMS_MAX,"parameter values").default({})}),StartImportJobDeclaredRequestSchema=RunSourceTransformationWireInputSchema.omit({idempotencyKey:!0}).strict(),SourceTransformationRunOutputOutcomeSchema=external_exports.enum(["landed","landing","failed","unconfirmed","unchanged"]),SourceTransformationRunOutputSchema=external_exports.object({output:external_exports.string().min(1),datasetId:external_exports.string().min(1),versionId:external_exports.string().min(1),outcome:SourceTransformationRunOutputOutcomeSchema.optional(),message:external_exports.string().min(1).optional()}),SourceTransformationRunLandingOutputSchema=external_exports.object({output:external_exports.string().min(1),datasetId:external_exports.string().min(1),outcome:SourceTransformationRunOutputOutcomeSchema,message:external_exports.string().min(1).optional()}),RunSourceTransformationAcceptedSchema=external_exports.object({runRecordId:external_exports.string().min(1),running:external_exports.literal(!0).optional(),jobId:external_exports.string().min(1).optional()}),SourceTransformationRunEngineSchema=external_exports.object({declared:external_exports.string().min(1),actual:external_exports.string().min(1).nullable(),requested:DuckdbEngineVersionSchema.optional()}),PreviewSourceTransformationInputBindingSchema=external_exports.strictObject({kind:external_exports.literal("dataset-version"),datasetId:external_exports.string().min(1),versionId:external_exports.string().min(1),format:TransformationInputFormatSchema.optional()}),PreviewSourceTransformationInputSchema=external_exports.strictObject({sql:external_exports.string().min(1),inputs:boundedRecord2(external_exports.string().min(1),PreviewSourceTransformationInputBindingSchema,SOURCE_TRANSFORMATION_RUN_INPUTS_MAX,"input bindings"),resultOutput:external_exports.string().min(1),resultFormat:SourceTransformationOutputFormatSchema.optional(),params:boundedRecord2(external_exports.string(),DeclaredParamValueSchema,SOURCE_TRANSFORMATION_RUN_PARAMS_MAX,"parameter values").optional()}),SourceTransformationPreviewSchema=external_exports.object({rows:external_exports.array(external_exports.record(external_exports.string(),external_exports.string())),rowCount:external_exports.number().int().nonnegative()}),SourceTransformationRunStatusSchema=external_exports.object({runRecordId:external_exports.string().min(1),status:external_exports.enum(["in-flight","landing","committed","failed"]),outputs:external_exports.array(SourceTransformationRunOutputSchema),landingOutputs:external_exports.array(SourceTransformationRunLandingOutputSchema).optional(),stats:external_exports.record(external_exports.string(),external_exports.number()),warnings:TransformationRunWarningsSchema.optional(),summary:external_exports.string().optional(),detail:external_exports.string().optional(),engine:SourceTransformationRunEngineSchema.optional().describe("The engine this run declared beside the engine that actually ran it. ABSENT on a receipt sealed before the engine was recorded; `actual` is null when the run failed before its engine was identified."),actor:external_exports.string().min(1).optional(),openedAt:external_exports.iso.datetime().optional(),failureCode:external_exports.literal(RUN_ENGINE_BUSY).optional(),engineBusy:EngineBusySchema.optional(),engineWait:EngineWaitSchema.optional(),progress:TransformationRunProgressSchema.optional(),queued:external_exports.literal(!0).optional(),stopped:external_exports.literal(!0).optional(),stoppedReason:external_exports.string().optional(),transformation:external_exports.object({transformationId:SourceTransformationIdSchema,version:external_exports.number().int().min(1)}).describe('The EXACT declaration version this run pinned, projected off the run Record own reads \u2014 the walk-back hop. ABSENT rather than guessed when the pin cannot be read, so treat its absence as "this receipt does not name what it ran", never as "version 1".').optional(),bindings:external_exports.object({inputs:external_exports.record(external_exports.string(),TransformationInputBindingSchema),params:external_exports.record(external_exports.string(),external_exports.union([external_exports.boolean(),external_exports.number(),external_exports.string()]))}).describe('What this run BOUND \u2014 one binding per declared slot plus the declared params it resolved, projected off the run Record own input digests and reads. ABSENT rather than guessed, and absence carries THREE indistinguishable causes: the pinned declaration could not be read back, no declared slot resolved at all, or the reads this projection needs FAILED. Read an absent `bindings` as "this receipt cannot name what it bound", never as "this run bound nothing". An individual slot that cannot be resolved faithfully is OMITTED from `inputs` rather than approximated, so treat a missing slot the same way \u2014 the run bound every declared slot or it never opened.').optional()}),GetSourceTransformationRunInputSchema=external_exports.object({runRecordId:external_exports.string().min(1)}),SourceTransformationRunSummarySchema=external_exports.object({runRecordId:external_exports.string().min(1),status:external_exports.enum(["in-flight","landing","committed","failed"]),actor:external_exports.string().min(1),at:external_exports.iso.datetime(),summary:external_exports.string().optional(),outputs:external_exports.array(SourceTransformationRunOutputSchema),landingOutputs:external_exports.array(SourceTransformationRunLandingOutputSchema).optional(),elapsedMs:external_exports.number().int().nonnegative().optional(),phase:external_exports.enum(["queued","stopped",...TRANSFORMATION_RUN_PHASES]).optional(),restarts:external_exports.number().int().nonnegative().optional()}),ListSourceTransformationRunsInputSchema=external_exports.object({datasetId:external_exports.string().min(1).optional(),transformationId:external_exports.string().min(1).optional(),take:external_exports.number().int().min(1).max(1e3).optional().describe(`Rows this call may return, 1\u2013${1e3}; defaults to ${100}. An ask above the maximum is REFUSED, not clamped (a clamp hands back a page the caller did not request and cannot tell apart from the one it did). The list is newest-first, so a bounded answer is the most recent runs. There is NO continuation token: this read cannot page past its own bound today, and it does not pretend to \u2014 asking for more means asking for a larger \`take\`.`)});var MAX_TRANSFORM_STEPS=200,MAX_STEP_INPUT_COLUMNS=200,MAX_LOOKUP_ENTRIES=100,MAX_LOOKUP_VALUE_LENGTH=512,MapStepSchema=external_exports.object({kind:external_exports.literal("map"),source:external_exports.string().min(1),target:external_exports.string().min(1)}),UnitConvertStepSchema=external_exports.object({kind:external_exports.literal("unitConvert"),source:external_exports.string().min(1),target:external_exports.string().min(1),factor:external_exports.number()}),ConstStepSchema=external_exports.object({kind:external_exports.literal("const"),target:external_exports.string().min(1),value:DatasetCellValueSchema}),ExpressionStepSchema=external_exports.object({kind:external_exports.literal("expression"),target:external_exports.string().min(1),expression:external_exports.string().min(1),inputs:external_exports.array(external_exports.string().min(1)).max(MAX_STEP_INPUT_COLUMNS)}),CastStepSchema=external_exports.object({kind:external_exports.literal("cast"),source:external_exports.string().min(1),target:external_exports.string().min(1),to:DatasetColumnTypeSchema}),LookupMapEntrySchema=external_exports.object({from:external_exports.string().min(1).max(MAX_LOOKUP_VALUE_LENGTH),to:external_exports.string().max(MAX_LOOKUP_VALUE_LENGTH)}),LookupMapStepSchema=external_exports.object({kind:external_exports.literal("lookupMap"),source:external_exports.string().min(1),target:external_exports.string().min(1),entries:external_exports.array(LookupMapEntrySchema).min(1).max(MAX_LOOKUP_ENTRIES),onMiss:external_exports.enum(["passthrough","null"])}),FilterRowsStepSchema=external_exports.object({kind:external_exports.literal("filterRows"),predicate:external_exports.string().min(1),inputs:external_exports.array(external_exports.string().min(1)).max(MAX_STEP_INPUT_COLUMNS)}),TransformStepSchema=external_exports.discriminatedUnion("kind",[MapStepSchema,UnitConvertStepSchema,ConstStepSchema,ExpressionStepSchema,CastStepSchema,LookupMapStepSchema,FilterRowsStepSchema]);var DATASET_SNAPSHOT_TYPES=["dataset-version","reference-table"];var SnapshotUuidAskSchema=external_exports.guid(),SnapshotAskSchema=external_exports.object({domain:external_exports.literal("datasets"),type:external_exports.enum(DATASET_SNAPSHOT_TYPES).describe("Which kind of datasets entity to snapshot: 'dataset-version', one load of a dataset, or 'reference-table', a reference table whose snapshot is one of its versions; anything else is refused, and the refusal names the accepted values."),id:SnapshotUuidAskSchema.brand(),version:SnapshotUuidAskSchema.brand().optional()}),SnapshotResultSchema=EntitySnapshotRefSchema;var DELIVERY_CADENCE_MIN_SECONDS=60,DELIVERY_CADENCE_MAX_SECONDS=366*24*60*60,DeliveryCadenceSecondsSchema=external_exports.number().int().min(DELIVERY_CADENCE_MIN_SECONDS).max(DELIVERY_CADENCE_MAX_SECONDS);var DatasetsDeliveryLateDetailSchema=external_exports.strictObject({datasetId:DatasetIdSchema,dueBy:external_exports.iso.datetime(),expectedEverySeconds:DeliveryCadenceSecondsSchema,lastDeliveredAt:external_exports.iso.datetime().optional()});var LOAD_RECONCILIATION_VERDICTS=["matches","short","over","not-stated","not-counted"],LoadReconciliationVerdictSchema=external_exports.enum(LOAD_RECONCILIATION_VERDICTS);var LoadReconciliationSchema=external_exports.object({versionId:DatasetVersionIdSchema,loadNumber:external_exports.number().int().positive(),landedRows:external_exports.number().int().nonnegative().optional(),declaredRows:external_exports.number().int().nonnegative().optional(),verdict:LoadReconciliationVerdictSchema,difference:external_exports.number().int().positive().optional()}),ListLoadReconciliationsInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema}),ListLoadReconciliationsOutputSchema=external_exports.object({items:external_exports.array(LoadReconciliationSchema)});var GetLandReceiptInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema.optional()}),ReceiptFactsShape={datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,loadNumber:external_exports.number().int().positive(),loadedAt:external_exports.iso.datetime(),actor:external_exports.string().min(1),openedAt:external_exports.iso.datetime()},LandReceiptSchema=external_exports.discriminatedUnion("kind",[external_exports.object({kind:external_exports.literal("land"),...ReceiptFactsShape,rowCount:external_exports.number().int().nonnegative(),captureId:external_exports.string().min(1).optional()}),external_exports.object({kind:external_exports.literal("scheduled-delivery"),...ReceiptFactsShape,landedAt:external_exports.iso.datetime().optional()}),external_exports.object({kind:external_exports.literal("connection-observe"),...ReceiptFactsShape})]);var ValidationRulesetIdSchema=external_exports.string().min(1).brand(),ValidationRuleKindSchema=external_exports.enum(["required","regex","numeric","range","uniqueness","allowedValues","sourceFlag"]);var VALIDATION_RULES_MAX=50,MAX_ALLOWED_VALUES=200,MAX_ALLOWED_VALUE_LENGTH=200;var MAX_RULE_REASON_LENGTH=280,RuleReasonSchema=external_exports.string().min(1).max(MAX_RULE_REASON_LENGTH).optional(),RuleOnBreakSchema=external_exports.enum(["fails","questions","notes"]),LEGACY_RULE_ON_BREAK="fails",RuleConditionSchema=external_exports.strictObject({column:external_exports.string().min(1),equals:external_exports.string().min(1)}),RequiredRuleSchema=external_exports.object({kind:external_exports.literal("required"),column:external_exports.string().min(1),when:RuleConditionSchema.optional(),onBreak:RuleOnBreakSchema,reason:RuleReasonSchema}),RegexRuleSchema=external_exports.object({kind:external_exports.literal("regex"),column:external_exports.string().min(1),pattern:external_exports.string().min(1),onBreak:RuleOnBreakSchema,reason:RuleReasonSchema}),NumericRuleSchema=external_exports.object({kind:external_exports.literal("numeric"),column:external_exports.string().min(1),onBreak:RuleOnBreakSchema,reason:RuleReasonSchema}),RangeRuleSchema=external_exports.object({kind:external_exports.literal("range"),column:external_exports.string().min(1),min:external_exports.number().optional(),max:external_exports.number().optional(),inclusive:external_exports.boolean(),onBreak:RuleOnBreakSchema,reason:RuleReasonSchema}),UniquenessRuleSchema=external_exports.object({kind:external_exports.literal("uniqueness"),column:external_exports.string().min(1),onBreak:RuleOnBreakSchema,reason:RuleReasonSchema}),AllowedValuesRuleSchema=external_exports.object({kind:external_exports.literal("allowedValues"),column:external_exports.string().min(1),values:external_exports.array(external_exports.string().min(1).max(MAX_ALLOWED_VALUE_LENGTH)).min(1).max(MAX_ALLOWED_VALUES),onBreak:RuleOnBreakSchema,reason:RuleReasonSchema});var SourceFlagRuleSchema=external_exports.object({kind:external_exports.literal("sourceFlag"),column:external_exports.string().min(1),values:external_exports.array(external_exports.string().trim().min(1).max(MAX_ALLOWED_VALUE_LENGTH)).min(1).max(MAX_ALLOWED_VALUES),reasonColumn:external_exports.string().min(1).optional(),onBreak:RuleOnBreakSchema,reason:RuleReasonSchema}),ValidationRuleSchema=external_exports.discriminatedUnion("kind",[RequiredRuleSchema,RegexRuleSchema,NumericRuleSchema,RangeRuleSchema,UniquenessRuleSchema,AllowedValuesRuleSchema,SourceFlagRuleSchema]),StoredValidationRuleSchema=external_exports.preprocess(value2=>typeof value2=="object"&&value2!==null&&!("onBreak"in value2)?{...value2,onBreak:LEGACY_RULE_ON_BREAK}:value2,ValidationRuleSchema);var ValidationRulesetSchema=external_exports.object({rulesetId:ValidationRulesetIdSchema,version:external_exports.number().int().positive(),name:external_exports.string().min(1),datasetId:DatasetIdSchema,rules:external_exports.array(StoredValidationRuleSchema),savedAt:external_exports.iso.datetime()}),SaveValidationRulesetInputSchema=external_exports.object({rulesetId:ValidationRulesetIdSchema.optional(),name:external_exports.string().min(1).max(200),datasetId:DatasetIdSchema,rules:external_exports.array(ValidationRuleSchema).min(1).max(VALIDATION_RULES_MAX),idempotencyKey:IdempotencyKeySchema}),ListValidationRulesetsInputSchema=external_exports.object({datasetId:DatasetIdSchema}),ListValidationRulesetVersionsInputSchema=external_exports.object({rulesetId:ValidationRulesetIdSchema}),VALIDATION_WINDOW_START_MAX=2147483647,ValidationViolationWindowSchema=external_exports.strictObject({start:external_exports.number().int().nonnegative().max(VALIDATION_WINDOW_START_MAX),take:external_exports.number().int().min(1).max(1e3),ruleIndex:external_exports.number().int().nonnegative().optional()}),ValidateInputSchema=external_exports.strictObject({rulesetId:ValidationRulesetIdSchema,rulesetVersion:external_exports.number().int().positive().optional(),versionId:DatasetVersionIdSchema.optional(),violations:ValidationViolationWindowSchema.optional()}),ValidationViolationSchema=external_exports.object({rowId:external_exports.string().min(1),rowIndex:external_exports.number().int().nonnegative().optional(),rowKey:external_exports.string().min(1).optional(),column:external_exports.string().min(1),rule:ValidationRuleKindSchema,ruleIndex:external_exports.number().int().nonnegative().optional(),message:external_exports.string().min(1),evaluated:external_exports.literal(!1).optional()}),ValidationRecordClassificationSchema=external_exports.enum(["good","uncertain","failed"]),ValidationRuleTallySchema=external_exports.object({ruleIndex:external_exports.number().int().nonnegative(),cellsFlagged:external_exports.number().int().nonnegative(),rowsAffected:external_exports.number().int().nonnegative(),cellsNotEvaluated:external_exports.number().int().nonnegative(),conditionRowsSelected:external_exports.number().int().nonnegative().optional(),onBreak:RuleOnBreakSchema});var ValidationRecordDistributionSchema=external_exports.object({good:external_exports.number().int().nonnegative(),uncertain:external_exports.number().int().nonnegative(),failed:external_exports.number().int().nonnegative()}),ValidationPageRecordSchema=external_exports.object({rowId:external_exports.string().min(1),rowIndex:external_exports.number().int().nonnegative().optional(),rowKey:external_exports.string().min(1).optional(),classification:ValidationRecordClassificationSchema});var ValidationPreviewSchema=external_exports.object({rowLimit:external_exports.number().int().positive(),rowsInLoad:external_exports.number().int().nonnegative().optional()}),StoredFindingsPageSchema=external_exports.object({state:external_exports.enum(["kept","expired"]),matching:external_exports.number().int().nonnegative(),perRuleLimit:external_exports.number().int().positive()}),ValidationReportSchema=external_exports.object({rulesetId:ValidationRulesetIdSchema,rulesetVersion:external_exports.number().int().positive(),datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,rowsChecked:external_exports.number().int().nonnegative(),violations:external_exports.array(ValidationViolationSchema).max(1e3),window:ValidationViolationWindowSchema,violationsMatching:external_exports.number().int().nonnegative(),rowsWithViolation:external_exports.number().int().nonnegative(),cellsFlagged:external_exports.number().int().nonnegative(),cellsNotEvaluated:external_exports.number().int().nonnegative(),recordDistribution:ValidationRecordDistributionSchema,pageRecords:external_exports.array(ValidationPageRecordSchema).max(1e3),perRule:external_exports.array(ValidationRuleTallySchema).max(VALIDATION_RULES_MAX),preview:ValidationPreviewSchema.optional(),loadInFlight:external_exports.literal(!0).optional(),findingsStored:StoredFindingsPageSchema.optional()});var LiveOwnerDomainSchema=external_exports.string().min(1).max(48).regex(LIVE_OWNER_DOMAIN_PATTERN);var LIVE_SAMPLE_MAX_ROWS=100;var LIVE_READ_MAX_ROWS=1e3,SaveLiveDefinitionInputSchema=external_exports.strictObject({slug:DatasetSlugSchema,name:external_exports.string().min(1),description:external_exports.string().min(1).optional(),ownerDomain:LiveOwnerDomainSchema,sql:external_exports.string().min(1),idempotencyKey:IdempotencyKeySchema}),LiveDefinitionViewSchema=external_exports.object({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,definitionVersion:external_exports.number().int().positive(),slug:DatasetSlugSchema,ownerDomain:LiveOwnerDomainSchema,sql:external_exports.string().min(1),columns:external_exports.array(DatasetColumnSchema2),broken:external_exports.boolean()}),CheckLiveDefinitionInputSchema=external_exports.strictObject({slug:DatasetSlugSchema,ownerDomain:LiveOwnerDomainSchema,sql:external_exports.string().min(1),sampleRows:external_exports.number().int().min(0).max(LIVE_SAMPLE_MAX_ROWS).optional()}),LiveDefinitionCheckSchema=external_exports.object({slug:DatasetSlugSchema,ownerDomain:LiveOwnerDomainSchema,columns:external_exports.array(DatasetColumnSchema2),rowCount:external_exports.number().int().nonnegative(),sampleRows:external_exports.array(DatasetRowSchema),sampleTruncated:external_exports.boolean(),durationMs:external_exports.number().int().nonnegative(),engine:external_exports.string().min(1),role:external_exports.string().min(1)}),ReadLiveInputSchema=DatasetRefSchema.extend({take:external_exports.number().int().min(1).max(LIVE_READ_MAX_ROWS).optional()});var DATASET_COLUMN_MEANING_MAX_LENGTH=2e3,DATASET_COLUMN_NOTE_URI_MAX_LENGTH=2048,DATASET_COLUMN_NOTE_COLUMN_MAX_LENGTH=255,DATASET_COLUMN_NOTES_PER_CALL_MAX=25,DATASET_COLUMN_NOTE_FIELDS=["meaning","unit","term","uri"],DatasetColumnNoteFieldSchema=external_exports.enum(DATASET_COLUMN_NOTE_FIELDS),DatasetColumnNoteSchema=external_exports.object({meaning:external_exports.string().optional(),unit:external_exports.string().optional(),term:external_exports.string().optional(),uri:external_exports.string().optional(),orphaned:external_exports.boolean(),typeChanged:external_exports.boolean(),profileVersion:external_exports.number().int().optional()}),DatasetColumnNotesInputSchema=external_exports.strictObject({datasetId:external_exports.string().min(1)}),DatasetColumnNotesSchema=external_exports.object({datasetId:external_exports.string().min(1),recordSet:external_exports.string().min(1).optional(),columns:external_exports.array(external_exports.object({name:external_exports.string().min(1),type:external_exports.string().min(1),note:DatasetColumnNoteSchema.optional()})),unmatched:external_exports.array(external_exports.object({column:external_exports.string().min(1),note:DatasetColumnNoteSchema}))}),meaning=external_exports.string().min(1).max(DATASET_COLUMN_MEANING_MAX_LENGTH),unit=external_exports.string().regex(CATALOG_QUDT_UNIT_PATTERN,"a unit is a QUDT unit, e.g. 'unit:M'"),term=external_exports.string().regex(CATALOG_CONCEPT_REF_PATTERN,"a term is 'scheme/slug'"),uri=external_exports.string().min(1).max(DATASET_COLUMN_NOTE_URI_MAX_LENGTH),columnName=external_exports.string().min(1).max(DATASET_COLUMN_NOTE_COLUMN_MAX_LENGTH),DatasetColumnNotePatchSchema=external_exports.strictObject({meaning:meaning.nullable().optional().describe("What the values in this column mean."),unit:unit.nullable().optional().describe("The column's unit as a QUDT unit, e.g. 'unit:M3-PER-HR'."),term:term.nullable().optional().describe("A term from the tenant's vocabulary, 'scheme/slug' \u2014 pick it with datasets.vocabulary.list."),uri:uri.nullable().optional().describe("A term reference outside the vocabulary, as an absolute IRI (e.g. https://\u2026); javascript:, data: and vbscript: are refused.")}),DatasetColumnNoteBeliefSchema=external_exports.strictObject({meaning:external_exports.string().nullable().optional(),unit:external_exports.string().nullable().optional(),term:external_exports.string().nullable().optional(),uri:external_exports.string().nullable().optional()}).nullable(),DescribeColumnsInputSchema=external_exports.strictObject({datasetId:external_exports.string().min(1),columns:external_exports.record(columnName,DatasetColumnNotePatchSchema.nullable()).describe(`Column name \u2192 what to change in its note, or null to remove the note. At most ${String(DATASET_COLUMN_NOTES_PER_CALL_MAX)} columns per call.`),get expected(){return external_exports.strictObject({versionId:external_exports.string().min(1).nullable(),columns:external_exports.record(external_exports.string().min(1),DatasetColumnNoteBeliefSchema)}).describe(`What you believe each column's note holds RIGHT NOW, read from datasets.columnNotes: every column this call writes must appear, null for "no note", and every field written must be stated (null for "believed empty"). Judged against the shared data platform; a wrong belief refuses the WHOLE call and names every column and field that moved. versionId is the load you read (null for none).`)},reason:DatasetLifecycleReasonSchema.optional(),get idempotencyKey(){return IdempotencyKeySchema}}),DatasetVocabularyInputSchema=external_exports.strictObject({scheme:external_exports.string().regex(CATALOG_SLUG_PATTERN,"a scheme is a catalog slug").optional().describe("Narrow to one concept scheme by its slug; omit to list every scheme.")}),DATASET_VOCABULARY_SCOPES=["tenant","shared"],DatasetVocabularyTermSchema=external_exports.object({term:external_exports.string().min(1),label:external_exports.string().min(1),definition:external_exports.string().optional(),uri:external_exports.string().optional(),scope:external_exports.enum(DATASET_VOCABULARY_SCOPES)}),DatasetVocabularySchemeSchema=external_exports.object({scheme:external_exports.string().min(1),name:external_exports.string().min(1),description:external_exports.string().optional(),uri:external_exports.string().optional(),scope:external_exports.enum(DATASET_VOCABULARY_SCOPES),terms:external_exports.array(DatasetVocabularyTermSchema)}),DatasetVocabularySchema=external_exports.object({schemes:external_exports.array(DatasetVocabularySchemeSchema)});var DESCRIPTION_PROPOSAL_DATASET_FIELDS=["description","notes","themes"],DESCRIPTION_PROPOSAL_COLUMN_FIELDS=["meaning","unit","term","uri","refersTo"],DESCRIPTION_PROPOSAL_REFERS_TO_VALUES=["assets/asset","assets/asset-type"],DESCRIPTION_PROPOSAL_REFERS_TO={"assets/asset":{...ASSET_COLUMN_ENTITY,pickerResource:"assets"},"assets/asset-type":{entity:{domain:"assets",type:"asset-type"}}};var DESCRIPTION_PROPOSAL_FIELDS=[...DESCRIPTION_PROPOSAL_DATASET_FIELDS,...DESCRIPTION_PROPOSAL_COLUMN_FIELDS],DescriptionProposalFieldSchema=external_exports.enum(DESCRIPTION_PROPOSAL_FIELDS),DESCRIPTION_PROPOSAL_COLUMNS_MAX=250,DESCRIPTION_PROPOSAL_VALUES_MAX=DESCRIPTION_PROPOSAL_DATASET_FIELDS.length+DESCRIPTION_PROPOSAL_COLUMN_FIELDS.length*DESCRIPTION_PROPOSAL_COLUMNS_MAX;var slot2=DescribeDatasetInputSchema.shape,note=DatasetColumnNotePatchSchema.shape,ProposedColumnNoteSchema=external_exports.strictObject({meaning:note.meaning.unwrap().unwrap().optional().describe("What the values in this column mean."),unit:note.unit.unwrap().unwrap().optional().describe("A QUDT unit, e.g. 'unit:M3-PER-HR'."),term:note.term.unwrap().unwrap().optional().describe("A term from datasets.vocabulary.list, 'scheme/slug'."),uri:note.uri.unwrap().unwrap().optional().describe("A term outside the vocabulary, as an absolute IRI \u2014 never beside a term."),refersTo:external_exports.string().optional().describe(`What the column's values are the ids of: ${DESCRIPTION_PROPOSAL_REFERS_TO_VALUES.map(value2=>`'${value2}'`).join(" or ")}. Propose it only when the sampled values match; leave it out otherwise.`)}),ProposeDescriptionInputSchema=external_exports.strictObject({datasetId:external_exports.string().min(1),versionId:external_exports.string().min(1).nullable().describe("The load you read \u2014 the dataset's currentVersionId when you read it, null for a dataset with no load yet. A load that is no longer current is refused."),description:slot2.description.unwrap().unwrap().optional().describe("A proposed description."),notes:slot2.notes.unwrap().unwrap().optional().describe("Proposed notes: what a naive reading gets wrong."),themes:slot2.themes.unwrap().unwrap().optional().describe("Proposed themes, each 'scheme/slug' from datasets.vocabulary.list."),columns:external_exports.record(external_exports.string().min(1).max(DATASET_COLUMN_NOTE_COLUMN_MAX_LENGTH),ProposedColumnNoteSchema).optional().describe(`Column name \u2192 the note you propose for it; leave out what you cannot support. At most ${String(DESCRIPTION_PROPOSAL_COLUMNS_MAX)} columns.`),reason:DatasetLifecycleReasonSchema.optional().describe("Why you propose this, for the person deciding."),get idempotencyKey(){return IdempotencyKeySchema}}),DescriptionProposalValueDataSchema=external_exports.union([external_exports.string(),external_exports.array(external_exports.string())]),DESCRIPTION_PROPOSAL_VALUE_STATUSES=["pending","applied","rejected","replaced"],DescriptionProposalValueStatusSchema=external_exports.enum(DESCRIPTION_PROPOSAL_VALUE_STATUSES),DESCRIPTION_PROPOSAL_DECISIONS=["accept","edit","reject"],DescriptionProposalDecisionKindSchema=external_exports.enum(DESCRIPTION_PROPOSAL_DECISIONS),DESCRIPTION_PROPOSAL_APPLIED_NOTES=["landed-before-refusal","already-in-place","cache-behind"],DescriptionProposalAppliedNoteSchema=external_exports.enum(DESCRIPTION_PROPOSAL_APPLIED_NOTES),DescriptionProposalAttemptSchema=external_exports.discriminatedUnion("outcome",[external_exports.object({outcome:external_exports.literal("superseded"),was:DescriptionProposalValueDataSchema.nullable(),at:external_exports.iso.datetime()}),external_exports.object({outcome:external_exports.literal("not-applied"),code:external_exports.string(),collateral:external_exports.literal(!0).optional(),at:external_exports.iso.datetime()}),external_exports.object({outcome:external_exports.literal("may-have-landed"),code:external_exports.string(),at:external_exports.iso.datetime()}),external_exports.object({outcome:external_exports.literal("applied"),note:DescriptionProposalAppliedNoteSchema,code:external_exports.string().optional(),at:external_exports.iso.datetime()})]),DescriptionProposalValueSchema=external_exports.object({valueId:external_exports.string(),field:DescriptionProposalFieldSchema,column:external_exports.string().nullable(),proposed:DescriptionProposalValueDataSchema,current:DescriptionProposalValueDataSchema.nullable(),status:DescriptionProposalValueStatusSchema,lastAttempt:DescriptionProposalAttemptSchema.nullable(),decision:DescriptionProposalDecisionKindSchema.nullable(),applied:DescriptionProposalValueDataSchema.nullable(),decidedBy:external_exports.string().nullable(),decidedAt:external_exports.iso.datetime().nullable(),decisionRecordId:external_exports.string().nullable()}),DESCRIPTION_PROPOSAL_STATUSES=["open","decided","replaced"],DescriptionProposalStatusSchema=external_exports.enum(DESCRIPTION_PROPOSAL_STATUSES),DescriptionProposalActorSchema=external_exports.object({principal:external_exports.string(),onBehalfOf:external_exports.string().optional()}),DescriptionProposalSchema=external_exports.object({proposalId:external_exports.string(),datasetId:external_exports.string(),versionId:external_exports.string().nullable(),proposedBy:DescriptionProposalActorSchema,proposedAt:external_exports.iso.datetime(),recordId:external_exports.string(),reason:external_exports.string().optional(),status:DescriptionProposalStatusSchema,values:external_exports.array(DescriptionProposalValueSchema)}),DescriptionProposalsInputSchema=external_exports.strictObject({datasetId:external_exports.string().min(1)}),DescriptionProposalsSchema=external_exports.object({proposals:external_exports.array(DescriptionProposalSchema),capped:external_exports.boolean()}),OpenDescriptionProposalsInputSchema=external_exports.strictObject({}),OpenDescriptionProposalSchema=external_exports.object({proposalId:external_exports.string(),datasetId:external_exports.string(),datasetName:external_exports.string(),proposedBy:DescriptionProposalActorSchema,proposedAt:external_exports.iso.datetime(),pending:external_exports.number().int().nonnegative(),total:external_exports.number().int().nonnegative()}),OpenDescriptionProposalsSchema=external_exports.object({proposals:external_exports.array(OpenDescriptionProposalSchema),capped:external_exports.boolean()}),DescriptionProposalDecisionSchema=external_exports.strictObject({valueId:external_exports.string().min(1),decision:DescriptionProposalDecisionKindSchema,value:DescriptionProposalValueDataSchema.optional().describe("Your own value, for `edit` only \u2014 typed as the field is.")}),DecideDescriptionProposalInputSchema=external_exports.strictObject({datasetId:external_exports.string().min(1),proposalId:external_exports.string().min(1),expected:external_exports.strictObject({versionId:external_exports.string().min(1).nullable().describe("The dataset's current load as you read it; null for a dataset with no load.")}),decisions:external_exports.array(DescriptionProposalDecisionSchema).min(1).max(DESCRIPTION_PROPOSAL_VALUES_MAX),reason:DatasetLifecycleReasonSchema.optional(),get idempotencyKey(){return IdempotencyKeySchema}}),DESCRIPTION_PROPOSAL_OUTCOMES=["applied","rejected","superseded","not-applied","may-have-landed"],DescriptionProposalOutcomeSchema=external_exports.object({valueId:external_exports.string(),outcome:external_exports.enum(DESCRIPTION_PROPOSAL_OUTCOMES),code:external_exports.string().optional(),collateral:external_exports.literal(!0).optional(),note:DescriptionProposalAppliedNoteSchema.optional()}),DecideDescriptionProposalSchema=external_exports.object({proposal:DescriptionProposalSchema,outcomes:external_exports.array(DescriptionProposalOutcomeSchema)});var DatasetColumnTermMatchesInputSchema=external_exports.strictObject({datasetId:external_exports.string().min(1)});var term2=external_exports.string().regex(CATALOG_CONCEPT_REF_PATTERN,"a term is 'scheme/slug'"),DatasetColumnTermMatchesSchema=external_exports.discriminatedUnion("state",[external_exports.object({state:external_exports.literal("unavailable")}),external_exports.object({state:external_exports.literal("available"),terms:external_exports.number().int().nonnegative(),truncated:external_exports.boolean(),datasets:external_exports.array(external_exports.object({datasetId:external_exports.string().min(1),name:external_exports.string().min(1),matches:external_exports.array(external_exports.object({term:term2,column:external_exports.string().min(1),ownColumns:external_exports.array(external_exports.string().min(1)).min(1)}))}))})]);var CORRECTION_METHODS=["replace","percent","revert","drop-row"],CorrectionMethodSchema=external_exports.enum(CORRECTION_METHODS);var MAX_CORRECTION_PERCENT=1e3,CorrectionChangeSchema=external_exports.discriminatedUnion("method",[external_exports.strictObject({method:external_exports.literal("replace"),value:DatasetCellValueSchema}),external_exports.strictObject({method:external_exports.literal("percent"),percent:external_exports.number().finite().min(0).max(MAX_CORRECTION_PERCENT)}),external_exports.strictObject({method:external_exports.literal("revert")}),external_exports.strictObject({method:external_exports.literal("drop-row")})]),CorrectionFromSchema=external_exports.strictObject({logicalId:external_exports.string().min(1).max(200),value:DatasetCellValueSchema}),MAX_CORRECTION_COLUMN_LENGTH=255,MAX_CORRECTION_ACT_ROWS=500,ReplaceEachChangeSchema=external_exports.strictObject({method:external_exports.literal("replace-each")}),CorrectionCellFromSchema=CorrectionFromSchema.extend({to:DatasetCellValueSchema}),CELL_KEEP_TAKE=["keep","take"],CellKeepTakeSchema=external_exports.enum(CELL_KEEP_TAKE),CHANGE_CORRECTION_FIELDS={column:external_exports.string().min(1).max(MAX_CORRECTION_COLUMN_LENGTH),change:CorrectionChangeSchema,from:external_exports.array(CorrectionFromSchema).max(MAX_CORRECTION_ACT_ROWS),undoes:external_exports.string().min(1).optional(),resolves:external_exports.strictObject({actId:external_exports.string().min(1),deliveryVersionId:external_exports.string().min(1),resolution:external_exports.enum(["keep","use-delivered"])}).optional(),countedOnVersionId:external_exports.string().min(1).optional()},ChangeCorrectionSchema=external_exports.strictObject(CHANGE_CORRECTION_FIELDS),PastedCorrectionSchema=external_exports.strictObject({column:external_exports.string().min(1).max(MAX_CORRECTION_COLUMN_LENGTH),change:ReplaceEachChangeSchema,from:external_exports.array(CorrectionCellFromSchema).min(1).max(MAX_CORRECTION_ACT_ROWS),keepTake:external_exports.record(external_exports.string().min(1).max(200),CellKeepTakeSchema).optional()}),ReviewCorrectionSchema=external_exports.union([ChangeCorrectionSchema,PastedCorrectionSchema]);var REQUEST_ROWS_LISTED_MAX=20,REQUEST_PREVIEW_ROWS_MAX=5;var RequestRowSchema=external_exports.object({logicalId:external_exports.string().min(1),key:external_exports.string().min(1),problems:external_exports.array(external_exports.string().min(1)),line:external_exports.string().min(1)}),RequestCorrectionDetailSchema=external_exports.object({datasetName:external_exports.string(),deliveryNumber:external_exports.number().int().nonnegative(),rows:external_exports.number().int().nonnegative(),selectionWords:external_exports.string(),filterWords:external_exports.string(),listed:external_exports.array(RequestRowSchema).max(REQUEST_ROWS_LISTED_MAX),moreLine:external_exports.string(),problemsComplete:external_exports.boolean().optional(),incompleteLine:external_exports.string().optional(),requesterName:external_exports.string(),requesterEmail:external_exports.string(),requestedAt:external_exports.iso.datetime(),expectedLine:external_exports.string().optional(),requesterLine:external_exports.string().optional(),subjectPath:external_exports.string().min(1)}),RequestCorrectionPreviewSchema=external_exports.object({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,rows:external_exports.number().int().nonnegative(),selectionWords:external_exports.string(),listed:external_exports.array(RequestRowSchema).max(REQUEST_PREVIEW_ROWS_MAX),moreLine:external_exports.string(),problemsComplete:external_exports.boolean(),incompleteLine:external_exports.string()});var REVIEW_ACT_KINDS=["flag","comment","dismiss","request","correct","withdraw"],ReviewActKindSchema=external_exports.enum(REVIEW_ACT_KINDS),REVIEW_SEVERITIES=["blocking","warning"],ReviewSeveritySchema=external_exports.enum(REVIEW_SEVERITIES),MAX_REVIEW_SELECTION_RECORDS=500,MAX_REVIEW_SELECTION_FILTERS=20,MAX_REVIEW_ID_LENGTH=200,ReviewRecordRefSchema=external_exports.strictObject({logicalId:external_exports.string().min(1).max(MAX_REVIEW_ID_LENGTH),recordId:external_exports.string().min(1).max(MAX_REVIEW_ID_LENGTH)}),ReviewSelectionSchema=external_exports.discriminatedUnion("kind",[external_exports.strictObject({kind:external_exports.literal("records"),records:external_exports.array(ReviewRecordRefSchema).min(1).max(MAX_REVIEW_SELECTION_RECORDS)}),external_exports.strictObject({kind:external_exports.literal("filter"),filters:external_exports.array(DatasetReadFilterSchema).min(1).max(MAX_REVIEW_SELECTION_FILTERS)})]),RULE_FINDING_RESOLUTIONS=["correction"],RuleFindingResolutionSchema=external_exports.enum(RULE_FINDING_RESOLUTIONS),ReviewRuleFindingSchema=external_exports.strictObject({kind:external_exports.literal("rule-finding"),rulesetId:external_exports.string().min(1).max(255).optional(),rulesetVersion:external_exports.number().int().positive().optional(),ruleIndex:external_exports.number().int().nonnegative(),column:external_exports.string().min(1).max(255),resolvedBy:RuleFindingResolutionSchema.optional()}),ReviewRuleFindingInputSchema=ReviewRuleFindingSchema.required({rulesetId:!0,rulesetVersion:!0}),ReviewFlagFindingSchema=external_exports.strictObject({kind:external_exports.literal("flag"),flagActId:external_exports.string().min(1)}),ReviewFindingRefSchema=external_exports.discriminatedUnion("kind",[ReviewRuleFindingSchema,ReviewFlagFindingSchema]),ReviewFindingRefInputSchema=external_exports.discriminatedUnion("kind",[ReviewRuleFindingInputSchema,ReviewFlagFindingSchema]),REVIEW_TEXT_PATTERN=/^[^\0-\x08\x0B\x0C\x0E-\x1F\x7F-\x9F\p{Cs}]*$/u,REVIEW_TEXT_HINT="may not contain control characters other than a line break or a tab";var reviewText=max2=>external_exports.string().trim().min(1).max(max2).regex(REVIEW_TEXT_PATTERN,REVIEW_TEXT_HINT),MAX_REVIEW_BODY_LENGTH=4e3,ReviewBodySchema=reviewText(MAX_REVIEW_BODY_LENGTH),ReviewDimensionSchema=reviewText(80),ACT_BASE={datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,selection:ReviewSelectionSchema,idempotencyKey:IdempotencyKeySchema.max(200)},flagColumn=external_exports.string().min(1).max(255).regex(REVIEW_TEXT_PATTERN,REVIEW_TEXT_HINT),FlagRecordsInputSchema=external_exports.strictObject({...ACT_BASE,severity:ReviewSeveritySchema,dimension:ReviewDimensionSchema.optional(),column:flagColumn.optional(),body:ReviewBodySchema.optional()}),CommentRecordsInputSchema=external_exports.strictObject({...ACT_BASE,body:ReviewBodySchema}),DismissFindingInputSchema=external_exports.strictObject({...ACT_BASE,finding:ReviewFindingRefInputSchema,body:ReviewBodySchema.optional()}),REVIEW_REQUEST_CHANNELS=["notification","manual"],ReviewRequestChannelSchema=external_exports.enum(REVIEW_REQUEST_CHANNELS),RequestCorrectionInputSchema=external_exports.strictObject({...ACT_BASE,body:ReviewBodySchema,expected:reviewText(1e3).optional(),channel:ReviewRequestChannelSchema.optional()}),REVIEW_REQUEST_RESOLUTIONS=["pending","resolved"],ReviewRequestResolutionSchema=external_exports.enum(REVIEW_REQUEST_RESOLUTIONS),ReviewActSchema=external_exports.object({actId:external_exports.string().min(1),kind:ReviewActKindSchema,datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,selection:ReviewSelectionSchema,severity:ReviewSeveritySchema.optional(),dimension:external_exports.string().min(1).optional(),column:external_exports.string().min(1).optional(),finding:ReviewFindingRefSchema.optional(),body:external_exports.string().min(1).optional(),expected:external_exports.string().min(1).optional(),channel:ReviewRequestChannelSchema.optional(),correction:ReviewCorrectionSchema.optional(),matchedCount:external_exports.number().int().positive().optional(),withdraws:external_exports.string().min(1).optional(),withdrawn:external_exports.object({whole:external_exports.boolean(),logicalIds:external_exports.array(external_exports.string().min(1))}).optional(),request:RequestCorrectionDetailSchema.optional(),actor:external_exports.string().min(1),at:external_exports.iso.datetime(),receiptId:external_exports.string().min(1)}),ReviewActsInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema});var ReviewActsSchema=external_exports.object({acts:external_exports.array(ReviewActSchema),truncated:external_exports.boolean()}),RECORD_REVIEW_STATES=["fine","warning","blocking","at-source","check-again"],RecordReviewStateKindSchema=external_exports.enum(RECORD_REVIEW_STATES),CHANGES_SINCE_REVIEW=["unchanged","updated","deleted"],ChangeSinceReviewSchema=external_exports.enum(CHANGES_SINCE_REVIEW),SinceReviewSchema=external_exports.discriminatedUnion("state",[external_exports.object({state:external_exports.literal("current")}),external_exports.object({state:external_exports.literal("compared"),currentVersionId:DatasetVersionIdSchema}),external_exports.object({state:external_exports.literal("not-comparable"),currentVersionId:DatasetVersionIdSchema,reason:external_exports.enum(["unkeyed","unreadable"])})]),RecordReviewStateInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,logicalIds:external_exports.array(external_exports.string().min(1).max(MAX_REVIEW_ID_LENGTH)).min(1).max(MAX_REVIEW_SELECTION_RECORDS)}),RecordReviewEntrySchema=external_exports.object({logicalId:external_exports.string().min(1),state:RecordReviewStateKindSchema,openFlags:external_exports.array(external_exports.string().min(1)),requests:external_exports.array(external_exports.object({actId:external_exports.string().min(1),resolution:ReviewRequestResolutionSchema})),dismissedRuleFindings:external_exports.array(external_exports.object({rulesetId:external_exports.string().min(1),rulesetVersion:external_exports.number().int().positive(),ruleIndex:external_exports.number().int().nonnegative(),column:external_exports.string().min(1)})),thread:external_exports.array(external_exports.string().min(1)),changeSinceReview:ChangeSinceReviewSchema.nullable(),carriedFrom:external_exports.number().int().nonnegative().optional(),checkAgain:external_exports.array(external_exports.string().min(1)).optional(),earlier:external_exports.array(external_exports.object({actId:external_exports.string().min(1),delivery:external_exports.number().int().nonnegative(),outcome:external_exports.enum(["carried","reopened"])})).optional()}),CarryFailureSchema=external_exports.object({code:external_exports.string().min(1),message:external_exports.string(),attempts:external_exports.number().int().positive().optional()}),RecordReviewStateSchema=external_exports.object({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,records:external_exports.array(RecordReviewEntrySchema),acts:external_exports.array(ReviewActSchema),truncated:external_exports.boolean(),sinceReview:SinceReviewSchema,carryPending:external_exports.literal(!0).optional(),carryFailure:CarryFailureSchema.optional(),carryRetrying:CarryFailureSchema.optional()}),REVIEWED_RECORDS_FILTERS=["blocking","warning","at-source","needs-attention","check-again","carried"],ReviewedRecordsFilterSchema=external_exports.enum(REVIEWED_RECORDS_FILTERS),MAX_REVIEWED_RECORDS=1e4;var ReviewedRecordsInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,filter:ReviewedRecordsFilterSchema}),CHECKS_UNLISTED_REASONS=["not-stored","too-many-acts","version-unreadable","row-not-found"],ChecksUnlistedReasonSchema=external_exports.enum(CHECKS_UNLISTED_REASONS),ReviewedRecordsSchema=external_exports.object({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,filter:ReviewedRecordsFilterSchema,logicalIds:external_exports.array(external_exports.string().min(1)).max(MAX_REVIEWED_RECORDS),counts:external_exports.object({blocking:external_exports.number().int().nonnegative(),warning:external_exports.number().int().nonnegative(),atSource:external_exports.number().int().nonnegative(),checkAgain:external_exports.number().int().nonnegative().optional(),carried:external_exports.number().int().nonnegative().optional()}),carriedFrom:external_exports.array(external_exports.number().int().nonnegative()).optional(),carryPending:external_exports.literal(!0).optional(),carryFailure:CarryFailureSchema.optional(),carryRetrying:CarryFailureSchema.optional(),truncated:external_exports.boolean(),checksUnlisted:external_exports.array(ChecksUnlistedReasonSchema).min(1).optional()}),REVIEW_REASON_RULES=["blocking","always"],ReviewReasonRuleSchema=external_exports.enum(REVIEW_REASON_RULES);var ReviewSettingsSchema=external_exports.strictObject({labels:external_exports.strictObject({blocking:reviewText(40),warning:reviewText(40)}),dimensions:external_exports.array(ReviewDimensionSchema).max(50),dimensionRequired:external_exports.boolean(),reasonRequiredOnFlag:ReviewReasonRuleSchema,reasonRequiredOnDismissal:ReviewReasonRuleSchema});var ReviewSettingsInputSchema=external_exports.strictObject({}),SaveReviewSettingsInputSchema=external_exports.strictObject({settings:ReviewSettingsSchema,idempotencyKey:IdempotencyKeySchema.max(200)}),FILTER_SELECTION_SAMPLE_MAX=5,PreviewFilterSelectionInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,filters:external_exports.array(DatasetReadFilterSchema).min(1).max(MAX_REVIEW_SELECTION_FILTERS),withOpenChecks:external_exports.boolean().optional()}),OpenCheckOnColumnSchema=external_exports.object({rulesetId:external_exports.string().min(1),rulesetVersion:external_exports.number().int().positive(),ruleIndex:external_exports.number().int().nonnegative(),column:external_exports.string().min(1),rulesetNames:external_exports.array(external_exports.string()),rows:external_exports.number().int().positive()}),FilterSelectionPreviewSchema=external_exports.object({matched:external_exports.number().int().nonnegative(),sample:external_exports.array(external_exports.record(external_exports.string(),DatasetCellValueSchema)).max(FILTER_SELECTION_SAMPLE_MAX),openChecks:external_exports.array(OpenCheckOnColumnSchema).optional()}),PreviewRequestCorrectionInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,selection:ReviewSelectionSchema});var CORRECTION_MODES=["update","persist"],CorrectionModeSchema=external_exports.enum(CORRECTION_MODES),CorrectionSettingsSchema=external_exports.strictObject({mode:CorrectionModeSchema,notifyOnOverwrite:external_exports.boolean(),conflictSeverity:ReviewSeveritySchema});var CORRECTION_REAPPLY_STEPS=["bound","not-bound"],CorrectionSettingsInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema}),CorrectedCopyFailureSchema=external_exports.object({reason:external_exports.string().min(1),failedAt:external_exports.iso.datetime()}),CorrectionSettingsViewSchema=external_exports.object({datasetId:DatasetIdSchema,settings:CorrectionSettingsSchema,saved:external_exports.boolean(),reapplyStep:external_exports.enum(CORRECTION_REAPPLY_STEPS),correctedCopyFailure:CorrectedCopyFailureSchema.optional()}),RetryCorrectedCopyInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema,idempotencyKey:IdempotencyKeySchema.max(200)}),RetryCorrectedCopyResultSchema=external_exports.object({datasetId:DatasetIdSchema,retried:external_exports.boolean()}),SaveCorrectionSettingsInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema,settings:CorrectionSettingsSchema,idempotencyKey:IdempotencyKeySchema.max(200)}),CORRECTIONS_CURRENCY_STATES=["no-corrections","current","not-reapplied"],CorrectionsCurrencySchema=external_exports.object({datasetId:DatasetIdSchema,state:external_exports.enum(CORRECTIONS_CURRENCY_STATES),mode:CorrectionModeSchema,holdsReadiness:external_exports.boolean(),currentVersionId:external_exports.string().min(1).optional(),builtFromVersionId:external_exports.string().min(1).optional(),currentLoadNumber:external_exports.number().int().positive().optional(),builtFromLoadNumber:external_exports.number().int().positive().optional(),builtInMode:CorrectionModeSchema.optional(),raisedConflicts:external_exports.number().int().nonnegative()}),CorrectionsCurrencyInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema}),CORRECTION_CONFLICT_CASES=["adopted","overwritten-unchanged","overwritten-changed","conflict","absent"],CORRECTION_CONFLICT_SEVERITIES=["blocking","warning","none"];var FILTER_CONFLICT_SAMPLE_MAX=5,FILTER_RESOLUTIONS=["keep","use-delivered"],FilterResolutionSchema=external_exports.enum(FILTER_RESOLUTIONS),FilterResolvesSchema=external_exports.strictObject({actId:external_exports.string().min(1),deliveryVersionId:external_exports.string().min(1),resolution:FilterResolutionSchema}),FilterCorrectionSchema=external_exports.object({actId:external_exports.string().min(1),at:external_exports.iso.datetime(),column:external_exports.string().min(1).max(MAX_CORRECTION_COLUMN_LENGTH),change:CorrectionChangeSchema,filters:external_exports.array(DatasetReadFilterSchema).min(1),rowsVersionId:external_exports.string().min(1),baseVersionId:external_exports.string().min(1),onlyChanged:external_exports.boolean(),matched:external_exports.number().int().nonnegative()}),FilterConflictSampleSchema=external_exports.object({logicalId:external_exports.string().min(1),delivered:external_exports.string().nullable(),corrected:external_exports.string().nullable()}),FilterConflictGroupSchema=external_exports.object({actId:external_exports.string().min(1),deliveryVersionId:external_exports.string().min(1),case:external_exports.enum(CORRECTION_CONFLICT_CASES),severity:external_exports.enum(CORRECTION_CONFLICT_SEVERITIES),rows:external_exports.number().int().positive(),sample:external_exports.array(FilterConflictSampleSchema).max(FILTER_CONFLICT_SAMPLE_MAX)}),FILTER_SIT_OUT_REASONS=["rows-version-unreadable","value-unfit"],FilterAppliedSchema=external_exports.object({actId:external_exports.string().min(1),rows:external_exports.number().int().nonnegative(),unapplied:external_exports.number().int().nonnegative(),reasons:external_exports.record(external_exports.string(),external_exports.number().int().positive()).optional(),later:external_exports.number().int().positive().optional(),sitOut:external_exports.enum(FILTER_SIT_OUT_REASONS).optional()});var FILTER_CORRECTION_STATES=["staged","applied","undone"],StagedFilterCorrectionSchema=external_exports.object({actId:external_exports.string().min(1),column:external_exports.string().min(1),change:CorrectionChangeSchema,filters:external_exports.array(DatasetReadFilterSchema).min(1),versionId:external_exports.string().min(1),matched:external_exports.number().int().nonnegative(),actor:external_exports.string().min(1),at:external_exports.iso.datetime(),reason:external_exports.string().min(1),state:external_exports.enum(FILTER_CORRECTION_STATES),resolves:FilterResolvesSchema.optional(),undoneBy:external_exports.string().min(1).optional(),undoTaken:external_exports.literal(!0).optional(),applied:FilterAppliedSchema.optional(),groups:external_exports.array(FilterConflictGroupSchema)});var CorrectRecordsInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,selection:ReviewSelectionSchema,column:external_exports.string().min(1).max(MAX_CORRECTION_COLUMN_LENGTH),change:CorrectionChangeSchema,from:external_exports.array(CorrectionFromSchema).min(1).max(500).optional(),undoes:external_exports.string().min(1).max(200).optional(),resolves:FilterResolvesSchema.optional(),confirmCount:external_exports.number().int().positive().optional(),resolveChecks:external_exports.boolean().optional(),body:ReviewBodySchema,idempotencyKey:IdempotencyKeySchema.max(200)}),ResolvedCheckSchema=external_exports.object({rulesetId:external_exports.string().min(1),rulesetVersion:external_exports.number().int().positive(),ruleIndex:external_exports.number().int().nonnegative(),column:external_exports.string().min(1),rows:external_exports.number().int().nonnegative(),act:ReviewActSchema}),CorrectRecordsResultSchema=ReviewActSchema.extend({resolvedChecks:external_exports.array(ResolvedCheckSchema).optional()}),STAGED_CORRECTION_STATES=["staged","applied","conflict","superseded","adopted","stale"],StagedCorrectionStateSchema=external_exports.enum(STAGED_CORRECTION_STATES),CORRECTION_UNAPPLIED_REASONS=["row-absent","from-mismatch","not-numeric","column-absent","unrepresentable","value-unfit"],CorrectionUnappliedReasonSchema=external_exports.enum(CORRECTION_UNAPPLIED_REASONS),CorrectionFindingSchema=external_exports.object({case:external_exports.enum(CORRECTION_CONFLICT_CASES),severity:external_exports.enum(CORRECTION_CONFLICT_SEVERITIES),delivered:external_exports.string().nullable(),corrected:external_exports.string().nullable()}),StagedCorrectionSchema=external_exports.object({logicalId:external_exports.string().min(1),recordId:external_exports.string().min(1),column:external_exports.string().min(1),change:CorrectionChangeSchema,from:DatasetCellValueSchema,actId:external_exports.string().min(1),versionId:DatasetVersionIdSchema,actor:external_exports.string().min(1),at:external_exports.iso.datetime(),reason:external_exports.string().min(1),state:StagedCorrectionStateSchema,finding:CorrectionFindingSchema.optional(),gone:external_exports.enum(["row","column"]).optional(),keptOver:external_exports.array(external_exports.string().min(1)).optional(),supersededBy:external_exports.string().min(1).optional(),unappliedReason:CorrectionUnappliedReasonSchema.optional(),heldByFilter:external_exports.string().min(1).optional()}),CORRECTION_APPLY_STATUSES=["in-flight","committed","failed"],LastCorrectionApplySchema=external_exports.object({applyRecordId:external_exports.string().min(1),status:external_exports.enum(CORRECTION_APPLY_STATUSES),sourceVersionId:external_exports.string().min(1),at:external_exports.iso.datetime(),sourceLoadNumber:external_exports.number().int().positive().optional(),correctedVersionId:external_exports.string().min(1).optional(),correctionsVersionId:external_exports.string().min(1).optional(),conflictsVersionId:external_exports.string().min(1).optional(),detail:external_exports.string().optional(),code:external_exports.string().min(1).optional(),job:external_exports.enum(["queued","landing"]).optional(),correctionCount:external_exports.number().int().nonnegative().optional(),corrections:external_exports.number().int().nonnegative().optional(),reason:external_exports.string().min(1).optional(),link:external_exports.object({url:external_exports.string().min(1),title:external_exports.string().min(1)}).optional()}),StagedCorrectionsInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema}),CORRECTION_OUTPUT_LABELS=["corrections","corrected","conflicts"],CorrectionOutputInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema}),CorrectionOutputSchema=external_exports.object({source:external_exports.object({datasetId:DatasetIdSchema,name:external_exports.string().min(1),output:external_exports.enum(CORRECTION_OUTPUT_LABELS),builtFrom:external_exports.object({versionId:external_exports.string().min(1),loadNumber:external_exports.number().int().positive()}).optional(),sourceCurrent:external_exports.object({versionId:external_exports.string().min(1),loadNumber:external_exports.number().int().positive()}).optional(),corrections:external_exports.number().int().nonnegative().optional(),currentApply:external_exports.object({applyRecordId:external_exports.string().min(1),status:external_exports.enum(CORRECTION_APPLY_STATUSES),at:external_exports.iso.datetime()}).optional()}).optional()}),CORRECTED_ROWS_MAX=1e3,CorrectedRowsInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,logicalIds:external_exports.array(external_exports.string().min(1).max(200)).max(CORRECTED_ROWS_MAX)}),CORRECTED_ROWS_UNAVAILABLE_REASONS=["no-corrected-dataset","apply-not-committed","unreadable"],CORRECTED_ROW_STATES=["in-corrected","left-out","not-yet"],CorrectedRowsSchema=external_exports.discriminatedUnion("state",[external_exports.object({state:external_exports.literal("aligned"),correctedDatasetId:DatasetIdSchema,correctedName:external_exports.string().min(1),correctedVersionId:DatasetVersionIdSchema,builtFrom:external_exports.object({versionId:DatasetVersionIdSchema,loadNumber:external_exports.number().int().positive()}),keyFields:external_exports.array(external_exports.string().min(1)).min(1),rows:external_exports.array(external_exports.object({logicalId:external_exports.string().min(1),state:external_exports.enum(CORRECTED_ROW_STATES),changed:external_exports.record(external_exports.string(),external_exports.object({value:external_exports.string().nullable(),delivered:external_exports.string().nullable()})),reason:external_exports.string().min(1).optional(),reasonSource:external_exports.enum(["correction","apply"]).optional(),moreReasons:external_exports.number().int().nonnegative().optional()})),repeated:external_exports.array(external_exports.string().min(1))}),external_exports.object({state:external_exports.literal("unavailable"),reason:external_exports.enum(CORRECTED_ROWS_UNAVAILABLE_REASONS),message:external_exports.string().min(1).optional()})]);var APPLY_IN_FLIGHT_HOLD_MS=3600*1e3,StagedCorrectionsSchema=external_exports.object({datasetId:DatasetIdSchema,cells:external_exports.array(StagedCorrectionSchema),pending:external_exports.number().int().nonnegative(),undosPending:external_exports.number().int().nonnegative().default(0),correctedDatasetId:external_exports.string().min(1).optional(),correctedName:external_exports.string().min(1).optional(),correctedArchived:external_exports.literal(!0).optional(),correctionsDatasetId:external_exports.string().min(1).optional(),conflictsDatasetId:external_exports.string().min(1).optional(),lastApply:LastCorrectionApplySchema.optional(),lastAttempt:LastCorrectionApplySchema.optional(),outputsBehind:external_exports.boolean(),raisedConflicts:external_exports.number().int().nonnegative(),truncated:external_exports.boolean(),filterCorrections:external_exports.array(StagedFilterCorrectionSchema).default([])}),ApplyCorrectionsKeySchema=IdempotencyKeySchema.max(200).describe("Client-minted replay key for an Apply of corrections \u2014 REQUIRED. Mint ONE per Apply (a UUID is fine) and reuse it only to re-send that Apply. Once it has COMPLETED, reusing the key returns its receipt without landing anything again; a call REFUSED before its Record opened consumed nothing. An Apply opens and seals across two transactions, so a key whose Apply is still in flight is refused CONFLICT (CORRECTIONS_IN_FLIGHT) rather than starting a second; re-sent while in flight, the server compares the request with what the receipt holds \u2014 the raw version and every correction it carried \u2014 and refuses CONFLICT (CORRECTIONS_KEY_INPUT_MISMATCH) on any difference. CORRECTIONS_IN_FLIGHT carries the receipt id (data.applyRecordId), so a caller that lost the answer can poll stagedCorrections. A COMPLETED key answers its receipt whatever was staged since: corrections staged since need a new key. An Apply that RAN and sealed FAILED freed its key, so re-sending it starts a second Apply."),APPLY_LINK_URL=/^https?:\/\/\S+$/i,ApplyLinkSchema=external_exports.strictObject({url:external_exports.string().trim().min(1).max(2e3).regex(APPLY_LINK_URL,"a link must start with http:// or https://"),title:external_exports.string().trim().min(1).max(200).optional()}),ApplyCorrectionsInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,link:ApplyLinkSchema.optional(),idempotencyKey:ApplyCorrectionsKeySchema});var ApplyCorrectionsAcceptedSchema=external_exports.object({applyRecordId:external_exports.string().min(1)}),AppliedCorrectionSchema=external_exports.object({actId:external_exports.string().min(1),logicalId:external_exports.string().min(1),recordId:external_exports.string().min(1),column:external_exports.string().min(1),change:CorrectionChangeSchema,from:DatasetCellValueSchema,versionId:external_exports.string().min(1)}),RetiredCorrectionSchema=external_exports.object({actId:external_exports.string().min(1),logicalId:external_exports.string().min(1),column:external_exports.string().min(1)});var SEED_CORRECTED_COPY_FAULT_VERB="seedCorrectedCopyFault",SEED_CORRECTED_COPY_FAULT_ACTION_NAME=`datasets.${SEED_CORRECTED_COPY_FAULT_VERB}`;var CorrectionApplyTriggerSchema=external_exports.object({kind:external_exports.literal("automatic-reapply"),deliveryVersionId:external_exports.string().min(1),deliveryLoadNumber:external_exports.number().int().nonnegative(),reapplyId:external_exports.string().min(1)}),ApplyCorrectionsRecordParamsSchema=external_exports.object({datasetId:external_exports.string().min(1),sourceVersionId:external_exports.string().min(1),reason:external_exports.string().min(1),citations:external_exports.array(CitationSchema),trigger:CorrectionApplyTriggerSchema.optional(),keyFields:external_exports.array(external_exports.string().min(1)).min(1),settings:CorrectionSettingsSchema,corrections:external_exports.array(AppliedCorrectionSchema),retired:external_exports.array(RetiredCorrectionSchema).optional(),retiredBefore:external_exports.iso.datetime().optional(),raised:external_exports.array(RetiredCorrectionSchema.extend(CorrectionFindingSchema.shape)).optional(),filterCorrections:external_exports.array(FilterCorrectionSchema).optional(),filterRetired:external_exports.array(external_exports.string().min(1)).optional()});var DatasetSortFieldSchema=external_exports.enum(["name","kind","updatedAt","rowCount","category"]),DatasetSortDirectionSchema=external_exports.enum(["asc","desc"]),DatasetOrderBySchema=external_exports.object({field:DatasetSortFieldSchema,direction:DatasetSortDirectionSchema}),DATASET_CATALOG_MAX_LIMIT=200;var DATASET_OWNER_FILTER_MAX=50,DATASET_OWNER_FILTER_NAME_MAX=100,DATASET_SEARCH_MAX=200,DATASET_NAME_CONTAINS_MAX=DATASET_SEARCH_MAX,SearchTermSchema=external_exports.string().min(1).max(DATASET_SEARCH_MAX).regex(/^[^\p{Cc}]*$/u,{message:"Search cannot hold control characters."}),DATASET_KEYWORD_FILTER_MAX=50;var DATASET_THEME_FILTER_MAX=50,DATASET_ID_FILTER_MAX=1e3,DATASET_NARROWING_MARKS_MAX=16,DatasetNarrowingSchemeSchema=external_exports.string().regex(/^[a-z][a-z0-9-]*\.[a-z][a-z0-9-]*$/).max(64),DatasetNarrowingMarkSchema=external_exports.string().regex(/^[a-z0-9][a-z0-9:._-]*$/).max(64),DatasetNarrowedBySchema=external_exports.strictObject({scheme:DatasetNarrowingSchemeSchema,anyOf:external_exports.array(DatasetNarrowingMarkSchema).max(DATASET_NARROWING_MARKS_MAX).optional(),noneOf:external_exports.array(DatasetNarrowingMarkSchema).max(DATASET_NARROWING_MARKS_MAX).optional()});var DatasetPromotionSchema=external_exports.enum(["promoted","unpromoted"]);var DatasetTimeCoveredFilterSchema=external_exports.strictObject({start:external_exports.iso.datetime({offset:!0}).optional(),end:external_exports.iso.datetime({offset:!0}).optional()}).refine(window=>window.start!==void 0||window.end!==void 0,"timeCovered cannot be open at both ends").refine(window=>window.start===void 0||window.end===void 0||Date.parse(window.start)<=Date.parse(window.end),"timeCovered ends before it starts"),ListDatasetsInputSchema=external_exports.strictObject({get kind(){return external_exports.array(DatasetKindSchema).max(DatasetKindSchema.options.length).optional()},status:external_exports.array(DatasetStatusSchema).max(DatasetStatusSchema.options.length).optional(),maturity:external_exports.array(DatasetMaturitySchema).max(DatasetMaturitySchema.options.length).optional(),ownerDomain:external_exports.array(external_exports.string().min(1).max(DATASET_OWNER_FILTER_NAME_MAX)).max(DATASET_OWNER_FILTER_MAX).optional(),promotion:DatasetPromotionSchema.optional(),get grain(){return external_exports.array(DatasetGrainSchema).max(DatasetGrainSchema.options.length).optional()},keyword:external_exports.array(external_exports.string().min(1).max(DATASET_KEYWORD_MAX_LENGTH)).max(DATASET_KEYWORD_FILTER_MAX).optional(),theme:external_exports.array(external_exports.string().regex(CATALOG_CONCEPT_REF_PATTERN,"a theme is 'scheme/slug'")).max(DATASET_THEME_FILTER_MAX).optional(),get timeCovered(){return DatasetTimeCoveredFilterSchema.optional()},search:SearchTermSchema.optional(),nameContains:SearchTermSchema.max(DATASET_NAME_CONTAINS_MAX).optional().describe("DEPRECATED \u2014 use `search` instead; this name is kept for one release. It is now an ALIAS of `search` rather than its old behaviour: it matches the dataset LABEL, DESCRIPTION and KEYWORDS as well as the NAME, so the same ask can only return MORE rows than it used to, never fewer. Sending both is not an error \u2014 they are OR'd."),provenance:DatasetProvenanceSchema.optional(),datasetIds:external_exports.array(external_exports.uuid()).max(DATASET_ID_FILTER_MAX).optional(),narrowedBy:DatasetNarrowedBySchema.optional(),includeArchived:external_exports.boolean().optional(),orderBy:DatasetOrderBySchema.optional(),offset:external_exports.number().int().min(0).optional(),limit:external_exports.number().int().min(1).max(DATASET_CATALOG_MAX_LIMIT).optional()}),DatasetSummarySchema=external_exports.object({get datasetId(){return DatasetIdSchema},name:external_exports.string().min(1),label:external_exports.string().min(1).optional(),createdAt:external_exports.iso.datetime().optional(),get kind(){return DatasetKindSchema},status:DatasetStatusSchema,maturity:DatasetMaturitySchema,get slug(){return DatasetSlugSchema},ownerDomain:external_exports.string().min(1).optional(),category:external_exports.string().min(1).optional(),dataOwner:external_exports.string().min(1).optional(),openIssues:external_exports.number().int().nonnegative().optional(),producedByRecordId:external_exports.string().min(1).optional(),description:external_exports.string().min(1).optional(),notes:external_exports.string().min(1).optional(),keywords:external_exports.array(external_exports.string().min(1)).optional(),themes:external_exports.array(external_exports.string().min(1)).optional(),get grain(){return DatasetGrainSchema.optional()},get timeCovered(){return DatasetTimeCoveredReadSchema.optional()},get tableRole(){return DatasetTableRoleSchema.optional()},get currentVersionId(){return DatasetVersionIdSchema.optional()},rowCount:external_exports.number().int().nonnegative().optional(),updatedAt:external_exports.iso.datetime().optional(),promoted:external_exports.boolean(),hasPromotedVersion:external_exports.boolean().optional(),provenance:DatasetProvenanceSchema,get replacedBy(){return DatasetReplacedBySchema.optional()},get correctionOf(){return external_exports.object({datasetId:DatasetIdSchema,name:external_exports.string().min(1),output:external_exports.enum(CORRECTION_OUTPUT_LABELS),status:DatasetStatusSchema.optional()}).optional()},get bundle(){return external_exports.object({correctedDatasetId:DatasetIdSchema,correctionsDatasetId:DatasetIdSchema.optional(),conflictsDatasetId:DatasetIdSchema.optional(),notYetReviewed:external_exports.boolean()}).optional()},correctedUnavailable:external_exports.enum(["archived","gone"]).optional(),held:external_exports.boolean().optional()}).describe("One dataset as the catalog and `datasets.list` report it: identity (`datasetId`, and `versionId` is deliberately absent \u2014 a summary describes the CURRENT load, so pin a load by building a `DatasetRef` yourself) plus the current load's size and state. PROMOTE-BEFORE-CONSUME gates governed CONSUMPTION, not reading: `datasets.read` and composition validation resolve an unpromoted version by design, so a successful read proves nothing about promotion. What refuses one is a governed consumer that turns dataset rows into domain state \u2014 `assets.composition.createMany` and the source-transformation inputs. The pipeline is land \u2192 promote \u2192 consume, and `promoted` here is that gate's answer for the current load. `rowCount` is ABSENT when nothing has landed and for every `live` dataset (a live version pins a definition, not rows) \u2014 absent means \"no size is knowable here\", never zero."),DatasetCatalogPageSchema=external_exports.object({items:external_exports.array(DatasetSummarySchema),total:external_exports.number().int().nonnegative(),nextCursor:external_exports.string().min(1).nullable()}),DatasetFacetBucketSchema=external_exports.object({value:external_exports.string().min(1),count:external_exports.number().int().nonnegative()}),DatasetFacetsSchema=external_exports.object({total:external_exports.number().int().nonnegative(),byKind:external_exports.array(DatasetFacetBucketSchema),byStatus:external_exports.array(DatasetFacetBucketSchema),byMaturity:external_exports.array(DatasetFacetBucketSchema),byOwnerDomain:external_exports.array(DatasetFacetBucketSchema),byPromotion:external_exports.array(DatasetFacetBucketSchema),byGrain:external_exports.array(DatasetFacetBucketSchema),byKeyword:external_exports.array(DatasetFacetBucketSchema),byTheme:external_exports.array(DatasetFacetBucketSchema)});var DATASET_USES_MAX_DATASETS=20,DatasetUseDatasetSchema=external_exports.object({datasetId:external_exports.string().min(1),name:external_exports.string().min(1)}),ListedDatasetSchema=DatasetUseDatasetSchema.extend({correctedDatasetId:external_exports.string().min(1).optional()}),ListDatasetUsesInputSchema=external_exports.object({datasets:external_exports.array(ListedDatasetSchema).min(1).max(DATASET_USES_MAX_DATASETS)}),DatasetUseReadsVersionSchema=external_exports.discriminatedUnion("mode",[external_exports.object({mode:external_exports.literal("follow")}),external_exports.object({mode:external_exports.literal("pinned"),versionId:external_exports.string().min(1)}),external_exports.object({mode:external_exports.literal("current")})]),DatasetUseStateSchema=external_exports.discriminatedUnion("status",[external_exports.object({status:external_exports.literal("generating"),versionId:external_exports.string().min(1),version:external_exports.number().int().min(1)}),external_exports.object({status:external_exports.literal("failed"),versionId:external_exports.string().min(1),version:external_exports.number().int().min(1),failure:external_exports.object({message:external_exports.string().min(1),nextStep:external_exports.enum(["retry","narrow-inputs","fix-template","fix-dataset","contact-support"])})})]),DatasetUseSchema=external_exports.object({useId:external_exports.string().min(1),datasetId:external_exports.string().min(1),kind:external_exports.string().min(1),name:external_exports.string().min(1),where:external_exports.array(external_exports.string().min(1)),href:external_exports.string().regex(/^\/(?!\/)/).optional(),canSwitch:external_exports.boolean(),cannotSwitchReason:external_exports.string().min(1).optional(),note:external_exports.string().min(1).optional(),readsVersion:DatasetUseReadsVersionSchema.optional(),readsKeys:external_exports.array(external_exports.string().min(1)).optional(),state:DatasetUseStateSchema.optional()}),ListDatasetUsesOutputSchema=external_exports.object({uses:external_exports.array(DatasetUseSchema)}),SwitchDatasetUseInputSchema=external_exports.object({useId:external_exports.string().min(1),from:DatasetUseDatasetSchema,to:DatasetUseDatasetSchema,idempotencyKey:external_exports.string().min(1).max(200).describe("Client-minted replay key for this governed write \u2014 the switch runs the owning domain's own revise under it. Mint ONE key per (item, from, to) and reuse it on every retry: a retry after a lost answer replays what the first attempt answered (a report whose switch is generating answers `switching` for the same version again), and an item that already reads `to` answers `switched` without changing anything.")}),SwitchDatasetUseResultSchema=external_exports.discriminatedUnion("outcome",[external_exports.object({useId:external_exports.string().min(1),outcome:external_exports.enum(["switched","left-as-draft"]),message:external_exports.string().min(1)}),external_exports.object({useId:external_exports.string().min(1),outcome:external_exports.literal("switching"),message:external_exports.string().min(1),versionId:external_exports.string().min(1),version:external_exports.number().int().min(1)})]);var ViewScopeSchema=external_exports.enum(["assets-list","datasets-list","events-list","scenarios-list","work-list","scenarios-workbench"]),SavedViewIdSchema=external_exports.string().min(1).brand(),SAVED_VIEW_NAME_MAX=100,VIEW_COLUMNS_MAX=100;function createViewPreferenceShapes(config2){let ScopeSchema2=external_exports.literal(config2.scope),SavedViewSchema3=external_exports.object({id:SavedViewIdSchema,scope:ScopeSchema2,name:external_exports.string().min(1).max(SAVED_VIEW_NAME_MAX),payload:config2.view,createdAt:external_exports.iso.datetime(),updatedAt:external_exports.iso.datetime()}),TablePreferencesSchema3=external_exports.object({scope:ScopeSchema2,preferences:config2.preferences,createdAt:external_exports.iso.datetime(),updatedAt:external_exports.iso.datetime()});return{ScopeSchema:ScopeSchema2,SavedViewSchema:SavedViewSchema3,TablePreferencesSchema:TablePreferencesSchema3,CreateSavedViewInputSchema:external_exports.strictObject({scope:ScopeSchema2,name:external_exports.string().min(1).max(SAVED_VIEW_NAME_MAX),payload:config2.view}),UpdateSavedViewInputSchema:external_exports.strictObject({id:SavedViewIdSchema,name:external_exports.string().min(1).max(SAVED_VIEW_NAME_MAX).optional(),payload:config2.view.optional()}),ListSavedViewsInputSchema:external_exports.strictObject({scope:ScopeSchema2}),DeleteSavedViewInputSchema:external_exports.strictObject({id:SavedViewIdSchema}),GetTablePreferencesInputSchema:external_exports.strictObject({scope:ScopeSchema2}),SetTablePreferencesInputSchema:external_exports.strictObject({scope:ScopeSchema2,preferences:config2.preferences})}}var DATASETS_LIST_VIEW_SCOPE="datasets-list",DatasetsListViewFiltersSchema=external_exports.looseObject({get kind(){return external_exports.array(DatasetKindSchema).max(DatasetKindSchema.options.length).optional()},status:external_exports.array(DatasetStatusSchema).max(DatasetStatusSchema.options.length).optional(),maturity:external_exports.array(DatasetMaturitySchema).max(DatasetMaturitySchema.options.length).optional(),ownerDomain:external_exports.array(external_exports.string().min(1).max(DATASET_OWNER_FILTER_NAME_MAX)).max(DATASET_OWNER_FILTER_MAX).optional(),promotion:DatasetPromotionSchema.optional(),search:external_exports.string().min(1).max(DATASET_SEARCH_MAX).optional(),nameContains:external_exports.string().min(1).max(DATASET_NAME_CONTAINS_MAX).optional().describe("DEPRECATED \u2014 use `search` instead; this name is kept for one release. It is now an ALIAS of `search` rather than its old behaviour: it matches the dataset DESCRIPTION and KEYWORDS as well as the NAME, so the same ask can only return MORE rows than it used to, never fewer. Sending both is not an error \u2014 they are OR'd."),get grain(){return external_exports.array(DatasetGrainSchema).max(DatasetGrainSchema.options.length).optional()},keyword:external_exports.array(external_exports.string().min(1).max(DATASET_KEYWORD_MAX_LENGTH)).max(DATASET_KEYWORD_FILTER_MAX).optional(),theme:external_exports.array(external_exports.string().regex(CATALOG_CONCEPT_REF_PATTERN,"a theme is 'scheme/slug'")).max(DATASET_THEME_FILTER_MAX).optional(),get timeCovered(){return DatasetTimeCoveredFilterSchema.optional()},includeArchived:external_exports.boolean().optional()}),DatasetsListViewSchema=external_exports.looseObject({filters:DatasetsListViewFiltersSchema.optional(),orderBy:DatasetOrderBySchema.optional(),columns:external_exports.array(external_exports.string().min(1)).max(VIEW_COLUMNS_MAX).optional()}),DatasetsTablePreferencesSchema=external_exports.looseObject({columns:external_exports.array(external_exports.string().min(1)).max(VIEW_COLUMNS_MAX).optional(),pageSize:external_exports.number().int().min(1).max(DATASET_CATALOG_MAX_LIMIT).optional()}),datasetsViewShapes=createViewPreferenceShapes({scope:DATASETS_LIST_VIEW_SCOPE,view:DatasetsListViewSchema,preferences:DatasetsTablePreferencesSchema}),SavedViewSchema=datasetsViewShapes.SavedViewSchema,CreateSavedViewInputSchema=datasetsViewShapes.CreateSavedViewInputSchema,UpdateSavedViewInputSchema=datasetsViewShapes.UpdateSavedViewInputSchema,ListSavedViewsInputSchema=datasetsViewShapes.ListSavedViewsInputSchema,DeleteSavedViewInputSchema=datasetsViewShapes.DeleteSavedViewInputSchema,GetTablePreferencesInputSchema=datasetsViewShapes.GetTablePreferencesInputSchema,SetTablePreferencesInputSchema=datasetsViewShapes.SetTablePreferencesInputSchema,TablePreferencesSchema=datasetsViewShapes.TablePreferencesSchema;var DATASET_CATEGORY_MAX_LENGTH=80,DATASET_DATA_OWNER_MAX_LENGTH=200,DatasetCategorySchema=external_exports.string().trim().min(1).max(DATASET_CATEGORY_MAX_LENGTH).regex(NO_CONTROL_CHARACTERS,{message:"A category cannot hold control characters."}).regex(SHOWS_SOMETHING,{message:"A category needs at least one character that shows."}).describe('The group the Datasets page lists this dataset under, e.g. "Emissions factors". Free text; a dataset with none is listed as Uncategorised.'),DatasetDataOwnerSchema=external_exports.string().trim().min(1).max(DATASET_DATA_OWNER_MAX_LENGTH).regex(NO_CONTROL_CHARACTERS,{message:"A member id cannot hold control characters."}).describe("The user id of the tenant member who is this dataset\u2019s data owner \u2014 the person its questions are sent to. Not the publishing module (`ownerDomain`)."),SetDatasetCatalogDetailsInputSchema=external_exports.strictObject({datasetId:external_exports.string().min(1),category:DatasetCategorySchema.nullable().optional(),dataOwner:DatasetDataOwnerSchema.nullable().optional(),reason:DatasetLifecycleReasonSchema.optional(),idempotencyKey:IdempotencyKeySchema});var SetDatasetColumnEntitiesInputSchema=external_exports.strictObject({datasetId:external_exports.string().min(1),columnEntities:DatasetColumnEntitiesPatchSchema,reason:DatasetLifecycleReasonSchema.optional(),idempotencyKey:IdempotencyKeySchema});var TENANT_LAKEHOUSES=["dedicated","shared","hybrid"],TenantLakehouseSchema=external_exports.enum(TENANT_LAKEHOUSES);var TenantLakehouseViewSchema=external_exports.object({lakehouse:TenantLakehouseSchema,hasConnectedLake:external_exports.boolean(),hasLegacyData:external_exports.boolean()});var DatasetsPromotedDetailSchema=external_exports.strictObject({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema});var REFERENCE_TABLE_SUBJECT_TYPE="reference-table",OBSERVE_REFERENCE_VERSION_VERB="observeReferenceVersion",OBSERVE_REFERENCE_VERSION_ACTION_NAME=`datasets.${OBSERVE_REFERENCE_VERSION_VERB}`;var HoldsSchema=external_exports.strictObject({holds:external_exports.boolean()}),ReferenceVersionFactsSchema=external_exports.strictObject({datesAbut:HoldsSchema,coverageKept:HoldsSchema,unitsKnown:HoldsSchema,saveSealed:HoldsSchema}),REFERENCE_APPROVAL_SETUPS=["covered","none"],ReferenceApprovalSetupSchema=external_exports.enum(REFERENCE_APPROVAL_SETUPS),ReferenceVersionFactDetailSchema=external_exports.object({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,facts:ReferenceVersionFactsSchema,clean:external_exports.boolean(),approval:ReferenceApprovalSetupSchema}),StepKeySchema=IdempotencyKeySchema.max(512),AssertReferenceVersionSignableInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema,idempotencyKey:StepKeySchema,requires:external_exports.array(external_exports.string().max(ENTITY_REF_MAX_IDENTITY_CHARS)).max(16).optional(),factRecordId:external_exports.uuid().max(ENTITY_REF_MAX_IDENTITY_CHARS).optional()}),ReferenceVersionSignableSchema=external_exports.object({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,facts:ReferenceVersionFactsSchema}),ActivateReferenceVersionInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema.optional(),idempotencyKey:StepKeySchema}),ReferenceVersionInUseSchema=external_exports.object({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,changed:external_exports.boolean(),held:external_exports.object({reason:external_exports.string().min(1).optional(),message:external_exports.string().min(1)}).optional()}),REFERENCE_VERSION_APPROVED_IN_APPROVALS="REFERENCE_VERSION_APPROVED_IN_APPROVALS",REFERENCE_VERSION_NOT_SIGNABLE="REFERENCE_VERSION_NOT_SIGNABLE",REFERENCE_VERSION_SUPERSEDED="REFERENCE_VERSION_SUPERSEDED";var REFERENCE_SAVE_STAGES=["checking-approval-setup","sent-for-approval","ready-to-send","approved","approved-outside-sign-off","rejected","withdrawn","approval-status-unknown","in-use","not-sent"],ReferenceSaveStageSchema=external_exports.enum(REFERENCE_SAVE_STAGES),REFERENCE_NOT_SENT_REASONS=["saver-cannot-save","approval-set-up-since","saved-before-approval"],ReferenceNotSentSchema=external_exports.object({reason:external_exports.enum(REFERENCE_NOT_SENT_REASONS),saver:external_exports.string().min(1),at:external_exports.iso.datetime()});var ReferenceCitationSchema=external_exports.object({title:external_exports.string().trim().min(1).max(300),url:external_exports.string().trim().min(1).max(2e3)}),REFERENCE_CITATIONS_MAX=20,ReferenceGovernanceSchema=external_exports.strictObject({authority:external_exports.string().trim().min(1).max(200).optional(),citations:external_exports.array(ReferenceCitationSchema).max(REFERENCE_CITATIONS_MAX).default([]),authorityEdition:external_exports.string().trim().min(1).max(100).optional(),notes:external_exports.string().trim().min(1).max(4e3).optional()});var REFERENCE_EDIT_ROWS_MAX=1e4,REFERENCE_EDIT_COLUMNS_MAX=100,ReferenceColumnSchema=external_exports.object({name:external_exports.string().trim().min(1).max(128),type:external_exports.enum(["text","number"])}),REFERENCE_CHANGE_TYPES=["new-edition","publisher-errata","local-correction"],ReferenceChangeTypeSchema=external_exports.enum(REFERENCE_CHANGE_TYPES),ReferenceCellSchema=external_exports.union([external_exports.string().max(4e3),external_exports.number(),external_exports.null()]),ReferenceEditRowSchema=external_exports.record(external_exports.string(),ReferenceCellSchema),SaveCommonShape={columns:external_exports.array(ReferenceColumnSchema).min(1).max(REFERENCE_EDIT_COLUMNS_MAX),rows:external_exports.array(ReferenceEditRowSchema).max(REFERENCE_EDIT_ROWS_MAX),reason:external_exports.string().trim().min(1).max(500),idempotencyKey:IdempotencyKeySchema.max(200)},SaveReferenceVersionInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema,baseVersionId:DatasetVersionIdSchema,authorityEdition:ReferenceGovernanceSchema.shape.authorityEdition,changeType:ReferenceChangeTypeSchema,...SaveCommonShape}),CreateReferenceTableInputSchema=external_exports.strictObject({name:external_exports.string().trim().min(1).max(200),keyFields:external_exports.array(external_exports.string().trim().min(1).max(128)).min(1).max(10),source:ReferenceGovernanceSchema.optional(),...SaveCommonShape}),SaveReferenceVersionAcceptedSchema=external_exports.object({saveRecordId:external_exports.string().min(1),datasetId:DatasetIdSchema.optional()}),REFERENCE_SAVE_FAILURE_CODES=["REFERENCE_BASE_MOVED","REFERENCE_SAVE_NOT_SAVABLE","REFERENCE_SAVE_UNCHANGED","REFERENCE_SAVE_SUPERSEDED","LAND_NAME_TAKEN","REFERENCE_SAVE_ABANDONED","REFERENCE_SAVE_FAILED"];var ReferenceSaveStatusInputSchema=external_exports.strictObject({saveRecordId:external_exports.string().min(1).max(ENTITY_REF_MAX_IDENTITY_CHARS)}),ReferenceSaveStatusSchema=external_exports.object({saveRecordId:external_exports.string().min(1),state:external_exports.enum(["saving","saved","failed"]),stage:ReferenceSaveStageSchema.optional(),notSent:ReferenceNotSentSchema.optional(),rejectedReason:external_exports.string().min(1).optional(),datasetId:DatasetIdSchema.optional(),versionId:DatasetVersionIdSchema.optional(),code:external_exports.enum(REFERENCE_SAVE_FAILURE_CODES).optional(),message:external_exports.string().min(1).optional()});var DatasetVersionSchema=external_exports.object({versionId:DatasetVersionIdSchema,datasetId:DatasetIdSchema,loadNumber:external_exports.number().int().positive(),rowCount:external_exports.number().int().nonnegative().optional(),loadedAt:external_exports.string().min(1),promotedAt:external_exports.iso.datetime().nullable(),completedAt:external_exports.iso.datetime().nullable().optional(),asOf:external_exports.iso.datetime().optional(),producedByRecordId:external_exports.string().min(1).optional(),save:external_exports.object({by:external_exports.string().min(1),reason:external_exports.string().min(1),changeType:ReferenceChangeTypeSchema.optional()}).optional(),governance:ReferenceGovernanceSchema.optional()}),ListDatasetVersionsInputSchema=DatasetRefSchema.extend({completeOnly:external_exports.boolean().optional().describe("true lists only loads that finished landing (`completedAt` set), plus the dataset\u2019s current load, which is finished by definition; omitted or false lists every load, one still importing included, whose climbing `rowCount` is its progress.")}).describe(DatasetRefSchema.description??""),DatasetVersionDiffUnkeyedSideSchema=external_exports.enum(["from","to","both"]),DatasetVersionDiffSchema=external_exports.discriminatedUnion("comparable",[external_exports.object({comparable:external_exports.literal(!0),fromVersionId:DatasetVersionIdSchema,toVersionId:DatasetVersionIdSchema,added:external_exports.number().int().nonnegative(),removed:external_exports.number().int().nonnegative(),changed:external_exports.number().int().nonnegative()}),external_exports.object({comparable:external_exports.literal(!1),fromVersionId:DatasetVersionIdSchema,toVersionId:DatasetVersionIdSchema,unkeyedSide:DatasetVersionDiffUnkeyedSideSchema})]);var MAX_REPLICA_TABLES=64,REPLICA_SLUG_SUFFIX_RESERVE=7,CATALOG_SLUG_CEILING=64,MAX_REPLICA_SLUG_LENGTH=CATALOG_SLUG_CEILING-REPLICA_SLUG_SUFFIX_RESERVE,REPLICA_SLUG_HINT='Lowercase letters, digits, "-" or "_"; starts with a letter, ends with a letter or digit.',ReplicaSlugSchema=external_exports.string().min(2).max(MAX_REPLICA_SLUG_LENGTH).regex(CATALOG_SLUG_PATTERN,REPLICA_SLUG_HINT),REPLICA_RECORD_SET_ORIENTATIONS=["fact","dimension","relation"],ReplicaRecordSetOrientationSchema=external_exports.enum(REPLICA_RECORD_SET_ORIENTATIONS),REMOTE_NAME_HINT="table names may not contain / or control characters",REMOTE_NAME_PATTERN=/^(?!\.\.?$)[^/\\\u0000-\u001f]+$/,RemoteNameSchema=external_exports.string().min(1).max(255).regex(REMOTE_NAME_PATTERN,REMOTE_NAME_HINT),MAX_REPLICA_KEY_FIELDS=32,MAX_REPLICA_KEY_FIELD_LENGTH=255,ReplicaTableSelectionSchema=external_exports.strictObject({name:RemoteNameSchema,keyFields:external_exports.array(external_exports.string().min(1).max(MAX_REPLICA_KEY_FIELD_LENGTH)).max(MAX_REPLICA_KEY_FIELDS).optional(),orientation:ReplicaRecordSetOrientationSchema.optional()}),REPLICA_TITLE_REQUIRED_HINT="Enter a name for this replica.",MAX_REPLICA_TITLE_LENGTH=200,DeclareReplicaBase={connectionRef:ConnectionRefSchema,tables:external_exports.array(ReplicaTableSelectionSchema).min(1).max(MAX_REPLICA_TABLES),replicaSlug:ReplicaSlugSchema,title:external_exports.string().min(1).max(MAX_REPLICA_TITLE_LENGTH).regex(/\S/,REPLICA_TITLE_REQUIRED_HINT),idempotencyKey:IdempotencyKeySchema},DeclareReplicaInputSchema=external_exports.union([external_exports.strictObject({...DeclareReplicaBase,share:RemoteNameSchema,schema:RemoteNameSchema}),external_exports.strictObject({...DeclareReplicaBase,schema:RemoteNameSchema})]),CatalogDatasetIdSchema=external_exports.string().regex(/^dataset:[a-z][a-z0-9_-]{0,62}[a-z0-9]$/),ReplicaLocatorSchema=external_exports.union([external_exports.strictObject({share:RemoteNameSchema,schema:RemoteNameSchema,tables:external_exports.array(RemoteNameSchema).min(1)}),external_exports.strictObject({schema:RemoteNameSchema,tables:external_exports.array(RemoteNameSchema).min(1)})]),ReplicaDeclarationSchema=external_exports.object({connectionRef:ConnectionRefSchema,replica:external_exports.object({datasetId:CatalogDatasetIdSchema,slug:ReplicaSlugSchema,title:external_exports.string().min(1)}),externalDataset:external_exports.object({datasetId:CatalogDatasetIdSchema,slug:external_exports.string().min(1),title:external_exports.string().min(1)}),importOperation:external_exports.object({slug:external_exports.string().min(1),enabled:external_exports.literal(!0),loadStrategy:external_exports.literal("full-refresh")}),locator:ReplicaLocatorSchema,recordSets:external_exports.array(external_exports.object({slug:external_exports.string().min(1),layerName:external_exports.string().min(1)})),distributions:external_exports.array(external_exports.object({distributionId:external_exports.string().min(1),table:RemoteNameSchema,accessURL:external_exports.string().min(1),accessService:external_exports.string().min(1)})),declaredAt:external_exports.iso.datetime()}),REPLICA_RECORD_SET_STATES=["declared","processing","landed"],ReplicaRecordSetStateSchema=external_exports.enum(REPLICA_RECORD_SET_STATES),ReplicaRecordSetViewSchema=external_exports.object({slug:external_exports.string().min(1),layerName:external_exports.string().min(1).optional(),loadStrategy:external_exports.string().min(1),keyFields:external_exports.array(external_exports.string()).optional(),state:ReplicaRecordSetStateSchema,sourceName:external_exports.string().min(1).optional(),landedVersion:external_exports.number().int().nonnegative().optional(),rowCount:external_exports.number().int().nonnegative().optional(),landedAt:external_exports.string().optional()}),ReplicaLandingsReadSchema=external_exports.enum(["ok","unavailable"]),ReplicaViewSchema=external_exports.object({datasetId:CatalogDatasetIdSchema,slug:external_exports.string().min(1),title:external_exports.string().min(1),importOperation:external_exports.object({slug:external_exports.string().min(1),enabled:external_exports.boolean()}).optional(),landingsRead:ReplicaLandingsReadSchema,recordSets:external_exports.array(ReplicaRecordSetViewSchema)}),ExternalDatasetViewSchema=external_exports.object({externalDatasetId:CatalogDatasetIdSchema,title:external_exports.string().min(1),connectionRef:ConnectionRefSchema,locator:ReplicaLocatorSchema.optional(),locatorUnreadable:external_exports.literal(!0).optional(),replicas:external_exports.array(ReplicaViewSchema)}),ListConnectionReplicasInputSchema=external_exports.strictObject({connectionRef:ConnectionRefSchema}),ConnectionReplicasSchema=external_exports.object({connectionRef:ConnectionRefSchema,externalDatasets:external_exports.array(ExternalDatasetViewSchema)}),REPLICA_REFUSAL_CODES={REPLICA_CONFLICT:"REPLICA_CONFLICT",REPLICA_VALIDATION:"REPLICA_VALIDATION",SERVICE_NOT_FOUND:"SERVICE_NOT_FOUND",PARTIAL_DECLARE:"PARTIAL_DECLARE",REPLICA_RETIRE_BLOCKED:"REPLICA_RETIRE_BLOCKED",PARTIAL_RETIRE:"PARTIAL_RETIRE",REPLICA_NOT_FOUND:"REPLICA_NOT_FOUND",REPLICA_CATALOG_UNAVAILABLE:"REPLICA_CATALOG_UNAVAILABLE",REPLICA_FILL_UNREADABLE:"REPLICA_FILL_UNREADABLE",REPLICA_FILL_PENDING:"REPLICA_FILL_PENDING"},REPLICA_DECLARE_STEPS=["external-dataset","distributions","replica-dataset","record-sets","import-operation","link-operation"],ReplicaDeclareStepSchema=external_exports.enum(REPLICA_DECLARE_STEPS),PartialDeclareDataSchema=external_exports.object({code:external_exports.literal(REPLICA_REFUSAL_CODES.PARTIAL_DECLARE),completed:external_exports.array(ReplicaDeclareStepSchema),failed:ReplicaDeclareStepSchema,written:external_exports.array(external_exports.string().min(1))}),REPLICA_RETIRE_STEPS=["disable-operation","detach-dataset","delete-operation","delete-external","archive-studio-rows"],ReplicaRetireStepSchema=external_exports.enum(REPLICA_RETIRE_STEPS),REPLICA_RETIRE_STEP_OUTCOMES=["done","already-gone"],ReplicaRetireStepOutcomeSchema=external_exports.enum(REPLICA_RETIRE_STEP_OUTCOMES),RetireReplicaInputSchema=external_exports.strictObject({replicaSlug:ReplicaSlugSchema,connectionRef:ConnectionRefSchema.optional(),idempotencyKey:IdempotencyKeySchema}),ReplicaRetirementSchema=external_exports.object({replicaSlug:ReplicaSlugSchema,retained:external_exports.object({datasetId:CatalogDatasetIdSchema,status:external_exports.literal("deprecated")}).optional(),steps:external_exports.array(external_exports.object({step:ReplicaRetireStepSchema,outcome:ReplicaRetireStepOutcomeSchema})).length(REPLICA_RETIRE_STEPS.length),archived:external_exports.array(external_exports.string().min(1)),retiredAt:external_exports.iso.datetime()}),ReplicaRetireBlockedDataSchema=external_exports.object({code:external_exports.literal(REPLICA_REFUSAL_CODES.REPLICA_RETIRE_BLOCKED),step:ReplicaRetireStepSchema,blockers:external_exports.array(external_exports.string().min(1)).min(1),completed:external_exports.array(ReplicaRetireStepSchema),hint:external_exports.string().min(1)}),PartialRetireDataSchema=external_exports.object({code:external_exports.literal(REPLICA_REFUSAL_CODES.PARTIAL_RETIRE),completed:external_exports.array(ReplicaRetireStepSchema),failed:ReplicaRetireStepSchema,remaining:external_exports.array(ReplicaRetireStepSchema),written:external_exports.array(external_exports.string().min(1))});var deltaSharingAccessUrlOf=(share,schema,table)=>`delta-sharing://${share}/${schema}/${table}`,DELTA_SHARING_ACCESS_URL=/^delta-sharing:\/\/([^/]+)\/([^/]+)\/([^/]+)$/,parseDeltaSharingAccessUrl=accessURL=>{let match=DELTA_SHARING_ACCESS_URL.exec(accessURL);if(match===null)return;let[,share,schema,table]=match;return share===void 0||schema===void 0||table===void 0?void 0:{share,schema,table}};var ObserveReplicaDatasetInputSchema=external_exports.strictObject({replicaDatasetId:CatalogDatasetIdSchema,idempotencyKey:IdempotencyKeySchema}),ReplicaDatasetObservationSchema=external_exports.discriminatedUnion("state",[external_exports.object({state:external_exports.literal("processing")}),external_exports.object({state:external_exports.literal("ready"),datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,rowCount:external_exports.number().int().nonnegative().optional(),landedAt:external_exports.string().optional()})]),ReplicaLandingFactSchema=external_exports.object({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema}),MAX_RESOLVE_SDP_REFS=100,ResolveSdpDatasetRefsInputSchema=external_exports.strictObject({refs:external_exports.array(CatalogDatasetIdSchema).min(1).max(MAX_RESOLVE_SDP_REFS)}),SdpDatasetLinkSchema=external_exports.object({sdpDatasetRef:CatalogDatasetIdSchema,datasetId:DatasetIdSchema}),SdpDatasetLinksSchema=external_exports.array(SdpDatasetLinkSchema);var RECORD_ENVELOPE_COLUMNS=["record_id","logical_id","manifest_id","valid_from","valid_to","system_from","system_to","is_current"],ENVELOPE_PATTERN=new RegExp(`^(${RECORD_ENVELOPE_COLUMNS.join("|")})(_\\d+)?$`);var DatasetTargetSchema=external_exports.strictObject({datasetId:DatasetIdSchema}),ReplicaTargetSchema=external_exports.strictObject({connectionRef:ConnectionRefSchema,replicaSlug:ReplicaSlugSchema,recordSetSlug:external_exports.string().min(1)}),SetKeyFieldsTargetSchema=external_exports.union([DatasetTargetSchema,ReplicaTargetSchema]),SET_KEY_FIELDS_WIRE_MAX=MAX_REPLICA_KEY_FIELDS*4,SetKeyFieldsInputSchema=external_exports.strictObject({target:SetKeyFieldsTargetSchema,keyFields:external_exports.array(external_exports.string()).max(SET_KEY_FIELDS_WIRE_MAX),idempotencyKey:IdempotencyKeySchema}),SetKeyFieldsResultSchema=external_exports.object({recordSetId:external_exports.string().min(1),keyFields:external_exports.array(external_exports.string().min(1)).min(1)}),KEY_FIELDS_ISSUE_REASONS=["empty","blank","padded","envelope","repeated","control-character","too-long","too-many"];var ReplicaRecordSetColumnsInputSchema=external_exports.strictObject({connectionRef:ConnectionRefSchema,replicaSlug:ReplicaSlugSchema,recordSetSlug:external_exports.string().regex(CATALOG_SLUG_PATTERN,"a record set slug is the catalog slug grammar")}),ReplicaRecordSetColumnsSchema=external_exports.discriminatedUnion("profiled",[external_exports.object({profiled:external_exports.literal(!0),columns:external_exports.array(external_exports.object({name:external_exports.string().min(1),type:external_exports.string()})).min(1),version:external_exports.number().int().nonnegative().optional()}),external_exports.object({profiled:external_exports.literal(!1),columns:external_exports.tuple([])})]);var DELTA_SHARING_KIND="delta-sharing",DELTA_SHARING_SCHEME="delta-sharing://",deltaPathOf=containerPath=>{let[share,schema]=containerPath;if(containerPath.length!==2||share===void 0||schema===void 0)throw new Error(`a delta-sharing container path is [share, schema]; got ${String(containerPath.length)} segment(s)`);return{share,schema}},deltaSharingBuilder={connectorKind:DELTA_SHARING_KIND,accessUrlScheme:DELTA_SHARING_SCHEME,accessUrlOf:(containerPath,table)=>{let{share,schema}=deltaPathOf(containerPath);return deltaSharingAccessUrlOf(share,schema,table)},parseAccessUrl:accessUrl=>{let parsed=parseDeltaSharingAccessUrl(accessUrl);return parsed===void 0?void 0:{containerPath:[parsed.share,parsed.schema],table:parsed.table}},declarationOf:({locator,secretName})=>{let{share,schema}=deltaPathOf(locator.containerPath);return{tablestore:"delta-sharing",share,schema,tables:[...locator.tables],secretName}},usesShare:!0,declaringDistributionNeedsAccessService:!1,declaringDistributionFirst:!1,disjointnessScopedToConnection:!1,locatorRefusalOf:locator=>locator.containerPath.length===2?void 0:{reason:`a delta-sharing replica is read from a share and a schema; got ${String(locator.containerPath.length)} path segment(s)`},externalDescriptionOf:(containerPath,connectionId)=>{let{share,schema}=deltaPathOf(containerPath);return`External Delta Share tables ${share}/${schema} reached through connection ${connectionId}`},distributionTitleOf:(containerPath,table)=>{let{share,schema}=deltaPathOf(containerPath);return`${share}.${schema}.${table}`},credentialRequiredReason:"a delta-sharing import names the secret the engine reads the share with",wireLocatorOf:locator=>{let{share,schema}=deltaPathOf(locator.containerPath);return{share,schema,tables:[...locator.tables]}}},SNOWFLAKE_KIND="snowflake",SNOWFLAKE_SCHEME="snowflake://",snowflakePathOf=containerPath=>{let[schema]=containerPath;if(containerPath.length!==1||schema===void 0)throw new Error(`a snowflake container path is [schema]; got ${String(containerPath.length)} segment(s)`);return{schema}},snowflakeSegment=segment=>encodeURIComponent(segment),decodeSnowflakeSegment=raw=>{if(raw!=="")try{let decoded=decodeURIComponent(raw);return decoded!==""&&snowflakeSegment(decoded)===raw?decoded:void 0}catch{return}},SELECTOR_DELIMITERS=/[./*]/,isSnowflakeNameAddressable=name2=>!SELECTOR_DELIMITERS.test(name2),snowflakeUnaddressableReason=name2=>`"${name2}" cannot be declared from a Snowflake connection \u2014 a schema or table name may not contain ".", "/" or "*"`,isEncodable=name2=>{try{return encodeURIComponent(name2),!0}catch{return!1}},snowflakeBuilder={connectorKind:SNOWFLAKE_KIND,accessUrlScheme:SNOWFLAKE_SCHEME,accessUrlOf:(containerPath,table)=>{let{schema}=snowflakePathOf(containerPath);return`${SNOWFLAKE_SCHEME}${snowflakeSegment(schema)}/${snowflakeSegment(table)}`},parseAccessUrl:accessUrl=>{if(!accessUrl.startsWith(SNOWFLAKE_SCHEME))return;let parts=accessUrl.slice(SNOWFLAKE_SCHEME.length).split("/");if(parts.length!==2)return;let[schema,table]=parts.map(decodeSnowflakeSegment);return schema===void 0||table===void 0?void 0:{containerPath:[schema],table}},declarationOf:({locator})=>{let{schema}=snowflakePathOf(locator.containerPath);return{tablestore:SNOWFLAKE_KIND,tables:locator.tables.map(table=>`${schema}.${table}`)}},externalDescriptionOf:(containerPath,connectionId)=>{let{schema}=snowflakePathOf(containerPath);return`External Snowflake tables ${schema} reached through connection ${connectionId}`},distributionTitleOf:(containerPath,table)=>{let{schema}=snowflakePathOf(containerPath);return`${schema}.${table}`},credentialRequiredReason:void 0,usesShare:!1,declaringDistributionNeedsAccessService:!0,declaringDistributionFirst:!0,disjointnessScopedToConnection:!0,locatorRefusalOf:locator=>{if(locator.containerPath.length!==1)return{reason:`a snowflake replica is read from a schema; got ${String(locator.containerPath.length)} path segment(s)`};let[schema]=locator.containerPath,unencodableReason="a Snowflake schema or table name must be well-formed text (it contains an unpaired surrogate character)";if(!isEncodable(schema??""))return{reason:unencodableReason,field:"schema"};let unencodableTable=locator.tables.find(name2=>!isEncodable(name2));if(unencodableTable!==void 0)return{reason:unencodableReason,field:"tables",table:unencodableTable};if(!isSnowflakeNameAddressable(schema??""))return{reason:snowflakeUnaddressableReason(schema??""),field:"schema"};let unaddressableTable=locator.tables.find(name2=>!isSnowflakeNameAddressable(name2));return unaddressableTable===void 0?void 0:{reason:snowflakeUnaddressableReason(unaddressableTable),field:"tables",table:unaddressableTable}},wireLocatorOf:locator=>{let{schema}=snowflakePathOf(locator.containerPath);return{schema,tables:[...locator.tables]}}},REPLICA_KIND_BUILDERS=new Map([[deltaSharingBuilder.connectorKind,deltaSharingBuilder],[snowflakeBuilder.connectorKind,snowflakeBuilder]]);var ReplicaCursorEntrySchema=external_exports.object({recordSet:external_exports.string().min(1).regex(/^[^,@]+$/,'a record-set slug may not contain "," or "@" \u2014 see the injectivity guard'),landed:external_exports.boolean(),landedVersion:external_exports.number().int().nonnegative().max(2147483647).optional(),landedAt:external_exports.string().optional(),manifestId:external_exports.string().min(1).optional(),landingName:external_exports.string().min(1).optional()}),ReplicaCursorVectorSchema=external_exports.array(ReplicaCursorEntrySchema);var ReplicaDeliveryVersionSchema=external_exports.object({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema}),ReplicaDeliveryFactSchema=external_exports.object({versions:external_exports.array(ReplicaDeliveryVersionSchema).min(1),cursor:ReplicaCursorVectorSchema}),OBSERVE_REPLICA_DELIVERY_VERB="observeReplicaDelivery",OBSERVE_REPLICA_DELIVERY_ACTION=`datasets.${OBSERVE_REPLICA_DELIVERY_VERB}`;var LANDED_ORIGINS=["delivery","upload","output"],LandedOriginSchema=external_exports.enum(LANDED_ORIGINS),VersionLandedFactSchema=external_exports.strictObject({origin:LandedOriginSchema,datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,captureId:external_exports.string().min(1).optional(),sourceId:external_exports.string().min(1).optional(),filename:external_exports.string().min(1).optional()}),OBSERVE_VERSION_LANDED_VERB="observeVersionLanded",OBSERVE_VERSION_LANDED_ACTION=`datasets.${OBSERVE_VERSION_LANDED_VERB}`;var ImportJobIdSchema=external_exports.uuid().brand(),ImportJobStateSchema=external_exports.enum(["PENDING","RUNNING","COMPLETED","FAILED"]);var ImportJobRefSchema=external_exports.strictObject({jobId:ImportJobIdSchema,state:ImportJobStateSchema});var ImportJobStatusInputSchema=external_exports.strictObject({jobId:ImportJobIdSchema});var ImportJobStatusSchema=external_exports.strictObject({jobId:ImportJobIdSchema,state:ImportJobStateSchema,attempt:external_exports.number().int().positive(),datasetId:DatasetIdSchema.optional(),versionId:DatasetVersionIdSchema.optional(),rowsLoaded:external_exports.number().int().nonnegative().optional(),outputs:external_exports.array(SourceTransformationRunOutputSchema).optional(),landingOutputs:external_exports.array(SourceTransformationRunLandingOutputSchema).optional(),runRecordId:external_exports.string().min(1).optional(),failureDetail:external_exports.string().optional(),failureCode:external_exports.enum([RUN_ENGINE_BUSY,DIRECTORY_SLOT_UNAVAILABLE]).optional(),engineBusy:EngineBusySchema.optional(),engineWait:EngineWaitSchema.optional(),progress:TransformationRunProgressSchema.optional(),restartReason:external_exports.string().optional(),startedAt:external_exports.iso.datetime(),updatedAt:external_exports.iso.datetime()}),DEFAULT_MAX_SYNCHRONOUS_LAND_ROWS=25e3,DEFAULT_MAX_SYNCHRONOUS_LAND_BYTES=1536*1024,DEFAULT_MAX_SYNCHRONOUS_TRANSFORM_ROWS=8e3,DEFAULT_MAX_SYNCHRONOUS_TRANSFORM_BYTES=512*1024,IMPORT_JOB_MODES=["land","transform","declared"],ImportJobModeSchema=external_exports.enum(IMPORT_JOB_MODES);var DEFAULT_SYNCHRONOUS_IMPORT_LIMITS=Object.freeze({land:Object.freeze({rows:DEFAULT_MAX_SYNCHRONOUS_LAND_ROWS,bytes:DEFAULT_MAX_SYNCHRONOUS_LAND_BYTES}),transform:Object.freeze({rows:DEFAULT_MAX_SYNCHRONOUS_TRANSFORM_ROWS,bytes:DEFAULT_MAX_SYNCHRONOUS_TRANSFORM_BYTES})});var GetDatasetTransformationInputSchema=external_exports.object({datasetId:DatasetIdSchema}),DatasetTransformationSummarySchema=external_exports.object({get specId(){return TransformSpecIdSchema},name:external_exports.string().min(1),version:external_exports.number().int().positive(),savedAt:external_exports.iso.datetime(),get sources(){return external_exports.array(RecipeSourceSchema).min(1)},get result(){return RecipeResultSchema}}),ListDatasetTransformationsInputSchema=external_exports.object({take:external_exports.number().int().min(1).max(1e3).optional()});var CorrectionCellValueSchema=DatasetCellValueSchema,CorrectionEditSchema=external_exports.discriminatedUnion("kind",[external_exports.object({kind:external_exports.literal("set-cell"),rowKey:external_exports.string().min(1),column:external_exports.string().min(1),from:CorrectionCellValueSchema,to:CorrectionCellValueSchema}),external_exports.object({kind:external_exports.literal("drop-row"),rowKey:external_exports.string().min(1)})]),CORRECTION_MAX_EDITS=500,CorrectionRecordParamsSchema=external_exports.object({datasetId:external_exports.string().min(1),sourceVersionId:external_exports.string().min(1),keyColumn:external_exports.string().min(1),reason:external_exports.string().min(1),citations:external_exports.array(CitationSchema).min(1),edits:external_exports.array(CorrectionEditSchema).min(1).max(CORRECTION_MAX_EDITS)}),GetCorrectionReceiptInputSchema=external_exports.object({correctionRecordId:external_exports.string().min(1)}),CorrectionReceiptSchema=external_exports.object({correctionRecordId:external_exports.string().min(1),status:external_exports.enum(["in-flight","committed","failed"]),datasetId:external_exports.string().min(1),sourceVersionId:external_exports.string().min(1),correctedVersionId:external_exports.string().min(1).optional(),keyColumn:external_exports.string().min(1),reason:external_exports.string().min(1),citations:external_exports.array(CitationSchema).min(1),edits:external_exports.array(CorrectionEditSchema).min(1).max(CORRECTION_MAX_EDITS),actor:external_exports.string().min(1).optional(),openedAt:external_exports.iso.datetime().optional(),detail:external_exports.string().optional(),engine:SourceTransformationRunEngineSchema.optional().describe("The engine this correction declared beside the engine that actually ran it. ABSENT on a receipt sealed before the engine was recorded; `actual` is null when no engine answered in the attempt that sealed. A correction always declares `cli`, so this pair names the engine rather than detecting drift from a declaration.")});var RunQualityCheckInputSchema=external_exports.strictObject({rulesetId:ValidationRulesetIdSchema,rulesetVersion:external_exports.number().int().positive(),datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,idempotencyKey:IdempotencyKeySchema});var QualityRunStoredFindingsSchema=external_exports.object({perRuleLimit:external_exports.number().int().positive(),cappedRuleIndexes:external_exports.array(external_exports.number().int().nonnegative()).max(VALIDATION_RULES_MAX)}),QualityRunSummarySchema=external_exports.object({rowsChecked:external_exports.number().int().nonnegative(),rowsWithFinding:external_exports.number().int().nonnegative(),cellsFlagged:external_exports.number().int().nonnegative(),cellsNotEvaluated:external_exports.number().int().nonnegative(),recordDistribution:ValidationRecordDistributionSchema,perRule:external_exports.array(ValidationRuleTallySchema).max(VALIDATION_RULES_MAX),storedFindings:QualityRunStoredFindingsSchema.optional()}),QualityRunRecordParamsSchema=external_exports.object({rulesetId:external_exports.string().min(1),rulesetVersion:external_exports.number().int().positive(),datasetId:external_exports.string().min(1),versionId:external_exports.string().min(1),reason:external_exports.string().min(1).max(500).optional()}),GetQualityRunInputSchema=external_exports.object({qualityRunId:external_exports.string().min(1)}),QualityRunRefusalSchema=external_exports.object({code:external_exports.string().min(1),message:external_exports.string().min(1).max(500)}),QualityRunReceiptSchema=external_exports.object({qualityRunId:external_exports.string().min(1),status:external_exports.enum(["in-flight","committed","failed"]),rulesetId:external_exports.string().min(1),rulesetVersion:external_exports.number().int().positive(),datasetId:external_exports.string().min(1).meta(DATASET_ENTITY_HINT),versionId:external_exports.string().min(1),summary:QualityRunSummarySchema.optional(),refusal:QualityRunRefusalSchema.optional(),actor:external_exports.string().min(1).optional(),reason:external_exports.string().min(1).optional(),ranAt:external_exports.iso.datetime().optional()}),RunQualityCheckResultSchema=QualityRunReceiptSchema.extend({replayed:external_exports.boolean()}),QualityRunExecutionSchema=external_exports.enum(["background","synchronous"]),ListQualityRunsInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,rulesetId:ValidationRulesetIdSchema.optional(),rulesetVersion:external_exports.number().int().positive().optional(),execution:QualityRunExecutionSchema.optional(),take:external_exports.number().int().min(1).max(1e3).optional().describe(`How many runs to return, 1\u2013${1e3}; defaults to ${100}. An ask above the maximum is REFUSED, not clamped.`),cursor:external_exports.string().min(1).optional()}),QualityRunPageSchema=external_exports.object({items:external_exports.array(QualityRunReceiptSchema),nextCursor:external_exports.string().min(1).nullable()}),ListQualityRunFindingsInputSchema=external_exports.strictObject({qualityRunId:external_exports.string().min(1),findings:ValidationViolationWindowSchema.optional()});var StartQualityRunInputSchema=RunQualityCheckInputSchema,QualityRunJobStateSchema=external_exports.enum(["PENDING","RUNNING","COMPLETED","FAILED"]);var StartQualityRunResultSchema=external_exports.strictObject({qualityRunId:external_exports.string().min(1),state:QualityRunJobStateSchema,joined:external_exports.boolean(),replayed:external_exports.boolean()});var QualityRunStatusInputSchema=external_exports.strictObject({qualityRunId:external_exports.string().min(1)}),QualityRunStatusSchema=external_exports.strictObject({qualityRunId:external_exports.string().min(1),state:QualityRunJobStateSchema,execution:QualityRunExecutionSchema,rowsChecked:external_exports.number().int().nonnegative(),rowsTotal:external_exports.number().int().nonnegative().optional(),attempt:external_exports.number().int().positive().optional(),runRecordId:external_exports.string().min(1).optional(),summary:QualityRunSummarySchema.optional(),refusal:QualityRunRefusalSchema.optional(),engineWait:EngineWaitSchema.optional(),engineBusy:EngineBusySchema.optional(),startedAt:external_exports.iso.datetime(),updatedAt:external_exports.iso.datetime()}),QualityRunCompletionDetailSchema=QualityRunSummarySchema.pick({rowsChecked:!0,rowsWithFinding:!0,cellsFlagged:!0,cellsNotEvaluated:!0,recordDistribution:!0});var INPUT_MARKER_SCOPE_MAX_LENGTH=128,InputMarkerScopeSchema=external_exports.string().max(INPUT_MARKER_SCOPE_MAX_LENGTH).regex(/^[A-Za-z0-9_][A-Za-z0-9_.:-]*$/,"a scope is a letter, digit or underscore, then letters, digits, underscores, dots, colons or hyphens"),InputFingerprintSchema=external_exports.string().regex(/^[0-9a-f]{64}$/,"a fingerprint is the 64-character hex a lookup step answers"),InputMarkerInputSchema=external_exports.strictObject({scope:InputMarkerScopeSchema,fingerprint:InputFingerprintSchema,idempotencyKey:IdempotencyKeySchema}),CheckInputsChangedInputSchema=InputMarkerInputSchema,MarkInputsProcessedInputSchema=InputMarkerInputSchema,BuiltDefinitionSchema=external_exports.strictObject({type:external_exports.enum(["source-transformation","transform-spec"]),id:external_exports.string().min(1),version:external_exports.number().int().min(1),newest:external_exports.number().int().min(1),pinned:external_exports.boolean()}),RunBuildsShape={built:external_exports.array(BuiltDefinitionSchema),builds:external_exports.array(external_exports.string().min(1)),pendingJobs:external_exports.array(external_exports.string().min(1))},InputMarkerSchema=external_exports.strictObject({recordId:external_exports.string(),fingerprint:InputFingerprintSchema,definitionVersion:external_exports.number().int().min(1).nullable().optional(),built:RunBuildsShape.built.optional(),builds:RunBuildsShape.builds.optional(),pendingJobs:RunBuildsShape.pendingJobs.optional(),markedAt:external_exports.iso.datetime()}),CheckInputsChangedResultSchema=external_exports.strictObject({changed:external_exports.boolean(),scope:InputMarkerScopeSchema,fingerprint:InputFingerprintSchema,lastProcessed:InputMarkerSchema.nullable()});var MarkInputsProcessedResultSchema=external_exports.strictObject({scope:InputMarkerScopeSchema,fingerprint:InputFingerprintSchema,...RunBuildsShape});var DATASET_NO_PROMOTED_VERSION="DATASET_NO_PROMOTED_VERSION",DATASET_ARCHIVED="DATASET_ARCHIVED",RESOLVE_PROMOTED_VERSIONS_MAX_SLOTS=64,ResolveSlotNameSchema=external_exports.string().regex(/^[A-Za-z_][A-Za-z0-9_-]*$/,"a slot name must be a flow path segment: a letter or underscore, then letters, digits, underscores or hyphens"),RESOLVE_PROMOTED_VERSIONS_MAX_DATASET_ID_LENGTH=128,ResolvePromotedVersionsDatasetsSchema=external_exports.record(ResolveSlotNameSchema,DatasetIdSchema.max(RESOLVE_PROMOTED_VERSIONS_MAX_DATASET_ID_LENGTH,`a dataset id is at most ${String(RESOLVE_PROMOTED_VERSIONS_MAX_DATASET_ID_LENGTH)} characters`)).refine(datasets=>Object.keys(datasets).length>=1,"name at least one dataset to resolve").refine(datasets=>Object.keys(datasets).length<=RESOLVE_PROMOTED_VERSIONS_MAX_SLOTS,`resolve at most ${String(RESOLVE_PROMOTED_VERSIONS_MAX_SLOTS)} datasets per call`),ResolvePromotedVersionsInputSchema=external_exports.strictObject({datasets:ResolvePromotedVersionsDatasetsSchema,idempotencyKey:IdempotencyKeySchema}),PinnedDatasetRefSchema=DatasetRefSchema.required(),ResolvedPromotedVersionSchema=external_exports.object({slot:ResolveSlotNameSchema,...PinnedDatasetRefSchema.shape,loadNumber:external_exports.number().int().positive(),promotedAt:external_exports.iso.datetime()}),ResolveUnresolvedReasonSchema=external_exports.enum([DATASET_NO_PROMOTED_VERSION]),UnresolvedPromotedVersionSchema=external_exports.strictObject({slot:ResolveSlotNameSchema,datasetId:DatasetIdSchema,reason:ResolveUnresolvedReasonSchema}),ResolvedPromotedVersionsAnswerSchema=external_exports.strictObject({status:external_exports.literal("resolved"),inputs:external_exports.record(ResolveSlotNameSchema,DatasetVersionInputBindingSchema),refs:external_exports.record(ResolveSlotNameSchema,PinnedDatasetRefSchema),resolved:external_exports.array(ResolvedPromotedVersionSchema),fingerprint:InputFingerprintSchema.optional()}),UnresolvedPromotedVersionsAnswerSchema=external_exports.strictObject({status:external_exports.literal("unresolved"),unresolved:external_exports.array(UnresolvedPromotedVersionSchema).min(1),resolved:external_exports.array(ResolvedPromotedVersionSchema)}),ResolvePromotedVersionsResultSchema=external_exports.discriminatedUnion("status",[ResolvedPromotedVersionsAnswerSchema,UnresolvedPromotedVersionsAnswerSchema]);var REFUSAL_SENTENCES={DATASET_NOT_FOUND:slot3=>`slot "${slot3}": dataset not found`,DATASET_READ_LIVE_UNSUPPORTED:slot3=>`slot "${slot3}" names a live dataset \u2014 its rows are computed when they are read rather than stored here, so there is no promoted load to pin; capture it to a frozen dataset and name that`,[DATASET_ARCHIVED]:slot3=>`slot "${slot3}" names an archived dataset \u2014 it is retired and its last promoted load is no longer current; name its replacement, or restore it first`};var DATASET_NO_VERSION="DATASET_NO_VERSION",DATASET_POINTER_DANGLING="DATASET_POINTER_DANGLING",DATASET_VERSION_UNSETTLED="DATASET_VERSION_UNSETTLED",ResolveLatestVersionsInputSchema=ResolvePromotedVersionsInputSchema,ResolvedLatestVersionSchema=ResolvedPromotedVersionSchema.extend({promoted:external_exports.boolean(),promotedAt:external_exports.iso.datetime().nullable()}),UnresolvedLatestVersionSchema=UnresolvedPromotedVersionSchema.extend({reason:external_exports.enum([DATASET_NO_VERSION,DATASET_POINTER_DANGLING,DATASET_VERSION_UNSETTLED])}),ResolvedLatestVersionsAnswerSchema=ResolvedPromotedVersionsAnswerSchema.extend({resolved:external_exports.array(ResolvedLatestVersionSchema)}),UnresolvedLatestVersionsAnswerSchema=UnresolvedPromotedVersionsAnswerSchema.extend({unresolved:external_exports.array(UnresolvedLatestVersionSchema).min(1),resolved:external_exports.array(ResolvedLatestVersionSchema)}),ResolveLatestVersionsResultSchema=external_exports.discriminatedUnion("status",[ResolvedLatestVersionsAnswerSchema,UnresolvedLatestVersionsAnswerSchema]);var QUALITY_CHECKS_VERB="runQualityChecks",QUALITY_CHECKS_ACTION_NAME=`datasets.${QUALITY_CHECKS_VERB}`;var QUALITY_CHECKS_RUNS_MAX=128;var QualityChecksSlotSchema=external_exports.string().max(64).regex(JOB_FIELD_PATTERN,"a table slot must be a walkable name: a letter or _, then letters, digits, _ or -"),QualityChecksTableSchema=external_exports.object({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema}),QualityChecksTablesSchema=external_exports.record(QualityChecksSlotSchema,QualityChecksTableSchema),QualityChecksTablesWireSchema=boundedRecord2(QualityChecksSlotSchema,QualityChecksTableSchema,QUALITY_CHECKS_TABLES_WIRE_MAX,"tables",{min:1}),StartQualityChecksInputSchema=external_exports.strictObject({tables:QualityChecksTablesWireSchema,idempotencyKey:IdempotencyKeySchema}),QualityCheckPinSchema=external_exports.object({slot:QualityChecksSlotSchema,datasetId:external_exports.string().min(1),versionId:external_exports.string().min(1),rulesetId:external_exports.string().min(1),rulesetVersion:external_exports.number().int().positive(),qualityRunId:external_exports.string().min(1),joined:external_exports.boolean()}),StartQualityChecksResultSchema=external_exports.strictObject({qualityChecksId:external_exports.string().min(1),state:QualityRunJobStateSchema,replayed:external_exports.boolean(),checks:external_exports.array(QualityCheckPinSchema).max(QUALITY_CHECKS_RUNS_MAX)}),QualityChecksCountsSchema=external_exports.object({rulesetsChecked:external_exports.number().int().nonnegative(),rowsChecked:external_exports.number().int().nonnegative(),failedRecords:external_exports.number().int().nonnegative(),uncertainRecords:external_exports.number().int().nonnegative(),rulesNeverApplied:external_exports.number().int().nonnegative()}),QualityChecksTotalsSchema=external_exports.object({tablesChecked:external_exports.number().int().nonnegative(),tablesWithoutRulesets:external_exports.number().int().nonnegative(),tablesWithNoRows:external_exports.number().int().nonnegative(),...QualityChecksCountsSchema.shape});var QualityChecksTotalsWithVerdictSchema=QualityChecksTotalsSchema.extend({passed:external_exports.boolean()}),QualityChecksRulesetResultSchema=external_exports.object({rulesetId:external_exports.string().min(1),rulesetVersion:external_exports.number().int().positive(),qualityRunId:external_exports.string().min(1),recordDistribution:ValidationRecordDistributionSchema}),QualityChecksTableResultSchema=external_exports.object({datasetId:external_exports.string().min(1),versionId:external_exports.string().min(1),...QualityChecksCountsSchema.shape,rulesets:external_exports.array(QualityChecksRulesetResultSchema).max(QUALITY_CHECKS_RUNS_MAX)}),QualityChecksResultSchema=QualityChecksTotalsWithVerdictSchema.extend({tables:external_exports.record(QualityChecksSlotSchema,QualityChecksTableResultSchema)}),QualityChecksCompletionDetailSchema=QualityChecksTotalsWithVerdictSchema.extend({tables:external_exports.record(QualityChecksSlotSchema,QualityChecksTableResultSchema.omit({rulesets:!0}))}),QualityChecksFailureSchema=external_exports.object({slot:QualityChecksSlotSchema,rulesetId:external_exports.string().min(1),rulesetVersion:external_exports.number().int().positive(),qualityRunId:external_exports.string().min(1),code:external_exports.string().min(1)}),QualityChecksRefusalSchema=external_exports.object({code:external_exports.string().min(1),message:external_exports.string().min(1).max(500),failures:external_exports.array(QualityChecksFailureSchema).min(1).max(QUALITY_CHECKS_RUNS_MAX)}),QualityChecksStatusInputSchema=external_exports.strictObject({qualityChecksId:external_exports.string().min(1)}),QualityChecksStatusSchema=external_exports.strictObject({qualityChecksId:external_exports.string().min(1),state:QualityRunJobStateSchema,runsTotal:external_exports.number().int().nonnegative(),runsFinished:external_exports.number().int().nonnegative(),runRecordId:external_exports.string().min(1).optional(),result:QualityChecksResultSchema.optional(),refusal:QualityChecksRefusalSchema.optional(),startedAt:external_exports.iso.datetime(),updatedAt:external_exports.iso.datetime()});var StartSourceTransformationDryRunInputSchema=PreviewSourceTransformationInputSchema,SourceTransformationDryRunStateSchema=external_exports.enum(["queued","running","succeeded","failed"]);var SourceTransformationDryRunPhaseSchema=external_exports.enum(["materializing-inputs","running","collecting-result"]),SourceTransformationDryRunSlotProgressSchema=external_exports.strictObject({rowsCopied:external_exports.number().int().nonnegative(),rowsTotal:external_exports.number().int().nonnegative().optional(),done:external_exports.boolean()}),SourceTransformationDryRunProgressSchema=external_exports.record(external_exports.string().min(1),SourceTransformationDryRunSlotProgressSchema),SourceTransformationDryRunResultSchema=external_exports.strictObject({columns:external_exports.array(external_exports.string()),rows:external_exports.array(external_exports.record(external_exports.string(),external_exports.string())),rowCount:external_exports.number().int().nonnegative()}),SourceTransformationDryRunFailureSchema=external_exports.strictObject({code:external_exports.string().min(1),message:external_exports.string().min(1)}),StartSourceTransformationDryRunResultSchema=external_exports.strictObject({dryRunId:external_exports.string().min(1),state:SourceTransformationDryRunStateSchema,joined:external_exports.boolean()}),SourceTransformationDryRunStatusInputSchema=external_exports.strictObject({dryRunId:external_exports.string().min(1)}),SourceTransformationDryRunStatusSchema=external_exports.strictObject({dryRunId:external_exports.string().min(1),state:SourceTransformationDryRunStateSchema,phase:SourceTransformationDryRunPhaseSchema.optional(),progress:SourceTransformationDryRunProgressSchema,attempt:external_exports.number().int().positive().optional(),result:SourceTransformationDryRunResultSchema.optional(),failure:SourceTransformationDryRunFailureSchema.optional(),startedAt:external_exports.iso.datetime(),updatedAt:external_exports.iso.datetime(),finishedAt:external_exports.iso.datetime().optional(),expiresAt:external_exports.iso.datetime()}),SOURCE_TRANSFORMATION_DRY_RUN_RETENTION_MS=10080*60*1e3;var SOURCE_TRANSFORMATION_DRY_RUN_RESULT_MAX_BYTES=64*1024*1024;var SOURCE_TRANSFORMATION_DRY_RUN_RESULT_MAX_HELD_BYTES=32*1024*1024;var StartProfileRunInputSchema=DatasetRefSchema,DatasetProfileRunStateSchema=external_exports.enum(["queued","running","succeeded","failed"]);var StartProfileRunResultSchema=external_exports.strictObject({runId:external_exports.string().min(1),datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,state:DatasetProfileRunStateSchema,joined:external_exports.boolean()}),GetProfileRunInputSchema=DatasetRefSchema,DatasetProfileRunProgressSchema=external_exports.strictObject({rowsTotal:external_exports.number().int().nonnegative().optional(),columnsTotal:external_exports.number().int().nonnegative().optional(),columnsProfiled:external_exports.number().int().nonnegative()}),DatasetProfileRunFailureSchema=external_exports.strictObject({code:external_exports.string().min(1),reason:external_exports.string().min(1).optional(),message:external_exports.string().min(1)}),DatasetProfileRunSchema=external_exports.strictObject({runId:external_exports.string().min(1),state:DatasetProfileRunStateSchema,attempt:external_exports.number().int().positive().optional(),progress:DatasetProfileRunProgressSchema,failure:DatasetProfileRunFailureSchema.optional(),startedAt:external_exports.iso.datetime(),updatedAt:external_exports.iso.datetime(),finishedAt:external_exports.iso.datetime().optional()}),StoredDatasetProfileSchema=external_exports.strictObject({computedAt:external_exports.iso.datetime(),topValues:external_exports.number().int().positive(),buckets:external_exports.number().int().positive(),profile:DatasetProfileSchema}),EarlierStoredProfileSchema=external_exports.strictObject({versionId:DatasetVersionIdSchema,loadNumber:external_exports.number().int().positive(),loadedAt:external_exports.iso.datetime(),computedAt:external_exports.iso.datetime()}),DatasetProfileRunStatusSchema=external_exports.strictObject({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,loadNumber:external_exports.number().int().positive(),run:DatasetProfileRunSchema.optional(),profile:StoredDatasetProfileSchema.optional(),previous:EarlierStoredProfileSchema.optional()});var MovementFormatSchema=external_exports.enum(["csv","xlsx"]),MovementMediaTypeSchema=external_exports.enum(["text/csv","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/gzip"]);var MovementFilterSchema=external_exports.strictObject({search:external_exports.string().min(1).max(256).optional(),columnFilters:external_exports.array(DatasetReadFilterSchema).max(8).default([])}),MovementAssetColumnsSchema=external_exports.strictObject({column:DatasetReadColumnNameSchema,system:external_exports.string().min(1).max(64).regex(NO_CONTROL_CHARS,"an ID system may not contain control characters").optional()}),MovementEstimateInputSchema=external_exports.strictObject({ref:DatasetRefSchema,filters:MovementFilterSchema.optional(),assetColumns:MovementAssetColumnsSchema.optional()}),MovementEstimateSchema=external_exports.object({rowCount:external_exports.number().int().nonnegative(),promoted:external_exports.boolean(),versionId:DatasetVersionIdSchema,maxRows:external_exports.number().int().positive().optional(),assetColumns:external_exports.object({unmatchedRows:external_exports.number().int().nonnegative()}).optional()}),MovementRowOrderSchema=external_exports.enum(["none","shown"]),MovementExportInputSchema=external_exports.strictObject({ref:DatasetRefSchema,format:MovementFormatSchema,filters:MovementFilterSchema.optional(),order:MovementRowOrderSchema.optional(),orderBy:DatasetReadOrderBySchema.optional(),assetColumns:MovementAssetColumnsSchema.optional(),idempotencyKey:IdempotencyKeySchema.describe("Client-minted replay key for this export authorization \u2014 unique per (tenant, caller, key). A retry with the same key and the same selection replays the ONE recorded authorization and returns a FRESH grant (a new URL with a future expiry) \u2014 never the first call's possibly-expired URL, and never a second Record. A reused key with a DIFFERENT version, format or filter is refused, as is another caller's key. Mint a new key per intended export.")}),MovementGrantSchema=external_exports.object({url:external_exports.url(),headers:external_exports.record(external_exports.string(),external_exports.string()),expiresAt:external_exports.iso.datetime(),mediaType:MovementMediaTypeSchema,filename:external_exports.string().min(1),rowCount:external_exports.number().int().nonnegative()}),EXPORT_ENGINE_BUSY="EXPORT_ENGINE_BUSY",DatasetExportJobStateSchema=external_exports.enum(["PENDING","RUNNING","READY","FAILED"]);var MovementExportHandleSchema=external_exports.object({exportId:external_exports.string().min(1),state:DatasetExportJobStateSchema,rowCount:external_exports.number().int().nonnegative()}),MovementExportStatusInputSchema=external_exports.strictObject({exportId:external_exports.string().min(1)}),MovementExportStatusSchema=external_exports.discriminatedUnion("state",[external_exports.object({state:external_exports.literal("pending"),rowCount:external_exports.number().int().nonnegative(),engineWait:EngineWaitSchema.optional(),tilesDone:external_exports.number().int().nonnegative().optional(),tilesTotal:external_exports.number().int().nonnegative().optional()}),external_exports.object({state:external_exports.literal("ready"),grant:MovementGrantSchema,byteSize:external_exports.number().int().nonnegative()}),external_exports.object({state:external_exports.literal("failed"),reason:external_exports.string().min(1),retryable:external_exports.boolean(),code:external_exports.literal(EXPORT_ENGINE_BUSY).optional(),engineBusy:EngineBusySchema.optional()})]);var EXPORT_STORE_UNAVAILABLE="EXPORT_STORE_UNAVAILABLE",EXPORT_PRICING_TIMED_OUT="EXPORT_PRICING_TIMED_OUT",ExportServiceUnavailableDataSchema=external_exports.object({code:external_exports.enum([EXPORT_STORE_UNAVAILABLE,EXPORT_PRICING_TIMED_OUT])}),ExportStoreUnavailableDataSchema=external_exports.object({code:external_exports.literal(EXPORT_STORE_UNAVAILABLE)});var ImportRunStateSchema=external_exports.enum(["never-run","queued","running","succeeded","failed","canceled"]);var ImportRunFailureReasonSchema=external_exports.enum(["UnreadableTableError","UnsafePartitionKeyError","ReadLocationError","CustodyRefusedError","UnknownImportOperationError","DisabledImportOperationError","LaneMismatchError","UndescribedDatasetError","UndescribableDatasetError","UnknownShareTableError","VersionTagRefusedError","unassigned","ambiguous","unknown"]),ImportRunFailureSchema=external_exports.object({reason:ImportRunFailureReasonSchema,table:external_exports.string().min(1).optional(),code:external_exports.string().min(1).optional(),detail:external_exports.string().optional(),wireReason:external_exports.string().min(1).optional()}),ImportRunLandedRecordSetSchema=external_exports.object({recordSet:external_exports.string().min(1),manifestId:external_exports.string().min(1).optional(),sourceName:external_exports.string().min(1).optional(),rowCount:external_exports.number().int().nonnegative().optional()}),ImportRunSchema=external_exports.object({state:ImportRunStateSchema,runId:external_exports.string().min(1).optional(),partitionKey:external_exports.string().min(1).optional(),startedAt:external_exports.string().optional(),endedAt:external_exports.string().optional(),triggeredVia:external_exports.string().min(1).optional(),rowCount:external_exports.number().int().nonnegative().optional(),landed:external_exports.number().int().nonnegative().optional(),skipped:external_exports.number().int().nonnegative().optional(),replayed:external_exports.number().int().nonnegative().optional(),recordSets:external_exports.array(ImportRunLandedRecordSetSchema).optional(),failure:ImportRunFailureSchema.optional()}),OperationImportRunsSchema=external_exports.object({operationSlug:external_exports.string().min(1),summary:ImportRunSchema,runs:external_exports.array(ImportRunSchema)}),ImportRecordSetLandingSchema=external_exports.object({sourceName:external_exports.string().min(1).optional(),rowCount:external_exports.number().int().nonnegative().optional(),landedAt:external_exports.string().optional()}),DatasetImportRecordSetSchema=external_exports.object({recordSet:external_exports.string().min(1),operationSlug:external_exports.string().min(1).optional(),lastLanded:ImportRecordSetLandingSchema.optional(),lastRun:ImportRunSchema.optional()}),DatasetImportRunsSchema=external_exports.object({recordSets:external_exports.array(DatasetImportRecordSetSchema)}),IMPORT_RUNS_LIMIT_DEFAULT=5,IMPORT_RUNS_LIMIT_MAX=25,IMPORT_RUNS_LIMIT_MIN=1;var ListImportOperationRunsInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema,operationSlug:external_exports.string().min(1),limit:external_exports.number().int().min(IMPORT_RUNS_LIMIT_MIN).max(IMPORT_RUNS_LIMIT_MAX).optional().default(IMPORT_RUNS_LIMIT_DEFAULT)}),GetDatasetImportRunsInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema});var GetWalkupLandingStatusInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema}),WalkupLandingStateSchema=external_exports.object({state:external_exports.enum(["processing","ready","no-data-yet","stalled"]),rowCount:external_exports.number().int().nonnegative().optional(),landedAt:external_exports.string().optional()}),WalkupLayerLandingStatusSchema=WalkupLandingStateSchema.extend({datasetId:DatasetIdSchema}),WalkupLandingStatusSchema=WalkupLandingStateSchema.extend({layers:external_exports.array(WalkupLayerLandingStatusSchema).optional()}),WALKUP_LANDING_STALL_MS=3600*1e3,WalkupLandingAmbiguousDataSchema=external_exports.object({recordSets:external_exports.array(external_exports.string())});var WALKUP_COLUMN_TYPES=["VARCHAR","BIGINT","DOUBLE","BOOLEAN","DATE","TIMESTAMP"],WalkupColumnTypeSchema=external_exports.enum(WALKUP_COLUMN_TYPES),MAX_PINNED_COLUMN_NAME_LENGTH=255,MAX_PINNED_COLUMNS=512,PINNED_COLUMN_NAME=/^[^\p{Cc}\p{Cf}"'\\]{1,255}$/u,WalkupPinnedColumnNameSchema=external_exports.string().min(1).max(MAX_PINNED_COLUMN_NAME_LENGTH).regex(PINNED_COLUMN_NAME,"column name may not contain quotes, backslashes or control characters");var WalkupColumnTypesSchema=external_exports.record(WalkupPinnedColumnNameSchema,WalkupColumnTypeSchema).refine(types=>Object.keys(types).length<=MAX_PINNED_COLUMNS,{message:`at most ${MAX_PINNED_COLUMNS} column type pins may ride one declare`}),MAX_WALKUP_KEY_FIELDS=32,WalkupKeyFieldsSchema=external_exports.array(WalkupPinnedColumnNameSchema).min(1).max(MAX_WALKUP_KEY_FIELDS),CONNECTED_OUTPUT_COLUMN_TYPES=["VARCHAR","BIGINT","DOUBLE","BOOLEAN","TIMESTAMPTZ"],ConnectedOutputColumnTypeSchema=external_exports.enum(CONNECTED_OUTPUT_COLUMN_TYPES),ConnectedOutputColumnTypesSchema=external_exports.record(WalkupPinnedColumnNameSchema,ConnectedOutputColumnTypeSchema).refine(types=>Object.keys(types).length<=MAX_PINNED_COLUMNS,{message:`at most ${MAX_PINNED_COLUMNS} column type pins may ride one output`}),WalkupColumnTimezonesSchema=external_exports.record(WalkupPinnedColumnNameSchema,external_exports.string().min(1).max(64)).refine(zones=>Object.keys(zones).length<=MAX_PINNED_COLUMNS,{message:`at most ${MAX_PINNED_COLUMNS} column timezone declarations may ride one declare`}),WALKUP_FILE_FORMATS=["csv","parquet","json","geojson","filegdb","xlsx"],WalkupFileFormatSchema=external_exports.enum(WALKUP_FILE_FORMATS),DialectCharacterSchema=external_exports.string().length(1).regex(/^[^\p{Cc}\p{Cf}\p{Cs}\p{Cn}]$/u,"must be one printable character"),WalkupCsvDialectSchema=external_exports.strictObject({quote:DialectCharacterSchema.optional(),escape:DialectCharacterSchema.optional()}),MAX_LAYER_NAME_LENGTH=160,MAX_WALKUP_LAYERS=64,WalkupLayerNamesSchema=external_exports.array(external_exports.string().min(1).max(MAX_LAYER_NAME_LENGTH).regex(/^[^\p{Cc}\p{Cf}\p{Cs}]+$/u,"must not contain control characters")).min(1).max(MAX_WALKUP_LAYERS),WALKUP_DECLARE_KEY_MAX_LENGTH=200,WalkupDeclareIdempotencyKeySchema=IdempotencyKeySchema.max(WALKUP_DECLARE_KEY_MAX_LENGTH).describe("REQUIRED client-minted key for this import \u2014 YOU generate it (a UUID is fine), once per file you mean to import, and send the SAME key on every retry of that import. A retry under the same key resumes the same declare, and once it has declared it replays that answer: it never creates a second dataset. A key is pinned to the declaration it first carried; declaring anything else under it is refused (data.code KEY_PARAM_MISMATCH), so mint a new key for a new file or changed options."),WalkupDeclareInputSchema=external_exports.strictObject({idempotencyKey:WalkupDeclareIdempotencyKeySchema,fileName:external_exports.string().min(1),displayName:external_exports.string().min(1).optional(),columnTypes:WalkupColumnTypesSchema.optional(),columnTimezones:WalkupColumnTimezonesSchema.optional(),keyFields:WalkupKeyFieldsSchema.optional().describe("Optional. The ordered column names that identify one row across every upload of this dataset \u2014 its key fields. Set ONLY when the dataset is created and never changeable: without them, rows cannot be reviewed or corrected across uploads. Refused beside intoDatasetId (data.code WALKUP_DECLARE_KEY_FIELDS_ON_NEW_VERSION \u2014 a new version keeps its dataset's key), for a FileGDB or an Excel workbook (WALKUP_DECLARE_KEY_FIELDS_NOT_FOR_FORMAT), and when a name repeats (WALKUP_DECLARE_KEY_FIELDS_DUPLICATED)."),format:WalkupFileFormatSchema.optional(),csv:WalkupCsvDialectSchema.optional(),layers:WalkupLayerNamesSchema.optional().describe("A FileGDB (format filegdb) or an Excel workbook (format xlsx) only, and required for both: the layers, or the SHEET names, to import \u2014 each becomes its own dataset. Refused for any other format (data.code WALKUP_DECLARE_LAYERS_NOT_FOR_FORMAT)."),intoDatasetId:DatasetIdSchema.optional().describe("Optional. The id of an existing connected dataset that was created by uploading a file (`get` answers `acceptsUploadedVersions: true`). When set, the file lands as that dataset's NEXT VERSION instead of creating a new dataset: `fileName` names only the file, never the dataset. Refused for any other dataset (data.code WALKUP_UPLOAD_VERSION_NOT_UPLOADED), an archived one (WALKUP_UPLOAD_VERSION_ARCHIVED), an unknown id (WALKUP_UPLOAD_VERSION_UNKNOWN_DATASET), a geodatabase (WALKUP_UPLOAD_VERSION_FORMAT_UNSUPPORTED). A dataset `get` names a `sheetName` for is one sheet of an Excel workbook: its next version is format xlsx with layers naming that sheet alone \u2014 another sheet is refused WALKUP_UPLOAD_VERSION_SHEET_MISMATCH, another format (or a workbook into a single file's dataset) WALKUP_UPLOAD_VERSION_FORMAT_MISMATCH. Refused too: one with no landed version to follow yet (WALKUP_UPLOAD_VERSION_NO_LANDED_VERSION, CONFLICT \u2014 retry once its upload lands), and one with another new version still being declared (WALKUP_UPLOAD_VERSION_BUSY, CONFLICT \u2014 retry once that finishes); a resume under a key a newer upload has replaced is refused WALKUP_UPLOAD_VERSION_SUPERSEDED (CONFLICT, final \u2014 start again under a new key). Columns may differ from the previous version. Poll getWalkupLandingStatus as for a new import, then promote."),replaceStalledUpload:external_exports.boolean().optional().describe("Optional, with intoDatasetId only. The person has confirmed uploading a new version while the dataset's previous upload has STALLED (uploaded longer than the landing stall window ago and not landed): admitting the new version may lose that upload. Without it such a declare is refused CONFLICT (data.code WALKUP_PREVIOUS_UPLOAD_STALLED, with data.fileName when known and data.startedAt). An upload still within the window is refused WALKUP_UPLOAD_VERSION_PREVIOUS_LANDING whatever this says."),referenceChange:external_exports.strictObject({reason:external_exports.string().trim().min(1).max(500),changeType:ReferenceChangeTypeSchema}).optional().describe("Required with intoDatasetId when the dataset is a reference table (kind constant), and refused otherwise: the reason the values change and the change type (new-edition, publisher-errata or local-correction), stamped on the version this upload lands. Missing for a reference table: BAD_REQUEST (data.code REFERENCE_UPLOAD_CHANGE_REQUIRED); given for any other upload: BAD_REQUEST (REFERENCE_UPLOAD_CHANGE_NOT_REFERENCE).")}),WalkupDeclaredLayerSchema=external_exports.object({layerName:external_exports.string().min(1),datasetId:DatasetIdSchema,datasetSlug:external_exports.string().min(1),recordSet:external_exports.string().min(1),datasetName:external_exports.string().min(1).optional()}),WalkupDeclareResultSchema=external_exports.object({datasetId:DatasetIdSchema,datasetSlug:external_exports.string().min(1),operationSlug:external_exports.string().min(1),sdpDatasetRef:external_exports.string().min(1),reused:external_exports.boolean(),layers:external_exports.array(WalkupDeclaredLayerSchema).min(1).optional()}),WalkupDeclareOutputSchema=external_exports.discriminatedUnion("state",[WalkupDeclareResultSchema.extend({state:external_exports.literal("declared"),attemptId:external_exports.string().min(1)}),external_exports.object({state:external_exports.literal("declaring"),attemptId:external_exports.string().min(1)})]),WalkupDeclareAttemptStateSchema=external_exports.enum(["declaring","declared","refused"]),WALKUP_DECLARE_LEASE_MS=5*6e4,WALKUP_DECLARE_INTERRUPTED="WALKUP_DECLARE_INTERRUPTED",WALKUP_DECLARE_ERRORS={[WALKUP_DECLARE_INTERRUPTED]:{status:503,message:"The import is still being set up \u2014 try the same import again, and it continues where it stopped"}};var RecordIdentityInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema}),connected={recordSet:external_exports.string().min(1),loadStrategy:external_exports.string().min(1)},RecordIdentitySchema=external_exports.discriminatedUnion("state",[external_exports.object({state:external_exports.literal("keyed"),...connected,keyFields:external_exports.array(external_exports.string().min(1)).min(1)}),external_exports.object({state:external_exports.literal("keyless"),...connected}),external_exports.object({state:external_exports.literal("not-connected")})]);var REVIEW_READINESS_NOTICES=["none","live-feed","reloading","upload-again","run-again","produced-again"],ReviewReadinessInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema}),ReviewReadinessSchema=external_exports.object({notice:external_exports.enum(REVIEW_READINESS_NOTICES)});var MAX_WITHDRAW_REASON_LENGTH=500,WithdrawReviewActInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,withdraws:external_exports.string().min(1).max(200),records:external_exports.array(ReviewRecordRefSchema).min(1).max(MAX_REVIEW_SELECTION_RECORDS).optional(),body:ReviewBodySchema.max(MAX_WITHDRAW_REASON_LENGTH).optional(),idempotencyKey:IdempotencyKeySchema.max(200)});var MAX_CORRECT_CELLS=MAX_CORRECTION_ACT_ROWS,MAX_CORRECT_CELLS_SENT=10*MAX_CORRECT_CELLS,MAX_CORRECT_CELLS_COLUMNS=10,CorrectCellSchema=external_exports.strictObject({logicalId:external_exports.string().min(1).max(200),recordId:external_exports.string().min(1).max(200),column:external_exports.string().min(1).max(MAX_CORRECTION_COLUMN_LENGTH),from:DatasetCellValueSchema,value:DatasetCellValueSchema,keepTake:CellKeepTakeSchema.optional()}),CorrectCellsInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,cells:external_exports.array(CorrectCellSchema).min(1).max(MAX_CORRECT_CELLS_SENT),body:ReviewBodySchema,dryRun:external_exports.boolean().optional(),idempotencyKey:IdempotencyKeySchema.max(200)}),CORRECT_CELL_REFUSALS=["VALUE_NOT_STORABLE","KEY_COLUMN","LAKE_WRITTEN_COLUMN","COLUMN_NOT_IN_VERSION","NOT_A_NUMBER","ROW_NOT_IN_VERSION","FROM_UNREPRESENTABLE","VALUE_DOES_NOT_FIT","OVER_LIMIT"],CorrectCellRefusalSchema=external_exports.enum(CORRECT_CELL_REFUSALS),OUTCOME_CELL={logicalId:external_exports.string().min(1),column:external_exports.string().min(1)},RefusedCellOutcomeSchema=external_exports.discriminatedUnion("code",[external_exports.strictObject({...OUTCOME_CELL,result:external_exports.literal("refused"),code:external_exports.literal("VALUE_DOES_NOT_FIT"),type:external_exports.string().min(1)}),external_exports.strictObject({...OUTCOME_CELL,result:external_exports.literal("refused"),code:external_exports.enum(CORRECT_CELL_REFUSALS.filter(code2=>code2!=="VALUE_DOES_NOT_FIT"))})]),CorrectCellOutcomeSchema=external_exports.discriminatedUnion("result",[external_exports.strictObject({...OUTCOME_CELL,result:external_exports.literal("changed")}),external_exports.strictObject({...OUTCOME_CELL,result:external_exports.literal("unchanged")}),RefusedCellOutcomeSchema]),CorrectCellsResultSchema=external_exports.object({cells:external_exports.array(CorrectCellOutcomeSchema),acts:external_exports.array(ReviewActSchema),laterApply:external_exports.number().int().nonnegative(),checkedTypes:external_exports.array(external_exports.string().min(1)),lakeRead:external_exports.boolean()}),CORRECT_CELLS_REFUSED="CORRECT_CELLS_REFUSED",CorrectCellsRefusedDataSchema=external_exports.object({code:external_exports.literal(CORRECT_CELLS_REFUSED),cells:external_exports.array(RefusedCellOutcomeSchema),count:external_exports.number().int().positive()});var CORRECTED_DIFFERENCES_MAX=1e4;var CorrectedDifferencesInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema}),CORRECTED_DIFFERENCE_KINDS=["changed","left-out"],CorrectedDifferencesSchema=external_exports.discriminatedUnion("state",[external_exports.object({state:external_exports.literal("listed"),correctedDatasetId:DatasetIdSchema,correctedName:external_exports.string().min(1),builtFrom:external_exports.object({versionId:DatasetVersionIdSchema,loadNumber:external_exports.number().int().positive()}),rows:external_exports.array(external_exports.object({logicalId:external_exports.string().min(1),kind:external_exports.enum(CORRECTED_DIFFERENCE_KINDS)})).max(CORRECTED_DIFFERENCES_MAX),counts:external_exports.object({changed:external_exports.number().int().nonnegative(),leftOut:external_exports.number().int().nonnegative(),repeated:external_exports.number().int().nonnegative()})}),external_exports.object({state:external_exports.literal("unavailable"),reason:external_exports.enum(CORRECTED_ROWS_UNAVAILABLE_REASONS),message:external_exports.string().min(1).optional()})]);var LATER_CORRECTIONS_MAX_REFS=200;var LaterCorrectionsRefSchema=external_exports.strictObject({datasetId:external_exports.string().min(1),versionId:external_exports.string().min(1),producedAt:external_exports.iso.datetime()}),LaterCorrectionsInputSchema=external_exports.strictObject({refs:external_exports.array(LaterCorrectionsRefSchema).min(1).max(LATER_CORRECTIONS_MAX_REFS)}),VersionPointerSchema=external_exports.object({datasetId:external_exports.string().min(1),versionId:external_exports.string().min(1)}),CORRECTIONS_PIN_KINDS=["delivered","corrected"],LATER_CORRECTION_REASONS=["applied-after","newer-version"],LaterCorrectionsEntrySchema=external_exports.object({datasetId:external_exports.string().min(1),versionId:external_exports.string().min(1),producedAt:external_exports.iso.datetime(),applied:external_exports.boolean(),reason:external_exports.enum(LATER_CORRECTION_REASONS).optional(),unsure:external_exports.boolean().optional(),pinned:external_exports.enum(CORRECTIONS_PIN_KINDS).optional(),delivery:external_exports.object({datasetId:external_exports.string().min(1),name:external_exports.string().min(1),versionId:external_exports.string().min(1),loadNumber:external_exports.number().int().positive().optional()}).optional(),correctedDataset:external_exports.object({datasetId:external_exports.string().min(1),name:external_exports.string().min(1)}).optional(),newerDelivery:external_exports.object({versionId:external_exports.string().min(1),loadNumber:external_exports.number().int().positive().optional()}).optional(),rowsChanged:external_exports.number().int().nonnegative().optional(),reasons:external_exports.array(external_exports.string()),corrections:VersionPointerSchema.optional(),repin:VersionPointerSchema.optional()}),LaterCorrectionsSchema=external_exports.object({refs:external_exports.array(LaterCorrectionsEntrySchema)});var ReviewDeliverySchema=external_exports.object({versionId:DatasetVersionIdSchema,loadNumber:external_exports.number().int().nonnegative()}),ReviewBaselineMarkSchema=ReviewDeliverySchema.extend({markedBy:external_exports.string().min(1),markedAt:external_exports.iso.datetime()}),ReviewBaselineInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema}),ReviewBaselineSchema=external_exports.object({datasetId:DatasetIdSchema,baseline:ReviewBaselineMarkSchema.nullable(),current:ReviewDeliverySchema.nullable(),notYetReviewed:external_exports.number().int().nonnegative(),applyNotStarted:external_exports.object({code:external_exports.string().min(1),message:external_exports.string().min(1),remaining:external_exports.number().int().positive().optional()}).optional()}),MarkDeliveryReviewedInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,idempotencyKey:IdempotencyKeySchema.max(200)});var ChangesSinceReviewedInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema}),ChangesSinceReviewedSchema=external_exports.discriminatedUnion("state",[external_exports.object({state:external_exports.literal("never-marked"),datasetId:DatasetIdSchema}),external_exports.object({state:external_exports.literal("no-current-delivery"),datasetId:DatasetIdSchema,baseline:ReviewBaselineMarkSchema}),external_exports.object({state:external_exports.literal("current"),datasetId:DatasetIdSchema,baseline:ReviewBaselineMarkSchema}),external_exports.object({state:external_exports.literal("compared"),datasetId:DatasetIdSchema,baseline:ReviewBaselineMarkSchema,current:ReviewDeliverySchema,added:external_exports.number().int().nonnegative(),removed:external_exports.number().int().nonnegative(),changed:external_exports.number().int().nonnegative(),unidentifiedRows:external_exports.object({from:external_exports.number().int().nonnegative(),to:external_exports.number().int().nonnegative()})}),external_exports.object({state:external_exports.literal("not-comparable"),datasetId:DatasetIdSchema,baseline:ReviewBaselineMarkSchema,current:ReviewDeliverySchema,unkeyedSide:DatasetVersionDiffUnkeyedSideSchema})]);var SetReviewEnabledInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema,enabled:external_exports.boolean(),idempotencyKey:IdempotencyKeySchema.max(200)}),REVIEW_CORRECTED_COPY_STATES=["ready","creating","catching-up","behind","waiting","failed","archived","no-delivery","at-first-apply","retired","none"],ReviewCorrectedCopySchema=external_exports.enum(REVIEW_CORRECTED_COPY_STATES),ReviewEnabledViewSchema=external_exports.object({datasetId:DatasetIdSchema,reviewEnabled:external_exports.boolean(),correctedCopy:ReviewCorrectedCopySchema});var ReapplyCorrectionsKeySchema=IdempotencyKeySchema.max(512),ReapplyCorrectionsInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,idempotencyKey:ReapplyCorrectionsKeySchema}),REAPPLY_OUTCOMES=["started","joined","current","no-corrections","deferred","not-current","not-applicable"],ReapplyOutcomeSchema=external_exports.enum(REAPPLY_OUTCOMES),REAPPLY_STATES=["queued","running","completed","failed"],ReapplyStateSchema=external_exports.enum(REAPPLY_STATES),ReapplyCorrectionsResultSchema=external_exports.object({reapplyId:external_exports.string().min(1),state:ReapplyStateSchema,outcome:ReapplyOutcomeSchema,applyRecordId:external_exports.string().min(1).optional(),message:external_exports.string().min(1).optional(),replayed:external_exports.boolean()}),ReapplyCorrectionsAcceptDetailSchema=external_exports.object({reapplyId:external_exports.string().min(1),state:ReapplyStateSchema,outcome:ReapplyOutcomeSchema,datasetId:external_exports.string().min(1),sourceVersionId:external_exports.string().min(1),applyRecordId:external_exports.string().min(1).optional(),correctedVersionId:external_exports.string().min(1).optional(),message:external_exports.string().min(1).optional()}),ReapplyCorrectionsStatusInputSchema=external_exports.strictObject({reapplyId:external_exports.string().min(1)}),ReapplyCorrectionsStatusSchema=external_exports.strictObject({reapplyId:external_exports.string().min(1),state:ReapplyStateSchema,outcome:ReapplyOutcomeSchema,completionRecordId:external_exports.string().min(1).optional(),code:external_exports.string().min(1).optional(),error:external_exports.string().min(1).optional(),message:external_exports.string().min(1).optional()}),ReapplyCorrectionsCompletionDetailSchema=external_exports.object({outcome:ReapplyOutcomeSchema.optional(),datasetId:external_exports.string().min(1),sourceVersionId:external_exports.string().min(1),correctedVersionId:external_exports.string().min(1).optional()});var MAX_VERSION_CHANGES_PAGE=500;var MAX_VERSION_CHANGE_ID_LENGTH=200,VERSION_CHANGE_TYPES=["insert","delete","update"],VersionChangeTypeSchema=external_exports.enum(VERSION_CHANGE_TYPES),ListVersionChangesInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema,fromVersionId:DatasetVersionIdSchema,toVersionId:DatasetVersionIdSchema,cursor:external_exports.string().min(1).max(MAX_VERSION_CHANGE_ID_LENGTH).optional(),limit:external_exports.number().int().min(1).max(MAX_VERSION_CHANGES_PAGE).optional()}),VersionChangeImageSchema=external_exports.object({recordId:external_exports.string().min(1),values:external_exports.record(external_exports.string(),external_exports.unknown())}),VersionChangeSchema2=external_exports.object({logicalId:external_exports.string().min(1),changeType:VersionChangeTypeSchema,before:VersionChangeImageSchema.nullable(),after:VersionChangeImageSchema.nullable(),changedColumns:external_exports.array(external_exports.string())}),VersionChangesSchema=external_exports.discriminatedUnion("comparable",[external_exports.object({comparable:external_exports.literal(!0),fromVersionId:DatasetVersionIdSchema,toVersionId:DatasetVersionIdSchema,changes:external_exports.array(VersionChangeSchema2),nextCursor:external_exports.string().min(1).nullable(),unidentifiedRows:external_exports.object({from:external_exports.number().int().nonnegative(),to:external_exports.number().int().nonnegative()})}),external_exports.object({comparable:external_exports.literal(!1),fromVersionId:DatasetVersionIdSchema,toVersionId:DatasetVersionIdSchema,unkeyedSide:DatasetVersionDiffUnkeyedSideSchema})]);var REFERENCE_VALIDITY_COLUMNS={validFrom:"validFrom",validTo:"validTo"},REFERENCE_PROBLEMS_SHOWN_MAX=20,BoundTextSchema=external_exports.string().nullable(),ReferenceGroupSchema=external_exports.record(external_exports.string(),external_exports.string().nullable()),ReferenceRowBoundsSchema=external_exports.object({validFrom:BoundTextSchema,validTo:BoundTextSchema}),REFERENCE_WINDOW_PROBLEM_KINDS=["bad-bound","inverted","open-start","open-end","overlap","gap"],ReferenceWindowProblemSchema=external_exports.object({kind:external_exports.enum(REFERENCE_WINDOW_PROBLEM_KINDS),group:ReferenceGroupSchema,rows:external_exports.array(ReferenceRowBoundsSchema).min(1).max(2),column:external_exports.enum(["validFrom","validTo"]).optional(),from:external_exports.iso.date().optional(),to:external_exports.iso.date().optional()}),ReferenceSpanSchema=external_exports.object({from:external_exports.iso.date().nullable(),to:external_exports.iso.date().nullable()});var VALIDITY=new Set(Object.values(REFERENCE_VALIDITY_COLUMNS));var ReferenceCodelistNameSchema=external_exports.string().trim().min(3).max(128).regex(/^[a-z][a-z0-9_-]*(\.[a-z0-9_-]+)+$/);var ReferenceKeyCodelistsSchema=external_exports.record(external_exports.string().trim().min(1).max(128),ReferenceCodelistNameSchema),ReferenceCodelistProblemSchema=external_exports.object({group:ReferenceGroupSchema,row:ReferenceRowBoundsSchema,column:external_exports.string().min(1),code:external_exports.string(),codelist:external_exports.string().min(1),reason:external_exports.enum(["not-found","retired"]),suggestion:external_exports.string().min(1).optional()});var SetReferenceKeyCodelistsInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema,keyCodelists:ReferenceKeyCodelistsSchema,idempotencyKey:IdempotencyKeySchema.max(200)}),ReferenceKeyCodelistsAnswerSchema=external_exports.object({datasetId:DatasetIdSchema,keyCodelists:ReferenceKeyCodelistsSchema});var ReferenceCoverageProblemSchema=external_exports.object({group:ReferenceGroupSchema,from:external_exports.iso.date().nullable(),to:external_exports.iso.date().nullable()});var REFERENCE_ROW_SOURCE_COLUMN="source",REFERENCE_ROW_SOURCE_LINK_COLUMN="source_link",REFERENCE_ROW_SOURCE_COLUMNS=[REFERENCE_ROW_SOURCE_COLUMN,REFERENCE_ROW_SOURCE_LINK_COLUMN],RESERVED=new Set(REFERENCE_ROW_SOURCE_COLUMNS);var ReferenceSourceLinkProblemSchema=external_exports.object({group:ReferenceGroupSchema,row:ReferenceRowBoundsSchema,link:external_exports.string().min(1),message:external_exports.string().min(1)});var DECIMAL_TEXT=/^([+-]?)([0-9]*)(?:\.([0-9]*))?(?:[eE]([+-]?[0-9]+))?$/;function scaledOf(text){if(text.length>2016)throw new RangeError("decimal text is longer than 2000 digits");let match=DECIMAL_TEXT.exec(text);if(match===null)return;let[,sign="",whole="",fraction="",exponent="0"]=match;if(whole===""&&fraction==="")return;if(whole.length+fraction.length>2e3)throw new RangeError(`"${text.slice(0,24)}\u2026" has more than 2000 digits`);if(Math.abs(Number(exponent))>400)throw new RangeError(`exponent ${exponent.slice(0,24)} is outside \xB1400`);let magnitude=BigInt(whole+fraction),shift=Number(exponent)-fraction.length,units=sign==="-"?-magnitude:magnitude;return shift>=0?{units:units*10n**BigInt(shift),scale:0}:{units,scale:-shift}}function stripTrailingZeros(text){let end=text.length;for(;end>0&&text.charCodeAt(end-1)===48;)end-=1;return text.slice(0,end)}function formatScaled(units,scale){if(units===0n)return"0";let digits=(units<0n?-units:units).toString().padStart(scale+1,"0"),whole=digits.slice(0,digits.length-scale),fraction=stripTrailingZeros(digits.slice(digits.length-scale));return`${units<0n?"-":""}${whole}${fraction===""?"":`.${fraction}`}`}function canonicalDecimal(text){let scaled=scaledOf(text);return scaled===void 0?void 0:formatScaled(scaled.units,scaled.scale)}function gcd(a,b){let[x2,y]=[a<0n?-a:a,b<0n?-b:b];for(;y!==0n;)[x2,y]=[y,x2%y];return x2}function rational(num,den){if(den===0n)throw new RangeError("Rational with a zero denominator");let divisor=gcd(num,den)||1n,sign=den<0n?-1n:1n;return{num:sign*num/divisor,den:sign*den/divisor}}function rationalOfDecimal(text){let scaled=scaledOf(text);if(scaled===void 0)throw new RangeError(`"${text}" is not a decimal number`);return rational(scaled.units,10n**BigInt(scaled.scale))}function mul(a,b){return rational(a.num*b.num,a.den*b.den)}function div(a,b){return rational(a.num*b.den,a.den*b.num)}function pow(a,n){let magnitude=BigInt(Math.abs(n)),[num,den]=n>=0?[a.num,a.den]:[a.den,a.num];return rational(num**magnitude,den**magnitude)}var BASE_QUANTITIES=["L","M","T","I","\u0398","N","J"],DIMENSIONLESS=[0,0,0,0,0,0,0];function dim(partial2){let[L=0,M=0,T=0,I=0,\u0398=0,N=0,J=0]=BASE_QUANTITIES.map(q=>partial2[q]??0);return[L,M,T,I,\u0398,N,J]}function zip2(a,f){let[L=0,M=0,T=0,I=0,\u0398=0,N=0,J=0]=a.map(f);return[L,M,T,I,\u0398,N,J]}function mulDim(a,b){return zip2(a,(x2,i2)=>x2+(b[i2]??0))}function powDim(a,n){return zip2(a,x2=>x2*n)}function dimEquals(a,b){return a.every((x2,i2)=>x2===b[i2])}var NAMED_DIMENSIONS={dimensionless:DIMENSIONLESS,length:dim({L:1}),area:dim({L:2}),volume:dim({L:3}),mass:dim({M:1}),time:dim({T:1}),temperature:dim({\u0398:1}),speed:dim({L:1,T:-1}),flowRate:dim({L:3,T:-1}),massFlowRate:dim({M:1,T:-1}),pressure:dim({M:1,L:-1,T:-2}),energy:dim({M:1,L:2,T:-2}),power:dim({M:1,L:2,T:-3}),concentration:dim({M:1,L:-3}),amount:dim({N:1})};function isNamedDimension(name2){return name2 in NAMED_DIMENSIONS}var NAMED_DIMENSION_NAMES=Object.keys(NAMED_DIMENSIONS).filter(isNamedDimension);function dimensionName(v){return NAMED_DIMENSION_NAMES.find(name2=>dimEquals(NAMED_DIMENSIONS[name2],v))}function vectorText(v){let parts=BASE_QUANTITIES.flatMap((q,i2)=>{let e=v[i2]??0;return e===0?[]:[e===1?q:`${q}^${e}`]});return parts.length===0?"1":parts.join(" ")}function clean(entries){return Object.fromEntries([...entries].filter(([,e])=>e!==0))}function mulBasis(a,b){let out=new Map(Object.entries(a));for(let[name2,e]of Object.entries(b))out.set(name2,(out.get(name2)??0)+e);return clean(out)}function powBasis(a,n){return clean(Object.entries(a).map(([name2,e])=>[name2,e*n]))}var FRACTION_KIND="-fraction";function fractionKind(v){let leading=v.find(e=>e!==0)??0,inverse=powDim(v,-1),name2=dimensionName(v)??dimensionName(inverse),positive=leading<0?inverse:v;return`${name2??vectorText(positive).replaceAll(" ","\xB7")}${FRACTION_KIND}`}var SI="SI Brochure 9th ed. (BIPM, 2019, with the 2022 prefix update)",NIST="NIST SP 811 (2008) App. B.8",SP811_RATIOS="NIST SP 811 (2008) \xA77.10.3",BARE_BTU="Bare Btu and MMBtu name no one energy, so they never convert to joules: 40 CFR 98.6 defines the Btu at \u201Cabout 39.2 degrees Fahrenheit\u201D, while Part 98 Subpart A Table A-2 converts joules to Btu by 9.47817\xD710\u207B\u2074 (the International Table Btu, rounded); Alberta Quantification Methodologies give 1 Btu = 1,055.056 J and 1 mmBtu = 1.055 GJ, the Canada Energy Regulator 1 MMBtu = 1.0551 GJ, and Statistics Canada and Measurement Canada 1 Btu = 1,054.615 J. Use Btu_IT, MMBtu_IT, Btu_th or MMBtu_th for a stated Btu.",MASS=dim({M:1}),VOLUME=dim({L:3}),TIME=dim({T:1}),ENERGY=dim({M:1,L:2,T:-2}),DEFINITIONS=[{kind:"atomic",id:"ppm",dimension:DIMENSIONLESS,factor:"0.000001",cite:`${SI} \xA75.4.7 (parts per million, 10\u207B\u2076)`},{kind:"atomic",id:"%",dimension:DIMENSIONLESS,factor:"0.01",cite:`${SI} \xA75.4.7 (percent, 10\u207B\xB2)`},{kind:"atomic",id:"fraction",dimension:DIMENSIONLESS,factor:"1",cite:`${SI} \xA72.3.3 (quantities of dimension one)`},{kind:"atomic",id:"g",dimension:MASS,factor:"0.001",prefixable:!0,cite:`${SI} ch. 3 (the kilogram is the only coherent SI unit that includes a prefix; the gram is 10\u207B\xB3 kg)`},{kind:"derived",id:"kg",expression:"kg"},{kind:"atomic",id:"t",dimension:MASS,factor:"1000",prefixable:"kilo-and-larger",cite:`${SI} Table 8 (tonne = 1 Mg = 10\xB3 kg)`},{kind:"atomic",id:"lb",dimension:MASS,factor:"0.45359237",cite:`${NIST} (avoirdupois pound = 0.45359237 kg exactly)`},{kind:"derived",id:"t CH4",expression:"t",basis:"CH4"},{kind:"derived",id:"t CO2",expression:"t",basis:"CO2"},{kind:"derived",id:"t CO2e",expression:"t",basis:"CO2e"},{kind:"derived",id:"kg CH4",expression:"kg",basis:"CH4"},{kind:"atomic",id:"Sm3",dimension:VOLUME,factor:"1",basis:"Sm3",cite:"One cubic metre of gas at the reference conditions of the framework that names it; which conditions is that framework\u2019s choice (AER Directive 017 and the BC Measurement Guideline use 15 \xB0C and 101.325 kPa; programs differ), so the basis is the id itself"},{kind:"vocabulary",id:"MSm3",dimension:VOLUME,basis:"Sm3",reason:"`M` is a thousand in oilfield usage and a million in Norwegian (Sodir) reporting, so its multiplier is not established and no factor to Sm3 is asserted"},{kind:"vocabulary",id:"e3m3",dimension:VOLUME,basis:"Sm3",reason:'Thousand cubic metres, the gas-volume unit Canadian regulators require (BC Measurement Guideline v2.4 \xA74.2: monthly gas volumes "must be reported in units of e3m3", at 101.325 kPa and 15 \xB0C); `e3m3 \u2192 Sm3` is \xD71000 only when both sit at the same base conditions, which is the framework\u2019s choice, so no factor is asserted'},{kind:"vocabulary",id:"MBOE",dimension:VOLUME,basis:"boe",reason:"`M` is thousand in oilfield usage, but the OGCI reporting framework writes \u201CMboe/day\u201D for million barrels of oil equivalent per day, so the multiplier is 10\xB3 or 10\u2076 by source; no factor to boe is asserted"},{kind:"derived",id:"kg CO2e/boe",expression:"kg CO2e / boe",dimensionLabel:"intensity"},{kind:"derived",id:"t CH4/1000 hp",expression:"t CH4 / (1000 hp)",dimensionLabel:"intensity"},{kind:"atomic",id:"h",dimension:TIME,factor:"3600",cite:`${SI} Table 8 (hour = 3600 s)`},{kind:"atomic",id:"s",dimension:TIME,factor:"1",prefixable:!0,cite:`${SI} Table 2 (second)`},{kind:"atomic",id:"hp",dimension:dim({M:1,L:2,T:-3}),factor:"745.69987158227022",cite:`${NIST} (mechanical horsepower = 550 ft\xB7lbf/s; standard gravity 9.80665 m/s\xB2, 3rd CGPM 1901)`},{kind:"derived",id:"kW",expression:"kW"},{kind:"atomic",id:"count",dimension:DIMENSIONLESS,factor:"1",basis:"count",cite:"A tally of items; dimension one, never a ratio"},{kind:"atomic",id:"J",dimension:ENERGY,factor:"1",prefixable:!0,cite:`${SI} Table 4 (joule)`},{kind:"derived",id:"kJ",expression:"kJ"},{kind:"derived",id:"MJ",expression:"MJ"},{kind:"derived",id:"GJ",expression:"GJ"},{kind:"derived",id:"TJ",expression:"TJ"},{kind:"derived",id:"kWh",expression:"kWh"},{kind:"derived",id:"\xB5g/L",expression:"\xB5g/L"},{kind:"derived",id:"mg/L",expression:"mg/L"},{kind:"derived",id:"g/L",expression:"g/L"},{kind:"atomic",id:"NTU",dimension:DIMENSIONLESS,factor:"1",basis:"NTU",dimensionLabel:"turbidity",cite:"EPA Method 180.1 (white-light nephelometric turbidity unit); factor 1 is an identity within the basis NTU, not a physical SI factor"},{kind:"atomic",id:"FNU",dimension:DIMENSIONLESS,factor:"1",basis:"FNU",dimensionLabel:"turbidity",cite:"ISO 7027 (near-infrared formazin nephelometric unit); factor 1 is an identity within the basis FNU, not a physical SI factor"},{kind:"atomic",id:"\xB0C",dimension:dim({\u0398:1}),factor:"1",offset:"273.15",cite:`${SI} \xA72.3.1 (degree Celsius: t/\xB0C = T/K \u2212 273.15)`},{kind:"atomic",id:"pH",dimension:DIMENSIONLESS,factor:"1",basis:"pH",cite:"IUPAC Gold Book (pH = \u2212log\u2081\u2080 a(H\u207A)); logarithmic; factor 1 is an identity within the basis pH, not a physical SI factor"},{kind:"derived",id:"kg CO2",expression:"kg",basis:"CO2"},{kind:"atomic",id:"scf",dimension:VOLUME,factor:"0.028316846592",basis:"scf",cite:`${NIST} (cubic foot = 0.3048\xB3 m\xB3 exactly); 40 CFR 98.6 (standard conditions are \u201Ceither 60 or 68 degrees Fahrenheit and 14.7 pounds per square inch absolute\u201D, the choice of the program, so scf-family conversions assume one program\u2019s reference conditions)`},{kind:"atomic",id:"Mcf",dimension:VOLUME,factor:"28.316846592",cite:`40 CFR 98.6 (Mcf means thousand cubic feet); ${NIST} (cubic foot = 0.3048\xB3 m\xB3 exactly). 98.6 gives Mcf no reference conditions and the abbreviation alone does not establish them, so it carries no basis and the package refuses Mcf \u2192 scf rather than assume`},{kind:"atomic",id:"boe",dimension:VOLUME,factor:"1",basis:"boe",cite:"A barrel of oil equivalent is a convention\u2019s reference unit; its energy and gas equivalence are data in the program that chose it. Factor 1 is an identity within the basis boe, not a physical SI factor"},{kind:"atomic",id:"MMBtu",dimension:ENERGY,factor:"1000000",basis:"Btu",cite:`${BARE_BTU} 40 CFR Part 98 Subpart A Table A-2 converts Btu to MMBtu by 10\u207B\u2076`},{kind:"atomic",id:"m",dimension:dim({L:1}),factor:"1",prefixable:!0,cite:`${SI} Table 2 (metre)`},{kind:"atomic",id:"L",dimension:VOLUME,factor:"0.001",prefixable:!0,cite:`${SI} Table 8 (litre = 10\u207B\xB3 m\xB3)`},{kind:"atomic",id:"Pa",dimension:dim({M:1,L:-1,T:-2}),factor:"1",prefixable:!0,cite:`${SI} Table 4 (pascal)`},{kind:"atomic",id:"W",dimension:dim({M:1,L:2,T:-3}),factor:"1",prefixable:!0,cite:`${SI} Table 4 (watt)`},{kind:"atomic",id:"Wh",dimension:ENERGY,factor:"3600",prefixable:!0,cite:`${SI} Table 8 (hour = 3600 s) and Table 4 (watt = J/s), so 1 Wh = 3600 J`},{kind:"atomic",id:"K",dimension:dim({\u0398:1}),factor:"1",prefixable:!0,cite:`${SI} Table 2 (kelvin)`},{kind:"atomic",id:"\xB0F",dimension:dim({\u0398:1}),factor:{num:"5",den:"9"},offset:"459.67",cite:`${NIST} (T/K = (t/\xB0F + 459.67) \xD7 5/9)`},{kind:"atomic",id:"min",dimension:TIME,factor:"60",cite:`${SI} Table 8 (minute = 60 s)`},{kind:"atomic",id:"d",dimension:TIME,factor:"86400",cite:`${SI} Table 8 (day = 86400 s)`},{kind:"atomic",id:"ft",dimension:dim({L:1}),factor:"0.3048",cite:`${NIST} (international foot = 0.3048 m exactly)`},{kind:"atomic",id:"psi",dimension:dim({M:1,L:-1,T:-2}),factor:{num:"8896443230521",den:"1290320000"},cite:`${NIST} (pound-force per square inch = 0.45359237 kg \xD7 9.80665 m/s\xB2 \xF7 (0.0254 m)\xB2)`},{kind:"derived",id:"kPa",expression:"kPa"},{kind:"derived",id:"kg CO2e",expression:"kg",basis:"CO2e"},{kind:"atomic",id:"Btu",dimension:ENERGY,factor:"1",basis:"Btu",cite:BARE_BTU},{kind:"atomic",id:"Btu_IT",dimension:ENERGY,factor:"1055.05585262",cite:`${NIST} (the International Table Btu, Btu_IT, is 1.055 055 852 62 kJ exactly, from the International Table calorie of 4.1868 J)`},{kind:"atomic",id:"MMBtu_IT",dimension:ENERGY,factor:"1055055852.62",cite:`${NIST} (Btu_IT = 1055.05585262 J exactly); MMBtu_IT is 10\u2076 Btu_IT`},{kind:"atomic",id:"Btu_th",dimension:ENERGY,factor:{num:"23722880951",den:"22500000"},cite:`${NIST} (Btu_th is based on the thermochemical calorie, 4.184 J exactly): 453.59237 g (lb) \xD7 4.184 J/g/K \xD7 5/9 K`},{kind:"vocabulary",id:"Btu_39",dimension:ENERGY,basis:"Btu_39",reason:"40 CFR 98.6 defines the Btu at \u201Cabout 39.2 degrees Fahrenheit\u201D; UCUM [Btu_39] is the Btu at 39 \xB0F, about 1.05967 kJ. The registry holds the id as vocabulary only: it refuses every other Btu, and no factor to joules is asserted"},{kind:"atomic",id:"Mscf",dimension:VOLUME,factor:"28.316846592",basis:"scf",cite:"40 CFR 98.6 (Mscf means thousand standard cubic feet)"},{kind:"atomic",id:"MMscf",dimension:VOLUME,factor:"28316.846592",basis:"scf",cite:"40 CFR 98.6 (Mscf means thousand standard cubic feet); 40 CFR Part 98 Subpart Y writes \u201Cmillion (MM) standard cubic feet per year, MMscf/year\u201D"},{kind:"atomic",id:"cf",dimension:VOLUME,factor:"0.028316846592",cite:`${NIST} (international cubic foot = 0.3048\xB3 m\xB3 exactly)`},{kind:"atomic",id:"MMcf",dimension:VOLUME,factor:"28316.846592",cite:`${NIST} (international cubic foot = 0.3048\xB3 m\xB3 exactly); MMcf is 10\u2076 cf`},{kind:"atomic",id:"ppb",dimension:DIMENSIONLESS,factor:"0.000000001",cite:`${SI} \xA75.4.7 (ppb: meanings are language dependent; the package reads the US-English 10\u207B\u2079); ${SP811_RATIOS} (ppm, ppb and ppt are not acceptable for use with the SI, and a law or regulation may require them). Names no kind of fraction`},{kind:"atomic",id:"mol",dimension:dim({N:1}),factor:"1",prefixable:!0,cite:`${SI} Table 2 (mole)`},{kind:"derived",id:"ppmv",expression:"\xB5L/L",cite:`Package definition: ppm by volume, a volume fraction of 10\u207B\u2076 written \xB5L/L (${SP811_RATIOS} does not accept ppm in SI use and defines no ppmv)`},{kind:"derived",id:"ppmw",expression:"mg/kg",cite:`Package definition: ppm by mass, a mass fraction of 10\u207B\u2076 written mg/kg (${SP811_RATIOS} does not accept ppm in SI use and defines no ppmw)`},{kind:"derived",id:"MMBtu_th",expression:"1000000 Btu_th",cite:`${NIST} (Btu_th, the thermochemical Btu, from the thermochemical calorie of 4.184 J exactly); MMBtu_th is 10\u2076 Btu_th`}];var ALIASES={mmBtu:"MMBtu","million Btu":"MMBtu",scfh:"scf/h","scf/hr":"scf/h",degC:"\xB0C"};var SI_PREFIXES={Q:30,R:27,Y:24,Z:21,E:18,P:15,T:12,G:9,M:6,k:3,h:2,da:1,d:-1,c:-2,m:-3,\u00B5:-6,n:-9,p:-12,f:-15,a:-18,z:-21,y:-24,r:-27,q:-30},PREFIX_ALIASES=new Map([["u","\xB5"],["\u03BC","\xB5"]]),canonicalPrefix=prefix=>PREFIX_ALIASES.get(prefix)??prefix;function prefixExponent(prefix){let canonical=canonicalPrefix(prefix);return Object.hasOwn(SI_PREFIXES,canonical)?SI_PREFIXES[canonical]:void 0}function splitPrefix(token,isPrefixable){for(let length of[2,1]){let prefix=token.slice(0,length),rest=token.slice(length);if(rest!==""&&prefixExponent(prefix)!==void 0&&isPrefixable(rest,prefix))return{prefix:canonicalPrefix(prefix),rest}}}var fail=(code2,message,part2)=>({ok:!1,code:code2,message,...part2===void 0?{}:{part:part2}}),ok=unit2=>({ok:!0,unit:unit2}),SUPERSCRIPT=new Map([["\xB2",2],["\xB3",3]]),NUMBER_PREFIX=/^(\d{1,12}(?:\.\d{1,12})?)\s+(\S.*)$/,MAX_EXPRESSION_LENGTH=64,MAX_EXPONENT=12,MAX_PRODUCT_TERMS=8,EXPONENT_SUFFIX=/^(.+?)(?:\^(-?\d+)|([²³])|([23]))$/;function refuseAffine(unit2){if(unit2.offset!==void 0)throw new RangeError(`"${unit2.text}" is a temperature scale with an offset; it stands alone, never with a multiplier, an exponent, a product or a ratio`)}var numeratorOf=u=>u.numerator??u.vector,denominatorOf=u=>u.denominator??DIMENSIONLESS;function kinded(unit2){let numerator=numeratorOf(unit2);return dimEquals(unit2.vector,DIMENSIONLESS)&&!dimEquals(numerator,DIMENSIONLESS)?{...unit2,basis:mulBasis(unit2.basis,{[fractionKind(numerator)]:1})}:unit2}function combine(a,b,text,sign){refuseAffine(a),refuseAffine(b);let factor=a.factor===void 0||b.factor===void 0?void 0:sign===1?mul(a.factor,b.factor):div(a.factor,b.factor),vector=mulDim(a.vector,sign===1?b.vector:powDim(b.vector,-1)),basis=mulBasis(a.basis,sign===1?b.basis:powBasis(b.basis,-1)),[bNum,bDen]=sign===1?[numeratorOf(b),denominatorOf(b)]:[denominatorOf(b),numeratorOf(b)];return{text,vector,basis,numerator:mulDim(numeratorOf(a),bNum),denominator:mulDim(denominatorOf(a),bDen),...factor===void 0?{}:{factor},citations:[...new Set([...a.citations,...b.citations])]}}function raised(unit2,exponent,text){if(!Number.isInteger(exponent)||Math.abs(exponent)>MAX_EXPONENT)throw new RangeError(`exponent ${exponent} is outside \xB1${MAX_EXPONENT}`);refuseAffine(unit2);let[numerator,denominator]=exponent>0?[numeratorOf(unit2),denominatorOf(unit2)]:[denominatorOf(unit2),numeratorOf(unit2)];return{text,vector:powDim(unit2.vector,exponent),basis:powBasis(unit2.basis,exponent),numerator:powDim(numerator,Math.abs(exponent)),denominator:powDim(denominator,Math.abs(exponent)),...unit2.factor===void 0?{}:{factor:pow(unit2.factor,exponent)},citations:unit2.citations}}function suffixed(text,exponent){return(exponent===2||exponent===3)&&!/\d$/.test(text)?`${text}${exponent}`:`${text}^${exponent}`}function prefixed(prefix,atom){let exponent=prefixExponent(prefix);if(exponent===void 0||atom.factor===void 0)return;let scale=rational(10n**BigInt(Math.abs(exponent)),1n);return{text:`${prefix}${atom.text}`,vector:atom.vector,basis:atom.basis,numerator:numeratorOf(atom),denominator:denominatorOf(atom),factor:exponent>=0?mul(atom.factor,scale):div(atom.factor,scale),citations:atom.citations}}function resolveToken(token,lookup2){let name2=lookup2.alias(token)??token,registered=lookup2.byId(name2);if(registered!==void 0)return registered;let split=splitPrefix(name2,(id,prefix)=>lookup2.prefixable(id,prefix)!==void 0),atom=split&&lookup2.prefixable(split.rest,split.prefix);return split&&atom?prefixed(split.prefix,atom):void 0}function resolvePiece(piece,lookup2){let text=piece.trim(),whole=resolveToken(text,lookup2);if(whole!==void 0)return ok(whole);let match=EXPONENT_SUFFIX.exec(text);if(match!==null){let[,base="",caret,superscript,digit]=match,exponent=caret!==void 0?Number(caret):SUPERSCRIPT.get(superscript??"")??Number(digit),unit2=resolveToken(base.trim(),lookup2);if(unit2!==void 0)return!Number.isInteger(exponent)||exponent===0||Math.abs(exponent)>MAX_EXPONENT?fail("UNIT_MALFORMED",`Exponent of "${text}" must be a non-zero whole number within \xB1${MAX_EXPONENT}.`):ok(raised(unit2,exponent,suffixed(unit2.text,exponent)))}return fail("UNIT_UNKNOWN",`Unknown unit "${text}".`,text)}function resolveSide(side,lookup2,allowMultiplier=!0){let text=side.trim(),wrapped=/^\((.*)\)$/.exec(text);wrapped!==null&&(text=(wrapped[1]??"").trim());let whole=resolveToken(text,lookup2);if(whole!==void 0)return ok(whole);let multiplier=allowMultiplier?NUMBER_PREFIX.exec(text):null;if(multiplier!==null){let[,number4="",rest=""]=multiplier,scale=rationalOfDecimal(number4);if(scale.num<=0n)return fail("UNIT_MALFORMED",`Multiplier "${number4}" must be greater than zero.`);let inner=resolveSide(rest,lookup2,!1);if(!inner.ok)return inner;let scaled=raised(inner.unit,1,`${canonicalDecimal(number4)} ${inner.unit.text}`);return ok(inner.unit.factor===void 0?scaled:{...scaled,factor:mul(inner.unit.factor,scale)})}let pieces=text.split(/[·*]/);if(pieces.length>MAX_PRODUCT_TERMS)return fail("UNIT_MALFORMED",`"${text}" has more than ${MAX_PRODUCT_TERMS} terms.`);let result;for(let piece of pieces){let resolved=resolvePiece(piece,lookup2);if(!resolved.ok)return resolved;result=result===void 0?resolved.unit:combine(result,resolved.unit,`${result.text}\xB7${resolved.unit.text}`,1)}return result===void 0?fail("UNIT_UNKNOWN",`Unknown unit "${text}".`,text):ok(result)}function resolveExpression2(input2,lookup2){if(input2.length>MAX_EXPRESSION_LENGTH)return fail("UNIT_MALFORMED",`A unit is at most ${MAX_EXPRESSION_LENGTH} characters.`);try{return resolveBounded(input2,lookup2)}catch(error62){if(error62 instanceof RangeError)return fail("UNIT_MALFORMED",`"${input2.trim()}" is not a usable unit: ${error62.message}.`);throw error62}}function resolveBounded(input2,lookup2){let trimmed=input2.trim();if(trimmed==="")return fail("UNIT_EMPTY","Unit is empty.");let text=lookup2.alias(trimmed)??trimmed,whole=lookup2.byId(text);if(whole!==void 0)return ok(whole);let parts=text.split("/");if(parts.length===1){let side=resolveSide(text,lookup2);return side.ok?ok(kinded(side.unit)):side}if(parts.length>2)return fail("UNIT_MALFORMED",`"${text}" has more than one "/".`);let[left="",right=""]=parts.map(p=>p.trim());if(left===""||right==="")return fail("UNIT_MALFORMED",`"${text}" has an empty side around "/".`);if(/[·*]/.test(right)&&!/^\(.*\)$/.test(right))return fail("UNIT_MALFORMED",`"${text}" has a product after "/"; "/" binds only to the term after it, so write the denominator in parentheses ("kg/(m\xB7s)").`);let numerator=resolveSide(left,lookup2);if(!numerator.ok)return numerator;let denominator=resolveSide(right,lookup2);if(!denominator.ok)return denominator;let ratio=combine(numerator.unit,denominator.unit,`${numerator.unit.text}/${denominator.unit.text}`,-1);return ok(lookup2.byId(ratio.text)??kinded(ratio))}function rationalOfFactor(factor){return typeof factor=="string"?rationalOfDecimal(factor):rational(BigInt(factor.num),BigInt(factor.den))}var resolvedById=new Map,prefixPolicies=new Map;function admits(policy,prefix){return policy===void 0?!1:policy===!0||prefix===void 0||(prefixExponent(prefix)??0)>=3}var lookup={byId:id=>resolvedById.get(id),prefixable:(id,prefix)=>admits(prefixPolicies.get(id),prefix)?resolvedById.get(id):void 0,alias:text=>Object.hasOwn(ALIASES,text)?ALIASES[text]:void 0};for(let def of DEFINITIONS){if(def.kind==="derived")continue;let basis={[def.basis??""]:1};resolvedById.set(def.id,{text:def.id,vector:def.dimension,basis:def.basis===void 0?{}:basis,...def.kind==="atomic"?{factor:rationalOfFactor(def.factor)}:{},...def.kind==="atomic"&&def.offset!==void 0?{offset:def.offset}:{},citations:def.kind==="atomic"?[def.cite]:[],registeredId:def.id,...def.kind==="atomic"&&def.dimensionLabel!==void 0?{dimensionLabel:def.dimensionLabel}:{}}),def.kind==="atomic"&&def.prefixable!==void 0&&prefixPolicies.set(def.id,def.prefixable)}var pending=DEFINITIONS.filter(def=>def.kind==="derived");for(;pending.length>0;){let stillPending=pending.filter(def=>{if(def.kind!=="derived")return!1;let result=resolveExpression2(def.expression,lookup);if(!result.ok)return!0;let{unit:unit2}=result;return resolvedById.set(def.id,{...unit2,text:def.id,basis:def.basis===void 0?unit2.basis:mulBasis(unit2.basis,{[def.basis]:1}),citations:def.cite===void 0?unit2.citations:[...unit2.citations,def.cite],registeredId:def.id,...def.basis===void 0?{}:{declaredBasis:def.basis},...def.dimensionLabel===void 0?{}:{dimensionLabel:def.dimensionLabel}}),!1});if(stillPending.length===pending.length)throw new Error(`units: unresolvable derived definitions: ${stillPending.map(d=>d.id).join(", ")}`);pending=stillPending}for(let def of DEFINITIONS){let policy=def.kind==="derived"?prefixPolicies.get(def.expression):void 0;def.kind==="derived"&&def.basis!==void 0&&policy!==void 0&&prefixPolicies.set(def.id,policy)}var dimensionOfResolved=resolved=>resolved.dimensionLabel??dimensionName(resolved.vector)??"derived";function toUnit(resolved){let{factor,offset}=resolved;return{id:resolved.text,dimension:dimensionOfResolved(resolved),vector:resolved.vector,basis:resolved.basis,...factor===void 0?{}:{factor:{num:factor.num.toString(),den:factor.den.toString()}},...offset===void 0?{}:{offset},citations:resolved.citations}}var UNITS=DEFINITIONS.flatMap(def=>{let resolved=resolvedById.get(def.id);return resolved===void 0?[]:[toUnit(resolved)]}),UNIT_BY_ID=new Map(UNITS.map(u=>[u.id,u]));var NONZERO_INTEGER=new RegExp(`^-?[1-9][0-9]{0,${1999}}$`);var INT128_MAX=2n**127n-1n;var c=(value2,from,to,places,expected)=>({name:`${value2} ${from} to ${to} at ${places}`,value:value2,from,to,places,expected}),UNIT_CONFORMANCE_CASES=[c("1000","kg","t",9,"1"),c("1","kWh","MJ",9,"3.6"),c("5","kg","lb",9,"11.023113109"),c("1","lb","g",9,"453.59237"),c("1","kW","hp",9,"1.34102209"),c("7200","s","h",9,"2"),c("1","s","h",9,"0.000277778"),c("100","\xB0C","K",9,"373.15"),c("-40","\xB0C","\xB0F",9,"-40"),c("212","\xB0F","\xB0C",9,"100"),c("0","K","\xB0C",9,"-273.15"),c("32","\xB0F","\xB0C",0,"0"),c("212","\xB0F","\xB0C",0,"100"),c("0","\xB0C","\xB0F",0,"32"),c("100","\xB0C","\xB0F",0,"212"),c("-40","\xB0C","\xB0F",0,"-40"),c("98.6","\xB0F","\xB0C",2,"37"),c("100","\xB0F","\xB0C",2,"37.78"),c("0","\xB0F","\xB0C",0,"-18"),c("0","\xB0F","\xB0C",2,"-17.78"),c("100.5","\xB0C","\xB0F",0,"213"),c("2.5","mg/L","g/L",9,"0.0025"),c("1","mg/L","kg/m3",9,"0.001"),c("1","Mscf","scf",9,"1000"),c("1","Mcf","m3",9,"28.316846592"),c("1","MMBtu_IT","GJ",9,"1.055055853"),c("1","MMBtu_th","GJ",9,"1.054350264"),c("0.5","fraction","%",9,"50"),c("10000","ppm","%",9,"1"),c("3","mg/kg","ppmw",9,"3"),c("1","kg CH4","t CH4",9,"0.001"),c("1","t CH4/1000 hp","kg CH4/hp",9,"1"),c("101.325","kPa","psi",9,"14.695948776"),c("1","m3/h","L/min",9,"16.666666667"),c("0.5","g","kg",3,"0.001"),c("-0.5","g","kg",3,"-0.001"),c("1.5","g","kg",3,"0.002"),c("99999999999999999999","g","kg",3,"99999999999999999.999"),c("5000","kW","hp",9,"6705.110447975"),c("5000","hp","kW",9,"3728.499357911"),c("1000000","kW","hp",9,"1341022.089595028"),c("0.000000005","kg","g",9,"0.000005"),c("123456789.123456789","kg","t",9,"123456.789123457"),c("50000000000000000000000000","kW","W",9,"50000000000000000000000000000")];var REFERENCE_UNIT_REFUSAL_CODES=["UNIT_EMPTY","UNIT_UNKNOWN","UNIT_MALFORMED"],ReferenceUnitProblemSchema=external_exports.object({group:ReferenceGroupSchema,row:ReferenceRowBoundsSchema,unit:external_exports.string().nullable(),code:external_exports.enum(REFERENCE_UNIT_REFUSAL_CODES),message:external_exports.string().min(1)});var REFERENCE_VERDICT_STATES=["passed","failed","too-large"],REFERENCE_VERDICT_SHAPE="reference-values/v2",ReferenceVerdictSchema=external_exports.object({shape:external_exports.literal(REFERENCE_VERDICT_SHAPE),state:external_exports.enum(REFERENCE_VERDICT_STATES),rowCount:external_exports.number().int().nonnegative(),span:ReferenceSpanSchema.nullable(),window:external_exports.array(ReferenceWindowProblemSchema).max(REFERENCE_PROBLEMS_SHOWN_MAX),windowCount:external_exports.number().int().nonnegative(),coverage:external_exports.array(ReferenceCoverageProblemSchema).max(REFERENCE_PROBLEMS_SHOWN_MAX),coverageCount:external_exports.number().int().nonnegative(),unit:external_exports.array(ReferenceUnitProblemSchema).max(REFERENCE_PROBLEMS_SHOWN_MAX),unitCount:external_exports.number().int().nonnegative(),codelist:external_exports.array(ReferenceCodelistProblemSchema).max(REFERENCE_PROBLEMS_SHOWN_MAX),codelistCount:external_exports.number().int().nonnegative(),sourceLink:external_exports.array(ReferenceSourceLinkProblemSchema).max(REFERENCE_PROBLEMS_SHOWN_MAX),sourceLinkCount:external_exports.number().int().nonnegative(),codelists:ReferenceKeyCodelistsSchema,comparedVersionId:DatasetVersionIdSchema.nullable()});var ReferenceCheckFailureSchema=external_exports.object({code:external_exports.string().min(1),message:external_exports.string().min(1),tries:external_exports.number().int().positive(),at:external_exports.iso.datetime()});var VERSION_READINESS_STATES=["ready","blocked","not-evaluated","stale"],VersionReadinessStateSchema=external_exports.enum(VERSION_READINESS_STATES),REFERENCE_READINESS_REASONS=["save-not-sealed","save-failed","reference-unchecked","reference-window","reference-coverage","reference-unit","reference-codelist","reference-source-link"],VERSION_READINESS_STALE_REASONS=["ruleset-changed","quality-run-on-another-pin","corrections-not-reapplied","review-not-carried",...REFERENCE_READINESS_REASONS],VersionReadinessStaleReasonSchema=external_exports.enum(VERSION_READINESS_STALE_REASONS),VersionReadinessInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema}),RuleResultDecidedSchema=external_exports.object({by:external_exports.string().min(1),at:external_exports.iso.datetime(),reason:external_exports.string().min(1)}),CappedRuleSchema=external_exports.object({rulesetId:ValidationRulesetIdSchema,rulesetVersion:external_exports.number().int().positive(),rulesetName:external_exports.string(),ruleIndex:external_exports.number().int().nonnegative(),decided:RuleResultDecidedSchema.nullable()});var UnlineagedDismissalSchema=external_exports.object({actId:external_exports.string().min(1),ruleIndex:external_exports.number().int().nonnegative(),column:external_exports.string().min(1),selection:ReviewSelectionSchema,body:external_exports.string().optional(),ambiguous:external_exports.boolean(),candidates:external_exports.array(external_exports.object({rulesetId:ValidationRulesetIdSchema,rulesetVersion:external_exports.number().int().positive(),rulesetName:external_exports.string()})).min(1),lineages:external_exports.array(external_exports.object({rulesetId:ValidationRulesetIdSchema,rulesetVersion:external_exports.number().int().positive(),rulesetName:external_exports.string()})).min(1)}),VersionReadinessQualityRunPendingSchema=external_exports.object({qualityRunId:external_exports.string().min(1),state:external_exports.enum(["PENDING","RUNNING"])}),VersionReadinessQualityRunFailureSchema=external_exports.object({qualityRunId:external_exports.string().min(1),code:external_exports.string().min(1),message:external_exports.string().min(1),retryAt:external_exports.iso.datetime().optional()}),VersionReadinessSchema=external_exports.object({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,state:VersionReadinessStateSchema,reason:VersionReadinessStaleReasonSchema.optional(),blocking:external_exports.number().int().nonnegative(),blockingFlags:external_exports.number().int().nonnegative().optional(),blockingRuleFailures:external_exports.number().int().nonnegative().optional(),warnings:external_exports.number().int().nonnegative(),open:external_exports.number().int().nonnegative(),qualityRunId:external_exports.string().min(1).nullable(),rulesetDeclared:external_exports.boolean(),dismissalsUnaccounted:external_exports.boolean(),dismissalsUnlineaged:external_exports.array(UnlineagedDismissalSchema).optional(),cappedRules:external_exports.array(CappedRuleSchema),carryFailure:CarryFailureSchema.optional(),carryRetrying:CarryFailureSchema.optional(),qualityRunPending:VersionReadinessQualityRunPendingSchema.optional(),qualityRunFailure:VersionReadinessQualityRunFailureSchema.optional(),qualityRunOwed:external_exports.literal(!0).optional(),reference:ReferenceVerdictSchema.optional(),referenceCheckFailure:ReferenceCheckFailureSchema.optional()}),RetryReviewCarryInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,idempotencyKey:IdempotencyKeySchema.max(200)}),RetryReviewCarryResultSchema=external_exports.object({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,retried:external_exports.boolean()});var DecideRuleResultInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,rulesetId:ValidationRulesetIdSchema,rulesetVersion:external_exports.number().int().positive(),ruleIndex:external_exports.number().int().nonnegative(),reason:external_exports.string().trim().min(1).max(2e3),idempotencyKey:IdempotencyKeySchema.max(200)}),RuleResultDecisionSchema=CappedRuleSchema.extend({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,decided:RuleResultDecidedSchema,receiptId:external_exports.string().min(1),alreadyDecided:external_exports.literal(!0).optional()});var PublishOverridesSchema=external_exports.object({apply:external_exports.enum(["in-flight","failed","couldnt-apply"]),applyRecordId:external_exports.string().min(1).optional(),started:external_exports.boolean().optional(),waiting:external_exports.number().int().nonnegative().optional(),failureCode:external_exports.string().optional(),column:external_exports.string().min(1).optional(),remaining:external_exports.number().int().positive().optional(),transient:external_exports.boolean().optional(),columns:external_exports.array(external_exports.string().min(1)).optional()}),PromoteIfReadyInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,idempotencyKey:IdempotencyKeySchema.max(512)}),PROMOTE_IF_READY_OUTCOMES=["promoted","held"],PromoteIfReadyResultSchema=external_exports.object({outcome:external_exports.enum(PROMOTE_IF_READY_OUTCOMES),readiness:VersionReadinessSchema}),RowCheckFindingsInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,recordIds:external_exports.array(external_exports.string().min(1).max(200)).min(1).max(500)}),RowCheckFindingSchema=external_exports.object({recordId:external_exports.string().min(1),rulesetId:external_exports.string().min(1),rulesetVersion:external_exports.number().int().positive(),rulesetName:external_exports.string(),ruleIndex:external_exports.number().int().nonnegative(),column:external_exports.string().min(1),onBreak:RuleOnBreakSchema,evaluated:external_exports.boolean(),atSource:external_exports.boolean()}),RowCheckFindingsSchema=external_exports.object({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,findings:external_exports.array(RowCheckFindingSchema),unaccounted:external_exports.boolean(),decidedCappedWarnings:external_exports.boolean().optional(),checksNotCurrent:external_exports.enum(["not-run","stale"]).optional()});var DATASET_HISTORY_KINDS=["data-version","full-check","override","accepted","asked-source","flag","flag-cleared","conflict","undone"],DatasetHistoryKindSchema=external_exports.enum(DATASET_HISTORY_KINDS);var DATASET_HISTORY_FACETS_MAX=500;var hasNoNul=value2=>!value2.includes("\0"),DatasetHistoryInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema,kinds:external_exports.array(DatasetHistoryKindSchema).min(1).max(DATASET_HISTORY_KINDS.length).optional(),column:external_exports.string().min(1).max(MAX_CORRECTION_COLUMN_LENGTH).refine(hasNoNul,{message:"A column cannot hold a NUL character."}).optional(),actor:external_exports.string().min(1).max(255).refine(hasNoNul,{message:"An actor cannot hold a NUL character."}).optional(),search:external_exports.string().min(1).max(256).refine(hasNoNul,{message:"Search cannot hold a NUL character."}).optional(),take:external_exports.number().int().min(1).max(1e3).optional(),cursor:external_exports.string().min(1).max(1e3).optional()}),DatasetHistorySelectionSchema=external_exports.discriminatedUnion("kind",[external_exports.object({kind:external_exports.literal("rows"),rows:external_exports.number().int().nonnegative()}),external_exports.object({kind:external_exports.literal("filter"),filters:external_exports.array(DatasetReadFilterSchema),matched:external_exports.number().int().nonnegative()})]);var OverrideCellCountsSchema=external_exports.partialRecord(StagedCorrectionStateSchema,external_exports.number().int().positive());var DATA_VERSION_HISTORY_STATES=["in-use","on-hold"],EntryBase={id:external_exports.string().min(1),at:external_exports.iso.datetime(),actor:external_exports.string().min(1).nullable(),versionId:external_exports.string().min(1).nullable(),loadNumber:external_exports.number().int().nullable()},ColumnNameSchema=external_exports.string().min(1).max(MAX_CORRECTION_COLUMN_LENGTH),DatasetHistoryPastedValueSchema=external_exports.strictObject({logicalId:CorrectionFromSchema.shape.logicalId,column:ColumnNameSchema.optional(),from:DatasetCellValueSchema,to:DatasetCellValueSchema}),DatasetHistoryReplaceEachChangeSchema=ReplaceEachChangeSchema.extend({values:external_exports.array(DatasetHistoryPastedValueSchema).min(1).max(MAX_CORRECTION_ACT_ROWS)}),DatasetHistoryOverrideChangeSchema=external_exports.discriminatedUnion("method",[...CorrectionChangeSchema.options,DatasetHistoryReplaceEachChangeSchema]),DATASET_HISTORY_UNDONE_KINDS=["accepted","asked-source","flag-cleared"],DatasetHistoryEntrySchema=external_exports.discriminatedUnion("kind",[external_exports.object({...EntryBase,kind:external_exports.literal("data-version"),rows:external_exports.number().int().nonnegative(),state:external_exports.enum(DATA_VERSION_HISTORY_STATES).optional()}),external_exports.object({...EntryBase,kind:external_exports.literal("full-check"),status:external_exports.enum(["in-flight","committed","failed"]),rulesetId:external_exports.string().min(1),rulesetVersion:external_exports.number().int().positive(),rowsChecked:external_exports.number().int().nonnegative().optional(),rowsWithFinding:external_exports.number().int().nonnegative().optional(),reason:external_exports.string().min(1).optional()}),external_exports.object({...EntryBase,kind:external_exports.literal("override"),column:external_exports.string().min(1).optional(),change:DatasetHistoryOverrideChangeSchema,undoes:external_exports.string().min(1).optional(),resolves:external_exports.string().min(1).optional(),selection:DatasetHistorySelectionSchema,oldValue:DatasetCellValueSchema.optional(),pasted:external_exports.array(external_exports.strictObject({actId:external_exports.string().min(1),column:ColumnNameSchema})).min(2).max(MAX_CORRECT_CELLS_COLUMNS).optional(),reason:external_exports.string(),state:StagedCorrectionStateSchema,cells:OverrideCellCountsSchema}),external_exports.object({...EntryBase,kind:external_exports.literal("accepted"),scope:external_exports.enum(["rows","rule"]),column:external_exports.string().min(1).optional(),rulesetId:external_exports.string().min(1).optional(),rulesetVersion:external_exports.number().int().positive().optional(),ruleIndex:external_exports.number().int().nonnegative(),selection:DatasetHistorySelectionSchema.optional(),reason:external_exports.string().min(1).optional()}),external_exports.object({...EntryBase,kind:external_exports.literal("asked-source"),selection:DatasetHistorySelectionSchema,reason:external_exports.string().min(1),expected:external_exports.string().min(1).optional(),channel:ReviewRequestChannelSchema}),external_exports.object({...EntryBase,kind:external_exports.literal("flag"),selection:DatasetHistorySelectionSchema,severity:ReviewSeveritySchema,dimension:external_exports.string().min(1).optional(),reason:external_exports.string().min(1).optional(),state:external_exports.enum(["open","cleared"])}),external_exports.object({...EntryBase,kind:external_exports.literal("flag-cleared"),selection:DatasetHistorySelectionSchema,flagActId:external_exports.string().min(1),reason:external_exports.string().min(1).optional()}),external_exports.object({...EntryBase,kind:external_exports.literal("undone"),undid:external_exports.string().min(1),undidKind:external_exports.enum(DATASET_HISTORY_UNDONE_KINDS),selection:DatasetHistorySelectionSchema,reason:external_exports.string().min(1).optional()}),external_exports.object({...EntryBase,kind:external_exports.literal("conflict"),rows:external_exports.number().int().positive()})]),DatasetHistoryPageSchema=external_exports.object({entries:external_exports.array(DatasetHistoryEntrySchema).max(1e3),nextCursor:external_exports.string().min(1).nullable()}),DatasetHistoryFacetsInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema}),DatasetHistoryFacetsSchema=external_exports.object({columns:external_exports.array(external_exports.string().min(1)).max(DATASET_HISTORY_FACETS_MAX),actors:external_exports.array(external_exports.string().min(1)).max(DATASET_HISTORY_FACETS_MAX),automatic:external_exports.boolean(),truncated:external_exports.boolean()});var DATASET_HISTORY_KIND_LABELS={"data-version":"Data version","full-check":"Full check",override:"Override",accepted:"Accepted as is","asked-source":"Asked the source",flag:"Flag","flag-cleared":"Flag cleared",conflict:"Conflict",undone:"Undone"},DATASET_HISTORY_KIND_FILTER_LABELS={...DATASET_HISTORY_KIND_LABELS,undone:"Undone or reopened"};var NEWER_DELIVERY_REASONS=["blocker-flags","failing-checks","checks-not-finished","corrections-not-reapplied","at-source","other","not-published"],NewerDeliveryReasonCodeSchema=external_exports.enum(NEWER_DELIVERY_REASONS),NewerDeliveryInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema,readVersionId:DatasetVersionIdSchema.optional(),periodColumns:external_exports.array(external_exports.string().min(1).max(200)).max(20),datePublished:external_exports.boolean().optional()}),NewerDeliveryLoadSchema=external_exports.object({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,loadNumber:external_exports.number().int().positive()}),NewerDeliveryReasonSchema=external_exports.object({reason:NewerDeliveryReasonCodeSchema,rows:external_exports.number().int().nonnegative()}),NewerDeliveryCellsSchema=external_exports.record(external_exports.string(),external_exports.array(external_exports.string().nullable())),NewerDeliverySchema=external_exports.object({read:external_exports.object({versionId:DatasetVersionIdSchema,loadNumber:external_exports.number().int().positive(),publishedSource:external_exports.boolean(),delivery:NewerDeliveryLoadSchema.nullable(),reasons:external_exports.array(NewerDeliveryReasonSchema)}).nullable(),newer:external_exports.object({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,loadNumber:external_exports.number().int().positive(),state:external_exports.enum(["blocked","published"]),reasons:external_exports.array(NewerDeliveryReasonSchema),rows:external_exports.number().int().nonnegative(),cells:NewerDeliveryCellsSchema,undated:external_exports.number().int().nonnegative(),changed:external_exports.object({rows:external_exports.number().int().nonnegative(),cells:NewerDeliveryCellsSchema,undated:external_exports.number().int().nonnegative()}).nullable()}).nullable(),newerPublished:external_exports.object({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,loadNumber:external_exports.number().int().positive(),rows:external_exports.number().int().nonnegative(),cells:NewerDeliveryCellsSchema,undated:external_exports.number().int().nonnegative()}).nullable(),atSource:external_exports.object({rows:external_exports.number().int().nonnegative(),cells:NewerDeliveryCellsSchema,undated:external_exports.number().int().nonnegative()}),blockingLabel:external_exports.string().min(1)});var GRANT_URL_PATTERN=/^(?:https:\/\/|http:\/\/(?:localhost|127\.0\.0\.1|\[::1\]|[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.localhost)(?::\d+)?(?:[/?#]|$))/,WALKUP_MAX_UPLOAD_BYTES=5*1024**3,WalkupUploadGrantInputSchema=external_exports.strictObject({sdpDatasetRef:external_exports.string().min(1),fileName:external_exports.string().min(1),contentType:external_exports.string().min(1),byteLength:external_exports.number().int().positive().max(WALKUP_MAX_UPLOAD_BYTES),sha256:external_exports.string().min(1).describe("Base64 of the raw 32-byte SHA-256 digest \u2014 S3's `x-amz-checksum-sha256` convention, NOT hex. A hex digest is 64 characters, which is itself legal base64 and decodes to 48 bytes; send the base64 encoding of the raw digest bytes instead."),idempotencyKey:external_exports.string().min(1).max(200).optional().describe("The idempotencyKey of the walkupDeclare this upload is for. It names that import rather than replaying anything: a reused key never replays an earlier grant, and every call mints a new one for the import the key names. Send it whenever you have it.")}),WalkupUploadGrantRefusalDataSchema=external_exports.object({code:external_exports.string(),detail:external_exports.string().optional()}),WalkupUploadGrantResultSchema=external_exports.object({url:external_exports.url().refine(value2=>GRANT_URL_PATTERN.test(value2),{message:"upload grant URL must be https (http is admitted for loopback only)"}),headers:external_exports.record(external_exports.string(),external_exports.string()),expiresAt:external_exports.iso.datetime()});var DATASET_ROW_KIND={domain:"datasets",type:"dataset-version"},datasetCountComponentContract={name:"dataset-count",binds:"collection",bindsToResource:"datasets",configVersion:"1",configSchema:external_exports.object({}),description:"Single-number tile: how many datasets the tenant has, under a sublabel.",grain:"widget",defaultLayout:{spanCol:4,spanRow:4},rowKind:DATASET_ROW_KIND},datasetManagerComponentContract={name:"dataset-manager",binds:"collection",bindsToResource:"datasets",configVersion:"1",configSchema:external_exports.object({}),description:"The tenant's datasets as a searchable, filterable catalog; a row opens that dataset's own page where the frame offers one. The import wizard, and the artifacts, transformations and runs surfaces, are separate Studio surfaces and are not part of it.",grain:"page",rowKind:DATASET_ROW_KIND},referenceTableManagerComponentContract={name:"reference-table-manager",binds:"collection",bindsToResource:"datasets",configVersion:"1",configSchema:external_exports.object({}),description:"The tenant's reference tables, the dated values calculations read: each with where it came from, the version in use, the dates its rows cover and its cited source; a row opens that table's own page where the frame offers one.",grain:"page",rowKind:DATASET_ROW_KIND},datasetCatalogComponentContract={name:"dataset-catalog",binds:"none",configVersion:"1",configSchema:external_exports.object({}).strict(),description:"The tenant's datasets grouped by category, with search and Category and Kind filters: name, kind, the run that produced it, owner, maturity, rows, open issues and when it last loaded. A row opens the dataset where the frame offers it. New dataset uploads files or a folder, each file its own dataset; New pipeline opens the Solution's pipelines page.",grain:"page"},datasetViewConfigSchema=external_exports.object({});var datasetProfileComponentContract={name:"dataset-profile",binds:"entity",bindsToResource:"datasets",entity:{domain:"datasets",type:"dataset-version"},configVersion:"1",configSchema:external_exports.object({}),description:"One load's column profile, a card per column: how much is empty, how many distinct values, and its top values or distribution \u2014 at whichever version the reference pins.",grain:"widget",defaultLayout:{spanCol:12,spanRow:3}},datasetRuleEditorComponentContract={name:"dataset-rule-editor",binds:"entity",bindsToResource:"datasets",entity:{domain:"datasets",type:"dataset-version"},configVersion:"1",configSchema:external_exports.object({}),description:"Author a dataset's validation ruleset: rules proposed from the pinned load's profile, each kept, edited or dropped with the violations it would raise on that load, then saved as a new ruleset version.",grain:"widget",defaultLayout:{spanCol:12,spanRow:8}},datasetRowsComponentContract={name:"dataset-rows",binds:"entity",bindsToResource:"datasets",entity:{domain:"datasets",type:"dataset-version"},configVersion:"1",configSchema:external_exports.object({}),description:"A working data view of one load, for inspecting a pipeline step's output: paged rows with the automatic checks' problems marked on the cells they flag, a column profile, and an Open issues filter that appears only when a row has an issue, with Full screen as its one size control. Unlike dataset-view, the read-only viewer that shows the first rows of a load as a reference embed, it reads the checks, narrows to issues and pages through the load.",grain:"widget",defaultLayout:{spanCol:12,spanRow:8}},editorTransformationId=SourceTransformationIdSchema.check(external_exports.regex(/\S/,"A transformation id cannot be blank.")).meta(SourceTransformationIdSchema.meta()??{}),datasetTransformationEditorComponentContract={name:"dataset-transformation-editor",binds:"none",configVersion:"2",configSchema:external_exports.object({transformationId:editorTransformationId.optional().describe("The transformation to revise. Set, the editor opens that transformation prefilled from its current version and saving appends the next version; unset, it authors a new transformation.")}).strict(),description:"Author a source transformation from pasted SQL: the input slots it reads are matched by name to the tenant's datasets, with a chooser for the rest; the outputs are read from its COPY \u2026 TO statements; saving mints a new transformation version, which a later run step references by id and version. With a transformationId set it revises that transformation instead, saving its next version.",grain:"widget",defaultLayout:{spanCol:12,spanRow:10}},referenceTableReviewComponentContract={name:"reference-table-review",binds:"entity",bindsToResource:"datasets",entity:{domain:"datasets",type:REFERENCE_TABLE_SUBJECT_TYPE},configVersion:"1",configSchema:external_exports.object({}),description:"One version of a reference table as its approver reviews it: the checks it passed or what holds it, its rows changed against the version in use, and which projects' next run approving it changes.",grain:"widget",viewer:!0,defaultLayout:{spanCol:12,spanRow:6}},datasetExportComponentContract={name:"dataset-export",binds:"entity",bindsToResource:"datasets",entity:{domain:"datasets",type:"dataset-version"},acceptsKinds:"any",configVersion:"1",configSchema:external_exports.object({}).strict(),description:"The dataset versions behind the bound record, found by walking what the record was made from, in two groups, decided from the step that produced each version: Raw data (landed from a source) and Transposed data (produced by a transformation or a calculation). Each row has its own Export, which downloads that version. Bind it to any record; it lists the dataset versions that record was made from.",grain:"widget",defaultLayout:{spanCol:12,spanRow:6}};var RELAND_REQUEST_KEY_MAX=512,RequestRelandInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema,idempotencyKey:IdempotencyKeySchema.max(RELAND_REQUEST_KEY_MAX)}),RelandRequestSchema=external_exports.object({requestId:external_exports.uuid(),datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema});var RELAND_LANDING_VERB="relandCurrentLoad",RELAND_LANDING_ACTION_NAME=`datasets.${RELAND_LANDING_VERB}`;var SetHoistedColumnsInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema,enabled:external_exports.boolean(),idempotencyKey:IdempotencyKeySchema.max(200)}),HOISTED_COLUMNS_TAKES_EFFECT=["next-full-refresh","next-run","recorded-only"],HoistedColumnsTakesEffectSchema=external_exports.enum(HOISTED_COLUMNS_TAKES_EFFECT),HoistedColumnsViewSchema=external_exports.object({datasetId:DatasetIdSchema,enabled:external_exports.boolean(),declaredColumns:external_exports.array(external_exports.string()),takesEffect:HoistedColumnsTakesEffectSchema,runStarted:external_exports.literal(!1),ignoredUntilFullRefresh:external_exports.boolean().optional(),startRunWith:external_exports.string().optional(),unchanged:external_exports.boolean()});var ReferenceOriginSchema=external_exports.discriminatedUnion("kind",[external_exports.object({kind:external_exports.literal("studio"),via:external_exports.enum(["create","mark"]),by:external_exports.string().min(1),at:external_exports.iso.datetime()}),external_exports.object({kind:external_exports.literal("pack"),pack:external_exports.string().min(1),itemKey:external_exports.string().min(1),version:external_exports.number().int().positive()})]);var SetReferenceSourceInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema,source:ReferenceGovernanceSchema.omit({authorityEdition:!0}),expectedUpdatedAt:external_exports.iso.datetime().nullable(),reason:external_exports.string().trim().min(1).max(500),idempotencyKey:IdempotencyKeySchema.max(200)}),ReferenceSourceInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema}),ReferenceTableSourceSchema=external_exports.object({datasetId:DatasetIdSchema,source:ReferenceGovernanceSchema.nullable(),updatedAt:external_exports.iso.datetime().nullable(),keyCodelists:ReferenceKeyCodelistsSchema.optional()}),REFERENCE_TABLES_MAX=200,ReferenceLastSaveSchema=external_exports.object({saveRecordId:external_exports.string().min(1),by:external_exports.string().min(1),reason:external_exports.string().min(1),at:external_exports.iso.datetime(),state:external_exports.enum(["saving","saved","failed"])}),ReferenceTableSchema=external_exports.object({datasetId:DatasetIdSchema,name:external_exports.string().min(1),label:external_exports.string().min(1).nullable(),origin:ReferenceOriginSchema.nullable(),currentVersionId:DatasetVersionIdSchema.nullable(),promotedVersionId:DatasetVersionIdSchema.nullable(),span:ReferenceSpanSchema.nullable(),source:ReferenceGovernanceSchema.nullable(),lastSave:ReferenceLastSaveSchema.nullable(),keyCodelists:ReferenceKeyCodelistsSchema.optional()}),ReferenceTablesInputSchema=external_exports.strictObject({}),ReferenceTablesSchema=external_exports.object({tables:external_exports.array(ReferenceTableSchema).max(REFERENCE_TABLES_MAX),more:external_exports.boolean()});var MarkReferenceValuesInputSchema=external_exports.discriminatedUnion("marked",[external_exports.strictObject({datasetId:DatasetIdSchema,marked:external_exports.literal(!0),source:ReferenceGovernanceSchema.optional(),idempotencyKey:IdempotencyKeySchema.max(200)}),external_exports.strictObject({datasetId:DatasetIdSchema,marked:external_exports.literal(!1),idempotencyKey:IdempotencyKeySchema.max(200)})]),MarkReferenceValuesResultSchema=external_exports.object({datasetId:DatasetIdSchema,kind:external_exports.enum(["raw","constant"]),changed:external_exports.boolean(),verdict:ReferenceVerdictSchema.optional()});var TransformSpecIdSchema=external_exports.string().min(1).brand(),DatasetKindSchema=external_exports.enum(["raw","constant","result","live"]),TransformStepKindSchema=external_exports.enum(["map","unitConvert","const","expression","cast","lookupMap","filterRows"]),DatasetReadInputSchema=DatasetRefSchema.extend({rows:external_exports.object({start:external_exports.number().int().nonnegative(),take:external_exports.number().int().min(1).max(1e3)}).optional(),offset:external_exports.number().int().nonnegative().optional().describe(`Rows to skip, in load order; defaults to 0. Sent WITHOUT \`limit\`, the page size defaults to ${100}. Mutually exclusive with \`rows\` \u2014 sending both is refused with \`DATASET_READ_WINDOW_AMBIGUOUS\`, never reconciled.`),limit:external_exports.number().int().min(1).max(1e3).optional().describe(`Page size, 1\u2013${1e3}; defaults to ${100}. Sent WITHOUT \`offset\`, the page starts at row 0. An ask above the maximum is REFUSED, not clamped. Mutually exclusive with \`rows\` \u2014 sending both is refused with \`DATASET_READ_WINDOW_AMBIGUOUS\`. Read \`totalRows\` for the full count.`),search:external_exports.string().min(1).max(256).optional(),cursor:external_exports.string().min(1).optional(),orderBy:DatasetReadOrderBySchema.optional(),filters:external_exports.array(DatasetReadFilterSchema).min(1).max(8).optional(),range:DatasetReadRangeSchema.optional(),includeTotal:external_exports.boolean().optional().describe("Send `false` to skip the exact total: the page omits `totalRows` (absent, never 0), no count runs, and `nextCursor` still marks the end \u2014 follow it until it is `null`. A window past the last row answers an empty page rather than `DATASET_READ_WINDOW_OUT_OF_RANGE`, which needs the total to decide. Default `true`.")}).strict(),DatasetVersionStatusSchema=external_exports.object({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,promoted:external_exports.boolean(),promotedAt:external_exports.iso.datetime().optional(),get columns(){return external_exports.array(DatasetColumnSchema2).optional()},loadNumber:external_exports.number().int().positive().optional(),rowCount:external_exports.number().int().nonnegative().optional(),loadedAt:external_exports.string().min(1).optional()}),ResolveDatasetNameInputSchema=external_exports.strictObject({name:external_exports.string().min(1),kind:DatasetKindSchema.optional()}),PromoteDatasetInputSchema=external_exports.strictObject({ref:DatasetRefSchema,idempotencyKey:IdempotencyKeySchema,reason:DatasetLifecycleReasonSchema.optional()}),RenameDatasetInputSchema=external_exports.strictObject({datasetId:external_exports.string().min(1),name:external_exports.string().min(1).optional().describe("The new system name. Omit it to leave the name as it is."),label:DatasetLabelSchema.nullable().optional().describe("The readable name to show; `null` clears it, so the dataset shows its `name` again. Never changes how the dataset is found."),ifUnlabeled:external_exports.literal(!0).optional().describe("Write `label` only while the dataset has no label; otherwise a no-op is recorded. Needs `label`; refused with `name`."),reason:DatasetLifecycleReasonSchema.optional(),idempotencyKey:IdempotencyKeySchema}),DatasetNameTakenDataSchema=external_exports.object({code:external_exports.literal("DATASET_NAME_TAKEN"),suggestedName:external_exports.string().min(1)}),SetDatasetKeyColumnInputSchema=external_exports.strictObject({datasetId:external_exports.string().min(1),keyColumn:external_exports.string().min(1),reason:DatasetLifecycleReasonSchema.optional(),idempotencyKey:IdempotencyKeySchema}),DatasetSchema=external_exports.object({datasetId:DatasetIdSchema,name:external_exports.string().min(1),...datasetReadabilityFields,kind:DatasetKindSchema,columns:external_exports.array(DatasetColumnSchema2),outdatedColumnTags:external_exports.array(external_exports.string().min(1)).optional(),createdAt:external_exports.iso.datetime().optional(),currentVersionId:DatasetVersionIdSchema.optional(),rowCount:external_exports.number().int().nonnegative().optional(),promoted:external_exports.boolean(),currentVersionAsOf:external_exports.iso.datetime().optional(),status:DatasetStatusSchema,maturity:DatasetMaturitySchema,slug:DatasetSlugSchema,ownerDomain:external_exports.string().min(1).optional(),description:external_exports.string().min(1).optional(),keyColumn:external_exports.string().min(1).optional(),notes:external_exports.string().min(1).optional(),keywords:external_exports.array(external_exports.string().min(1)).optional(),themes:external_exports.array(external_exports.string().min(1)).optional(),get grain(){return DatasetGrainSchema.optional()},get timeCovered(){return DatasetTimeCoveredReadSchema.optional()},get tableRole(){return DatasetTableRoleSchema.optional()},isDerived:external_exports.boolean().optional(),hasSourceRuns:external_exports.boolean().optional(),acceptsUploadedVersions:external_exports.boolean().optional(),importRunsAvailable:external_exports.boolean().optional(),uploadVersionsUnavailableReason:UploadVersionsUnavailableReasonSchema.optional(),sheetName:external_exports.string().min(1).optional(),reviewEnabled:external_exports.boolean().optional(),provenance:DatasetProvenanceSchema,get replacedBy(){return DatasetReplacedBySchema.optional()}}),DatasetPageSchema=external_exports.object({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,columns:external_exports.array(DatasetColumnSchema2),rows:external_exports.array(DatasetRowSchema),totalRows:external_exports.number().int().nonnegative().optional(),nextCursor:external_exports.string().nullable().optional(),producedBy:DatasetVersionProducerSchema.optional()});var TransformSpecSchema=external_exports.object({specId:TransformSpecIdSchema,name:external_exports.string().min(1),sourceDatasetId:DatasetIdSchema,sourceVersionId:DatasetVersionIdSchema.nullable(),steps:external_exports.array(TransformStepSchema)}),SaveTransformSpecInputSchema=external_exports.object({specId:TransformSpecIdSchema.optional(),name:external_exports.string().min(1),sourceDatasetId:DatasetIdSchema,sourceVersionId:DatasetVersionIdSchema,steps:external_exports.array(TransformStepSchema).max(MAX_TRANSFORM_STEPS),idempotencyKey:IdempotencyKeySchema}),LiveDatasetReadSchema=external_exports.object({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,columns:external_exports.array(DatasetColumnSchema2),rows:external_exports.array(DatasetRowSchema),totalRows:external_exports.number().int().nonnegative(),truncated:external_exports.boolean(),executedAt:external_exports.iso.datetime(),durationMs:external_exports.number().int().nonnegative()}),TransformInputSchema=external_exports.object({specId:TransformSpecIdSchema,specVersion:external_exports.number().int().positive().optional(),idempotencyKey:TransformRunKeyInputSchema}),GetTransformSpecInputSchema=external_exports.object({sourceDatasetId:DatasetIdSchema,specId:TransformSpecIdSchema.optional(),version:external_exports.number().int().positive().optional()}),MAX_SPEC_VERSION_HISTORY=50,TransformSpecVersionSchema=external_exports.object({version:external_exports.number().int().positive(),savedAt:external_exports.string().datetime(),stepCount:external_exports.number().int().nonnegative().nullable()}),SavedTransformSpecSchema=TransformSpecSchema.extend({version:external_exports.number().int().positive(),isLatest:external_exports.boolean(),savedAt:external_exports.string().datetime(),versions:external_exports.array(TransformSpecVersionSchema).max(MAX_SPEC_VERSION_HISTORY),versionCount:external_exports.number().int().nonnegative()}),RecipeSourceSchema=external_exports.object({slot:external_exports.string().min(1),datasetId:DatasetIdSchema,name:external_exports.string().min(1),kind:DatasetKindSchema,provenance:DatasetProvenanceSchema}),DatasetTransformationSchema=SavedTransformSpecSchema.omit({sourceDatasetId:!0}).extend({sources:external_exports.array(RecipeSourceSchema).min(1),result:RecipeResultSchema,sourcePin:RecipeSourcePinSchema.nullable(),currentLoad:external_exports.object({loadNumber:external_exports.number().int().positive(),specVersion:external_exports.number().int().positive().nullable(),madeByMaker:external_exports.boolean().optional()}).nullable()});var PreviewReturnRowsSchema=external_exports.enum(["none","all"]).describe("Whether to return the sampled ROW PAYLOADS. `none` (THE DEFAULT) returns the column diff and the counts only \u2014 which is what a caller iterating on a step list is reading, and it keeps the source data's own cell values out of a reply that does not need them. `all` returns `sourceRows` and `rows` as well, for a client that renders the sample. The counts (`sampledRows`, `sourceRowCount`, `resultRows`, `stepsEvaluated`) and the whole column diff ride on the wire in EVERY mode, so nothing about what the steps DO is hidden by the default."),PreviewSpecStepsInputSchema=external_exports.object({sourceDatasetId:DatasetIdSchema,sourceVersionId:DatasetVersionIdSchema.optional(),steps:external_exports.array(TransformStepSchema).max(MAX_TRANSFORM_STEPS),upToIndex:external_exports.number().int().nonnegative().optional(),returnRows:PreviewReturnRowsSchema.optional()}),PreviewRemovedColumnSchema=DatasetColumnSchema2.extend({renamedTo:external_exports.string().min(1).optional()}),PreviewRetypedColumnSchema=external_exports.object({name:external_exports.string().min(1),from:DatasetColumnTypeSchema,to:DatasetColumnTypeSchema}),PreviewColumnDiffSchema=external_exports.object({added:external_exports.array(DatasetColumnSchema2),removed:external_exports.array(PreviewRemovedColumnSchema),retyped:external_exports.array(PreviewRetypedColumnSchema)}),SpecStepsPreviewSchema=external_exports.object({columnsBefore:external_exports.array(DatasetColumnSchema2),columnsAfter:external_exports.array(DatasetColumnSchema2),diff:PreviewColumnDiffSchema,sourceRows:external_exports.array(DatasetRowSchema).optional(),rows:external_exports.array(DatasetRowSchema).optional(),resultRows:external_exports.number().int().nonnegative(),sampledRows:external_exports.number().int().nonnegative(),sourceRowCount:external_exports.number().int().nonnegative(),stepsEvaluated:external_exports.number().int().nonnegative()}),StartImportJobTransformRequestSchema=TransformInputSchema.omit({idempotencyKey:!0}).strict(),StartImportJobInputSchema=external_exports.discriminatedUnion("mode",[external_exports.strictObject({mode:external_exports.literal("land"),idempotencyKey:ImportJobLandIdempotencyKeySchema,request:RawLandWireInputSchema}),external_exports.strictObject({mode:external_exports.literal("transform"),idempotencyKey:ImportJobTransformIdempotencyKeySchema,request:StartImportJobTransformRequestSchema}),external_exports.strictObject({mode:external_exports.literal("declared"),idempotencyKey:ImportJobDeclaredIdempotencyKeySchema,request:StartImportJobDeclaredRequestSchema})]),ImportJobWorkSchema=external_exports.discriminatedUnion("mode",[external_exports.strictObject({mode:external_exports.literal("land"),request:LandInputSchema}),external_exports.strictObject({mode:external_exports.literal("transform"),request:TransformInputSchema}),external_exports.strictObject({mode:external_exports.literal("declared"),request:RunSourceTransformationInputSchema})]);var rejectedConfigSource={config:external_exports.never({error:REJECTED_CONFIG_SOURCE}).optional()},inspectColumnTypesFacet={columnTypes:columnTypesWireFacet.columnTypes.describe(INSPECT_COLUMN_TYPES_DESCRIPTION)},inspectParseFacets={...parseFacets,sheet:parseFacets.sheet.describe(INSPECT_SHEET_DESCRIPTION)},inspectInlineTextSource={content:inlineTextSource.content.describe(INSPECT_CONTENT_DESCRIPTION)},inspectInlineBase64Source={contentBase64:inlineBase64Source.contentBase64.describe(INSPECT_CONTENT_BASE64_DESCRIPTION)},inspectUploadRefSource={uploadRef:uploadRefSource.uploadRef.describe(INSPECT_UPLOAD_REF_DESCRIPTION)},INSPECT_OBJECT_REF_DESCRIPTION="An opaque handle to an object captured through the Integrations capture seam (`integrations.beginCapture` \u2192 a direct-to-bucket PUT \u2192 `integrations.completeCapture`) \u2014 how a CAPTURED file gets previewed before it is landed. The server never reads the bytes: it resolves the ref server-side and the query engine reads the object directly from object storage, so the preview is bounded work at ANY object size \u2014 the header plus a bounded row sample. csv only, exactly like the land this previews (`csvDialect` applies, gzip comes from the capture source's registration). ONE HONEST GAP: the response carries NO `rowCount` \u2014 counting is a full pass over the object, which is the read a preview must not cost; the landing job counts. Recipe: capture \u2192 `inspectUpload` with the ref \u2192 `datasets.startImportJob` (mode `land`) naming the same ref. Inspecting neither consumes nor extends the capture. Exactly one of `content` / `contentBase64` / `uploadRef` / `objectRef` may be supplied.",inspectObjectRefSource={objectRef:objectRefSource.objectRef.describe(INSPECT_OBJECT_REF_DESCRIPTION)},InspectUploadInputSchema=external_exports.intersection(external_exports.object(rejectedConfigSource),external_exports.union([external_exports.object({...inspectParseFacets,...inspectColumnTypesFacet,...inspectInlineTextSource}).strict(),external_exports.object({...inspectParseFacets,...inspectColumnTypesFacet,...inspectInlineBase64Source}).strict(),external_exports.object({...inspectParseFacets,...inspectColumnTypesFacet,...inspectUploadRefSource}).strict(),external_exports.object({...inspectParseFacets,...csvDialectFacet,...inspectObjectRefSource}).strict()])),UploadSheetSchema=external_exports.object({name:external_exports.string().min(1),empty:external_exports.boolean(),rowCount:external_exports.number().int().nonnegative().optional(),columnCount:external_exports.number().int().nonnegative().optional()}),CAST_REPORT_MAX_SAMPLES=5,CAST_SAMPLE_MAX_LENGTH=256,ColumnCastSampleSchema=external_exports.object({value:external_exports.string().max(CAST_SAMPLE_MAX_LENGTH),row:external_exports.number().int().positive()}),ColumnCastReportSchema=external_exports.object({column:external_exports.string().min(1),declared:DatasetColumnTypeSchema,failingCount:external_exports.number().int().nonnegative(),samples:external_exports.array(ColumnCastSampleSchema).max(CAST_REPORT_MAX_SAMPLES)}),UploadInspectionSchema=external_exports.object({format:DatasetFormatSchema,sheets:external_exports.array(UploadSheetSchema),sheet:external_exports.string().min(1).optional(),columns:external_exports.array(DatasetColumnSchema2),rows:external_exports.array(DatasetRowSchema),rowCount:external_exports.number().int().nonnegative().optional(),castReport:external_exports.array(ColumnCastReportSchema).optional()});var CountSchema=external_exports.number().int().nonnegative();var SkippedDatasetSchema=external_exports.object({datasetName:external_exports.string(),slug:external_exports.string(),fallbackSlug:external_exports.string().optional(),code:external_exports.string(),reason:external_exports.string()}),DirectoryLastRunSchema=external_exports.discriminatedUnion("outcome",[external_exports.object({outcome:external_exports.literal("published"),finishedAt:external_exports.iso.datetime(),asOf:external_exports.iso.datetime(),identifierCount:CountSchema,assetCount:CountSchema,assetsWithoutLocation:CountSchema.optional(),skippedDatasets:external_exports.array(SkippedDatasetSchema).optional()}),external_exports.object({outcome:external_exports.literal("refused"),finishedAt:external_exports.iso.datetime(),asOf:external_exports.iso.datetime(),skippedDatasets:external_exports.array(SkippedDatasetSchema).min(1)}),external_exports.object({outcome:external_exports.literal("empty"),finishedAt:external_exports.iso.datetime(),asOf:external_exports.iso.datetime()}),external_exports.object({outcome:external_exports.literal("failed"),finishedAt:external_exports.iso.datetime(),reason:external_exports.string().min(1)})]),DirectoryPublishedSchema=external_exports.object({finishedAt:external_exports.iso.datetime(),asOf:external_exports.iso.datetime(),identifierCount:CountSchema,assetCount:CountSchema,assetsWithoutLocation:CountSchema.optional(),previousAssetsWithoutLocation:CountSchema.optional(),skippedDatasets:external_exports.array(SkippedDatasetSchema).optional()}),PublishDirectoryInputSchema=external_exports.strictObject({idempotencyKey:IdempotencyKeySchema}),PublishDirectoryResultSchema=external_exports.discriminatedUnion("kind",[external_exports.object({kind:external_exports.literal("started")}),external_exports.object({kind:external_exports.literal("already-running")})]),DirectoryAutoRefreshSchema=external_exports.object({enabled:external_exports.boolean(),pending:external_exports.boolean(),pendingSince:external_exports.iso.datetime().nullable(),lastChangedAt:external_exports.iso.datetime().nullable(),lastRunFailed:external_exports.boolean().optional(),lastFailedAt:external_exports.iso.datetime().nullable().optional(),consecutiveFailures:external_exports.number().int().nonnegative().optional()}),DirectoryPublishStatusSchema=external_exports.object({everPublished:external_exports.boolean(),runInProgress:external_exports.boolean(),runStale:external_exports.boolean(),lastRun:DirectoryLastRunSchema.nullable(),lastPublished:DirectoryPublishedSchema.nullable(),autoRefresh:DirectoryAutoRefreshSchema});var ASSET_SELECTION_OMITTED={orderBy:!0,offset:!0,limit:!0,cursor:!0,asOf:!0,knownAt:!0,subtreeOf:!0,underAssetIds:!0,conditions:!0};var DELETE_IMPACT_MAX_IDS=100,DELETE_MANY_MAX_IDS=100,DeleteImpactVerdictSchema=external_exports.enum(["deletable","reparentable","reparentable-too-wide","blocked","not-found"]),HierarchyEdgeDirectionSchema=external_exports.enum(["child","parent"]),DeleteRefusalReasonSchema=external_exports.enum(["not-found","has-relationships","has-external-id-bindings"]);var SET_LOCATION_MANY_MAX_PLACEMENTS=1e4;var AssetPlacementSchema=external_exports.strictObject({get assetId(){return AssetIdSchema},get geometry(){return GeoJsonGeometryInputSchema}}),IDEMPOTENCY_KEY_MAX_LENGTH=200,SetLocationManyInputSchema=external_exports.strictObject({placements:external_exports.array(AssetPlacementSchema).min(1).max(SET_LOCATION_MANY_MAX_PLACEMENTS),idempotencyKey:IdempotencyKeySchema.max(IDEMPOTENCY_KEY_MAX_LENGTH),returnResults:ReturnResultsSchema.optional()}),SetLocationManyErrorCodeSchema=external_exports.enum(["asset-not-found","invalid-geometry","conflict"]),SetLocationManyItemResultSchema=external_exports.discriminatedUnion("status",[external_exports.object({get assetId(){return AssetIdSchema},status:external_exports.literal("placed")}),external_exports.object({get assetId(){return AssetIdSchema},status:external_exports.literal("failed"),error:external_exports.object({code:SetLocationManyErrorCodeSchema,message:external_exports.string().min(1)})})]),SetLocationManyOutputSchema=external_exports.object({summary:external_exports.object({requested:external_exports.number().int().nonnegative(),placed:external_exports.number().int().nonnegative(),failed:external_exports.number().int().nonnegative()}),results:external_exports.array(SetLocationManyItemResultSchema)});var DerivedPropertyCodeSchema=external_exports.string().min(1).max(64),DerivedPropertyDeclarationSchema=external_exports.strictObject({code:DerivedPropertyCodeSchema,displayName:external_exports.string().min(1)}),DerivedRoutingRuleSchema=external_exports.strictObject({propertyCode:DerivedPropertyCodeSchema,projectId:external_exports.string().min(1),element:external_exports.string().min(1)}),DerivedRoutingConfigSchema=external_exports.strictObject({rules:external_exports.array(DerivedRoutingRuleSchema).max(200)}),SaveDerivedRoutingInputSchema=external_exports.strictObject({config:DerivedRoutingConfigSchema,idempotencyKey:IdempotencyKeySchema.max(IDEMPOTENCY_KEY_MAX_LENGTH)}),DerivedValueProvenanceSchema=external_exports.strictObject({runId:external_exports.string().min(1),datasetVersionId:external_exports.string().min(1),periodId:external_exports.string().min(1)}),DerivedValueSchema=external_exports.strictObject({propertyCode:DerivedPropertyCodeSchema,displayName:external_exports.string().min(1),valueKind:external_exports.string().min(1),value:external_exports.string(),unit:external_exports.string().min(1).optional(),computedAt:external_exports.iso.datetime(),provenance:DerivedValueProvenanceSchema}),ListDerivedValuesInputSchema=external_exports.strictObject({get assetId(){return AssetIdSchema}}),ApplyDerivedValuesInputSchema=external_exports.strictObject({datasetVersionId:external_exports.string().min(1)}),ApplyDerivedValuesReportSchema=external_exports.strictObject({datasetVersionId:external_exports.string().min(1),slotsWritten:external_exports.number().int().nonnegative(),slotsRemoved:external_exports.number().int().nonnegative(),assetsTouched:external_exports.number().int().nonnegative(),skipped:external_exports.number().int().nonnegative().default(0)}),DueDerivedApplySchema=external_exports.strictObject({datasetVersionId:external_exports.string().min(1),datasetId:external_exports.string().min(1),triggeredAt:external_exports.iso.datetime()});var NumberingSchemeSchema=external_exports.strictObject({prefix:external_exports.string().min(1).max(32).optional(),categoryCode:external_exports.string().min(1).max(32).optional(),counterWidth:external_exports.number().int().min(1).max(12),suffix:external_exports.string().min(1).max(32).optional(),separator:external_exports.string().max(4),locked:external_exports.boolean()});var NumberingCategoryOverrideSchema=external_exports.strictObject({get categoryId(){return AssetCategoryIdSchema},scheme:NumberingSchemeSchema}),NumberingConfigSchema=external_exports.strictObject({defaultScheme:NumberingSchemeSchema.nullable(),categoryOverrides:external_exports.array(NumberingCategoryOverrideSchema)}),NUMBERING_CATEGORY_OVERRIDES_WIRE_MAX=1e3,NumberingConfigInputSchema=NumberingConfigSchema.extend({categoryOverrides:external_exports.array(NumberingCategoryOverrideSchema).max(NUMBERING_CATEGORY_OVERRIDES_WIRE_MAX)}),SaveNumberingConfigInputSchema=external_exports.strictObject({config:NumberingConfigInputSchema,idempotencyKey:IdempotencyKeySchema}),SuggestAssetCodeInputSchema=external_exports.strictObject({get categoryId(){return AssetCategoryIdSchema.optional()}}),SuggestAssetCodeResultSchema=external_exports.strictObject({code:external_exports.string().nullable(),scheme:NumberingSchemeSchema.nullable(),locked:external_exports.boolean().describe("ADVISORY: the active scheme declares the code field read-only in the UI. The backend does NOT enforce it \u2014 any string a caller binds is accepted; uniqueness alone is enforced (DB natural-key index).")});var EXTERNAL_ID_RESOLVE_MANY_MAX=500,ResolveManySystemSchema=external_exports.discriminatedUnion("kind",[external_exports.strictObject({kind:external_exports.literal("asset-id")}),external_exports.strictObject({kind:external_exports.literal("external-id"),key:ExternalIdSystemSchema})]),ResolveExternalIdManyInputSchema=external_exports.strictObject({system:ResolveManySystemSchema,values:external_exports.array(ExternalIdValueSchema).min(1).max(EXTERNAL_ID_RESOLVE_MANY_MAX)}),ResolvedExternalIdSchema=external_exports.object({value:external_exports.string().min(1),outcome:external_exports.enum(["matched","ambiguous","not-found"]),assetIds:external_exports.array(AssetIdSchema)}),ResolveExternalIdManyOutputSchema=external_exports.object({results:external_exports.array(ResolvedExternalIdSchema)}),EXTERNAL_ID_SYSTEM_NOT_CONFIGURED="EXTERNAL_ID_SYSTEM_NOT_CONFIGURED";var SetAssetTemplateInputSchema=external_exports.strictObject({idempotencyKey:UnreceiptedIdempotencyKeySchema,assetTypeId:AssetTypeIdSchema,get properties(){return external_exports.array(TemplatePropertyInputSchema).max(TEMPLATE_PROPERTIES_WIRE_MAX).describe("The type's authored properties \u2014 a FULL-STATE REPLACE, always: whatever you send becomes the new version's complete property set, so a property you omit is REMOVED and `[]` erases them all. Read the current template first and send it back with your edit applied; there is no partial-update form. Every existing asset of this type is validated against the new definition from here on, so adding a `required` property makes every asset that lacks it fail its next write, and dropping `required` from one is what makes previously-refused rows importable. Versioning is APPEND-ONLY \u2014 the previous version stays readable and the assets that pinned it keep pointing at it \u2014 so an edit is recoverable, not destructive.")},get derivedProperties(){return external_exports.array(DerivedPropertyDeclarationSchema).max(TEMPLATE_DERIVED_PROPERTIES_WIRE_MAX).optional().describe('Derived-property declarations. This field is GENUINELY OPTIONAL and OMITTING IT IS SAFE \u2014 the answer to "does leaving it out clear them?" is NO. ABSENT = the current version\'s declarations are carried FORWARD untouched, which is what lets a caller edit `properties` without knowing this field exists (and is why it carries no `[]` default: a default would make every such caller submit an empty full-state replace and destroy them). PRESENT = a FULL-STATE replace exactly like `properties` \u2014 an omitted declaration is a removal, and `[]` clears them all. So: omit to preserve, send the full list to change, send `[]` to clear.')}}),RawSetAssetTemplateInputSchema=SetAssetTemplateInputSchema.omit({idempotencyKey:!0});var MAX_NEARBY_RADIUS_METERS=20015087;var SPATIAL_QUERY_MAX_LIMIT=200,BoundingBoxSchema=external_exports.strictObject({southWest:GeoJsonPositionSchema,northEast:GeoJsonPositionSchema}),NearbyAssetsInputSchema=external_exports.strictObject({center:GeoJsonPositionSchema,radiusMeters:external_exports.number().positive().max(MAX_NEARBY_RADIUS_METERS),limit:external_exports.number().int().min(1).max(SPATIAL_QUERY_MAX_LIMIT).optional()}),NearbyAssetMatchSchema=external_exports.object({get asset(){return AssetSchema},distanceMeters:external_exports.number().min(0)}),NearbyAssetsOutputSchema=external_exports.object({items:external_exports.array(NearbyAssetMatchSchema),total:external_exports.number().int().min(0)}),AssetsWithinBoundsInputSchema=external_exports.strictObject({bounds:BoundingBoxSchema,limit:external_exports.number().int().min(1).max(SPATIAL_QUERY_MAX_LIMIT).optional()}),AssetsWithinBoundsOutputSchema=external_exports.object({get items(){return external_exports.array(AssetSchema)},total:external_exports.number().int().min(0)}),WITHIN_POLYGON_IDS_MAX=200,AssetsWithinPolygonInputSchema=external_exports.strictObject({polygon:GeoJsonPolygonSchema}),AssetsWithinPolygonOutputSchema=external_exports.object({get assetIds(){return external_exports.array(AssetIdSchema).max(WITHIN_POLYGON_IDS_MAX)},total:external_exports.number().int().min(0)}),MAP_AGGREGATE_MIN_ZOOM=0,MAP_AGGREGATE_MAX_ZOOM=22;var MapAggregateInputSchema=external_exports.strictObject({bounds:BoundingBoxSchema,zoom:external_exports.number().int().min(MAP_AGGREGATE_MIN_ZOOM).max(MAP_AGGREGATE_MAX_ZOOM)}),MapAggregateBinSchema=external_exports.object({count:external_exports.number().int().min(1),centroid:GeoJsonPositionSchema,cellBounds:BoundingBoxSchema}),MapAggregateOutputSchema=external_exports.object({bins:external_exports.array(MapAggregateBinSchema),total:external_exports.number().int().min(0)}),MAP_FEATURES_MAX_LIMIT=2e3;var MapFeaturesInputSchema=external_exports.strictObject({bounds:BoundingBoxSchema,limit:external_exports.number().int().min(1).max(MAP_FEATURES_MAX_LIMIT).optional()}),MapFeatureSchema=external_exports.object({get id(){return AssetIdSchema},name:external_exports.string().min(1),position:GeoJsonPositionSchema}),MapFeaturesOutputSchema=external_exports.object({items:external_exports.array(MapFeatureSchema),total:external_exports.number().int().min(0)});var ASSET_LOCATIONS_MAX_LIMIT=2e3;var AssetLocationsInputSchema=external_exports.strictObject({get categoryIds(){return external_exports.array(AssetCategoryIdSchema).min(1).max(50).optional()},get assetTypeIds(){return external_exports.array(AssetTypeIdSchema).min(1).max(50).optional()},get lifecycleStatuses(){return external_exports.array(AssetLifecycleStatusSchema).min(1).max(50).optional()},nameContains:external_exports.string().min(1).optional(),get assetIds(){return external_exports.array(AssetIdSchema).min(1).max(ASSET_IDS_MAX_PER_PAGE).optional()},within:GeoJsonPolygonSchema.optional(),search:AssetSearchSchema.optional(),limit:external_exports.number().int().min(1).max(ASSET_LOCATIONS_MAX_LIMIT).optional()}),AssetLocationSchema=external_exports.object({get assetId(){return AssetIdSchema},name:external_exports.string().min(1),geometry:GeoJsonGeometrySchema}),AssetLocationsOutputSchema=external_exports.object({items:external_exports.array(AssetLocationSchema),total:external_exports.number().int().min(0),totalAtLeast:external_exports.literal(!0).optional()});var CreateManyErrorCodeSchema=external_exports.enum(["target-not-found","target-ambiguous","template-validation","type-not-found","type-ambiguous","identity-conflict","history-too-long","invalid-geometry","would-cycle"]);var CompositionFailureClassSchema=external_exports.strictObject({code:CreateManyErrorCodeSchema,rows:external_exports.number().int().positive()}),CompositionFailureClassesSchema=external_exports.array(CompositionFailureClassSchema);var KEY_COLUMNS_WIRE_MAX=64,PROPERTY_COLUMNS_WIRE_MAX=1e3,RELATIONSHIPS_WIRE_MAX=256,ADDITIONAL_EXTERNAL_IDS_WIRE_MAX=64,PropertyColumnsInputSchema=wireBoundedRecord(external_exports.string().min(1),external_exports.string().min(1).max(64),PROPERTY_COLUMNS_WIRE_MAX);var AdditionalExternalIdImportMappingSchema=external_exports.strictObject({system:ExternalIdSystemSchema,column:external_exports.string().min(1)}),AdditionalExternalIdsSchema=external_exports.array(AdditionalExternalIdImportMappingSchema),AdditionalExternalIdsInputSchema=AdditionalExternalIdsSchema.max(ADDITIONAL_EXTERNAL_IDS_WIRE_MAX);var AdditionalIdentifiersAlreadyBoundSchema=external_exports.object({count:external_exports.number().int().positive(),sample:external_exports.array(external_exports.object({rowIndex:external_exports.number().int().nonnegative(),system:ExternalIdSystemSchema}))});var AssetImportDeliveryThresholdsSchema=external_exports.strictObject({maxAbsentShare:external_exports.number().min(0).max(1).optional().describe("Refuse the delivery when more than this SHARE of the tenant\u2019s live bindings in the mapping\u2019s external-ID system are NOT named by it. Catches a file exported from the wrong filter, which reports complete success while touching a fraction of the estate. Absent \u21D2 the house default."),maxPropertiesWouldClearShare:external_exports.number().min(0).max(1).optional().describe("Refuse the delivery when more than this SHARE of it would have template properties CLEARED \u2014 an update replaces the whole property map, so a file narrower than the original import blanks every optional code absent from it. An UPPER BOUND: the accept cannot tell a matched row that will write from one already in agreement. Absent \u21D2 the house default."),maxMoves:external_exports.number().int().nonnegative().optional().describe('Refuse the delivery when `edgePolicy: "replace"` would MOVE more than this many matched assets to a different parent. Overrides `MOVE_CEILING_PER_DELIVERY`. Enforced where the count is known \u2014 above every write in the reconciliation arm, not at accept, because the move count needs the rows classified. PER TILE, therefore, not per submission: a tile is the unit that classifies rows, so a job of many tiles may move more than this in total while no single tile does. Absent \u21D2 the constant.'),giveUpFailureShare:external_exports.number().min(0).max(1).optional().describe("Stop claiming tiles once this SHARE of the rows the job has seen have failed, and seal FAILED with honest counts. Absent \u21D2 `COMPOSITION_JOB_GIVE_UP_FAILURE_SHARE`."),giveUpMinRows:external_exports.number().int().nonnegative().optional().describe("The floor the give-up share is only judged above, so a bad first tile alone cannot trip it. Absent \u21D2 `COMPOSITION_JOB_GIVE_UP_MIN_ROWS`.")}).describe("OPT-IN delivery gate. ABSENT \u21D2 no gate and no measurement \u2014 the accept pays nothing. `{}` \u21D2 gate with the house defaults. A breach refuses the WHOLE delivery at accept with a declared refusal naming the threshold and the measured value; nothing is written. NOTE: the FAILING-ROW share is deliberately NOT among these \u2014 no accept-time signal for it exists on a delivery above the rows-mode cap, and the refusal text says so rather than letting a gate look more complete than it is.");var DeliveryThresholdNameSchema=external_exports.enum(["maxAbsentShare","maxPropertiesWouldClearShare"]),DeliveryThresholdCoverageSchema=external_exports.union([external_exports.strictObject({complete:external_exports.literal(!0)}),external_exports.strictObject({complete:external_exports.literal(!1),unevaluated:external_exports.array(DeliveryThresholdNameSchema).min(1),reason:external_exports.string().min(1)})]),DeliveryThresholdBreachSchema=external_exports.object({threshold:DeliveryThresholdNameSchema,limit:external_exports.number(),measured:external_exports.number(),failureShareUnchecked:external_exports.boolean()});var AssetEdgePolicySchema=external_exports.enum(["keep","report","replace"]).describe("What a MATCHED row's hierarchy edge does. `keep` (the default) leaves the edge the first import placed and reports how many rows name a different parent; `report` is the same writes with the same count, asked for deliberately; `replace` MOVES the asset \u2014 ending its current parent edge and writing the file's \u2014 inside the import's own transaction, with visibility routes rewritten before the call returns. None of the three needs the import to name a hierarchy: a matched asset holding exactly ONE open parent has an unambiguous edge to report or replace, one holding SEVERAL is left untouched and counted as `skippedAmbiguousParent`, and one holding NONE in a NAMED tree is counted as `attachable` \u2014 and under `replace` it is ATTACHED to the file's parent, dated by `projection.effectiveFrom` when the import declares one. A single call naming more moves than the move ceiling is refused whole before it writes; a tiled background delivery whose running total breaches it stops and fails, and the moves it already committed stand. Attaches do not count toward the move ceiling.");var HierarchyDivergenceSchema=external_exports.object({divergent:external_exports.number().int().nonnegative(),moved:external_exports.number().int().nonnegative(),skippedAmbiguousParent:external_exports.number().int().nonnegative().optional(),attachable:external_exports.number().int().positive().optional(),attached:external_exports.number().int().positive().optional(),parentUnresolved:external_exports.number().int().positive().optional(),unplacedInBucket:external_exports.number().int().positive().optional()}),HierarchyDivergencePreviewSchema=external_exports.object({divergent:external_exports.number().int().nonnegative(),skippedAmbiguousParent:external_exports.number().int().nonnegative().optional(),attachable:external_exports.number().int().positive().optional(),parentUnresolved:external_exports.number().int().positive().optional(),unplacedInBucket:external_exports.number().int().positive().optional(),moveCeiling:external_exports.number().int().nonnegative()});var NESTING_PAIRS_MAX=500,NESTING_TYPE_KEY_MAX=200;var TypeKeySchema=external_exports.string().min(1).max(NESTING_TYPE_KEY_MAX).regex(/^[^\u0000\ud800-\udfff]*$/u,"a type key a stored rule can hold"),NestingPairSchema=external_exports.strictObject({parentType:TypeKeySchema.describe("The KEY of the asset type that may be the parent."),childType:TypeKeySchema.describe("The KEY of the asset type that may sit directly under it.")}),NestingRulesSchema=external_exports.strictObject({pairs:external_exports.array(NestingPairSchema).max(NESTING_PAIRS_MAX)}),SaveNestingRulesInputSchema=external_exports.strictObject({rules:NestingRulesSchema,idempotencyKey:IdempotencyKeySchema});var NESTING_BREAKS_MAX=500,INT4_MAX=2147483647,NestingBreakSchema=external_exports.strictObject({parentType:external_exports.string().min(1),childType:external_exports.string().min(1),count:external_exports.number().int().positive().max(INT4_MAX)}),NestingBreaksReportSchema=external_exports.strictObject({total:external_exports.number().int().positive().max(INT4_MAX),pairs:external_exports.array(NestingBreakSchema).max(NESTING_BREAKS_MAX)});var NestingCheckSchema=external_exports.literal("unavailable"),StoredNestingRulesSchema=external_exports.object({pairs:external_exports.array(external_exports.object({parentType:external_exports.string().min(1),childType:external_exports.string().min(1)}))});var PROPERTY_COLUMNS_DESCRIPTION='Which columns become asset properties, as `{ "dataset column": "template property code" }`. OMITTING THIS IS NOT "no properties" \u2014 it means IDENTITY MODE: EVERY column not consumed structurally (the name, row-key, asset-type, lifecycle and geometry columns, plus an external-ID column) is copied as a property under its own column name. With `assetType.from: "constant"`, a type whose template does not define those columns\' names fails EVERY one of its rows with `unknown property code "..."` issues \u2014 which is why a wide sheet imported into a pre-existing type usually needs this stated explicitly there. With `assetType.from: "column"`, there is no per-property field table to state this with, so each row\'s identity-copied columns are instead matched against ITS OWN RESOLVED TYPE\'s template with case/whitespace/punctuation-insensitive normalization (`"API Number"` matches a template code `apiNumber`), and a column that still matches nothing is DROPPED for that row rather than failing it \u2014 never affecting the SEPARATE required-property-missing check, which still fails a row whose template requires a property no surviving column supplied a value for. Supply `{}` to import NO properties at all. In explicit mode only the listed columns are copied, renamed to their codes. A NULL OR ABSENT CELL IS OMITTED FOR THAT ROW IN EITHER MODE \u2014 identity mode skips it exactly as an explicit mapping does, so a sparsely-populated column yields the property only on the rows that have it, and the template\'s required-ness is then what decides whether each row passes.';var RelationshipMatchOnSchema=external_exports.union([external_exports.string().min(1).max(64),external_exports.strictObject({get externalId(){return ExternalIdSystemSchema}})]);var TemplateConflictRouteSchema=external_exports.enum(["exclude","supply","template_set"]);var TemplateConflictPropertySchema=external_exports.object({code:external_exports.string().min(1).describe("The template property code this batch cannot satisfy."),get valueType(){return PropertyValueTypeSchema},satisfiablePct:external_exports.number().min(0).max(100).describe('What percentage of this type\'s scanned rows carry a value the template ACCEPTS for this property \u2014 validity, not mere presence, so a required NUMBER whose column holds "150 psi" counts as unsatisfied. The denominator is `assetType.rowsScanned`. 0 and 100 are RESERVED for the absolutes: `0` means no scanned row satisfies it, and a rate that is merely very small or very large reads `0.1` / `99.9` rather than rounding into one. This is the number that separates "the column is populated on a sixth of these rows" from "nothing in this file maps to it" \u2014 two situations that want different routes.')}),TemplateConflictSchema=external_exports.object({code:external_exports.literal("TEMPLATE_CONFLICT"),message:external_exports.string().min(1),assetType:external_exports.object({get id(){return AssetTypeIdSchema},key:external_exports.string().min(1),displayName:external_exports.string().min(1),preExisting:external_exports.boolean().describe("TRUE when this type was already the tenant's before the import \u2014 including a type another writer created concurrently that this call adopted rather than minted. Only a pre-existing type can collide: a type THIS call auto-created carries a derived template with zero required properties, so it can never produce a conflict. Stated rather than left to be inferred, because it is what makes the routes make sense \u2014 you are being asked about vocabulary you own."),rowsScanned:external_exports.number().int().nonnegative().describe("How many rows of this type reached TEMPLATE VALIDATION \u2014 the denominator behind `failedRows` and every `satisfiablePct`. Rows refused earlier (assembly, relationship targets, type binding) never produced a property map to judge, so they are outside this report and are not counted here; their own per-row failures name their own causes. A matched external-ID UPDATE row IS scanned here, against the PROJECTED type \u2014 it had to pass that template to reach reconciliation at all. What this report does NOT reflect is the SECOND validation such a row then gets against the MATCHED asset's own current type; that verdict rides on the row's own per-row failure, not this count.")}),requiredProperties:external_exports.array(TemplateConflictPropertySchema).min(1),failedRows:external_exports.number().int().nonnegative().describe("How many of the `assetType.rowsScanned` rows cannot satisfy at least ONE of the required properties above. Not the same as the number of rows this import refused overall \u2014 a row can also fail for reasons that have nothing to do with this template."),routes:external_exports.array(TemplateConflictRouteSchema).min(1).describe("The sanctioned ways forward, as a closed set, ORDERED BY WHO MAY DECIDE. `exclude` leaves the slice out; `supply` puts the values in the source data and re-imports. Both are yours to take. `template_set` is LAST and differs in KIND: it REQUIRES TENANT ADMIN \u2014 a `tenant:member` caller is refused FORBIDDEN on `vocabulary.template.set`, the same authority `vocabulary.type.create` requires \u2014 and editing the template changes the tenant's data contract for EVERY asset of that type, existing ones included, so it is an OPERATOR decision \u2014 an automated caller should surface this report to its operator and stop, not relax the requirement to finish its own task. The edit being versioned, append-only and recoverable makes it repairable, not authorised. Required properties ARE the contract: there is deliberately no fourth route and no relaxation flag, and this verb never fabricates a value or edits a template on your behalf.")});var VALUE_MAP_COLUMN_NAME_MAX=256,VALUE_MAP_TEXT_MAX=256,STORABLE_TEXT=/^[^\u0000\ud800-\udfff]*$/u,storableText=()=>external_exports.string().min(1).regex(STORABLE_TEXT,"text a stored mapping can hold"),ProjectedValueMapsSchema=external_exports.record(storableText().max(VALUE_MAP_COLUMN_NAME_MAX),external_exports.record(storableText().max(VALUE_MAP_TEXT_MAX),storableText().max(VALUE_MAP_TEXT_MAX))).describe('Optional value lists, `{ "dataset column": { "source value": "value to use" } }`. A cell whose text is exactly a listed source value reads as the replacement; any other cell is unchanged. Never applied to the row key or the external-ID column. Saved with the import mapping so a re-run maps the same way. At most 50 columns, 1,000 entries each, 5,000 in all.');var GetDerivedPropertiesInputSchema=external_exports.strictObject({get assetId(){return AssetIdSchema},projectId:external_exports.string().min(1),periodId:external_exports.string().min(1)}),DerivedPropertyValueSchema=external_exports.object({element:external_exports.string().min(1),period:external_exports.string().min(1),valueKind:external_exports.string().min(1),value:external_exports.string(),unit:external_exports.string().min(1).optional(),provenanceRef:external_exports.string().min(1)}),DerivedPropertiesSchema=external_exports.object({get assetId(){return AssetIdSchema},projectId:external_exports.string().min(1),periodId:external_exports.string().min(1),runId:external_exports.string().min(1),values:external_exports.array(DerivedPropertyValueSchema)});var ProjectedAssetTypeSchema=external_exports.discriminatedUnion("from",[external_exports.object({from:external_exports.literal("column"),column:external_exports.string().min(1)}),external_exports.object({from:external_exports.literal("constant"),get value(){return AssetTypeIdSchema}})]).describe('Which asset type each row is created under: one `constant` type for the whole import, or a `column` whose cell classifies each row. A column cell is matched against the tenant\'s LIVE asset types in this order \u2014 (1) an asset-type **id**, uuid-shaped, matched case-INsensitively; (2) the type\'s **key** and its **displayName**, searched TOGETHER as one candidate set, EXACT match: no case-folding, no trimming, no synonyms, so "separator" does not match a type named "Separator". A value equal to a live type\'s displayName RESOLVES to that type \u2014 it never creates a second one. A value matching MORE THAN ONE live type fails those rows `type-ambiguous` rather than picking one (disambiguate by putting the asset-type id, or a unique key, in the column). A value matching NOTHING fails those rows `type-not-found` \u2014 unless `createMissingTypes` is supplied, which creates a new type whose key AND displayName are the raw cell value, verbatim. The cell is structurally REQUIRED: absent, null, or blank fails that row.'),ProjectedLifecycleStatusSchema=external_exports.discriminatedUnion("from",[external_exports.object({from:external_exports.literal("column"),column:external_exports.string().min(1)}),external_exports.object({from:external_exports.literal("constant"),value:AssetLifecycleStatusSchema})]).describe('REQUIRED \u2014 every created asset carries a lifecycle status and the server applies no default, so this field must be stated: a `constant` applied to EVERY row, or a `column` read per row. The accepted values are exactly `PRE_PRODUCTION`, `ACTIVE`, `INACTIVE`, `SHUT_IN`, `DECOMMISSIONED`. A COLUMN cell is stringified and compared to that list EXACTLY \u2014 CASE-SENSITIVE, no trimming, no mapping of source vocabulary \u2014 so "Active", "active", "Shut In" and "In Service" each FAIL their row (`template-validation`); they are not normalised to a status. An absent, null, or blank cell fails its row the same way. Map source status vocabulary onto these five values in the dataset transform BEFORE importing, or state a constant \u2014 but a constant is applied to every row, including the rows whose source data says something else, so a column of real statuses should be mapped, not overridden.');var ProjectedGeometrySchema=external_exports.strictObject({latColumn:external_exports.string().min(1),lonColumn:external_exports.string().min(1),overwrite:external_exports.boolean().optional().describe("Only for an external-ID import: whether a MATCHED asset that already has a location takes the file's instead. Absent or false (the default) FILLS MISSING locations only: a matched asset with no location takes the file's, one that already has a location keeps it and counts in `locationsKept` when they differ. true restores \"the file wins\": every matched row that names a location replaces the stored one. Created rows always take the file's.")}),KeyColumnFieldSchema=external_exports.string().min(1).describe("ONE dataset column whose cell IS the created asset's row key \u2014 the identity stamped on its provenance, and what makes a re-import of the same file converge instead of duplicating. The row key must be stated EXACTLY ONCE: supply this OR `keyColumns`, never neither and never both (both spellings yield the identical key for a single column). The cell is structurally REQUIRED \u2014 absent, null, or blank fails that row. Unrelated to the DATASET's own `keyColumn` at land time: that one stamps the dataset's `row_key` for load-to-load diffing, this one decides asset provenance, and setting either never sets or defaults the other."),KeyColumnsFieldSchema=external_exports.array(external_exports.string().min(1)).min(1).describe('An ORDERED composite row key, for the common case of an inventory with no single unique column: the listed cells are hashed into one deterministic key. ORDER IS PART OF THE KEY (`["a","b"]` and `["b","a"]` differ), and every listed cell is structurally REQUIRED. ONE column here is identical to `keyColumn` \u2014 the raw cell, byte for byte, unhashed \u2014 so switching spelling between imports cannot fork one estate into two; hashing starts at the SECOND column. State this OR `keyColumn`, never neither and never both. ONE LIMITATION: a multi-column key cannot join the dataset\'s own single-column `row_key`, so an import that must feed that join keeps to one key column and builds the composite as a real column in the transform instead.'),AssetProjectionBaseSchema=external_exports.strictObject({nameColumn:external_exports.string().min(1).describe("The dataset column holding each asset's name. Structurally REQUIRED per row: an absent, null, or blank cell fails that row rather than creating an unnamed asset."),keyColumn:KeyColumnFieldSchema.optional(),keyColumns:KeyColumnsFieldSchema.optional(),assetType:ProjectedAssetTypeSchema,lifecycleStatus:ProjectedLifecycleStatusSchema,propertyColumns:external_exports.record(external_exports.string().min(1),external_exports.string().min(1).max(64)).optional().describe(PROPERTY_COLUMNS_DESCRIPTION),geometry:ProjectedGeometrySchema.optional(),effectiveFrom:ProjectedEffectiveFromSchema.optional(),...ProjectedReplaceFields,valueMaps:ProjectedValueMapsSchema.optional()}),ASSET_PROJECTION_DESCRIPTION='How each dataset row is assembled into an asset. STATE THE ROW KEY EXACTLY ONCE: every projection carries either `keyColumn` (one column) or `keyColumns` (an ordered composite), never neither and never both \u2014 which is why this publishes as two variants. A projection with NEITHER is refused by the shape itself, and one with BOTH is refused by the server ("state the row key exactly once"), since "exactly one of" is the one part of the rule a JSON Schema cannot express. Without a row key there is no stable identity to stamp on each created asset, so a re-import would duplicate instead of converging \u2014 no key is ever generated for you.',AssetProjectionSchema=external_exports.union([AssetProjectionBaseSchema.extend({keyColumn:KeyColumnFieldSchema}),AssetProjectionBaseSchema.extend({keyColumns:KeyColumnsFieldSchema})]).describe(ASSET_PROJECTION_DESCRIPTION),KeyColumnsInputSchema=KeyColumnsFieldSchema.max(KEY_COLUMNS_WIRE_MAX),AssetProjectionInputBaseSchema=AssetProjectionBaseSchema.extend({keyColumns:KeyColumnsInputSchema.optional(),propertyColumns:PropertyColumnsInputSchema.optional().describe(PROPERTY_COLUMNS_DESCRIPTION)}),AssetProjectionInputSchema=external_exports.union([AssetProjectionInputBaseSchema.extend({keyColumn:KeyColumnFieldSchema}),AssetProjectionInputBaseSchema.extend({keyColumns:KeyColumnsInputSchema})]).describe(ASSET_PROJECTION_DESCRIPTION),ExternalIdImportMappingSchema=external_exports.strictObject({system:ExternalIdSystemSchema,column:external_exports.string().min(1),edgePolicy:AssetEdgePolicySchema.optional()}),CreateMissingTypesSchema=external_exports.strictObject({get categoryId(){return AssetCategoryIdSchema}}).describe("Auto-create the asset types this data names but the tenant does not have yet. ABSENT (the default) = an unmatched `assetType` value fails its rows `type-not-found`. Requires the `assets.createType` and `assets.setTemplate` actions, and at most 50 distinct types per call.\n\n`categoryId` is the ONE category EVERY type this call creates is filed under \u2014 there is no per-value category and no default, and a category is immutable once a type carries it, so an import whose new types belong in different categories needs one call per category (the other types filtered out) or the types created up front through the vocabulary verbs. It must name a LIVE category or the whole call is refused.\n\nWHAT ONE CREATED TYPE IS, and why it behaves differently from a type you already had: `key` and `displayName` are the raw column value verbatim (so a re-import resolves by key and reuses it), and the type is created WITH its first template, DERIVED from the batch \u2014 the property codes the projection produced, valueType inferred from the values observed (all-number \u2192 NUMBER, all-boolean \u2192 BOOLEAN, otherwise STRING), and EVERY property OPTIONAL. An auto-created type therefore has ZERO REQUIRED PROPERTIES, so no row of it can fail for a missing required value \u2014 which is exactly why a bulk import sails through the vocabulary it invents and can still hard-fail on a PRE-EXISTING type whose template requires properties the data does not carry. The derived template is a starting point to edit afterwards, not a claim to have understood the data; a genuinely mixed column lands STRING and its non-string rows then fail loudly rather than being coerced. An import whose rows fail PER ROW still leaves the created type and its template behind (they were written before the rows were judged), and the re-import reuses them; a TOP-LEVEL refusal is different \u2014 it aborts the transaction, so no type and no template survive it."),CreatedAssetTypeSchema=external_exports.object({get id(){return AssetTypeIdSchema},key:external_exports.string().min(1)}),RelationshipTargetScopeSchema=external_exports.discriminatedUnion("by",[external_exports.object({by:external_exports.literal("category"),get categoryId(){return AssetCategoryIdSchema}}),external_exports.object({by:external_exports.literal("assetType"),get assetTypeId(){return AssetTypeIdSchema}})]),RelationshipCardinalitySchema=external_exports.strictObject({required:external_exports.boolean(),multiplicity:external_exports.enum(["one","many"])}),RelationshipTargetSchema=external_exports.strictObject({endpoint:external_exports.enum(["subject","object"]),scope:RelationshipTargetScopeSchema,matchColumn:external_exports.string().min(1),get matchOn(){return RelationshipMatchOnSchema},cardinality:RelationshipCardinalitySchema}),RelationshipMappingSchema=external_exports.strictObject({get relationshipType(){return AssetRelationshipTypeSchema},target:RelationshipTargetSchema}),RelationshipListInput=external_exports.array(RelationshipMappingSchema).max(RELATIONSHIPS_WIRE_MAX),CREATE_MANY_ROW_CAP=1e5,ROW_RANGE_DESCRIPTION=`OPTIONAL half-open \`[start, end)\` slice of the source version, so one large landed dataset imports as several bounded calls. ABSENT = the whole dataset.
|
|
441
|
+
`).action(flags=>runMapped(async()=>{let name2=selectedProfileName();if(flags.baseUrl!==void 0){let baseUrl=flags.baseUrl;typedAddressProfile(baseUrl,name2,reason=>{throw new CliInputError(`the Studio address given cannot be used: ${reason}`)}),asCliInput(()=>upsertLoginProfile({name:name2,baseUrl}))}let active=profileOf();if(active.auth.mode!=="login")throw new CliInputError(`profile "${active.name}" is ${active.auth.mode} \u2014 it has nothing to log in to. Create a login profile with: ${INVOCATION} login --profile <name> --base-url <origin>`);let confirmed;try{confirmed=await deviceLogin({profile:active,write,open:openBrowser})}catch(error62){if(error62 instanceof DeviceLoginError){writeError(stringifyRedacted({error:error62.message})),process.exitCode=1;return}throw error62}write(stringifyRedacted({...whoamiReport(active),confirmed:{subject:confirmed.subject,tenant:confirmed.tenant}},2))})),program3.command("logout").description("revoke this session\u2019s renewal chain server-side, then delete its cached credential").action(()=>runMapped(async()=>{let active;try{active=profileOf()}catch(error62){let missing=missingProfileOf(error62);if(missing===void 0)throw error62;let cached2=cachedSignInOf(missing.profileName);if(cached2 instanceof CredentialCacheError){if(missing instanceof UnknownProfileError)throw unknownNameUnreadableCache(missing,cached2);write(stringifyRedacted({profile:missing.profileName,removed:deleteCredential(missing.profileName),revoked:!1,detail:UNREADABLE_CACHE_DELETED},2));return}if(cached2!==void 0)active=cachedSignInProfile(missing.profileName,cached2);else if(missing instanceof NoStudioAddressError){write(stringifyRedacted({profile:missing.profileName,removed:!1,revoked:!1,detail:"nothing to remove \u2014 no Studio address is configured and nothing is cached"},2));return}else throw error62}let{removed,revoked}=await revokeThenDeleteCredential(active);write(stringifyRedacted(logoutReport(active,removed,revoked),2))})),program3.command("whoami").description("the active profile, its auth mode, and (login mode) session state").option("--check","also ask the server whether it accepts the session, renewing it first if it is expiring").action(flags=>runMapped(async()=>{let active;try{active=profileOf()}catch(error62){let missing=missingProfileOf(error62);if(missing===void 0)throw error62;let cached2=cachedSignInOf(missing.profileName);if(cached2 instanceof CredentialCacheError&&missing instanceof UnknownProfileError)throw unknownNameUnreadableCache(missing,cached2);if(cached2!==void 0&&!(cached2 instanceof CredentialCacheError))active=cachedSignInProfile(missing.profileName,cached2);else{if(!(missing instanceof NoStudioAddressError))throw error62;let noAddress=missing;write(stringifyRedacted({profile:noAddress.profileName,...cached2===void 0?{session:"none",detail:"no Studio address is configured"}:{session:"unreadable",detail:cached2.message},hint:`run: ${noAddress.command}`,build:artifactBuildReport({})},2));return}}if(flags.check!==!0||active.auth.mode!=="login"){write(stringifyRedacted(whoamiReport(active),2));return}let server=await checkSessionWithServer(active);write(stringifyRedacted({...whoamiReport(active),server},2))})),program3}var VERB_SEGMENT_PATTERN=/^[a-zA-Z][a-zA-Z0-9]*$/,DOMAIN_VERB_PATTERN=/^[a-z][a-z0-9-]*\.[a-zA-Z][a-zA-Z0-9]*$/,QUALIFIED_ACTION_PATTERN=/^[a-z][a-z0-9-]*(\.[a-zA-Z][a-zA-Z0-9]*)+$/,DOMAIN_VIEW_ACTION_PATTERN=/^[a-z][a-z0-9-]*:view$/,CONTRACT_PROCEDURE_PATTERN=/^[a-zA-Z][a-zA-Z0-9]*(\.[a-zA-Z][a-zA-Z0-9]*)*$/,JOB_FIELD_PATTERN=/^[A-Za-z_][A-Za-z0-9_-]*$/,RESOURCE_KIND_PATTERN=/^[a-z][a-z0-9-]*\.[a-z][a-z0-9_-]*$/;var LINK_TYPE_CODE_PATTERN=/^[A-Za-z][A-Za-z0-9_-]*$/,LINK_TENANT_TYPE_CODE_PREFIX="CUSTOM_",LINK_MODULE_NAME_PATTERN=/^[a-z][a-z0-9-]*$/,LINK_RECORD_TYPE_PATTERN=/^[a-z][a-z0-9_-]*$/,LINK_PINNINGS=["pinned","following"],LINK_ENFORCEMENT_CLASSES=["structural","fold","display-only"],LINK_CARDINALITY_SIDES=["subject","object"],LINK_CONSTRAINT_KEYS=["cardinality","acyclic"],LinkObjectTypeSchema=external_exports.strictObject({domain:external_exports.string().regex(LINK_MODULE_NAME_PATTERN),type:external_exports.string().regex(LINK_RECORD_TYPE_PATTERN)}),LinkCardinalityConstraintSchema=external_exports.strictObject({side:external_exports.enum(LINK_CARDINALITY_SIDES),max:external_exports.literal(1)}),LinkTypeConstraintsSchema=external_exports.strictObject({cardinality:LinkCardinalityConstraintSchema.optional(),acyclic:external_exports.literal(!0).optional()},{error:issue2=>issue2.code==="unrecognized_keys"?`unknown link constraint key(s) ${issue2.keys.map(key=>`"${key}"`).join(", ")} \u2014 the closed vocabulary is ${LINK_CONSTRAINT_KEYS.join(", ")}`:void 0}).refine(constraints=>constraints.cardinality!==void 0||constraints.acyclic,{message:`constraints declares nothing \u2014 name at least one of ${LINK_CONSTRAINT_KEYS.join(", ")}, or omit it on a non-structural type`,when:payload=>payload.issues.length===0}),LinkTypeDeclarationSchema=external_exports.strictObject({code:external_exports.string().regex(LINK_TYPE_CODE_PATTERN),name:external_exports.string().min(1),inverseName:external_exports.string().min(1),allowedObjects:external_exports.array(LinkObjectTypeSchema),pinning:external_exports.enum(LINK_PINNINGS).optional(),enforcementClass:external_exports.enum(LINK_ENFORCEMENT_CLASSES),constraints:LinkTypeConstraintsSchema.optional(),system:external_exports.literal(!0,{error:"a declared link type is shipped \u2014 system is true or omitted; a tenant-added type is created by linkTypes.create, never declared"}).optional()}).superRefine((declaration,ctx)=>{declaration.code.startsWith(LINK_TENANT_TYPE_CODE_PREFIX)&&ctx.addIssue({code:"custom",path:["code"],message:`link type "${declaration.code}" takes the "${LINK_TENANT_TYPE_CODE_PREFIX}" prefix, which is reserved for tenant-added types \u2014 a shipped code may not begin with it`}),declaration.allowedObjects.length===0&&ctx.addIssue({code:"custom",path:["allowedObjects"],message:`link type "${declaration.code}" allows no objects \u2014 allowedObjects must name at least one {domain, type}`}),declaration.enforcementClass==="structural"&&declaration.constraints===void 0&&ctx.addIssue({code:"custom",path:["constraints"],message:`link type "${declaration.code}" is structural but declares no constraints`}),declaration.enforcementClass!=="structural"&&declaration.constraints!==void 0&&ctx.addIssue({code:"custom",path:["constraints"],message:`link type "${declaration.code}" is ${declaration.enforcementClass} but declares constraints \u2014 a constraint is only legal on a structural type`})}),LinkTypesManifestFacetSchema=external_exports.array(LinkTypeDeclarationSchema).superRefine((declarations,ctx)=>{let seen=new Set;declarations.forEach((declaration,index)=>{seen.has(declaration.code)&&ctx.addIssue({code:"custom",path:[index,"code"],message:`link type "${declaration.code}" is declared twice \u2014 a code is unique within its slice`}),seen.add(declaration.code)})}),LinkableStandingSchema=external_exports.union([external_exports.literal("on-create"),external_exports.strictObject({promotedBy:external_exports.string().regex(DOMAIN_VERB_PATTERN)})]),LinkableDeclarationSchema=external_exports.strictObject({type:external_exports.string().regex(LINK_RECORD_TYPE_PATTERN),standing:LinkableStandingSchema}),LinkableManifestFacetSchema=external_exports.array(LinkableDeclarationSchema).superRefine((declarations,ctx)=>{let seen=new Set;declarations.forEach((declaration,index)=>{seen.has(declaration.type)&&ctx.addIssue({code:"custom",path:[index,"type"],message:`record type "${declaration.type}" is declared linkable twice`}),seen.add(declaration.type)})});var ReadContractDeclarationSchema=external_exports.strictObject({name:external_exports.string().regex(VERB_SEGMENT_PATTERN,"read contract name must match the verb-segment grammar"),version:external_exports.number().int().positive(),procedurePath:external_exports.string().regex(CONTRACT_PROCEDURE_PATTERN),title:external_exports.string().trim().min(1).max(120).optional(),description:external_exports.string().trim().min(1).max(500).optional(),composable:external_exports.boolean(),answers:external_exports.literal("complete"),viewPermission:external_exports.string().refine(action=>DOMAIN_VERB_PATTERN.test(action)||DOMAIN_VIEW_ACTION_PATTERN.test(action),'viewPermission must be "<domain>.<verb>" or "<domain>:view"').optional()}),ReadContractsManifestFacetSchema=external_exports.array(ReadContractDeclarationSchema);var RECIPE_NAME_PATTERN=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,RECIPE_MAP_MAX=64;var RECIPE_PARAMETER_MAX=64,RECIPE_STEP_MAX=128,VALUE_PATH_PATTERN=/^[A-Za-z_][A-Za-z0-9_-]*(?:\.[A-Za-z_][A-Za-z0-9_-]*)*$/,ParameterName=external_exports.string().regex(VERB_SEGMENT_PATTERN),ParameterWords={title:external_exports.string().min(1).max(80),help:external_exports.string().min(1).max(400).optional()},Optional={optional:external_exports.literal(!0).optional()},RecipeEntityHintSchema=external_exports.strictObject({domain:external_exports.string().min(1),type:external_exports.string().min(1),pickerResource:external_exports.string().min(1).optional(),scopedBy:external_exports.record(external_exports.string().min(1),ParameterName).optional(),pinsTo:external_exports.strictObject({picker:external_exports.string().min(1)}).optional()}),StringParameterSchema=external_exports.strictObject({type:external_exports.literal("string"),...ParameterWords,...Optional,segment:external_exports.literal(!0).optional(),maxLength:external_exports.int().min(1).max(4096).optional()}),NumberParameterSchema=external_exports.strictObject({type:external_exports.literal("number"),...ParameterWords,...Optional,integer:external_exports.literal(!0).optional(),min:external_exports.number().optional(),max:external_exports.number().optional()}),BooleanParameterSchema=external_exports.strictObject({type:external_exports.literal("boolean"),...ParameterWords,...Optional}),EntityParameterSchema=external_exports.strictObject({type:external_exports.literal("entity"),...ParameterWords,...Optional,hint:RecipeEntityHintSchema}),RecipeValueParameterSchema=external_exports.discriminatedUnion("type",[StringParameterSchema,NumberParameterSchema,BooleanParameterSchema,EntityParameterSchema]),MapParameterSchema=external_exports.strictObject({type:external_exports.literal("map"),...ParameterWords,of:RecipeValueParameterSchema,min:external_exports.int().min(0).max(RECIPE_MAP_MAX).optional(),max:external_exports.int().min(1).max(RECIPE_MAP_MAX),keyTitle:external_exports.string().min(1).max(80)}).refine(map2=>(map2.min??0)<=map2.max,{message:"min must not exceed max"}),RecipeParameterSchema=external_exports.discriminatedUnion("type",[StringParameterSchema,NumberParameterSchema,BooleanParameterSchema,EntityParameterSchema,MapParameterSchema]),RecipeParamRefSchema=external_exports.strictObject({param:ParameterName,path:external_exports.string().regex(VALUE_PATH_PATTERN).optional()}),EntryPath=external_exports.union([external_exports.literal(""),external_exports.string().regex(VALUE_PATH_PATTERN)]),RecipeEntryRefSchema=external_exports.strictObject({entry:EntryPath}),RecipeEachEntryRefSchema=external_exports.strictObject({each:ParameterName,entry:EntryPath}),ScalarLeafSchema=external_exports.union([external_exports.string(),external_exports.number(),external_exports.boolean(),external_exports.null()]),RecipeLeafSchema=external_exports.union([ScalarLeafSchema,RecipeParamRefSchema,RecipeEntryRefSchema,RecipeEachEntryRefSchema]),RecipeVerbStepTemplateSchema=external_exports.strictObject({id:external_exports.string().min(1).max(200),type:external_exports.literal("verb").optional(),each:ParameterName.optional(),verb:external_exports.string().regex(DOMAIN_VERB_PATTERN),args:external_exports.record(external_exports.string().min(1),RecipeLeafSchema)}),DurationSchema=external_exports.strictObject({amount:external_exports.number(),unit:external_exports.string().min(1)}),BranchGateTemplateSchema=external_exports.strictObject({kind:external_exports.literal("branch"),config:external_exports.strictObject({cases:external_exports.array(external_exports.strictObject({when:external_exports.strictObject({field:external_exports.string().min(1),op:external_exports.string().min(1),value:external_exports.union([RecipeLeafSchema,external_exports.array(RecipeLeafSchema).min(1)])}),next:external_exports.string().min(1)})).min(1),otherwise:external_exports.union([external_exports.strictObject({next:external_exports.string().min(1)}),external_exports.strictObject({end:external_exports.literal(!0)})]),merge:external_exports.string().min(1)})}),JobGateTemplateSchema=external_exports.strictObject({kind:external_exports.literal("job"),config:external_exports.strictObject({startedBy:external_exports.string().min(1),giveUpAfter:DurationSchema.optional()})}),DelayGateTemplateSchema=external_exports.strictObject({kind:external_exports.literal("delay"),config:external_exports.strictObject({duration:DurationSchema})}),RecipeGateStepTemplateSchema=external_exports.strictObject({id:external_exports.string().min(1).max(200),type:external_exports.literal("gate"),gate:external_exports.discriminatedUnion("kind",[BranchGateTemplateSchema,JobGateTemplateSchema,DelayGateTemplateSchema])}),RecipeStepTemplateSchema=external_exports.union([RecipeVerbStepTemplateSchema,RecipeGateStepTemplateSchema]),RecipeDefinitionTemplateSchema=external_exports.strictObject({compensation:external_exports.string().min(1),inputSchema:external_exports.strictObject({fields:external_exports.record(external_exports.string().min(1),external_exports.record(external_exports.string(),external_exports.unknown()))}).optional(),steps:external_exports.array(RecipeStepTemplateSchema).min(1).max(RECIPE_STEP_MAX)}),MappingLeafSchema=external_exports.union([ScalarLeafSchema,RecipeParamRefSchema]),RecipeMappingValueSchema=external_exports.union([MappingLeafSchema,external_exports.record(external_exports.string().min(1),MappingLeafSchema)]),RecipeBindingTemplateSchema=external_exports.strictObject({recordAction:external_exports.string().regex(DOMAIN_VERB_PATTERN),match:external_exports.record(external_exports.string().min(1),MappingLeafSchema).optional(),inputMapping:external_exports.record(external_exports.string().min(1),RecipeMappingValueSchema)}),RecipeDeclarationSchema=external_exports.strictObject({name:external_exports.string().max(64).regex(RECIPE_NAME_PATTERN),title:external_exports.string().min(1).max(80),description:external_exports.string().min(1).max(400),parameters:external_exports.record(ParameterName,RecipeParameterSchema).refine(parameters=>Object.keys(parameters).length<=RECIPE_PARAMETER_MAX,{message:`a recipe declares at most ${String(RECIPE_PARAMETER_MAX)} parameters`}),definition:RecipeDefinitionTemplateSchema,binding:RecipeBindingTemplateSchema.optional()}),RecipesManifestFacetSchema=external_exports.array(RecipeDeclarationSchema);var LabelWordsSchema=external_exports.strictObject({singular:external_exports.string().min(1).max(60),plural:external_exports.string().min(1).max(60)}),SignOffLabelSchema=LabelWordsSchema.extend({short:LabelWordsSchema.optional()}).strict(),SignOffStepDeclarationSchema=external_exports.strictObject({id:external_exports.string().regex(VERB_SEGMENT_PATTERN),verb:external_exports.string().regex(VERB_SEGMENT_PATTERN),subjectIdArg:external_exports.string().regex(VERB_SEGMENT_PATTERN),factsArg:external_exports.string().regex(VERB_SEGMENT_PATTERN).optional(),factRecordArg:external_exports.string().regex(VERB_SEGMENT_PATTERN).optional()}),NewerRunSchema=external_exports.enum(["supersede","keep"]),SignOffStepsDeclarationSchema=external_exports.strictObject({inputField:external_exports.string().regex(VERB_SEGMENT_PATTERN),before:external_exports.array(SignOffStepDeclarationSchema).max(4),after:external_exports.array(SignOffStepDeclarationSchema).max(4),newerRun:NewerRunSchema.optional(),ownerHost:external_exports.strictObject({host:external_exports.strictObject({domain:external_exports.string().min(1),type:external_exports.string().min(1)}),slot:external_exports.string().min(1),label:external_exports.string().min(1).max(60)}).optional()}),FACT_PATH_PATTERN=/^[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)+$/,SignOffKindFactSchema=external_exports.strictObject({name:external_exports.string().regex(VERB_SEGMENT_PATTERN),label:external_exports.string().min(1).max(60),path:external_exports.string().regex(FACT_PATH_PATTERN)}),SIGN_OFF_FACTS_MAX=16,SignOffKindFactsSchema=external_exports.array(SignOffKindFactSchema).min(1).max(SIGN_OFF_FACTS_MAX).refine(facts=>new Set(facts.map(fact=>fact.name)).size===facts.length,{message:"each fact name appears once"}),EntityKindFields={domain:external_exports.string().min(1),type:external_exports.string().min(1)},SignOffFactSubjectSchema=external_exports.strictObject({...EntityKindFields,idPath:external_exports.string().min(1),versionPath:external_exports.string().min(1).optional()}),SignOffFactScopeSchema=external_exports.strictObject({path:external_exports.string().min(1),...EntityKindFields,pickerResource:external_exports.string().min(1).optional()}),SignOffFactSchema=external_exports.strictObject({label:external_exports.string().min(1).max(80),subjects:external_exports.array(SignOffFactSubjectSchema).min(1).max(4),scopes:external_exports.array(SignOffFactScopeSchema).max(8)});var asSchema=value2=>value2 instanceof external_exports.ZodType?value2:void 0;function unwrapOnce(schema){if(schema instanceof external_exports.ZodOptional||schema instanceof external_exports.ZodNullable||schema instanceof external_exports.ZodDefault||schema instanceof external_exports.ZodPrefault||schema instanceof external_exports.ZodCatch||schema instanceof external_exports.ZodReadonly||schema instanceof external_exports.ZodLazy)return asSchema(schema.unwrap())}function unwrapSchema(schema){let current=schema;for(let depth=0;depth<32;depth+=1){let next=unwrapOnce(current);if(next===void 0)return current;current=next}return current}function shapeOf(schema){let unwrapped=unwrapSchema(schema);if(!(unwrapped instanceof external_exports.ZodObject))return;let shape=unwrapped.shape,entries=Object.entries(shape).flatMap(([key,value2])=>{let field=asSchema(value2);return field===void 0?[]:[[key,field]]});return Object.fromEntries(entries)}function unionOptionsOf(schema){let unwrapped=unwrapSchema(schema);return unwrapped instanceof external_exports.ZodUnion?unwrapped.def.options.flatMap(option=>{let branch=asSchema(option);return branch===void 0?[]:[branch]}):void 0}function literalValuesOf(schema){let unwrapped=unwrapSchema(schema);if(unwrapped instanceof external_exports.ZodEnum)return unwrapped.options.filter(value2=>typeof value2=="string");if(unwrapped instanceof external_exports.ZodLiteral)return[...unwrapped.values].filter(value2=>typeof value2=="string");let branches=unionOptionsOf(unwrapped);if(branches!==void 0){let perBranch=branches.map(branch=>literalValuesOf(branch));return perBranch.some(values2=>values2===void 0)?void 0:perBranch.flatMap(values2=>values2??[])}}function indexedElements(schema){let collect=values2=>{let elements2=values2.flatMap(value2=>{let element=asSchema(value2);return element===void 0?[]:[element]});return elements2.length===0?void 0:elements2};if(schema instanceof external_exports.ZodArray)return collect([schema.element]);if(schema instanceof external_exports.ZodSet)return collect([schema.def.valueType]);if(schema instanceof external_exports.ZodMap)return collect([schema.def.valueType]);if(schema instanceof external_exports.ZodTuple){let items=schema.def.items;return collect([...items,schema.def.rest])}}function keyedMembers(schema){if(schema instanceof external_exports.ZodObject)return Object.entries(shapeOf(schema)??{});if(schema instanceof external_exports.ZodRecord){let value2=asSchema(schema.def.valueType);return value2===void 0?[]:[["*",value2]]}return schema instanceof external_exports.ZodUnion?(unionOptionsOf(schema)??[]).map(branch=>["",branch]):schema instanceof external_exports.ZodIntersection?[asSchema(schema.def.left),asSchema(schema.def.right)].flatMap(side=>side===void 0?[]:[["",side]]):[]}function recordKeysAreNameable(schema){let keyType=asSchema(schema.def.keyType);if(keyType===void 0)return!1;let literals=literalValuesOf(keyType);return literals!==void 0?literals.length>0&&literals.every(value2=>JOB_FIELD_PATTERN.test(value2)):(unwrapSchema(keyType).def.checks??[]).some(check2=>regexOf(check2)===patternIdentity(JOB_FIELD_PATTERN))}var patternIdentity=pattern=>`${pattern.source}/${pattern.flags}`;function regexOf(check2){let inner=check2===null||typeof check2!="object"?void 0:Reflect.get(check2,"_zod"),def=inner===null||typeof inner!="object"?void 0:Reflect.get(inner,"def"),pattern=def===null||typeof def!="object"?void 0:Reflect.get(def,"pattern");return pattern instanceof RegExp?patternIdentity(pattern):void 0}var join4=(path3,segment)=>segment===""?path3:path3===""?segment:`${path3}.${segment}`,MAX_DETAIL_DEPTH=24;function firstNamedPath(schema,depth){if(depth>=MAX_DETAIL_DEPTH)return"";let unwrapped=unwrapSchema(schema);for(let[segment,member]of keyedMembers(unwrapped))return join4(segment,firstNamedPath(member,depth+1));return""}function unwalkableCompletionDetailPath(schema){let visit2=(current,path3,depth)=>{if(depth>=MAX_DETAIL_DEPTH)return;let unwrapped=unwrapSchema(current);if(unwrapped instanceof external_exports.ZodRecord&&!recordKeysAreNameable(unwrapped))return join4(path3,"*");let elements2=indexedElements(unwrapped);if(elements2!==void 0){for(let element of elements2){let inner=unwrapSchema(element);if(keyedMembers(inner).length===0&&indexedElements(inner)===void 0)continue;let beneath=firstNamedPath(element,depth+1);return`${path3}[]${beneath===""?"":`.${beneath}`}`}return}for(let[segment,member]of keyedMembers(unwrapped)){let found=visit2(member,join4(path3,segment),depth+1);if(found!==void 0)return found}};return visit2(schema,"",0)}var StartsJobSchema=external_exports.strictObject({handleField:external_exports.string().regex(JOB_FIELD_PATTERN,"handleField must be a walkable field name"),completionAction:external_exports.string().regex(DOMAIN_VERB_PATTERN,"completionAction must be <domain>.<verb>"),status:external_exports.string().regex(CONTRACT_PROCEDURE_PATTERN,"status must be a contract path"),completionDetail:external_exports.custom(value2=>value2 instanceof external_exports.ZodType,{message:"completionDetail must be a zod schema"}),cancel:external_exports.string().regex(VERB_SEGMENT_PATTERN,"cancel must be a verb name").optional(),panel:external_exports.string().min(1).optional(),waitOnly:external_exports.literal(!0).optional()}).superRefine((declaration,ctx)=>{let unwalkable=unwalkableCompletionDetailPath(declaration.completionDetail);unwalkable!==void 0&&ctx.addIssue({code:"custom",path:["completionDetail"],message:`completionDetail holds "${unwalkable}" \u2014 no dot expression can walk it (O7): an array between its root and a leaf, or a record whose key schema lets a key be anything. Publish a KEYED PROJECTION of those members instead, keyed by their own declared name, and seal that shape`})});var JOB_STATE_WORDS=Object.freeze({pending:"running",queued:"running",running:"running",completed:"completed",failed:"failed"}),TERMINAL_STATE_WORDS=Object.entries(JOB_STATE_WORDS).flatMap(([word,engine])=>engine==="running"?[]:[word]);var VERB_GRADES=["G0","G1","G2","G3"],VerbGradeSchema=external_exports.enum(VERB_GRADES),VerbDialSchema=external_exports.object({target:VerbGradeSchema,enforced:VerbGradeSchema}).refine(dial=>VERB_GRADES.indexOf(dial.enforced)<=VERB_GRADES.indexOf(dial.target),{message:"verb dial: enforced grade must be \u2264 target grade"}),REFUSAL_CODE_PATTERN=/^[A-Z][A-Z0-9_]*$/,VerbDeclarationSchema=external_exports.object({name:external_exports.string().regex(VERB_SEGMENT_PATTERN,"verb name must match the verb-segment grammar"),version:external_exports.number().int().positive(),title:external_exports.string().trim().min(1).max(120).optional(),description:external_exports.string().trim().min(1).max(500).optional(),dial:VerbDialSchema.optional(),procedurePath:external_exports.string().regex(CONTRACT_PROCEDURE_PATTERN).optional(),composable:external_exports.boolean(),startsJob:StartsJobSchema.optional(),needsJobsWaited:external_exports.literal(!0).optional(),signOffFact:SignOffFactSchema.optional(),personFacingRefusals:external_exports.array(external_exports.string().regex(REFUSAL_CODE_PATTERN,"a refusal code is SCREAMING_SNAKE_CASE")).min(1).refine(codes=>new Set(codes).size===codes.length,"refusal codes are listed once").optional()}),AUTHZ_AUTHORITIES=["view","edit","manage"],PLATFORM_RESOURCE_KIND_PREFIX="platform.",AUTHZ_TENANT_ROOT_KIND=`${PLATFORM_RESOURCE_KIND_PREFIX}tenant`,ScopingModeSchema=external_exports.discriminatedUnion("mode",[external_exports.object({mode:external_exports.literal("hierarchical")}),external_exports.object({mode:external_exports.literal("derived-via-link"),refColumn:external_exports.string().min(1)}),external_exports.object({mode:external_exports.literal("tenant-wide")})]),AuthzResourceTypeSchema=external_exports.object({name:external_exports.string().regex(RESOURCE_KIND_PATTERN),scoping:ScopingModeSchema,attributes:external_exports.array(external_exports.string())}),PROCEDURE_PATH_PATTERN=/^[a-zA-Z][a-zA-Z0-9]*(\.[a-zA-Z][a-zA-Z0-9]*)+$/,AuthzVerbSchema=external_exports.object({verb:external_exports.string().regex(VERB_SEGMENT_PATTERN),requiredAuthority:external_exports.enum(AUTHZ_AUTHORITIES),targetResourceType:external_exports.string().min(1),procedurePath:external_exports.string().regex(PROCEDURE_PATH_PATTERN).optional(),reachesBelowTenant:external_exports.boolean().optional()}),AuthzDeclarationSchema=external_exports.object({resourceTypes:external_exports.array(AuthzResourceTypeSchema),verbs:external_exports.array(AuthzVerbSchema),noTenantWriteSurface:external_exports.literal(!0).optional(),noGovernedVerb:external_exports.array(external_exports.object({procedurePath:external_exports.string().regex(PROCEDURE_PATH_PATTERN),reason:external_exports.string().min(1)})).optional()}).refine(declaration=>declaration.noTenantWriteSurface!==!0||declaration.verbs.length===0,{message:"noTenantWriteSurface claims the module mounts nothing on a tenant write tier, but authz.verbs declares authority verbs",path:["noTenantWriteSurface"]}),SnapshotMintDeclarationSchema=external_exports.strictObject({procedurePath:external_exports.string().regex(CONTRACT_PROCEDURE_PATTERN),kindLabels:external_exports.record(external_exports.string().min(1),SignOffLabelSchema).optional(),signOffSteps:external_exports.record(external_exports.string().min(1),SignOffStepsDeclarationSchema).optional(),signOffFacts:external_exports.record(external_exports.string().min(1),SignOffKindFactsSchema).optional()}),DomainReadsSchema=external_exports.strictObject({snapshotMint:SnapshotMintDeclarationSchema.optional()}),CodelistTermDefaultSchema=external_exports.strictObject({code:external_exports.string().min(1),label:external_exports.string().min(1),description:external_exports.string().optional(),system:external_exports.boolean().optional()}),CodelistDeclarationSchema=external_exports.strictObject({codelist:external_exports.string().min(1),defaultTerms:external_exports.array(CodelistTermDefaultSchema)}),CodelistsManifestFacetSchema=external_exports.strictObject({codelists:external_exports.array(CodelistDeclarationSchema)}),AgentGuidanceSourceSchema=external_exports.discriminatedUnion("kind",[external_exports.strictObject({kind:external_exports.literal("repoFile"),text:external_exports.string().min(1)}),external_exports.strictObject({kind:external_exports.literal("generated"),text:external_exports.string().min(1)})]),AgentGuidanceResourceSchema=external_exports.strictObject({uri:external_exports.string().min(1),name:external_exports.string().min(1),description:external_exports.string().min(1),mimeType:external_exports.string().min(1),source:AgentGuidanceSourceSchema}),AgentGuidancePromptArgumentSchema=external_exports.strictObject({name:external_exports.string().min(1),description:external_exports.string().min(1),required:external_exports.boolean().optional()}),AgentGuidancePromptSchema=external_exports.strictObject({name:external_exports.string().min(1),description:external_exports.string().min(1),arguments:external_exports.array(AgentGuidancePromptArgumentSchema),template:external_exports.string().min(1)}),AgentGuidanceManifestFacetSchema=external_exports.strictObject({scheme:external_exports.string().regex(/^[a-z][a-z0-9+.-]*$/u),resources:external_exports.array(AgentGuidanceResourceSchema),prompts:external_exports.array(AgentGuidancePromptSchema)}),DomainManifestSchema=external_exports.object({name:external_exports.string().min(1),plane:external_exports.literal("resource"),events:external_exports.array(external_exports.string()),routerKey:external_exports.string().min(1),verbs:external_exports.array(VerbDeclarationSchema).optional(),reads:DomainReadsSchema.optional(),readContracts:ReadContractsManifestFacetSchema.optional(),authz:AuthzDeclarationSchema,codelists:CodelistsManifestFacetSchema.optional(),agentGuidance:AgentGuidanceManifestFacetSchema.optional(),linkTypes:LinkTypesManifestFacetSchema.optional(),linkable:LinkableManifestFacetSchema.optional(),recipes:RecipesManifestFacetSchema.optional()});var PlatformManifestSchema=external_exports.object({name:external_exports.string().min(1),plane:external_exports.literal("platform"),events:external_exports.array(external_exports.string()),routerKey:external_exports.string().min(1),verbs:external_exports.array(VerbDeclarationSchema).optional(),authz:AuthzDeclarationSchema,codelists:CodelistsManifestFacetSchema.optional(),agentGuidance:AgentGuidanceManifestFacetSchema.optional(),linkTypes:LinkTypesManifestFacetSchema.optional(),linkable:LinkableManifestFacetSchema.optional()});var IdempotencyKeySchema=external_exports.string().min(1).describe("Client-minted replay key for this governed write \u2014 YOU generate it (a UUID is fine), the server never does. REPLAY SEMANTICS: once a call has COMPLETED, reusing its key returns that original receipt without re-executing. A call refused before its change applied filed no receipt, so the same key is free to run again \u2014 but a refusal that says the change landed, or may have landed, outside this server means exactly that: re-read before re-sending. Mint a NEW key whenever you change the inputs; reuse one only to safely re-send the identical intent, e.g. after a network timeout."),RecordIdSchema=external_exports.string().min(1).brand(),EntityRefSchema=external_exports.object({domain:external_exports.string().min(1),type:external_exports.string().min(1),id:external_exports.string().min(1),version:external_exports.string().min(1).optional()});var EntitySnapshotRefSchema=external_exports.object({domain:external_exports.string().min(1),type:external_exports.string().min(1),id:external_exports.string().min(1),snapshot:external_exports.string().min(1).describe("Opaque snapshot identity minted by the owning domain \u2014 get it from that domain's own `snapshot` procedure. Never construct or parse one: the same value always means the same content, and any change to the entity yields a new value.")}),ENTITY_REF_MAX_KIND_CHARS=64,ENTITY_REF_MAX_IDENTITY_CHARS=200,RecordIdInputSchema=RecordIdSchema.max(ENTITY_REF_MAX_IDENTITY_CHARS),EntityRefInputSchema=EntityRefSchema.extend({domain:EntityRefSchema.shape.domain.max(ENTITY_REF_MAX_KIND_CHARS),type:EntityRefSchema.shape.type.max(ENTITY_REF_MAX_KIND_CHARS),id:EntityRefSchema.shape.id.max(ENTITY_REF_MAX_IDENTITY_CHARS),version:EntityRefSchema.shape.version.unwrap().max(ENTITY_REF_MAX_IDENTITY_CHARS).optional()}),EntitySnapshotRefInputSchema=EntitySnapshotRefSchema.extend({domain:EntitySnapshotRefSchema.shape.domain.max(ENTITY_REF_MAX_KIND_CHARS),type:EntitySnapshotRefSchema.shape.type.max(ENTITY_REF_MAX_KIND_CHARS),id:EntitySnapshotRefSchema.shape.id.max(ENTITY_REF_MAX_IDENTITY_CHARS),snapshot:EntitySnapshotRefSchema.shape.snapshot.max(ENTITY_REF_MAX_IDENTITY_CHARS)}),ActionRefSchema=external_exports.object({name:external_exports.string().regex(QUALIFIED_ACTION_PATTERN,"action name must be dot-qualified"),version:external_exports.number().int().positive()}),ActorSchema=external_exports.object({principal:external_exports.string().min(1),onBehalfOf:external_exports.string().min(1).optional(),viaFlowRun:external_exports.string().min(1).optional(),originFlowRun:external_exports.string().min(1).optional()}),WriteActorSchema=ActorSchema.omit({viaFlowRun:!0,originFlowRun:!0}),RecordStatusSchema=external_exports.enum(["in-flight","committed","failed"]),ActionRecordSchema=external_exports.object({id:RecordIdSchema,tenantId:external_exports.string().min(1),action:ActionRefSchema,actor:ActorSchema,time:external_exports.iso.datetime(),params:external_exports.unknown(),effects:external_exports.array(EntityRefSchema),reads:external_exports.array(EntityRefSchema),status:RecordStatusSchema,committedAt:external_exports.iso.datetime().optional(),idempotencyKey:IdempotencyKeySchema,detail:external_exports.unknown().optional()}),FlowRunOutcomeSchema=external_exports.enum(["completed","completed-with-account","ended-at-branch","ended-at-gate"]),FlowRunRecordSchema=ActionRecordSchema.extend({definition:external_exports.object({name:external_exports.string().min(1),version:external_exports.number().int().positive()}),steps:external_exports.array(RecordIdSchema),outcome:FlowRunOutcomeSchema.optional()}),WriteRecordInputSchema=ActionRecordSchema.omit({id:!0,tenantId:!0,time:!0,status:!0}).extend({actor:WriteActorSchema}),VerbEnvelopeInputSchema=WriteRecordInputSchema.omit({effects:!0,detail:!0});var ReactionSchema=external_exports.object({type:external_exports.literal("toast"),message:external_exports.string().min(1).optional()}).strict(),ActionBindingExprSchema=external_exports.discriminatedUnion("source",[external_exports.object({source:external_exports.literal("literal"),value:external_exports.unknown()}).strict(),external_exports.object({source:external_exports.literal("subject"),as:external_exports.enum(["identity","id"])}).strict(),external_exports.object({source:external_exports.literal("selection"),channel:external_exports.string().min(1)}).strict(),external_exports.object({source:external_exports.literal("prompt"),label:external_exports.string().min(1).max(200).optional(),help:external_exports.string().min(1).max(500).optional()}).strict()]),ActionSchema=external_exports.object({definition:external_exports.string().min(1),label:external_exports.string().min(1),confirmLabel:external_exports.string().min(1).optional(),input:external_exports.record(external_exports.string().min(1),ActionBindingExprSchema),onCommitted:ReactionSchema,onFailed:ReactionSchema,onParked:ReactionSchema.optional()}).strict();var ACTION_SLOT_MARKER="forge:actionSlot",MAX_ACTIONS_PER_SLOT=20;function actionSlot(opts){return external_exports.array(ActionSchema).max(MAX_ACTIONS_PER_SLOT).meta({[ACTION_SLOT_MARKER]:{subject:opts.subject}})}function peelDeclarationWrappers(schema){let candidate=schema;for(;candidate instanceof external_exports.ZodOptional||candidate instanceof external_exports.ZodDefault||candidate instanceof external_exports.ZodNullable||candidate instanceof external_exports.ZodReadonly||candidate instanceof external_exports.ZodCatch||candidate instanceof external_exports.ZodPrefault;)candidate=candidate.unwrap();return candidate}var CHANNEL_PAYLOAD_TYPES=["string","number","boolean","ref","entity-ref"],ChannelDeclarationSchema=external_exports.object({name:external_exports.string().min(1),payload:external_exports.enum(CHANNEL_PAYLOAD_TYPES),scope:external_exports.enum(["page","solution"])}).strict(),MAX_CHANNELS_PER_PAGE=20,MAX_CHANNELS_PER_SOLUTION=20;var NON_BLANK_TRIMMED_RE=/^\S(.*\S)?(?![\s\S])/,CONFIG_VERSION_RE=/^[1-9][0-9]*$/;var PICK_KINDS=["dimension.member","geo.within","assets.set"],PickKindSchema=external_exports.enum(PICK_KINDS),PICK_ASSET_SET_MAX=200,MAX_PICK_RENDITIONS=3,MAX_PICK_LABEL_LENGTH=60,MAX_PICK_RING_POSITIONS=1e3,MAX_PICK_PART_CHARS=200;var PickPositionSchema=external_exports.tuple([external_exports.number().min(-180).max(180),external_exports.number().min(-90).max(90)]),isClosedRing=ring=>{let first=ring[0],last=ring.at(-1);return first!==void 0&&last!==void 0&&first[0]===last[0]&&first[1]===last[1]},PickPolygonSchema=external_exports.strictObject({type:external_exports.literal("Polygon"),coordinates:external_exports.array(external_exports.array(PickPositionSchema).min(4).max(MAX_PICK_RING_POSITIONS).refine(isClosedRing,"a ring is closed: its first position equals its last")).min(1).max(1)}),PickEntityRefSchema=external_exports.strictObject({domain:external_exports.string().min(1).max(64),type:external_exports.string().min(1).max(64)}),PickRenditionSchema=external_exports.discriminatedUnion("kind",[external_exports.strictObject({kind:external_exports.literal("dimension.member"),dimension:external_exports.string().min(1).max(MAX_PICK_PART_CHARS),value:external_exports.string().max(MAX_PICK_PART_CHARS),refersTo:PickEntityRefSchema.optional()}),external_exports.strictObject({kind:external_exports.literal("geo.within"),geometry:PickPolygonSchema}),external_exports.strictObject({kind:external_exports.literal("assets.set"),assetIds:external_exports.array(external_exports.string().min(1).max(MAX_PICK_PART_CHARS)).max(PICK_ASSET_SET_MAX)})]),PagePickSchema=external_exports.strictObject({sourceInstanceId:external_exports.string().min(1),label:external_exports.string().max(MAX_PICK_LABEL_LENGTH).regex(NON_BLANK_TRIMMED_RE),renditions:external_exports.array(PickRenditionSchema).max(MAX_PICK_RENDITIONS),omitted:external_exports.array(external_exports.strictObject({kind:PickKindSchema,total:external_exports.number().int().min(1)})).max(MAX_PICK_RENDITIONS).refine(entries=>new Set(entries.map(e=>e.kind)).size===entries.length,"an omitted kind is listed once").optional()}).refine(pick2=>pick2.renditions.length>0||(pick2.omitted?.length??0)>0,"a pick with no renditions records what it omitted");var KIND_PART_MAX_CHARS=64,kindPart=label=>external_exports.string().min(1).max(KIND_PART_MAX_CHARS).regex(/^[^/]+$/,`a record kind's ${label} may not contain "/"`),RecordKindSchema=external_exports.object({domain:kindPart("domain"),type:kindPart("type")}).strict(),ROW_CLICKS=["blade","page","none"],ROW_CLICK_MESSAGE=`rowClick is "blade" (open the row in a blade), "page" (go to its record page), "none" (rows do nothing) or { publish: '<channel>' } (publish the row's reference on that channel)`,RowClickSchema=external_exports.union([external_exports.enum(ROW_CLICKS),external_exports.object({publish:external_exports.string().min(1,ROW_CLICK_MESSAGE)},{error:issue2=>issue2.code==="unrecognized_keys"?ROW_CLICK_MESSAGE:void 0}).strict()],{error:ROW_CLICK_MESSAGE}),MAX_SOLUTION_BLADES=20,MAX_BLADE_TABS=6,MAX_BLADE_TAB_LABEL_LENGTH=40,BLADE_TAB_BINDS=["record","subject"];var SolutionBladeTabSectionSchema=external_exports.object({componentName:external_exports.string().min(1).describe(`A registered binds "entity" component that can bind this kind; a component appears at most once across a blade entry's tabs and sections.`),config:external_exports.unknown().optional(),configVersion:external_exports.string().regex(CONFIG_VERSION_RE)}).strict(),SolutionBladeTabSchema=external_exports.object({label:external_exports.string().min(1).max(MAX_BLADE_TAB_LABEL_LENGTH).regex(NON_BLANK_TRIMMED_RE).describe(`The tab's heading \u2014 non-blank, no leading or trailing whitespace, at most ${String(MAX_BLADE_TAB_LABEL_LENGTH)} characters, unique within the blade and never "Details".`),componentName:external_exports.string().min(1).describe(`A registered binds "entity" component that can bind this kind; a component appears at most once across a blade entry's tabs and sections.`),config:external_exports.unknown().optional(),configVersion:external_exports.string().regex(CONFIG_VERSION_RE),bind:external_exports.enum(BLADE_TAB_BINDS).optional().describe('What the tab shows: "record" (the record on screen; the default) or "subject" (the record that one is about, at its pin). "subject" only on a kind whose records have one; a subject the component cannot show hides the tab.'),sections:external_exports.array(SolutionBladeTabSectionSchema).max(50).optional().describe("Further components shown under the tab's own, in this order, each bound as the tab is. A section whose component cannot bind that record is hidden; the tab stays.")}).strict(),SolutionBladeSchema=external_exports.object({entity:RecordKindSchema,view:external_exports.literal("details",{error:`a blade shows the module's Details view \u2014 "details" is the only view there is`}),tabs:external_exports.array(SolutionBladeTabSchema).max(MAX_BLADE_TABS).optional().describe("Catalog widgets placed as further tabs on this kind's record view, after Details and the modules' own tabs, each bound to the record on screen.")}).strict();var MAX_SOLUTION_FILTERS=10,MAX_FILTER_DIMENSION_LENGTH=255,MAX_FILTER_ID_LENGTH=MAX_FILTER_DIMENSION_LENGTH,MAX_FILTER_PAGES=100,FilterIdSchema=external_exports.string().min(1).max(MAX_FILTER_ID_LENGTH).regex(NON_BLANK_TRIMMED_RE,{error:"a filter id must be non-blank with no leading or trailing whitespace"}),FilterDimensionColumnSchema=external_exports.string().min(1).max(MAX_FILTER_DIMENSION_LENGTH).regex(NON_BLANK_TRIMMED_RE,{error:"dimension must be a non-blank column name without leading or trailing whitespace"}),DAY_PATTERN=String.raw`\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])`;var RANGE_KEY=new RegExp(String.raw`^(${DAY_PATTERN})\.\.(${DAY_PATTERN})$`),periodKeyRange=key=>{let match=RANGE_KEY.exec(key);return match?.[1]===void 0||match[2]===void 0?void 0:{start:match[1],end:match[2]}},PeriodKeySchema=external_exports.string().regex(new RegExp(String.raw`^(\d{4}(-(0[1-9]|1[0-2])|-Q[1-4])?|${DAY_PATTERN}\.\.${DAY_PATTERN})$`),{error:"a period key is a year (2026), a quarter (2026-Q3), a month (2026-09) or a range of days (2026-03-15..2026-04-14)"}),PERIOD_GRAINS=["month","quarter","year"],PeriodGrainSchema=external_exports.enum(PERIOD_GRAINS),PeriodDefaultSchema=external_exports.union([external_exports.strictObject({policy:external_exports.literal("currentPeriod"),grain:PeriodGrainSchema}),external_exports.strictObject({policy:external_exports.literal("lastClosedPeriod"),grain:PeriodGrainSchema}),external_exports.strictObject({policy:external_exports.literal("fixed"),key:PeriodKeySchema})]),PeriodWindowSchema=external_exports.strictObject({from:external_exports.iso.datetime(),to:external_exports.iso.datetime()}),KIND_SEGMENT=external_exports.string().regex(/^[a-z0-9-]+$/),PublishedFilterKindSchema=external_exports.templateLiteral([KIND_SEGMENT,".",KIND_SEGMENT]),FilterLabelSchema=external_exports.string().min(1).describe("What the viewer reads above the control. Absent = the kind's own label."),FilterPagesSchema=external_exports.array(external_exports.string().min(1)).max(MAX_FILTER_PAGES).describe("Ids of the pages that show this filter, top-level or child. Absent = every page; empty = no page. A page that does not show a filter is not narrowed by it."),PeriodSolutionFilterSchema=external_exports.strictObject({id:FilterIdSchema,kind:external_exports.literal("period"),label:FilterLabelSchema.optional(),pages:FilterPagesSchema.optional(),default:PeriodDefaultSchema.optional().describe("The period a page opens on: the current month, quarter or year, the last closed one, or a fixed key. Absent = any time.")}),FILTER_OPTIONS_WIRE_MAX=1e3,DimensionSolutionFilterSchema=external_exports.strictObject({id:FilterIdSchema,kind:external_exports.literal("dimension"),label:FilterLabelSchema.optional(),pages:FilterPagesSchema.optional(),dimension:FilterDimensionColumnSchema,options:external_exports.array(external_exports.string().min(1)).optional().describe("The values the control offers \u2014 exactly what the author typed.")}),PublishedSolutionFilterSchema=external_exports.strictObject({id:FilterIdSchema,kind:PublishedFilterKindSchema,label:FilterLabelSchema.optional(),pages:FilterPagesSchema.optional()}),SolutionFilterSchema=external_exports.union([PeriodSolutionFilterSchema,DimensionSolutionFilterSchema,PublishedSolutionFilterSchema]),SolutionFilterInputSchema=external_exports.union([PeriodSolutionFilterSchema,DimensionSolutionFilterSchema.extend({options:external_exports.array(external_exports.string().min(1)).max(FILTER_OPTIONS_WIRE_MAX).optional().describe("The values the control offers \u2014 exactly what the author typed.")}),PublishedSolutionFilterSchema]);var PageDateRangeSchema=external_exports.strictObject({label:FilterLabelSchema.optional(),default:PeriodWindowSchema.optional().describe("The range the page opens on. Absent = any time.")});var ROW_SOURCE_MAX_LIMIT=200,MAX_ROW_SOURCE_COLUMNS=100,MAX_ROW_SOURCE_FILTERS=50,MAX_ROW_SOURCE_OPTIONS=100,MAX_ROW_SOURCE_FILTER_TERMS=50,MAX_ROW_SOURCE_IN_VALUES=100,MAX_FIELD_KEY_LENGTH=64,MAX_CURSOR_LENGTH=2048,MAX_LABEL_LENGTH=120,MAX_DESCRIPTION_LENGTH=500,MAX_TEXT_VALUE_LENGTH=1e3,RowSourceIdSchema=PublishedFilterKindSchema.refine(id=>id.length<=MAX_LABEL_LENGTH,`a row source id is at most ${MAX_LABEL_LENGTH} characters`);var LabelSchema=external_exports.string().max(MAX_LABEL_LENGTH).regex(NON_BLANK_TRIMMED_RE),FieldKeySchema=external_exports.string().max(MAX_FIELD_KEY_LENGTH).regex(/^[A-Za-z][A-Za-z0-9_]*$/,'a column or filter key is letters, digits and "_"'),ROW_SOURCE_COLUMN_TYPES=["text","number","date","datetime","boolean","enum","entity"],RowSourceColumnSchema=external_exports.strictObject({key:FieldKeySchema,label:LabelSchema,type:external_exports.enum(ROW_SOURCE_COLUMN_TYPES),unit:LabelSchema.optional(),sortable:external_exports.boolean(),shownByDefault:external_exports.boolean()}),ROW_SOURCE_FILTER_VALUE_TYPES=["text","number","boolean","date","enum","entity"],ROW_SOURCE_FILTER_OPERATORS=["eq","in","contains","gte","lte"],OPERATORS_FOR={text:["eq","in","contains"],number:["eq","in","gte","lte"],boolean:["eq"],date:["eq","gte","lte"],enum:["eq","in"],entity:["eq","in"]},RowSourceFilterSchema=external_exports.strictObject({key:FieldKeySchema,label:LabelSchema,valueType:external_exports.enum(ROW_SOURCE_FILTER_VALUE_TYPES),operators:external_exports.array(external_exports.enum(ROW_SOURCE_FILTER_OPERATORS)).min(1),options:external_exports.array(external_exports.strictObject({value:external_exports.string().min(1).max(MAX_LABEL_LENGTH),label:LabelSchema})).min(1).max(MAX_ROW_SOURCE_OPTIONS).optional(),kind:RecordKindSchema.optional()}),RowSourceOrderBySchema=external_exports.strictObject({field:external_exports.string().min(1).max(MAX_FIELD_KEY_LENGTH),direction:external_exports.enum(["asc","desc"])}),duplicates=values2=>{let seen=new Set,repeated2=new Set;for(let v of values2)(seen.has(v)?repeated2:seen).add(v);return[...repeated2]},RowSourcePageScopeSchema=external_exports.strictObject({period:external_exports.boolean().optional(),dateRange:external_exports.boolean().optional(),dimensions:external_exports.boolean().optional(),facets:external_exports.array(PublishedFilterKindSchema).optional(),picks:external_exports.array(PickKindSchema).max(PICK_KINDS.length).refine(kinds=>duplicates(kinds).length===0,"a pick kind is listed once").optional(),resolves:external_exports.array(PickEntityRefSchema).optional()}),RowSourceDescriptionSchema=external_exports.object({id:RowSourceIdSchema,label:LabelSchema,description:external_exports.string().regex(NON_BLANK_TRIMMED_RE).max(MAX_DESCRIPTION_LENGTH),bindsTo:RecordKindSchema.optional(),rowKind:RecordKindSchema.optional(),pageScope:RowSourcePageScopeSchema.optional(),columns:external_exports.array(RowSourceColumnSchema).min(1).max(MAX_ROW_SOURCE_COLUMNS),filters:external_exports.array(RowSourceFilterSchema).max(MAX_ROW_SOURCE_FILTERS),defaultSort:RowSourceOrderBySchema,limit:external_exports.strictObject({default:external_exports.number().int().min(1),max:external_exports.number().int().min(1).max(ROW_SOURCE_MAX_LIMIT)}),pending:external_exports.strictObject({reason:external_exports.string().regex(NON_BLANK_TRIMMED_RE).max(MAX_DESCRIPTION_LENGTH)}).optional()}).superRefine((source,ctx)=>{let problem=message=>ctx.addIssue({code:"custom",message});for(let key of duplicates(source.columns.map(column2=>column2.key)))problem(`declares column key "${key}" twice`);source.columns.find(column2=>column2.key===source.defaultSort.field)?.sortable!==!0&&problem(`default sort "${source.defaultSort.field}" is not a sortable column`);for(let key of duplicates(source.filters.map(filter=>filter.key)))problem(`declares filter key "${key}" twice`);for(let filter of source.filters){filter.valueType==="enum"&&filter.options===void 0&&problem(`enum filter "${filter.key}" lists no options`),filter.valueType!=="enum"&&filter.options!==void 0&&problem(`filter "${filter.key}" is not an enum and cannot list options`),filter.valueType==="entity"&&filter.kind===void 0&&problem(`entity filter "${filter.key}" names no kind`),filter.valueType!=="entity"&&filter.kind!==void 0&&problem(`filter "${filter.key}" is not an entity and cannot name a kind`);for(let op of duplicates(filter.operators))problem(`filter "${filter.key}" offers "${op}" twice`);for(let value2 of duplicates((filter.options??[]).map(o=>o.value)))problem(`enum filter "${filter.key}" lists option "${value2}" twice`);for(let op of new Set(filter.operators))OPERATORS_FOR[filter.valueType].includes(op)||problem(`filter "${filter.key}" offers "${op}", which a ${filter.valueType} cannot take`)}source.limit.default>source.limit.max&&problem(`default limit ${source.limit.default} exceeds its maximum ${source.limit.max}`)}),RowSourceRowSchema=external_exports.strictObject({id:external_exports.string().min(1),values:external_exports.record(external_exports.string(),external_exports.unknown())}),RowSourcePickableSchema=external_exports.union([external_exports.strictObject({assetIds:external_exports.array(external_exports.string().min(1).max(MAX_PICK_PART_CHARS)).max(PICK_ASSET_SET_MAX).refine(ids=>duplicates(ids).length===0,"an asset id is listed once")}),external_exports.strictObject({total:external_exports.number().int().gt(PICK_ASSET_SET_MAX)})]),RowSourcePageSchema=external_exports.strictObject({rows:external_exports.array(RowSourceRowSchema).max(ROW_SOURCE_MAX_LIMIT),nextCursor:external_exports.string().min(1).max(MAX_CURSOR_LENGTH).nullable(),unappliedPicks:external_exports.array(PickKindSchema).max(PICK_KINDS.length).refine(kinds=>duplicates(kinds).length===0,"a pick kind is listed once").optional(),pickable:RowSourcePickableSchema.optional()}),FilterTermScalarSchema=external_exports.union([external_exports.string().max(MAX_TEXT_VALUE_LENGTH),external_exports.number(),external_exports.boolean()]),FilterTermSchema=external_exports.strictObject({key:external_exports.string().max(MAX_FIELD_KEY_LENGTH),op:external_exports.enum(ROW_SOURCE_FILTER_OPERATORS),value:external_exports.union([FilterTermScalarSchema,external_exports.array(FilterTermScalarSchema).max(MAX_ROW_SOURCE_IN_VALUES)])});var RowSourceRequestSchema=external_exports.strictObject({boundId:external_exports.string().min(1).max(MAX_LABEL_LENGTH).optional(),filter:external_exports.array(FilterTermSchema).max(MAX_ROW_SOURCE_FILTER_TERMS).default([]),orderBy:RowSourceOrderBySchema.optional(),cursor:external_exports.string().min(1).max(MAX_CURSOR_LENGTH).optional(),limit:external_exports.number().int().min(1).max(ROW_SOURCE_MAX_LIMIT).optional()});var CHANNEL_REF_MARKER="forge:channelRef";function channelRef(opts){return external_exports.string().min(1).meta({[CHANNEL_REF_MARKER]:{payload:opts.payload}})}var HOST_ONLY_MARKER="forge:hostOnly";function hostOnly(schema){if(peelDeclarationWrappers(schema)!==schema)throw new Error("hostOnly wraps the base type, before .optional() \u2014 write hostOnly(z.boolean()).optional(), not hostOnly(z.boolean().optional())");if(schema.meta()?.id!==void 0)throw new Error("hostOnly refuses a schema with a meta id \u2014 a reused id is emitted once and $ref-ed, so its markers would not count true; declare a fresh schema per key");return schema.meta({[HOST_ONLY_MARKER]:!0})}var MAX_DRILL_TARGET_LABEL_LENGTH=80,DrillTargetSchema=external_exports.object({page:external_exports.string().min(1).describe("Id of the page this block opens."),label:external_exports.string().min(1).max(MAX_DRILL_TARGET_LABEL_LENGTH).regex(NON_BLANK_TRIMMED_RE).optional().describe(`Hover text and accessible name for the block's open-page control \u2014 the same trim and non-blank check as a placement title, at most ${String(MAX_DRILL_TARGET_LABEL_LENGTH)} code points. Absent = "Open <target page name>".`)}).strict(),CONTAINER_DRILL_TARGET_MESSAGE="a layout container has no content of its own to drill from \u2014 set the drill target on the blocks inside it";var STATUS_SLOT_MARKER="forge:statusSlot",StatusSlotFillSchema=external_exports.object({componentName:external_exports.string().min(1).describe("A registered component that declares rowStatus and can bind the host\u2019s row kind."),config:external_exports.unknown().optional(),configVersion:external_exports.string().regex(CONFIG_VERSION_RE)}).strict();function statusSlot(){return StatusSlotFillSchema.meta({[STATUS_SLOT_MARKER]:!0})}var COMPONENT_BINDS=["none","collection","entity"],COMPONENT_GRAINS=["page","widget"];var PageLayoutSchema=external_exports.object({fullBleed:external_exports.boolean().default(!1),mode:external_exports.never({error:'layout.mode is a manifest v1 key and this manifest declares schemaVersion 2 \u2014 every page is the 12-column grid now; remove "mode" and use layout.fullBleed to select chromeless rendering'}).optional()}),GRID_MAX_COLS=12,GRID_MAX_ROWS=12,SpacingScaleSchema=external_exports.enum(["sm","default","lg"]),LayoutSchema=external_exports.object({spanCol:external_exports.number().int().min(1).max(GRID_MAX_COLS).optional(),spanRow:external_exports.number().int().min(1).max(GRID_MAX_ROWS).optional(),grow:external_exports.boolean().optional(),padding:SpacingScaleSchema.optional()});var SolutionIdSchema=external_exports.string().min(1).brand(),PageIdSchema=external_exports.string().min(1).brand(),InstanceIdSchema=external_exports.string().min(1).brand(),SOLUTION_SLUG_RE=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,SolutionSlugSchema=external_exports.string().regex(SOLUTION_SLUG_RE).brand(),PageSlugSchema=external_exports.string().regex(SOLUTION_SLUG_RE).brand();var SolutionItemBindingSchema=external_exports.union([external_exports.object({resourceId:external_exports.string().regex(/\S/).optional()}).strict(),external_exports.object({entity:external_exports.object({domain:external_exports.string().min(1),type:external_exports.string().min(1),id:external_exports.string().regex(/\S/),version:external_exports.string().min(1).optional(),snapshot:external_exports.string().regex(/\S/).optional().describe("Opaque snapshot identity minted by the owning domain \u2014 get it from that domain's own `snapshot` procedure. Never construct or parse one: the same value always means the same content, and any change to the entity yields a new value.")}).strict()}).strict(),external_exports.object({selectionChannel:external_exports.string().min(1)}).strict()]);var MAX_ITEM_TITLE_LENGTH=120,SolutionLeafItemSchema=external_exports.object({instanceId:external_exports.string().min(1),componentName:external_exports.string().min(1),title:external_exports.string().min(1).max(MAX_ITEM_TITLE_LENGTH).regex(NON_BLANK_TRIMMED_RE).optional().describe("Author-set heading for this placement \u2014 non-blank, no leading or trailing whitespace. Absent = the runtime page renders no heading and the builder canvas falls back to the component id."),configVersion:external_exports.string().regex(CONFIG_VERSION_RE),config:external_exports.unknown(),binding:SolutionItemBindingSchema,layout:LayoutSchema.optional(),span:external_exports.never({error:"span is a manifest v1 key and this manifest declares schemaVersion 2 \u2014 use layout.spanCol / layout.spanRow instead ({ w, h } becomes { spanCol: w, spanRow: h })"}).optional(),items:external_exports.never().optional(),ignoredFilters:external_exports.array(FilterIdSchema).max(MAX_SOLUTION_FILTERS).optional().describe("Solution filter ids this block does NOT follow. Absent = follow every filter shown on the page that the component can honour."),ignoredPicks:external_exports.array(PickKindSchema).min(1).max(PICK_KINDS.length).refine(kinds=>new Set(kinds).size===kinds.length,{message:"ignoredPicks must not repeat a pick kind"}).optional().describe("Pick kinds this block does NOT follow. Non-empty and without repeats; absent is the only way to follow every pick kind the component declares in pageScope.picks."),mutedPicks:external_exports.literal(!0).optional().describe("True stops this placement publishing picks and click-filters to other blocks. Absent = publish every kind declared by the component."),rowClick:RowClickSchema.optional().describe("What clicking one of this block's rows does: 'blade' opens the record in a blade over the page, 'page' goes to the Solution's record page for its kind, 'none' leaves rows unclickable, { publish: '<channel>' } publishes the clicked row's reference on that entity-ref channel. Absent = 'blade'."),drillTarget:DrillTargetSchema.optional().describe("Another page of this Solution the block opens from its open-page control, keeping the Solution filters and period. Not on a layout container. Absent = the block opens no page.")}),SolutionItemSchema=SolutionLeafItemSchema.extend({items:external_exports.array(SolutionLeafItemSchema).max(50).optional()}).superRefine((item,context)=>{item.items!==void 0&&item.drillTarget!==void 0&&context.addIssue({code:"custom",path:["drillTarget"],message:CONTAINER_DRILL_TARGET_MESSAGE})});var SolutionPageFieldsSchema=external_exports.looseObject({id:PageIdSchema,slug:PageSlugSchema,name:external_exports.string().min(1),order:external_exports.number().int().nonnegative(),layout:PageLayoutSchema,items:external_exports.array(SolutionItemSchema).max(50),path:external_exports.string().min(1).optional(),icon:external_exports.string().min(1).optional(),requiresCapability:external_exports.string().min(1).optional(),separatorBefore:external_exports.boolean().optional(),channels:external_exports.array(ChannelDeclarationSchema).max(MAX_CHANNELS_PER_PAGE).optional(),record:RecordKindSchema.optional().describe("Makes this page the Solution's record page for one kind: a reference to such a record opens here, at /s/<solution>/<page>/<id>. One page per kind, and only a page with no children."),hideFromNav:external_exports.boolean().optional().describe("Leaves this page out of the Solution's menu. A record page still opens from a reference to one of its records; any other page must be reached by a drill target chain from a page in the menu. A hidden record page starts no chain: nothing in the Solution leads to its own address. Not on a group."),filters:external_exports.never({error:"page filters moved to the Solution \u2014 declare them in the manifest's root `filters` and list this page's id in each filter's `pages`; a date range only this page offers goes in the page's `dateRange`"}).optional(),dateRange:PageDateRangeSchema.optional().describe("A date range this page alone offers its viewers, not kept across pages. Absent = none.")}),SolutionLeafPageSchema=SolutionPageFieldsSchema.extend({children:external_exports.never().optional()}),SolutionPageSchema=SolutionPageFieldsSchema.extend({children:external_exports.array(SolutionLeafPageSchema).max(50).optional()});var SolutionManifestSchema=external_exports.object({schemaVersion:external_exports.string().regex(CONFIG_VERSION_RE),pages:external_exports.array(SolutionPageSchema).max(50),channels:external_exports.array(ChannelDeclarationSchema).max(MAX_CHANNELS_PER_SOLUTION).optional(),filters:external_exports.array(SolutionFilterSchema).max(MAX_SOLUTION_FILTERS).optional().describe("Solution-wide filters: declared once, shown on the pages each one lists, kept as a viewer moves between pages."),blades:external_exports.array(SolutionBladeSchema).max(MAX_SOLUTION_BLADES).optional().describe("How each record kind's record view shows, in a blade and on its record page, one entry per kind: the module's Details view, then the modules' own tabs, then the entry's tabs. Absent for a kind = the module's Details view and the modules' own tabs.")}).meta({examples:[{schemaVersion:"2",filters:[{id:"period",kind:"period",label:"Period",default:{policy:"currentPeriod",grain:"month"}},{id:"site",kind:"assets.subtree",label:"Assets",pages:["page-overview"]}],pages:[{id:"page-overview",slug:"overview",name:"Overview",order:0,layout:{},items:[{instanceId:"item-1",componentName:"asset-count",configVersion:"1",config:{label:"assets tracked"},binding:{},layout:{spanCol:4,spanRow:2}}]},{id:"page-details",slug:"details",name:"Details",order:1,layout:{},items:[{instanceId:"item-2",componentName:"layout-grid",configVersion:"1",config:{columns:2,gap:"default"},binding:{},items:[{instanceId:"item-2a",componentName:"dataset-count",configVersion:"1",config:{},binding:{},layout:{spanCol:1}},{instanceId:"item-2b",componentName:"asset-count",configVersion:"1",config:{label:"assets tracked"},binding:{},layout:{spanCol:1}}]}]},{id:"page-admin",slug:"admin",name:"Admin",order:2,layout:{fullBleed:!0},path:"/admin",icon:"settings",requiresCapability:"tenant:admin",items:[{instanceId:"item-3",componentName:"asset-manager",configVersion:"1",config:{},binding:{}}]}]}]});var approvalTemplateVersionConfigSchema=external_exports.object({variant:external_exports.enum(["full","name","stages","summary","label"]).default("full").describe("full (default): stages and rules cards. name: the linked name and version, inline. stages: one short line per stage. summary: only its name and stage count, on one line. label: the bare template name as plain text, no link and no participant lookup.")});var approvalRequestConfigSchema=external_exports.object({templateVersionId:external_exports.string().regex(external_exports.regexes.uuid(),"Expected a template version id").optional().describe("Show only sign-offs raised under this approval template version. Unset shows any. Bound to a record, or answering a table row\u2019s status, it picks that record\u2019s standing request among this version\u2019s only."),subjectChannel:channelRef({payload:"entity-ref"}).optional().describe("Publish this sign-off's subject ref \u2014 opaque, whole, never decoded here \u2014 onto this declared page channel on load and on change, for another placement bound `{ selectionChannel }` to follow. Unset publishes nothing.")});var APPROVAL_DETAIL_DEFAULT_LAYOUT={spanCol:6,spanRow:6},approvalDetailComponentContract={name:"approval-detail",binds:"entity",bindsToResource:"approval-request",entity:{domain:"approval",type:"approval"},configVersion:"1",configSchema:external_exports.object({}),description:"One approval in full: what is being signed off, the decision, the workflow, comments and history.",grain:"widget",viewer:!0,recordSubject:!0,defaultLayout:APPROVAL_DETAIL_DEFAULT_LAYOUT},APPROVAL_ROW_KIND={domain:"approval",type:"approval"},approvalQueueComponentContract={name:"approval-queue",binds:"collection",bindsToResource:"approval",configVersion:"1",configSchema:external_exports.object({}),description:"Approval inbox and full list. Selecting a row opens the approval in a side-blade the component owns, or in the Solution\u2019s blade where it configures one for approvals, so it never navigates away. A link to the templates admin appears only where the frame offers that page.",grain:"page",rowKind:APPROVAL_ROW_KIND},approvalQueueShowcaseComponentContract={name:"approval-queue-showcase",binds:"collection",bindsToResource:"approval",configVersion:"1",configSchema:external_exports.object({}),description:"Approval queue grouped by the kind of thing being approved, each row carrying the subject, its headline figure and the variance against the owning domain\u2019s own basis. A subject whose domain publishes no figure shows its name, approvers and status only. Selecting a row opens the approval in a side-blade the component owns, or in the Solution\u2019s blade where it configures one for approvals, so it never navigates away.",grain:"page",rowKind:APPROVAL_ROW_KIND},approvalTemplatesComponentContract={name:"approval-templates",binds:"none",configVersion:"1",configSchema:external_exports.object({}),description:"Approval template admin: the reusable sign-off templates approvals are requested against. Creating a template works in any frame (a self-contained dialog); opening a row appears only where the frame offers a destination.",grain:"page"},approvalRecentForSubjectsConfigSchema=external_exports.object({subjects:external_exports.array(external_exports.discriminatedUnion("kind",[external_exports.object({kind:external_exports.literal("entity"),domain:external_exports.string().min(1),type:external_exports.string().min(1),id:external_exports.string().min(1)})])).optional().describe("The subjects whose sign-offs to list, most recent subject first."),limit:external_exports.number().int().min(1).max(20).optional().describe("How many sign-offs to show. Defaults to five.")});var ApprovalIdSchema=external_exports.string().min(1).brand(),ApprovalRefSchema=external_exports.object({approvalId:ApprovalIdSchema}),PartyRefSchema=external_exports.string().min(1).brand(),ApprovalSubjectSchema=EntitySnapshotRefSchema,ApprovalSubjectEntitySchema=ApprovalSubjectSchema.omit({snapshot:!0}),ApprovalStatusSchema=external_exports.enum(["in-progress","approved","rejected","cancelled"]),ApprovalStatusProjectionSchema=external_exports.object({approvalId:ApprovalIdSchema,subject:ApprovalSubjectSchema,status:ApprovalStatusSchema}),EntityApprovalSchema=ApprovalStatusProjectionSchema.extend({requestedBy:PartyRefSchema,createdAt:external_exports.iso.datetime(),originFlowRun:external_exports.string().min(1).optional()}),SubjectHasOpenRequestDataSchema=external_exports.object({code:external_exports.literal("SUBJECT_HAS_OPEN_REQUEST"),standing:external_exports.object({approvalId:ApprovalIdSchema,templateVersionId:external_exports.string(),requestedBy:PartyRefSchema}).nullable()}),SubjectSnapshotRejectedDataSchema=external_exports.object({code:external_exports.literal("SUBJECT_SNAPSHOT_REJECTED"),rejected:external_exports.object({approvalId:ApprovalIdSchema,templateVersionId:external_exports.string()})}),RequestRefusalDataSchema=external_exports.discriminatedUnion("code",[SubjectHasOpenRequestDataSchema,SubjectSnapshotRejectedDataSchema]),LIST_BY_SUBJECTS_MAX=200;var PATH_SEGMENT=/^[A-Za-z_][A-Za-z0-9_-]*$/;var PROTOTYPE_SEGMENTS=["__proto__","constructor","prototype"];function isArgumentPathSegment(segment){return PATH_SEGMENT.test(segment)&&!PROTOTYPE_SEGMENTS.includes(segment)}var FLOW_INPUT_LIST_MAX=200,LIST_ELEMENT_KINDS=["string","number","boolean","principal"],PrincipalRefSchema=external_exports.strictObject({kind:external_exports.enum(["user","group","role"]),id:external_exports.string().min(1).max(ENTITY_REF_MAX_IDENTITY_CHARS)}),StoredPrincipalRefSchema=external_exports.strictObject({...PrincipalRefSchema.shape,id:external_exports.string().min(1)});var ListInputFieldSchema=external_exports.object({type:external_exports.literal("list"),element:external_exports.enum(LIST_ELEMENT_KINDS),max:external_exports.number().int().positive().max(FLOW_INPUT_LIST_MAX,`a list input holds at most ${String(FLOW_INPUT_LIST_MAX)} elements (the platform ceiling)`),optional:external_exports.literal(!0).optional()}).strict(),PrincipalInputFieldSchema=external_exports.object({type:external_exports.literal("principal"),nullable:external_exports.literal(!0),optional:external_exports.literal(!0).optional()}).strict(),PRINCIPAL_SHAPE="a principal {kind: user|group|role, id}";var NULLABLE_PRINCIPAL_SHAPE=`${PRINCIPAL_SHAPE} or null`;var FLOW_INPUT_CHOICES_MAX=50,FLOW_INPUT_CHOICE_MAX_CHARS=200,FLOW_INPUT_STRING_MAX_LENGTH=1e4,VISIBLE_CHARACTER=/[^\s\p{Cf}\u034F\uFE00-\uFE0F\u3164\uFFA0\u2800]/u;var lengthBound=which=>external_exports.number().int().min(1,`${which} is at least 1 \u2014 leave it out for no bound`).max(FLOW_INPUT_STRING_MAX_LENGTH,`${which} is at most ${String(FLOW_INPUT_STRING_MAX_LENGTH)} (the platform ceiling)`),StringInputFieldSchema=external_exports.object({type:external_exports.literal("string"),optional:external_exports.literal(!0).optional(),choices:external_exports.array(external_exports.string().min(1).max(FLOW_INPUT_CHOICE_MAX_CHARS,`a choice is at most ${String(FLOW_INPUT_CHOICE_MAX_CHARS)} characters (the platform ceiling)`).regex(VISIBLE_CHARACTER,"a choice cannot be blank")).min(1).max(FLOW_INPUT_CHOICES_MAX,`a string input offers at most ${String(FLOW_INPUT_CHOICES_MAX)} choices (the platform ceiling)`).optional().describe("The only values accepted, matched exactly. Not together with a length."),minLength:lengthBound("minLength").optional().describe("Fewest characters, not counting leading and trailing white space."),maxLength:lengthBound("maxLength").optional().describe("Most characters, not counting leading and trailing white space.")}).strict();var InputFieldSchema=external_exports.discriminatedUnion("type",[StringInputFieldSchema,external_exports.object({type:external_exports.literal("number"),optional:external_exports.literal(!0).optional()}).strict(),external_exports.object({type:external_exports.literal("boolean"),optional:external_exports.literal(!0).optional()}).strict(),external_exports.object({type:external_exports.literal("ref"),kind:external_exports.string().min(1).describe("The resource kind this reference names, carried FOR CONSUMERS (a surface needs to know what to offer). DOCUMENTARY in v1: the platform checks only that the value is version-pinned, never that it refers to a resource of this kind."),optional:external_exports.literal(!0).optional()}).strict(),external_exports.object({type:external_exports.literal("entity-ref"),optional:external_exports.literal(!0).optional()}).strict(),ListInputFieldSchema,PrincipalInputFieldSchema]),EntityIdentitySchema=external_exports.strictObject(EntityRefInputSchema.shape).describe("An unpinned entity identity the gate subject port mints: {domain, type, id, version?}"),StoredEntityIdentitySchema=external_exports.strictObject(EntityRefSchema.shape),CompositionInputContractSchema=external_exports.object({fields:external_exports.record(external_exports.string().min(1).regex(PATH_SEGMENT,"a declared field name must be bindable as $input.<name> \u2014 a bare identifier (letter or underscore, then letters/digits/underscores/hyphens)"),InputFieldSchema),startingRecord:external_exports.string().regex(PATH_SEGMENT).optional()}).strict().superRefine((contract,ctx)=>{if(contract.startingRecord===void 0)return;let field=Object.hasOwn(contract.fields,contract.startingRecord)?contract.fields[contract.startingRecord]:void 0;(field?.type!=="string"||field.optional!==!0)&&ctx.addIssue({code:"custom",path:["startingRecord"],message:`startingRecord "${contract.startingRecord}" must name a declared optional string field`})});var RunStateSchema=external_exports.enum(["running","parked","done"]),TransitionKindSchema=external_exports.enum(["started","parked","resumed","routed","anchored","reclaimed","sealed"]),ApprovalAwaitingSchema=external_exports.object({kind:external_exports.literal("approval"),ref:external_exports.string().min(1),subject:EntitySnapshotRefSchema.optional(),until:external_exports.iso.datetime().optional(),replaced:external_exports.string().min(1).optional()}).strict(),DelayAwaitingSchema=external_exports.object({kind:external_exports.literal("delay"),until:external_exports.iso.datetime()}).strict(),JobAwaitingSchema=external_exports.object({kind:external_exports.literal("job"),verb:external_exports.string().regex(DOMAIN_VERB_PATTERN,'verb must be "<domain>.<verbName>"'),handle:external_exports.string().min(1),until:external_exports.iso.datetime()}).strict(),FindingsAwaitingSchema=external_exports.object({kind:external_exports.literal("findings"),until:external_exports.iso.datetime()}).strict(),AwaitingSchema=external_exports.discriminatedUnion("kind",[ApprovalAwaitingSchema,DelayAwaitingSchema,JobAwaitingSchema,FindingsAwaitingSchema]),ParkedAtStepSchema=external_exports.string().min(1),DueModeSchema=external_exports.enum(["wake","give-up"]),AttemptSchema=external_exports.number().int().min(1).brand(),DefinitionVersionSchema=external_exports.number().int().min(1).max(2147483647).brand(),DefinitionVersionNumberSchema=external_exports.number().int().min(1).max(2147483647);var ExpressionSchema=external_exports.string().min(1),STEP_ID_PATTERN=/^[^/#]+$/u,STEP_ID_MESSAGE='step id must not contain the key delimiters "/" or "#"',StepIdSchema=external_exports.string().min(1).regex(STEP_ID_PATTERN,STEP_ID_MESSAGE).refine(id=>id!=="__proto__",'a step cannot be named "__proto__"; choose another name'),refuseRepeats=label=>(entries,context)=>{let seen=new Set;for(let entry of entries)seen.has(entry)&&context.addIssue({code:"custom",message:`${label} lists "${entry}" twice`}),seen.add(entry)},CompensationPolicySchema=external_exports.enum(["keep-and-account"]),DefinitionAvailabilitySchema=external_exports.enum(["active","retired"]),TemporalModeSchema=external_exports.enum(["action-time","period-time"]),VersionRuleSchema=external_exports.enum(["current","period-effective"]);var GateSubjectBindingSchema=external_exports.string().min(1).regex(/^\$(steps|input)\./u,"a gate subject must be a $steps.* lookup, or $input.* for a declared entity-ref field"),GateExclusionBindingSchema=external_exports.string().min(1).regex(/^\$steps\./u,"a gate exclusion basis must be a $steps.* lookup \u2014 it names who may NOT approve, so it must be a value the flow itself produced, never input (R1/P3; G6/Q1)"),GateDurationSchema=external_exports.object({amount:external_exports.number().int().min(1),unit:external_exports.enum(["minutes","hours","days"])}).strict().describe("At least 5 minutes and at most 30 days, checked at save and at load."),StandingRequestPolicySchema=external_exports.enum(["stand-down","supersede"]),GateApprovalConfigSchema=external_exports.object({templateVersionId:external_exports.string().min(1),subjectSource:GateSubjectBindingSchema,excludedPartiesSource:GateExclusionBindingSchema.optional(),temporalMode:TemporalModeSchema,versionRule:VersionRuleSchema,giveUpAfter:GateDurationSchema.optional(),onStandingRequest:StandingRequestPolicySchema.optional()}).strict(),ApprovalGateSchema=external_exports.object({kind:external_exports.literal("approval"),config:GateApprovalConfigSchema}).strict(),BranchTargetSchema=StepIdSchema,BranchOperatorSchema=external_exports.enum(["equals","not-equals","greater","greater-or-equal","less","less-or-equal","is-one-of","is-type"]);var BranchConditionSchema=external_exports.object({field:ExpressionSchema,op:BranchOperatorSchema,value:external_exports.union([ExpressionSchema,external_exports.array(ExpressionSchema).min(1)])}).strict(),BranchAllGroupSchema=external_exports.object({all:external_exports.array(BranchConditionSchema).min(2)}).strict(),BranchAnyGroupSchema=external_exports.object({any:external_exports.array(BranchConditionSchema).min(2)}).strict(),BranchWhenSchema=external_exports.union([BranchConditionSchema,BranchAllGroupSchema,BranchAnyGroupSchema]),BranchArmEndSchema=external_exports.object({end:external_exports.literal(!0)}).strict(),BranchCaseSchema=external_exports.object({when:BranchWhenSchema,next:BranchTargetSchema,then:BranchArmEndSchema.optional()}).strict(),BranchOtherwiseSchema=external_exports.union([external_exports.object({next:BranchTargetSchema,then:BranchArmEndSchema.optional()}).strict(),external_exports.object({end:external_exports.literal(!0)}).strict()]),GateBranchConfigSchema=external_exports.object({cases:external_exports.array(BranchCaseSchema).min(1),otherwise:BranchOtherwiseSchema,merge:BranchTargetSchema}).strict(),BranchGateSchema=external_exports.object({kind:external_exports.literal("branch"),config:GateBranchConfigSchema}).strict(),GateDelayConfigSchema=external_exports.object({duration:GateDurationSchema}).strict(),DelayGateSchema=external_exports.object({kind:external_exports.literal("delay"),config:GateDelayConfigSchema}).strict(),GateJobConfigSchema=external_exports.object({startedBy:StepIdSchema,giveUpAfter:GateDurationSchema.optional()}).strict(),JobGateSchema=external_exports.object({kind:external_exports.literal("job"),config:GateJobConfigSchema}).strict(),findingsFromList=max2=>{let sources=external_exports.array(StepIdSchema).min(1);return(max2===void 0?sources:sources.max(max2)).superRefine(refuseRepeats("findingsFrom"))},GateFindingsConfigSchema=external_exports.object({findingsFrom:findingsFromList(),giveUpAfter:GateDurationSchema.optional(),ownerWorkType:external_exports.string().min(1)}).strict(),FindingsGateSchema=external_exports.object({kind:external_exports.literal("findings"),config:GateFindingsConfigSchema}).strict(),GateSchema=external_exports.discriminatedUnion("kind",[ApprovalGateSchema,BranchGateSchema,DelayGateSchema,JobGateSchema,FindingsGateSchema]);var absentPaths=max2=>{let paths=external_exports.array(external_exports.string().refine(path3=>path3.split(".").every(isArgumentPathSegment),`an absent path is a dotted argument path: every segment a plain name, never ${PROTOTYPE_SEGMENTS.join(", ")}`)).min(1);return(max2===void 0?paths:paths.max(max2)).superRefine(refuseRepeats("absent"))},AbsentPathsSchema=absentPaths(),VerbStepSchema=external_exports.object({id:StepIdSchema,type:external_exports.literal("verb").optional(),verb:external_exports.string().regex(DOMAIN_VERB_PATTERN,'verb must be "<domain>.<verbName>"'),args:external_exports.record(external_exports.string().min(1),ExpressionSchema),title:external_exports.string().trim().min(1).max(120).optional(),absent:AbsentPathsSchema.optional(),version:DefinitionVersionNumberSchema.optional(),forEach:ExpressionSchema.optional()}).strict(),GateStepSchema=external_exports.object({id:StepIdSchema,type:external_exports.literal("gate"),gate:GateSchema,title:external_exports.string().trim().min(1).max(120).optional()}).strict(),READ_ANSWER_MAX_BYTES=256*1024,READ_STEP_MAX_BYTES=1024*1024;var ReadStepSchema=external_exports.object({id:StepIdSchema,type:external_exports.literal("read"),read:external_exports.string().regex(DOMAIN_VERB_PATTERN,'read must be "<domain>.<readName>"'),version:external_exports.number().int().positive(),args:external_exports.record(external_exports.string().min(1),ExpressionSchema),title:external_exports.string().trim().min(1).max(120).optional(),forEach:ExpressionSchema.optional()}).strict(),CompositionStepSchema=external_exports.union([VerbStepSchema,GateStepSchema,ReadStepSchema]);function isApprovalGateStep(step){return step.type==="gate"&&step.gate.kind==="approval"}var WriteCompositionDefinitionSchema=external_exports.object({name:external_exports.string().min(1),version:DefinitionVersionNumberSchema,compensation:CompensationPolicySchema,steps:external_exports.array(CompositionStepSchema).min(1),inputSchema:CompositionInputContractSchema.optional(),title:external_exports.string().trim().min(1).max(200).optional(),description:external_exports.string().trim().min(1).max(2e3).optional()}).strict();var ATTEMPT_MARKER="#attempt-",RUN_KEY_ATTEMPT_PATTERN=new RegExp(`^[\\s\\S]+${ATTEMPT_MARKER}[1-9]\\d*$`,"u");var BaseRunKeySchema=external_exports.string().min(1).brand(),RunKeySchema=external_exports.string().min(1).brand();var MS_PER_UNIT={minutes:6e4,hours:36e5,days:864e5},WAIT_FLOOR_MS=5*MS_PER_UNIT.minutes,WAIT_CEILING_MS=30*MS_PER_UNIT.days;var FINDING_MATCH_KEY_MAX_LENGTH=256,FINDING_COUNT_MAX=2147483647,FindingHandlingSchema=external_exports.enum(["exclude","carry"]),FINDING_FAMILY_MAX_LENGTH=128,FINDING_ROWS_REF_MAX_LENGTH=2048,FamilySchema=external_exports.string().max(FINDING_FAMILY_MAX_LENGTH).regex(RESOURCE_KIND_PATTERN,'a finding family is "<module>.<name>"'),FindingSchema=external_exports.strictObject({family:FamilySchema,count:external_exports.number().int().min(1).max(FINDING_COUNT_MAX),rowsRef:external_exports.string().min(1).max(FINDING_ROWS_REF_MAX_LENGTH),matchKey:external_exports.string().min(1).max(FINDING_MATCH_KEY_MAX_LENGTH).nullable(),handling:FindingHandlingSchema}),AcceptedFindingOutcomeSchema=external_exports.enum(["accept","send-to-owner"]),AcceptedFindingSchema=external_exports.strictObject({family:FindingSchema.shape.family,matchKey:FindingSchema.shape.matchKey,handling:FindingSchema.shape.handling,count:FindingSchema.shape.count,outcome:AcceptedFindingOutcomeSchema,decisionId:external_exports.string().min(1),recordRef:external_exports.string().min(1),decidedAt:external_exports.iso.datetime()});var ENDS_AFTER_ARM=Object.freeze({endsRun:!0});var ANY_VALUE_LEAF=Object.freeze({}),NO_VALUE_LEAF=Object.freeze({not:Object.freeze({})});var GateGiveUpSchema=external_exports.object({step:external_exports.string().min(1),reason:external_exports.literal("gave-up"),limit:external_exports.iso.datetime(),overdueMs:external_exports.number().int().nonnegative(),verb:external_exports.string().min(1).optional(),unreadable:external_exports.string().min(1).optional().catch(void 0),gate:external_exports.literal("findings").optional(),openFindings:external_exports.array(external_exports.strictObject({family:FindingSchema.shape.family,matchKey:FindingSchema.shape.matchKey,count:FindingSchema.shape.count})).optional()});var EmptyForEachDetailSchema=external_exports.object({emptyForEachSteps:external_exports.array(external_exports.string().min(1))});var BranchRoutingSchema=external_exports.object({step:external_exports.string().min(1),selected:external_exports.string().min(1).nullable(),divergedFrom:external_exports.string().min(1).nullable().optional(),unevaluatable:external_exports.string().optional(),ends:external_exports.literal(!0).optional(),wroteAnchor:external_exports.literal(!0).optional(),evaluated:external_exports.array(external_exports.object({held:external_exports.boolean(),member:external_exports.number().int().nonnegative().optional()})).optional()});var GateEndedSchema=external_exports.discriminatedUnion("endedBecause",[external_exports.object({gate:external_exports.string().min(1),endedBecause:external_exports.literal("standing-request"),standing:external_exports.array(external_exports.object({approvalRef:external_exports.string().min(1).optional(),requestedBy:external_exports.string().min(1).optional()})).readonly()}),external_exports.object({gate:external_exports.string().min(1),endedBecause:external_exports.literal("superseded"),approvalRef:external_exports.string().min(1),supersededBy:external_exports.string().min(1)}),external_exports.object({gate:external_exports.string().min(1),endedBecause:external_exports.literal("withdraw-refused"),approvalRef:external_exports.string().min(1),requestedBy:external_exports.string().min(1),error:external_exports.string()})]);var StepRefusalSchema=external_exports.object({code:external_exports.string().min(1),message:external_exports.string().trim().min(1)}),RefusalCarrierSchema=external_exports.object({refusal:StepRefusalSchema});var SealSchema=external_exports.object({step:external_exports.string().min(1).optional().catch(void 0),error:external_exports.string().optional().catch(void 0),gate:external_exports.unknown().optional()}),GateSchema2=external_exports.object({status:external_exports.string().optional().catch(void 0),reason:external_exports.string().optional().catch(void 0),error:external_exports.string().optional().catch(void 0),verb:external_exports.string().optional().catch(void 0),unreadable:external_exports.string().optional().catch(void 0),refusalCode:external_exports.string().optional().catch(void 0)}),RUN_FAILURE_REASON_MAX=500;var StepDetailSchema=external_exports.object({step:external_exports.string().min(1)}),RoutedDetailSchema=StepDetailSchema.extend({selected:external_exports.string().min(1).nullable()});var PublishedAwaitingMembers={approval:ApprovalAwaitingSchema.extend({ref:external_exports.string().min(1).nullable()}),delay:DelayAwaitingSchema,job:JobAwaitingSchema.extend({panel:external_exports.string().min(1).nullable()}),findings:FindingsAwaitingSchema},PublishedAwaitingSchema=external_exports.discriminatedUnion("kind",[PublishedAwaitingMembers.approval,PublishedAwaitingMembers.delay,PublishedAwaitingMembers.job,PublishedAwaitingMembers.findings]),RunTransitionSchema=external_exports.object({kind:TransitionKindSchema,causeRecordRef:external_exports.string().min(1).nullable(),at:external_exports.iso.datetime(),detail:external_exports.unknown().optional()}),RunFailureSchema=external_exports.object({step:external_exports.string().min(1).nullable(),cause:external_exports.enum(["failed","refused","rejected","cancelled","gave-up","errored"]),reason:external_exports.string().min(1).max(RUN_FAILURE_REASON_MAX).optional()}),runStatusCommonShape={flowRunRecordId:RecordIdSchema,definition:external_exports.object({name:external_exports.string().min(1),version:DefinitionVersionNumberSchema}),attempt:AttemptSchema.optional(),record:external_exports.object({status:RecordStatusSchema,outcome:FlowRunOutcomeSchema.optional()}),failure:RunFailureSchema.nullable(),trail:external_exports.array(RunTransitionSchema)},RunStatusSchema=external_exports.discriminatedUnion("state",[external_exports.object({...runStatusCommonShape,state:external_exports.literal("parked"),parkedAtStep:ParkedAtStepSchema,awaiting:PublishedAwaitingSchema}),external_exports.object({...runStatusCommonShape,state:RunStateSchema.exclude(["parked"]),parkedAtStep:external_exports.null(),awaiting:external_exports.null()})]),RunSummarySchema=external_exports.object({state:RunStateSchema,record:external_exports.object({status:RecordStatusSchema,outcome:FlowRunOutcomeSchema.optional()}),updatedAt:external_exports.iso.datetime().optional()}),DefinitionDescriptionSchema=external_exports.object({name:external_exports.string().min(1),version:DefinitionVersionNumberSchema,title:external_exports.string().min(1).optional(),description:external_exports.string().min(1).optional(),inputSchema:CompositionInputContractSchema.optional(),steps:external_exports.array(CompositionStepSchema).min(1),availability:DefinitionAvailabilitySchema}),runListItemCommonShape={flowRunRecordId:RecordIdSchema,definition:external_exports.object({name:external_exports.string().min(1),version:DefinitionVersionNumberSchema}),attempt:AttemptSchema.optional(),record:external_exports.object({status:RecordStatusSchema,outcome:FlowRunOutcomeSchema.optional()}),failure:RunFailureSchema.nullable(),createdAt:external_exports.iso.datetime(),updatedAt:external_exports.iso.datetime()},RunListItemSchema=external_exports.discriminatedUnion("state",[external_exports.object({...runListItemCommonShape,state:external_exports.literal("parked"),parkedAtStep:ParkedAtStepSchema,awaiting:PublishedAwaitingSchema}),external_exports.object({...runListItemCommonShape,state:RunStateSchema.exclude(["parked"]),parkedAtStep:external_exports.null(),awaiting:external_exports.null()})]),RunsPageSchema=external_exports.object({items:external_exports.array(RunListItemSchema),cursor:external_exports.string().min(1).optional(),unreadableCount:external_exports.number().int().nonnegative()}),RunRecordStepSchema=external_exports.object({id:external_exports.string().min(1),item:external_exports.string().min(1).optional(),nested:external_exports.boolean()}),RunRecordSchema=ActionRecordSchema.extend({step:RunRecordStepSchema.nullable()}),RunRecordsPageSchema=external_exports.object({items:external_exports.array(RunRecordSchema),cursor:external_exports.string().min(1).optional()});var ApplyResultSchema=external_exports.discriminatedUnion("kind",[external_exports.object({kind:external_exports.literal("sealed"),record:FlowRunRecordSchema}),external_exports.object({kind:external_exports.literal("parked"),flowRunRecordId:external_exports.string().min(1),parkedAtStep:external_exports.string().min(1),awaiting:AwaitingSchema})]);var TriggerBindingSchema=external_exports.object({name:external_exports.string().min(1),version:DefinitionVersionNumberSchema,enabled:external_exports.boolean(),recordAction:external_exports.string().regex(DOMAIN_VERB_PATTERN),match:external_exports.unknown().optional(),definition:external_exports.object({name:external_exports.string().min(1),version:DefinitionVersionNumberSchema}),inputMapping:external_exports.unknown()}).strict();var TriggerBindingPauseCauseSchema=external_exports.enum(["circuit-open"]),TriggerClaimStatusSchema=external_exports.enum(["pending","started","failed","skipped"]),TriggerClaimReasonSchema=external_exports.enum(["mapping-unresolved","apply-failed","definition-retired","input-refused","binding-unreadable","record-unreadable","binding-missing","record-missing","self-triggered","chain-too-long","circuit-open","rule-paused","unknown","previous-run-in-flight","waiting-for-run","verb-changed"]),INPUT_ISSUE_CODES={"not-an-object":"not-an-object","missing-required":"missing-required","undeclared-field":"undeclared-field","wrong-type":"wrong-type","list-too-long":"list-too-long","list-element-wrong-type":"list-element-wrong-type","not-a-choice":"not-a-choice","string-too-short":"string-too-short","string-too-long":"string-too-long","number-not-finite":"number-not-finite","ref-unpinned":"ref-unpinned","entity-ref-shape":"entity-ref-shape","nested-unpinned-ref":"nested-unpinned-ref"},TriggerClaimInputIssueSchema=external_exports.object({code:external_exports.enum(INPUT_ISSUE_CODES),field:external_exports.string().min(1).nullable()}).strict(),TriggerMappingMissSchema=external_exports.discriminatedUnion("effect",[external_exports.object({effect:external_exports.literal("left-out"),field:external_exports.string(),path:external_exports.string().min(1)}).strict(),external_exports.object({effect:external_exports.literal("skips"),field:external_exports.string().nullable(),path:external_exports.string().min(1)}).strict()]),TriggerClaimSchema=external_exports.object({id:external_exports.string().min(1),recordId:external_exports.string().min(1),bindingName:external_exports.string().min(1),bindingVersion:DefinitionVersionNumberSchema,status:TriggerClaimStatusSchema,attempts:external_exports.number().int().positive(),flowRunRecordId:RecordIdSchema.nullable(),run:RunSummarySchema.nullable(),reason:TriggerClaimReasonSchema.nullable(),inputIssue:TriggerClaimInputIssueSchema.nullable(),mappingMisses:external_exports.array(TriggerMappingMissSchema).min(1).nullable(),claimedAt:external_exports.iso.datetime(),updatedAt:external_exports.iso.datetime()}).strict();var RECORD_ROOTS=["params","detail","effects","actor"],SCALAR_LEAVES=["id","committedAt"];var ROOT_LIST=[...SCALAR_LEAVES,...RECORD_ROOTS].map(root=>`$record.${root}`).join(", ");var DEFINITION_STEPS_WIRE_MAX=400,STEP_ARGS_WIRE_MAX=500,STEP_ABSENT_WIRE_MAX=500,BRANCH_CASES_WIRE_MAX=200,BRANCH_GROUP_WIRE_MAX=100,BRANCH_VALUE_LIST_WIRE_MAX=1e3,INPUT_FIELDS_WIRE_MAX=500,DEFINITION_CONFIG_WIRE_MAX=1e3,WIRE_BOUNDED_RECORDS=[],boundedRecord=(key,value2,max2)=>{let schema=external_exports.record(key,value2).refine(record2=>Object.keys(record2).length<=max2,{message:`at most ${String(max2)} entries`});return WIRE_BOUNDED_RECORDS.push([schema,max2]),schema},BranchConditionInputSchema=BranchConditionSchema.extend({value:external_exports.union([ExpressionSchema,external_exports.array(ExpressionSchema).min(1).max(BRANCH_VALUE_LIST_WIRE_MAX)])}),BranchWhenInputSchema=external_exports.union([BranchConditionInputSchema,BranchAllGroupSchema.extend({all:external_exports.array(BranchConditionInputSchema).min(2).max(BRANCH_GROUP_WIRE_MAX)}),BranchAnyGroupSchema.extend({any:external_exports.array(BranchConditionInputSchema).min(2).max(BRANCH_GROUP_WIRE_MAX)})]),GateBranchConfigInputSchema=GateBranchConfigSchema.extend({cases:external_exports.array(BranchCaseSchema.extend({when:BranchWhenInputSchema})).min(1).max(BRANCH_CASES_WIRE_MAX)}),GateFindingsConfigInputSchema=GateFindingsConfigSchema.extend({findingsFrom:findingsFromList(DEFINITION_STEPS_WIRE_MAX)}),GateInputSchema=external_exports.discriminatedUnion("kind",[ApprovalGateSchema,BranchGateSchema.extend({config:GateBranchConfigInputSchema}),DelayGateSchema,JobGateSchema,FindingsGateSchema.extend({config:GateFindingsConfigInputSchema})]),CompositionStepInputSchema=external_exports.union([VerbStepSchema.extend({args:boundedRecord(external_exports.string().min(1),ExpressionSchema,STEP_ARGS_WIRE_MAX),absent:absentPaths(STEP_ABSENT_WIRE_MAX).optional()}),GateStepSchema.extend({gate:GateInputSchema}),ReadStepSchema.extend({args:boundedRecord(external_exports.string().min(1),ExpressionSchema,STEP_ARGS_WIRE_MAX)})]),CompositionInputContractInputSchema=CompositionInputContractSchema.safeExtend({fields:boundedRecord(CompositionInputContractSchema.shape.fields.keyType,CompositionInputContractSchema.shape.fields.valueType,INPUT_FIELDS_WIRE_MAX)});var ApprovalNotifiedSchema=external_exports.array(PrincipalRefSchema),ApprovalNotificationFactsSchema=external_exports.object({notified:ApprovalNotifiedSchema,requester:PrincipalRefSchema,subjectPath:external_exports.string().min(1),stageOpened:external_exports.literal(!0).optional()}),ApprovalCancelFactsSchema=external_exports.object({notified:ApprovalNotifiedSchema,requester:PrincipalRefSchema,subjectPath:external_exports.string().min(1),superseded:external_exports.boolean()});var ApprovalSubjectInputSchema=EntitySnapshotRefInputSchema,ApprovalSubjectEntityInputSchema=ApprovalSubjectInputSchema.omit({snapshot:!0}),PARTY_REF_NOT_AN_EMAIL="a party is a principal id (jwt.sub), never an email \u2014 B8",PRINCIPAL_ID_PATTERN=/^[^@]*$/,NewPartyRefSchema=external_exports.string().min(1).regex(PRINCIPAL_ID_PATTERN,PARTY_REF_NOT_AN_EMAIL).brand(),AvailabilitySchema=external_exports.enum(["draft","published","retired"]),SegregationConfigSchema=external_exports.object({selfApproval:external_exports.boolean().default(!1),crossStep:external_exports.boolean().default(!1)}),CancelAuthoritySchema=external_exports.object({allowRequester:external_exports.boolean().default(!0),allowTenantAdmin:external_exports.boolean().default(!0),additionalPrincipals:external_exports.array(PartyRefSchema).default([])}),STAGE_NAME_MAX_LENGTH=80,StageSpecSchema=external_exports.object({name:external_exports.string().trim().min(1).max(STAGE_NAME_MAX_LENGTH).optional(),parties:external_exports.array(PartyRefSchema).min(1),m:external_exports.number().int().min(1)}).refine(stage=>stage.m<=stage.parties.length,{message:"threshold M must not exceed the number of named approvers N (1 <= M <= N; M1 named-principals floor)",path:["m"]}).refine(stage=>new Set(stage.parties).size===stage.parties.length,{message:"a step names each approver at most once",path:["parties"]});var TemplateContentSchema=external_exports.object({name:external_exports.string().min(1),stages:external_exports.array(StageSpecSchema).min(1),segregation:SegregationConfigSchema.prefault({}),cancelAuthority:CancelAuthoritySchema.prefault({}),singleOpenRequestPerSubject:external_exports.boolean().default(!1)}),TEMPLATE_STAGES_MAX=50,TEMPLATE_PARTIES_MAX=200,NewStageSpecSchema=StageSpecSchema.safeExtend({parties:external_exports.array(NewPartyRefSchema).min(1).max(TEMPLATE_PARTIES_MAX)}),NewCancelAuthoritySchema=CancelAuthoritySchema.safeExtend({additionalPrincipals:external_exports.array(NewPartyRefSchema).max(TEMPLATE_PARTIES_MAX).default([])}),NewTemplateContentSchema=TemplateContentSchema.safeExtend({stages:external_exports.array(NewStageSpecSchema).min(1).max(TEMPLATE_STAGES_MAX),cancelAuthority:NewCancelAuthoritySchema.prefault({})}),ResolvedStageSchema=external_exports.object({stageIndex:external_exports.number().int().min(0),voters:external_exports.array(external_exports.string().min(1)),n:external_exports.number().int().min(0),m:external_exports.number().int().min(1)}).refine(stage=>stage.n===stage.voters.length,{message:"frozen N must equal the resolved voter count",path:["n"]}).refine(stage=>stage.m<=stage.n,{message:"threshold M cannot exceed the frozen resolved N (F3 owns the loud service error)",path:["m"]}).refine(stage=>new Set(stage.voters).size===stage.voters.length,{message:"a resolved voter set contains each principal at most once",path:["voters"]}),ResolutionSnapshotSchema=external_exports.object({stages:external_exports.array(ResolvedStageSchema).min(1),excludedParties:external_exports.array(external_exports.string().min(1)).default([])}).refine(snapshot=>snapshot.stages.every((stage,index)=>stage.stageIndex===index),{message:"step indexes must be contiguous from 0 (the engine addresses steps by position)",path:["stages"]}),VoteOutcomeSchema=external_exports.enum(["approve","reject"]),TemplateVersionViewSchema=external_exports.object({templateId:external_exports.string().min(1),versionId:external_exports.string().min(1),version:external_exports.number().int().min(1),availability:AvailabilitySchema,content:TemplateContentSchema,createdAt:external_exports.iso.datetime(),updatedAt:external_exports.iso.datetime()}),TemplateVersionLookupSchema=TemplateVersionViewSchema.nullable(),TemplateSummarySchema=external_exports.object({templateId:external_exports.string().min(1),name:external_exports.string().min(1),latestVersion:external_exports.number().int().min(1),latestVersionId:external_exports.string().min(1),availability:AvailabilitySchema}),TemplateDetailSchema=external_exports.object({templateId:external_exports.string().min(1),versions:external_exports.array(TemplateVersionViewSchema).min(1)}),RowIdSchema=external_exports.uuid(),GetApprovalInputSchema=external_exports.object({approvalId:RowIdSchema}),GetTemplateInputSchema=external_exports.object({templateId:RowIdSchema}),ListBySubjectInputSchema=external_exports.object({subject:ApprovalSubjectInputSchema,templateVersionId:RowIdSchema.optional()}),ListBySubjectsInputSchema=external_exports.object({subjects:external_exports.array(ApprovalSubjectInputSchema).min(1).max(LIST_BY_SUBJECTS_MAX),templateVersionId:RowIdSchema.optional()}),ListByEntitiesInputSchema=external_exports.object({entities:external_exports.array(ApprovalSubjectEntityInputSchema).min(1).max(LIST_BY_SUBJECTS_MAX),templateVersionId:RowIdSchema.optional(),sameTemplateAs:RowIdSchema.optional()}),TemplateVersionRefInputSchema=external_exports.object({templateVersionId:RowIdSchema}),TemplateVersionPublishedSchema=external_exports.object({published:external_exports.boolean()}),TemplateCreateInputSchema=external_exports.object({content:NewTemplateContentSchema,idempotencyKey:IdempotencyKeySchema}),TemplateReviseInputSchema=external_exports.object({templateId:RowIdSchema,content:NewTemplateContentSchema,idempotencyKey:IdempotencyKeySchema}),TemplatePublishInputSchema=external_exports.object({templateVersionId:RowIdSchema,idempotencyKey:IdempotencyKeySchema}),TemplateRetireInputSchema=external_exports.object({templateVersionId:RowIdSchema,idempotencyKey:IdempotencyKeySchema}),EXCLUDED_PARTIES_MAX=200;var RequestApprovalInputSchema=external_exports.object({templateVersionId:RowIdSchema,subject:ApprovalSubjectInputSchema,excludedParties:external_exports.array(NewPartyRefSchema).max(EXCLUDED_PARTIES_MAX).default([]),idempotencyKey:IdempotencyKeySchema}),ApprovalViewSchema=external_exports.object({approvalId:external_exports.string().min(1),subject:ApprovalSubjectSchema,templateVersionId:external_exports.string().min(1),status:ApprovalStatusSchema,currentStage:external_exports.number().int().min(0),requesterId:external_exports.string().min(1),resolution:ResolutionSnapshotSchema,createdAt:external_exports.iso.datetime(),updatedAt:external_exports.iso.datetime(),originFlowRun:external_exports.string().min(1).optional()}),ApprovalDetailSchema=ApprovalViewSchema.extend({requestedAt:external_exports.iso.datetime().optional()}),ApprovalRecordDetailSchema=ApprovalViewSchema.extend(ApprovalNotificationFactsSchema.shape),ApprovalCancelRecordDetailSchema=ApprovalViewSchema.extend(ApprovalCancelFactsSchema.shape),AUDIT_TEXT_MAX_LENGTH=2e3,AuditTextSchema=external_exports.string().trim().min(1).max(AUDIT_TEXT_MAX_LENGTH),ApproveInputSchema=external_exports.object({approvalId:RowIdSchema,onBehalfOf:external_exports.string().min(1).optional(),note:AuditTextSchema.optional(),idempotencyKey:IdempotencyKeySchema}),RejectInputSchema=external_exports.object({approvalId:RowIdSchema,reason:AuditTextSchema,onBehalfOf:external_exports.string().min(1).optional(),idempotencyKey:IdempotencyKeySchema}),CancelInputSchema=external_exports.object({approvalId:RowIdSchema,reason:AuditTextSchema,idempotencyKey:IdempotencyKeySchema}),CommentInputSchema=external_exports.object({approvalId:RowIdSchema,text:AuditTextSchema,idempotencyKey:IdempotencyKeySchema}),DelegateInputSchema=external_exports.object({approvalId:RowIdSchema,toPrincipal:external_exports.string().min(1).regex(PRINCIPAL_ID_PATTERN,PARTY_REF_NOT_AN_EMAIL),idempotencyKey:IdempotencyKeySchema}),RemindInputSchema=external_exports.object({approvalId:RowIdSchema,idempotencyKey:IdempotencyKeySchema}),RemindResultSchema=external_exports.object({approvalId:RowIdSchema,notified:ApprovalNotifiedSchema.min(1),remindedAt:external_exports.iso.datetime()}),ApprovalActivityVerbSchema=external_exports.enum(["request","approve","reject","cancel","comment","delegate","remind"]),ApprovalActivityEntrySchema=external_exports.object({recordId:external_exports.string().min(1),verb:ApprovalActivityVerbSchema,principal:external_exports.string().min(1),onBehalfOf:external_exports.string().min(1).optional(),time:external_exports.iso.datetime(),reason:external_exports.string().optional(),text:external_exports.string().optional(),toPrincipal:external_exports.string().optional(),notified:external_exports.array(external_exports.string()).optional()}),ApprovalActivityPageSchema=external_exports.object({items:external_exports.array(ApprovalActivityEntrySchema),truncated:external_exports.boolean()}),StageProgressSchema=external_exports.object({index:external_exports.number().int().min(0),m:external_exports.number().int().min(1),n:external_exports.number().int().min(0)}),InboxStageSchema=external_exports.object({index:external_exports.number().int().min(0),m:external_exports.number().int().min(1),name:external_exports.string().min(1).max(STAGE_NAME_MAX_LENGTH).optional(),voters:external_exports.array(external_exports.string().min(1)).min(1)}),InboxRowSchema=external_exports.object({approvalId:external_exports.string().min(1),subject:ApprovalSubjectSchema,status:ApprovalStatusSchema,requesterId:external_exports.string().min(1),templateName:external_exports.string().min(1),templateVersion:external_exports.number().int().min(1),updatedAt:external_exports.iso.datetime(),currentStage:StageProgressSchema,stages:external_exports.array(InboxStageSchema).min(1)}),InboxPageSchema=external_exports.object({items:external_exports.array(InboxRowSchema),total:external_exports.number().int().min(0)}),ApprovalListRowSchema=InboxRowSchema,ApprovalStatusCountsSchema=external_exports.object({inProgress:external_exports.number().int().min(0),approved:external_exports.number().int().min(0),rejected:external_exports.number().int().min(0),cancelled:external_exports.number().int().min(0)}),ApprovalListPageSchema=external_exports.object({items:external_exports.array(ApprovalListRowSchema),total:external_exports.number().int().min(0),counts:ApprovalStatusCountsSchema}),ListApprovalsInputSchema=external_exports.object({status:ApprovalStatusSchema.optional()});var ApprovalStatusPageSchema=external_exports.object({items:external_exports.array(ApprovalStatusProjectionSchema),total:external_exports.number().int().min(0)}),ApprovalsBySubjectPageSchema=external_exports.object({items:external_exports.array(external_exports.object({subject:ApprovalSubjectSchema,approvals:external_exports.array(ApprovalStatusProjectionSchema)})),total:external_exports.number().int().min(0)}),ApprovalsByEntityPageSchema=external_exports.object({items:external_exports.array(external_exports.object({entity:ApprovalSubjectEntitySchema,approvals:external_exports.array(EntityApprovalSchema)})),total:external_exports.number().int().min(0)}),TemplateSummaryPageSchema=external_exports.object({items:external_exports.array(TemplateSummarySchema),total:external_exports.number().int().min(0)}),approvalContract=oc.router({getStatus:oc.input(GetApprovalInputSchema).output(ApprovalStatusProjectionSchema),listBySubject:oc.input(ListBySubjectInputSchema).output(ApprovalStatusPageSchema),listBySubjects:oc.input(ListBySubjectsInputSchema).output(ApprovalsBySubjectPageSchema),listByEntities:oc.input(ListByEntitiesInputSchema).output(ApprovalsByEntityPageSchema),isTemplateVersionPublished:oc.input(TemplateVersionRefInputSchema).output(TemplateVersionPublishedSchema),getDetail:oc.input(GetApprovalInputSchema).output(ApprovalDetailSchema),getActivity:oc.input(GetApprovalInputSchema).output(ApprovalActivityPageSchema).meta({agenticSurface:"excluded",agenticSurfaceReason:"semantic"}),inbox:oc.output(InboxPageSchema),listApprovals:oc.input(ListApprovalsInputSchema).output(ApprovalListPageSchema),listTemplates:oc.output(TemplateSummaryPageSchema),getTemplate:oc.input(GetTemplateInputSchema).output(TemplateDetailSchema),getTemplateVersion:oc.input(TemplateVersionRefInputSchema).output(TemplateVersionLookupSchema),request:oc.input(RequestApprovalInputSchema).output(ApprovalViewSchema).errors({BAD_REQUEST:{data:RequestRefusalDataSchema}}),approve:oc.input(ApproveInputSchema).output(ApprovalViewSchema),reject:oc.input(RejectInputSchema).output(ApprovalViewSchema),cancel:oc.input(CancelInputSchema).output(ApprovalViewSchema),comment:oc.input(CommentInputSchema).output(ApprovalViewSchema),delegate:oc.input(DelegateInputSchema).output(ApprovalViewSchema),remind:oc.input(RemindInputSchema).output(RemindResultSchema),templateCreate:oc.input(TemplateCreateInputSchema).output(TemplateVersionViewSchema),templateRevise:oc.input(TemplateReviseInputSchema).output(TemplateVersionViewSchema),templatePublish:oc.input(TemplatePublishInputSchema).output(TemplateVersionViewSchema),templateRetire:oc.input(TemplateRetireInputSchema).output(TemplateVersionViewSchema)});var AssetIdSchema=external_exports.string().min(1).brand().describe("The asset's DURABLE identity \u2014 stable across every version of the asset. This is the id every write and every graph call takes (get / update / delete / setLocation / relationships / subtree). It is NOT the `id` an asset read returns: that one is the VERSION-ROW id, which changes on every edit and is output-only. When a create returns both, keep `assetId`.");var AccessUpdateStateSchema=external_exports.enum(["current","updating","failed"]),AccessUpdateJobIdSchema=external_exports.uuid().brand(),AccessUpdateJobStateSchema=external_exports.enum(["PENDING","RUNNING","COMPLETED","FAILED"]);var AccessStatusInputSchema=external_exports.strictObject({assetId:AssetIdSchema}),AccessUpdateJobSummarySchema=external_exports.strictObject({jobId:AccessUpdateJobIdSchema,state:AccessUpdateJobStateSchema,nodesDone:external_exports.number().int().nonnegative(),failureDetail:external_exports.string().optional()}),AccessStatusSchema=external_exports.strictObject({state:AccessUpdateStateSchema,job:AccessUpdateJobSummarySchema.optional(),failureDetail:external_exports.string().optional()}),RerunAccessUpdateResultSchema=external_exports.strictObject({reopened:external_exports.boolean(),job:AccessUpdateJobSummarySchema.optional()}),ACCESS_UPDATE_RUNNER_UNAVAILABLE="ACCESS_UPDATE_RUNNER_UNAVAILABLE",AccessUpdateRunnerUnavailableDataSchema=external_exports.object({code:external_exports.literal(ACCESS_UPDATE_RUNNER_UNAVAILABLE)});var WIRE_BOUNDED_RECORDS2=[],wireBoundedRecord=(key,value2,max2)=>{let schema=external_exports.record(key,value2).refine(record2=>Object.keys(record2).length<=max2,{message:`at most ${String(max2)} entries`});return WIRE_BOUNDED_RECORDS2.push({schema,max:max2}),schema},wireRecordPublished=({max:max2})=>({maxProperties:max2});var DatasetColumnSchema=external_exports.object({name:external_exports.string().min(1),type:external_exports.string().min(1)});var NUMERIC_STRING_PATTERN="^-?[0-9]+(\\.[0-9]+)?([eE][+-]?[0-9]+)?$",NUMERIC_STRING_RE=new RegExp(NUMERIC_STRING_PATTERN);var LIVE_OWNER_DOMAIN_PATTERN=/^[a-z][a-z0-9_]*$/;var SdpConnectorKindSchema=external_exports.string().min(1).max(64).regex(/^[a-z][a-z0-9-]*$/,'connector kind is a lowercase slug (e.g. "delta-share")'),SdpConnectionRefSchema=external_exports.object({connectionId:external_exports.string().min(1)}),SdpConnectionProfileSchema=external_exports.object({connectorKind:SdpConnectorKindSchema,name:external_exports.string().min(1),endpointUrl:external_exports.string().min(1),config:external_exports.record(external_exports.string(),external_exports.unknown()).default({}),secretArn:external_exports.string().min(1).optional(),credential:external_exports.string().min(1).optional()}),ConfigureSdpConnectionInputSchema=external_exports.object({name:external_exports.string().min(1).optional(),endpointUrl:external_exports.string().min(1).optional(),config:external_exports.record(external_exports.string(),external_exports.unknown()).optional(),secretArn:external_exports.string().min(1).nullable().optional()}).refine(changes=>Object.values(changes).some(value2=>value2!==void 0),{message:"a configure must change at least one field"}),SdpConnectionSchema=SdpConnectionRefSchema.extend(SdpConnectionProfileSchema.shape),SDP_CONNECTION_PROBE_FAILURES=["unreachable","unauthorized","protocol_mismatch","timeout"],SdpConnectionProbeFailureSchema=external_exports.enum(SDP_CONNECTION_PROBE_FAILURES),TestSdpConnectionInputSchema=external_exports.union([external_exports.object({connection:SdpConnectionRefSchema}),external_exports.object({draft:SdpConnectionProfileSchema})]),SdpConnectionTestResultSchema=external_exports.discriminatedUnion("ok",[external_exports.object({ok:external_exports.literal(!0),durationMs:external_exports.number().int().nonnegative()}),external_exports.object({ok:external_exports.literal(!1),failure:SdpConnectionProbeFailureSchema,reason:external_exports.string().min(1),durationMs:external_exports.number().int().nonnegative()})]),MAX_SDP_LISTING_DEPTH=8,SdpListingPathSchema=external_exports.array(external_exports.string().min(1)).max(MAX_SDP_LISTING_DEPTH),browsePathSchema=external_exports.array(external_exports.string().min(1)).max(MAX_SDP_LISTING_DEPTH-1),SdpListingEntrySchema=external_exports.object({name:external_exports.string().min(1),path:SdpListingPathSchema,kind:external_exports.enum(["container","dataset"]),readable:external_exports.boolean().optional()}),MAX_SDP_LISTING_ENTRIES=1e3,BrowseSdpListingsInputSchema=external_exports.object({path:browsePathSchema.default([])}),SdpConnectionListingSchema=external_exports.object({path:browsePathSchema,entries:external_exports.array(SdpListingEntrySchema).max(MAX_SDP_LISTING_ENTRIES)});var CATALOG_SLUG_PATTERN=/^[a-z][a-z0-9_-]{0,62}[a-z0-9]$/;var CATALOG_CONCEPT_REF_PATTERN=/^[a-z][a-z0-9_-]{0,62}[a-z0-9]\/[a-z][a-z0-9_-]{0,62}[a-z0-9]$/,CATALOG_QUDT_UNIT_PATTERN=/^[a-z][a-z0-9]*:[A-Za-z0-9][A-Za-z0-9._-]*$/;var SDP_FIELD_ANNOTATION_COLUMN_MAX=255,SDP_FIELD_ANNOTATION_URI_MAX=2048,ABSOLUTE_IRI=/^[A-Za-z][A-Za-z0-9+.-]*:\S+$/,UNSAFE_URI_SCHEMES=new Set(["javascript","data","vbscript"]),hasC0Control=value2=>{for(let index=0;index<value2.length;index+=1)if(value2.charCodeAt(index)<32)return!0;return!1},SdpFieldAnnotationColumnSchema=external_exports.string().min(1).max(SDP_FIELD_ANNOTATION_COLUMN_MAX).refine(column2=>!column2.includes("/"),"a column name cannot contain '/'").refine(column2=>column2!=="."&&column2!=="..","a column name cannot be . or ..").refine(column2=>!hasC0Control(column2),"a column name cannot hold control characters"),SdpFieldAnnotationUriSchema=external_exports.string().min(1).max(SDP_FIELD_ANNOTATION_URI_MAX).regex(ABSOLUTE_IRI,"must be an absolute IRI, e.g. 'https://schema.org/value'").refine(uri2=>!hasC0Control(uri2),"a uri cannot hold control characters").refine(uri2=>!UNSAFE_URI_SCHEMES.has((uri2.split(":",1)[0]??"").toLowerCase()),"the javascript, data and vbscript schemes are refused");var UnreceiptedIdempotencyKeySchema=external_exports.string().min(1).describe("Client-minted key for this write \u2014 YOU generate it (a UUID is fine), the server never does. NOT A REPLAY KEY, unlike the receipted governed writes: this call files no Record, so nothing is stored under this key and a reused one is never replayed \u2014 the call simply executes again. Mint a fresh key per attempt, and treat a re-send after a timeout as a second write rather than a safe retry.");var ExternalIdSystemSchema=external_exports.string().min(1).max(64),ExternalIdValueSchema=external_exports.string().min(1).max(512);var AssetExternalIdSchema=external_exports.object({get assetId(){return AssetIdSchema},system:ExternalIdSystemSchema,value:ExternalIdValueSchema}),AssetSystemIdSchema=external_exports.string().min(1).brand(),ExternalIdFormatSchema=external_exports.strictObject({pattern:external_exports.string().min(1).max(200).optional(),minLength:external_exports.number().int().min(1).max(1e3).optional(),maxLength:external_exports.number().int().min(1).max(1e3).optional()}),AssetSystemTermSchema=external_exports.string().regex(CATALOG_CONCEPT_REF_PATTERN,"a term is 'scheme/slug'"),AssetSystemSchema=external_exports.object({id:AssetSystemIdSchema,key:ExternalIdSystemSchema,displayLabel:external_exports.string().min(1).max(64),idFormat:ExternalIdFormatSchema.nullable(),term:AssetSystemTermSchema.nullable().default(null),createdAt:external_exports.iso.datetime(),updatedAt:external_exports.iso.datetime()}),CreateAssetSystemInputSchema=external_exports.strictObject({idempotencyKey:UnreceiptedIdempotencyKeySchema,key:ExternalIdSystemSchema,displayLabel:external_exports.string().min(1).max(64),idFormat:ExternalIdFormatSchema.optional(),term:AssetSystemTermSchema.optional()}),RawCreateAssetSystemInputSchema=CreateAssetSystemInputSchema.omit({idempotencyKey:!0}),GetAssetSystemInputSchema=external_exports.strictObject({id:AssetSystemIdSchema}),ListAssetSystemsInputSchema=external_exports.strictObject({}),UpdateAssetSystemInputSchema=external_exports.strictObject({idempotencyKey:UnreceiptedIdempotencyKeySchema,id:AssetSystemIdSchema,displayLabel:external_exports.string().min(1).max(64).optional(),idFormat:ExternalIdFormatSchema.nullable().optional(),term:AssetSystemTermSchema.nullable().optional()}),DeleteAssetSystemInputSchema=external_exports.strictObject({idempotencyKey:UnreceiptedIdempotencyKeySchema,id:AssetSystemIdSchema}),ExternalIdBindingIdSchema=external_exports.string().min(1).brand(),ExternalIdBindingSchema=external_exports.object({bindingId:ExternalIdBindingIdSchema,get assetId(){return AssetIdSchema},system:ExternalIdSystemSchema,value:ExternalIdValueSchema,effectiveFrom:external_exports.iso.datetime(),effectiveTo:external_exports.iso.datetime().nullable()}),BindExternalIdInputSchema=external_exports.strictObject({get assetId(){return AssetIdSchema},system:ExternalIdSystemSchema,value:ExternalIdValueSchema}),UnbindExternalIdInputSchema=external_exports.strictObject({bindingId:ExternalIdBindingIdSchema}),GovernedBindExternalIdInputSchema=BindExternalIdInputSchema.extend({idempotencyKey:IdempotencyKeySchema}),GovernedUnbindExternalIdInputSchema=UnbindExternalIdInputSchema.extend({idempotencyKey:IdempotencyKeySchema}),ListAssetExternalIdsInputSchema=external_exports.strictObject({get assetId(){return AssetIdSchema}}),ResolveExternalIdInputSchema=external_exports.strictObject({system:ExternalIdSystemSchema,value:ExternalIdValueSchema}),ExternalIdDirectoryInputSchema=external_exports.strictObject({system:ExternalIdSystemSchema,cursor:external_exports.string().min(1).optional(),limit:external_exports.number().int().min(1).max(1e4).optional(),asOf:external_exports.iso.datetime().optional()}),ExternalIdDirectoryEntrySchema=external_exports.object({value:ExternalIdValueSchema,get assetId(){return AssetIdSchema}}),ExternalIdDirectoryOutputSchema=external_exports.object({items:external_exports.array(ExternalIdDirectoryEntrySchema),nextCursor:external_exports.string().nullable()}),BULK_BIND_EXTERNAL_ID_MAX_ROWS=100,BulkBindExternalIdItemSchema=external_exports.strictObject({get assetId(){return AssetIdSchema},system:ExternalIdSystemSchema,value:ExternalIdValueSchema}),BulkBindExternalIdInputSchema=external_exports.strictObject({bindings:external_exports.array(BulkBindExternalIdItemSchema).min(1).max(BULK_BIND_EXTERNAL_ID_MAX_ROWS),idempotencyKey:IdempotencyKeySchema}),BulkBindExternalIdErrorCodeSchema=external_exports.enum(["asset-not-found","invalid-value","already-bound"]),BulkBindExternalIdRowResultSchema=external_exports.discriminatedUnion("status",[external_exports.object({get assetId(){return AssetIdSchema},system:ExternalIdSystemSchema,value:ExternalIdValueSchema,status:external_exports.literal("bound"),bindingId:ExternalIdBindingIdSchema}),external_exports.object({get assetId(){return AssetIdSchema},system:ExternalIdSystemSchema,value:ExternalIdValueSchema,status:external_exports.literal("refused"),error:external_exports.object({code:BulkBindExternalIdErrorCodeSchema,message:external_exports.string().min(1),get holdingAssetId(){return AssetIdSchema.optional()}})})]),BulkBindExternalIdOutputSchema=external_exports.object({summary:external_exports.object({requested:external_exports.number().int().min(0),bound:external_exports.number().int().min(0),reasserted:external_exports.number().int().min(0),refused:external_exports.number().int().min(0)}),results:external_exports.array(BulkBindExternalIdRowResultSchema)});var ASSET_SEARCH_MAX=512,ASSET_SEARCH_PREFIX_MIN_LENGTH=3;var SearchCapReachedSchema=external_exports.enum(["names","checked","ids"]);var AssetSearchSchema=external_exports.string().min(1).max(ASSET_SEARCH_MAX).regex(/^[^\u0000]*$/,"search cannot contain a NUL character").describe(`The search box: an asset matches when its NAME contains this text (any case) OR it holds a current external ID, in any system, that STARTS WITH this text ignoring case (${String(ASSET_SEARCH_PREFIX_MIN_LENGTH)} characters or more; \`equipment_1055\` finds \`EQUIPMENT_105558\`; never the middle of an ID, no numeric coercion). An external ID typed whole and exactly is always found, at any length. The text is trimmed and both sides are literal, so \`%\`, \`_\` and \`\\\` are ordinary characters. Unlike \`nameContains\`, which is name-only, this also finds an asset by an external ID.`);var AssetLifecycleStatusSchema=external_exports.enum(["PRE_PRODUCTION","ACTIVE","INACTIVE","SHUT_IN","DECOMMISSIONED"]),LifecycleMoveSchema=external_exports.strictObject({from:AssetLifecycleStatusSchema,to:AssetLifecycleStatusSchema}),LifecycleGateBindingSchema=LifecycleMoveSchema.extend({approvalTemplateVersionId:external_exports.uuid()}),LifecycleRuleSchema=LifecycleMoveSchema.extend({gated:external_exports.boolean(),approvalTemplateVersionId:external_exports.uuid().optional()}),LifecycleRulesSchema=external_exports.strictObject({moves:external_exports.array(LifecycleRuleSchema).max(25)}),LifecyclePolicyOverlaySchema=external_exports.strictObject({disabledMoves:external_exports.array(LifecycleMoveSchema).max(25),addedGates:external_exports.array(LifecycleGateBindingSchema).max(25)}),EMPTY_LIFECYCLE_OVERLAY=Object.freeze({disabledMoves:[],addedGates:[]}),EffectiveMoveSchema=LifecycleRuleSchema,EffectiveLifecyclePolicySchema=external_exports.object({moves:external_exports.array(EffectiveMoveSchema)}).brand(),LifecyclePolicyViewSchema=external_exports.object({rules:LifecycleRulesSchema.nullable(),overlay:LifecyclePolicyOverlaySchema.nullable(),effective:EffectiveLifecyclePolicySchema.nullable()}),SaveLifecycleRulesInputSchema=external_exports.strictObject({rules:LifecycleRulesSchema,idempotencyKey:IdempotencyKeySchema}),SaveLifecyclePolicyInputSchema=external_exports.strictObject({overlay:LifecyclePolicyOverlaySchema,idempotencyKey:IdempotencyKeySchema});var AssetSummarySchema=external_exports.object({total:external_exports.number().int().min(0),byLifecycleStatus:external_exports.record(AssetLifecycleStatusSchema,external_exports.number().int().min(0)),atLeast:external_exports.literal(!0).optional(),capReached:SearchCapReachedSchema.optional()});var LongitudeSchema=external_exports.number().min(-180).max(180),LatitudeSchema=external_exports.number().min(-90).max(90),GeoJsonPositionSchema=external_exports.tuple([LongitudeSchema,LatitudeSchema]),GEOJSON_ARRAY_WIRE_MAX=2e6,bounded=(element,min,max2)=>{let list=external_exports.array(element).min(min);return max2===void 0?list:list.max(max2)},ringOf=max2=>bounded(GeoJsonPositionSchema,4,max2),buildPolygonSchema=(max2,ringMax=max2)=>external_exports.strictObject({type:external_exports.literal("Polygon"),coordinates:bounded(ringOf(ringMax),1,max2)}),buildGeometrySchema=max2=>{let ring=ringOf(max2);return external_exports.discriminatedUnion("type",[external_exports.strictObject({type:external_exports.literal("Point"),coordinates:GeoJsonPositionSchema}),external_exports.strictObject({type:external_exports.literal("LineString"),coordinates:bounded(GeoJsonPositionSchema,2,max2)}),buildPolygonSchema(max2),external_exports.strictObject({type:external_exports.literal("MultiPoint"),coordinates:bounded(GeoJsonPositionSchema,1,max2)}),external_exports.strictObject({type:external_exports.literal("MultiLineString"),coordinates:bounded(bounded(GeoJsonPositionSchema,2,max2),1,max2)}),external_exports.strictObject({type:external_exports.literal("MultiPolygon"),coordinates:bounded(bounded(ring,1,max2),1,max2)})])},GeoJsonGeometrySchema=buildGeometrySchema(void 0),GeoJsonGeometryInputSchema=buildGeometrySchema(GEOJSON_ARRAY_WIRE_MAX),WITHIN_POLYGON_MAX_VERTICES=1e3,GeoJsonPolygonSchema=buildPolygonSchema(GEOJSON_ARRAY_WIRE_MAX,WITHIN_POLYGON_MAX_VERTICES);var HierarchyRelationshipTypeSchema=external_exports.enum(["CONTAINS","PART_OF","REPORTS_TO","BELONGS_TO"]).describe("Edge type to walk, read subject\u2192object (`CONTAINS`: subject contains object). Only the four HIERARCHICAL types are walkable \u2014 the storage-only `FLOWS_TO` / `CONNECTED_TO` are rejected here, though `relationships.create`/`listFor` accept them.");var HIERARCHY_ID_SHAPE=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,HierarchyIdSchema=external_exports.string().regex(HIERARCHY_ID_SHAPE,"must be a uuid").brand().describe("The named tree an edge lives in \u2014 `hierarchy.id`, stable for the tree's lifetime."),HIERARCHY_NAME_MAX=120,HierarchyNameSchema=external_exports.string().trim().min(1,"a hierarchy name cannot be blank").max(HIERARCHY_NAME_MAX).describe("The tree's operator-facing name, UNIQUE PER TENANT. Compositions reference a hierarchy by this name and the import resolves-or-creates on it, so the name is the durable ref an operator types \u2014 not an internal code.");var HierarchySchema=external_exports.object({id:HierarchyIdSchema,name:HierarchyNameSchema,createdAt:external_exports.iso.datetime()}),CreateHierarchyInputSchema=external_exports.strictObject({idempotencyKey:UnreceiptedIdempotencyKeySchema,name:HierarchyNameSchema}),ListHierarchiesInputSchema=external_exports.strictObject({}),HierarchyEdgeCountSchema=external_exports.object({relationshipType:HierarchyRelationshipTypeSchema,edgeCount:external_exports.number().int().min(1)}),HierarchyListItemSchema=HierarchySchema.extend({edgeCounts:external_exports.array(HierarchyEdgeCountSchema).optional()}),ListHierarchiesOutputSchema=external_exports.array(HierarchyListItemSchema),HierarchyScopeSchema=external_exports.discriminatedUnion("by",[external_exports.object({by:external_exports.literal("hierarchy"),get hierarchyId(){return HierarchyIdSchema}}),external_exports.object({by:external_exports.literal("unassigned")})]).describe('REQUIRED \u2014 which tree to walk. `{by:"hierarchy", hierarchyId}` walks that named tree; `{by:"unassigned"}` walks the edges that predate hierarchies (the only bucket where a child may have more than one parent). There is no "all trees" option: the union of two trees is not a tree.');var AssetForestSchema=external_exports.strictObject({hierarchy:HierarchyScopeSchema,relationshipType:HierarchyRelationshipTypeSchema});var UNDER_ASSET_IDS_MAX=50,AssetBranchScopeSchema=external_exports.strictObject({forest:AssetForestSchema,assetIds:external_exports.array(AssetIdSchema).min(1).max(UNDER_ASSET_IDS_MAX)}),UNDER_ASSET_IDS_DESCRIPTION="Show only assets in the branch of ANY of these items: each item AND everything under it, walked in ONE tree (`forest.hierarchy`) by one relationship type, so a set of items is an OR. Node-inclusive: the item itself is in its own branch. 1 to 50 items. There is no size cap on a branch, which is walked to a depth of 64 as `subtreeOf` is: one too large for the request's time budget is refused with `TX_BUDGET_OVERRUN`, never truncated. An id that is not a UUID is dropped (an all-malformed set matches nothing, never everything); an id with no edge in the tree matches itself alone. ANDs with every other filter. Read-only: bulk writes and export do not take it. `subtreeOf` is the capped (10,000), single-item form kept for existing callers; this key has no cap.";var AssetCategoryIdSchema=external_exports.string().min(1).brand(),ASSET_TYPE_ENTITY_HINT={entity:{domain:"assets",type:"asset-type"}},ASSET_ENTITY_HINT={entity:{domain:"assets",type:"asset"},pickerResource:"assets"},AssetTypeIdSchema=external_exports.string().min(1).brand().meta(ASSET_TYPE_ENTITY_HINT),AssetCategorySchema=external_exports.object({id:AssetCategoryIdSchema,key:external_exports.string().min(1),displayName:external_exports.string().min(1),createdAt:external_exports.iso.datetime(),updatedAt:external_exports.iso.datetime()}),CreateAssetCategoryInputSchema=external_exports.strictObject({idempotencyKey:UnreceiptedIdempotencyKeySchema,key:external_exports.string().min(1),displayName:external_exports.string().min(1)}),RawCreateAssetCategoryInputSchema=CreateAssetCategoryInputSchema.omit({idempotencyKey:!0}),GetAssetCategoryInputSchema=external_exports.strictObject({id:AssetCategoryIdSchema}),UpdateAssetCategoryInputSchema=external_exports.strictObject({idempotencyKey:UnreceiptedIdempotencyKeySchema,id:AssetCategoryIdSchema,displayName:external_exports.string().min(1)}),ListAssetCategoriesInputSchema=external_exports.strictObject({}),DeleteAssetCategoryInputSchema=external_exports.strictObject({idempotencyKey:UnreceiptedIdempotencyKeySchema,id:AssetCategoryIdSchema}),AssetTypeSchema=external_exports.object({id:AssetTypeIdSchema,key:external_exports.string().min(1),displayName:external_exports.string().min(1),categoryId:AssetCategoryIdSchema,createdAt:external_exports.iso.datetime(),updatedAt:external_exports.iso.datetime()}),CreateAssetTypeInputSchema=external_exports.strictObject({idempotencyKey:UnreceiptedIdempotencyKeySchema,key:external_exports.string().min(1),displayName:external_exports.string().min(1),categoryId:AssetCategoryIdSchema}),RawCreateAssetTypeInputSchema=CreateAssetTypeInputSchema.omit({idempotencyKey:!0}),GetAssetTypeInputSchema=external_exports.strictObject({id:AssetTypeIdSchema}),UpdateAssetTypeInputSchema=external_exports.strictObject({idempotencyKey:UnreceiptedIdempotencyKeySchema,id:AssetTypeIdSchema,displayName:external_exports.string().min(1)}),ListAssetTypesInputSchema=external_exports.strictObject({categoryId:AssetCategoryIdSchema.optional()}),DeleteAssetTypeInputSchema=external_exports.strictObject({idempotencyKey:UnreceiptedIdempotencyKeySchema,id:AssetTypeIdSchema});var ASSETS_SUBTREE_FILTER_KIND="assets.subtree",ASSETS_TYPE_FILTER_KIND="assets.type",AssetSubtreeScopeSchema=external_exports.strictObject({forest:AssetForestSchema,assetId:AssetIdSchema}).describe("The asset `assetId` AND everything under it, walked in ONE tree (`forest.hierarchy`) by one relationship type. Node-inclusive. An asset reachable only through another tree is not in it."),AssetSubtreeFilterValueSchema=external_exports.union([AssetSubtreeScopeSchema,AssetBranchScopeSchema]),AssetTypeFilterValueSchema=external_exports.strictObject({assetTypeIds:external_exports.array(AssetTypeIdSchema).min(1).max(50)});var AsOfSchema=external_exports.iso.datetime().describe("Point-in-time instant to resolve as-of (half-open effectiveFrom <= asOf < effectiveTo). UTC, Z-only \u2014 a numeric offset (+HH:MM) is rejected; the OpenAPI date-time format cannot express Z-only, so this note is where the constraint lives. Absent \u2192 the current state."),KnownAtSchema=external_exports.iso.datetime().refine(value2=>Date.parse(value2)<=Date.now(),{message:"A known-at instant cannot be in the future."}).describe("Replay an as-of read as known at this instant: only dated values recorded at or before it and not retired by it are merged; version rows are read as stored. UTC, Z-only. Never in the future, and only with asOf. Absent \u2192 now."),EffectiveFromSchema=external_exports.iso.datetime({precision:3}).describe("Instant the change took effect (the successor version opens here). UTC, Z-only \u2014 a numeric offset (+HH:MM) is rejected \u2014 and pinned to MILLISECOND precision. Must be after the current version\u2019s effectiveFrom and not in the future. Absent \u2192 the instant the request is applied."),EffectiveToSchema=external_exports.iso.datetime({precision:3}).describe("Instant the interval closed (the row stops being in force here). UTC, Z-only \u2014 a numeric offset (+HH:MM) is rejected \u2014 and pinned to MILLISECOND precision. Must be after the row\u2019s own effectiveFrom and not in the future. Absent \u2192 the instant the request is applied (or, on a create, the edge stays open)."),InitialEffectiveFromSchema=external_exports.iso.datetime({precision:3}).describe("Instant this asset first existed \u2014 its FIRST version opens here, so a reporting window that closes before it resolves the asset as not-yet-created. UTC, Z-only \u2014 a numeric offset (+HH:MM) is rejected \u2014 and pinned to MILLISECOND precision. Must NOT be in the future; there is no lower bound (a first version has no predecessor to invert). Absent \u2192 the instant the request is applied, byte-identically to a create that predates this field.");var RelationshipNeighborsInputSchema=external_exports.strictObject({get assetId(){return AssetIdSchema},get relationshipType(){return HierarchyRelationshipTypeSchema},hierarchy:HierarchyScopeSchema,get asOf(){return AsOfSchema.optional()}}),RelationshipRootsInputSchema=external_exports.strictObject({get relationshipType(){return HierarchyRelationshipTypeSchema},hierarchy:HierarchyScopeSchema,get asOf(){return AsOfSchema.optional()},offset:external_exports.number().int().min(0).optional(),get limit(){return external_exports.number().int().min(1).max(QUALITY_PAGE_LIMIT_MAX).optional()}}),HIERARCHY_MAX_DEPTH=64,AssetSubtreeInputSchema=external_exports.strictObject({get assetId(){return AssetIdSchema},get relationshipType(){return HierarchyRelationshipTypeSchema},hierarchy:HierarchyScopeSchema,get asOf(){return AsOfSchema.optional()},maxDepth:external_exports.number().int().min(1).max(HIERARCHY_MAX_DEPTH).describe("REQUIRED \u2014 how many edges deep to walk (1\u201364). There is no default: omitting it is a validation error, not an unbounded walk. Depth 1 = immediate neighbours only.")}),AssetAncestorsInputSchema=external_exports.strictObject({get assetId(){return AssetIdSchema},get relationshipType(){return HierarchyRelationshipTypeSchema},hierarchy:HierarchyScopeSchema,get asOf(){return AsOfSchema.optional()},maxDepth:external_exports.number().int().min(1).max(HIERARCHY_MAX_DEPTH).describe("REQUIRED \u2014 how many edges deep to walk (1\u201364). There is no default: omitting it is a validation error, not an unbounded walk. Depth 1 = immediate neighbours only.")}),SubtreeNodeSchema=external_exports.object({get assetId(){return AssetIdSchema},name:external_exports.string().min(1),get assetTypeId(){return AssetTypeIdSchema},lifecycleStatus:AssetLifecycleStatusSchema}),HierarchyBrowseNodeSchema=SubtreeNodeSchema.extend({hasChildren:external_exports.boolean()});var RelationshipRootsCountSchema=external_exports.discriminatedUnion("kind",[external_exports.object({kind:external_exports.literal("exact"),total:external_exports.number().int().min(0)}),external_exports.object({kind:external_exports.literal("atLeast"),total:external_exports.number().int().min(0)})]),RelationshipRootsOutputSchema=external_exports.object({items:external_exports.array(HierarchyBrowseNodeSchema),count:RelationshipRootsCountSchema}),RelationshipHasChildrenInputSchema=external_exports.strictObject({get assetIds(){return external_exports.array(AssetIdSchema).min(1).max(ASSET_IDS_MAX_PER_PAGE)},get relationshipType(){return HierarchyRelationshipTypeSchema},hierarchy:HierarchyScopeSchema,get asOf(){return AsOfSchema.optional()}}),RelationshipHasChildrenOutputSchema=external_exports.array(external_exports.object({get assetId(){return AssetIdSchema},hasChildren:external_exports.boolean()})),AssetSubtreeOutputSchema=external_exports.array(external_exports.object({node:SubtreeNodeSchema,depth:external_exports.number().int().min(0),get parentAssetId(){return AssetIdSchema.nullable()}})),AssetAncestorsOutputSchema=external_exports.array(external_exports.object({node:SubtreeNodeSchema,depth:external_exports.number().int().min(0),get childAssetId(){return AssetIdSchema.nullable()}})),RelationshipAncestorsManyInputSchema=external_exports.strictObject({get assetIds(){return external_exports.array(AssetIdSchema).min(1).max(ASSET_IDS_MAX_PER_PAGE)},get relationshipType(){return HierarchyRelationshipTypeSchema},hierarchy:HierarchyScopeSchema,get asOf(){return AsOfSchema.optional()},maxDepth:external_exports.number().int().min(1).max(HIERARCHY_MAX_DEPTH).describe("REQUIRED \u2014 how many edges deep to walk above each asset (1\u201364). There is no default: omitting it is a validation error, not an unbounded walk.")}),RelationshipAncestorsManyOutputSchema=external_exports.array(external_exports.object({get assetId(){return AssetIdSchema},ancestors:AssetAncestorsOutputSchema})),UNDER_COUNT_IDS_MAX=50,DescendantCountsInputSchema=external_exports.strictObject({get forest(){return AssetForestSchema},get assetIds(){return external_exports.array(AssetIdSchema).min(1).max(UNDER_COUNT_IDS_MAX)},get asOf(){return AsOfSchema.optional()}}),DescendantCountsOutputSchema=external_exports.array(external_exports.object({get assetId(){return AssetIdSchema},count:external_exports.number().int().min(0)}));var AssetDescendantsInputSchema=external_exports.strictObject({get assetId(){return AssetIdSchema},get relationshipType(){return HierarchyRelationshipTypeSchema},hierarchy:HierarchyScopeSchema,get asOf(){return AsOfSchema.optional()},maxDepth:external_exports.number().int().min(1).max(HIERARCHY_MAX_DEPTH).describe("REQUIRED \u2014 how many edges deep to walk (1\u201364). There is no default: omitting it is a validation error, not an unbounded walk. Depth 1 = immediate neighbours only."),get assetTypeIds(){return external_exports.array(AssetTypeIdSchema).min(1).max(50).optional()}}),DescendantNodeSchema=external_exports.object({get assetId(){return AssetIdSchema},get assetTypeId(){return AssetTypeIdSchema},lifecycleStatus:AssetLifecycleStatusSchema,depth:external_exports.number().int().min(0),current:external_exports.boolean()}),AssetDescendantsOutputSchema=external_exports.object({root:external_exports.object({get assetId(){return AssetIdSchema},name:external_exports.string().min(1)}),nodes:external_exports.array(DescendantNodeSchema),reachedCount:external_exports.number().int().min(0).optional(),maxDepthReached:external_exports.number().int().min(0).optional()});var DESCENDANT_GEOMETRY_MAX_ITEMS=1e3,DESCENDANT_GEOMETRY_HIERARCHY_TYPES_WIRE_MAX=16,DescendantGeometryInputSchema=external_exports.strictObject({get assetId(){return AssetIdSchema},get hierarchyTypes(){return external_exports.array(HierarchyRelationshipTypeSchema).min(1).max(DESCENDANT_GEOMETRY_HIERARCHY_TYPES_WIRE_MAX).optional()},limit:external_exports.number().int().min(1).max(DESCENDANT_GEOMETRY_MAX_ITEMS).optional()}),LocatedDescendantSchema=SubtreeNodeSchema.extend({geometry:GeoJsonGeometrySchema}),DescendantGeometryOutputSchema=external_exports.object({items:external_exports.array(LocatedDescendantSchema),total:external_exports.number().int().min(0)});var CONDITIONS_MAX=10,CONDITION_VALUE_MAX=512,DISTINCT_VALUES_LIMIT_MAX=20,ConditionScalarSchema=external_exports.union([external_exports.string().max(CONDITION_VALUE_MAX),external_exports.number(),external_exports.boolean()]),ConditionFieldSchema=external_exports.string().regex(/^(asset:(name|type|category|status)|prop:[\s\S]{1,64}|ext:(\*|[\s\S]{1,64}))$/).describe("A condition field: `asset:name`, `asset:type`, `asset:category`, `asset:status`, `prop:<property code>`, `ext:<external-ID system key>` or `ext:*` (any system)."),ConditionRowSchema=external_exports.discriminatedUnion("op",[external_exports.strictObject({field:ConditionFieldSchema,op:external_exports.literal("is"),value:ConditionScalarSchema}),external_exports.strictObject({field:ConditionFieldSchema,op:external_exports.literal("isNot"),value:ConditionScalarSchema}),external_exports.strictObject({field:ConditionFieldSchema,op:external_exports.literal("contains"),value:external_exports.string().min(1).max(CONDITION_VALUE_MAX)}),external_exports.strictObject({field:ConditionFieldSchema,op:external_exports.literal("gt"),value:external_exports.number()}),external_exports.strictObject({field:ConditionFieldSchema,op:external_exports.literal("lt"),value:external_exports.number()}),external_exports.strictObject({field:ConditionFieldSchema,op:external_exports.literal("isEmpty")}),external_exports.strictObject({field:ConditionFieldSchema,op:external_exports.literal("isNotEmpty")})]),AssetConditionsSchema=external_exports.strictObject({match:external_exports.enum(["all","any"]),rows:external_exports.array(ConditionRowSchema).min(1).max(CONDITIONS_MAX)}).describe('Operator conditions, 1 to 10 rows of { field, op, value }, combined by `match` (`all` or `any`). `any` applies only among these rows: every facet, `nameContains`, `propertyFilters` and the id sets still combine with And. Fields: `asset:name`, `asset:type` (a type id), `asset:category` (a category id), `asset:status`, `prop:<code>`, `ext:<system>` or `ext:*`. Operators: `is`, `isNot`, `contains`, `gt`, `lt`, `isEmpty`, `isNotEmpty`. `is` on `asset:name` and `prop:` ignores case and coerces numbers ("42" matches 42); on `ext:`, `asset:type`, `asset:category` and `asset:status` it is exact. `isNot` is its complement and includes assets without the property. `contains` is a literal, case-insensitive substring of the value text. `gt` / `lt` compare numbers and numeric strings. Empty means absent, "" or a stored JSON null. Unlike `propertyFilters` (exact, JSON-typed `equals` / `oneOf` / `noneOf`), these rules are loose by design. A property or external-ID condition alone reads every asset and may be refused with TX_BUDGET_OVERRUN: narrow by a type or category first. A field, operator and value that do not fit is refused with INVALID_CONDITION naming the row.'),INVALID_CONDITION="INVALID_CONDITION",InvalidConditionReasonSchema=external_exports.enum(["operator-not-allowed","value-not-allowed","invalid-status","invalid-text","prefix-required","values-not-allowed"]),InvalidConditionDataSchema=external_exports.object({code:external_exports.literal(INVALID_CONDITION),reason:InvalidConditionReasonSchema,index:external_exports.number().int().min(0).optional(),field:external_exports.string().optional(),op:external_exports.string().optional()});var PropertyCodeSchema=external_exports.string().min(1).max(64),PropertyScalarSchema=external_exports.union([external_exports.string(),external_exports.number(),external_exports.boolean()]),PropertyValuesSchema=external_exports.record(PropertyCodeSchema,PropertyScalarSchema),PROPERTY_VALUES_WIRE_MAX=1e3,PropertyValuesInputSchema=wireBoundedRecord(PropertyCodeSchema,PropertyScalarSchema,PROPERTY_VALUES_WIRE_MAX),PROPERTY_FILTER_MAX=10,PROPERTY_FILTER_VALUES_MAX=20,PROPERTY_FILTER_VALUE_TEXT_MAX=CONDITION_VALUE_MAX,PropertyFilterListValueSchema=external_exports.union([external_exports.string().max(PROPERTY_FILTER_VALUE_TEXT_MAX).regex(/^[^\u0000\ud800-\udfff]*$/u,"a value cannot hold a NUL character or an unpaired surrogate"),external_exports.number(),external_exports.boolean()]),PropertyFilterValuesSchema=external_exports.array(PropertyFilterListValueSchema).min(1).max(PROPERTY_FILTER_VALUES_MAX),AssetPropertyEqualsSchema=external_exports.strictObject({code:PropertyCodeSchema,equals:PropertyScalarSchema}),AssetPropertyOneOfSchema=external_exports.strictObject({code:PropertyCodeSchema,oneOf:PropertyFilterValuesSchema}),AssetPropertyNoneOfSchema=external_exports.strictObject({code:PropertyCodeSchema,noneOf:PropertyFilterValuesSchema}),AssetPropertyPredicateSchema=external_exports.union([AssetPropertyEqualsSchema,AssetPropertyOneOfSchema,AssetPropertyNoneOfSchema]),AssetPropertyFilterSchema=external_exports.array(AssetPropertyPredicateSchema).min(1).max(PROPERTY_FILTER_MAX).describe(`Narrow to assets whose static properties hold these values \u2014 one entry per property \`code\`, ANDed. Each entry is exactly one of \`{code, equals}\`, \`{code, oneOf: [..]}\` (any of the values) or \`{code, noneOf: [..]}\` (none of them; an asset without the property is kept). A list holds 1 to ${String(PROPERTY_FILTER_VALUES_MAX)} values; an empty list is refused. Equality is JSON-typed and exact: the number 42 does NOT match a stored "42", and "Sold" does not match "SOLD". For \`equals\` and \`oneOf\`, a code no asset carries matches nothing; for \`noneOf\` it keeps every asset. Resolved against the version effective at \`asOf\` when that is supplied, so a past-instant page and its \`total\` describe the same population. This is the EXACT form, kept as an alias: the looser operator filter is \`conditions\`, whose \`is\` ignores case and coerces numbers.`),AssetPropertyEqualsFilterSchema=external_exports.array(AssetPropertyEqualsSchema).min(1).max(PROPERTY_FILTER_MAX).describe('Narrow to assets whose static properties hold exactly these values \u2014 one `{code, equals}` entry per property, ANDed, JSON-typed (42 does NOT match a stored "42"). A bulk write takes `equals` only; `oneOf` / `noneOf` are refused here.');var DUPLICATE_ASSETS_PAGE_SIZE_MAX=100,DUPLICATE_ASSETS_SEARCH_MAX=200,DUPLICATE_ASSETS_GROUP_MEMBERS_MAX=50,DUPLICATE_ASSETS_MIN_MEMBERS_DEFAULT=2,DuplicateEvidenceKindSchema=external_exports.enum(["SAME_SYSTEM","DIFFERENT_SYSTEMS","TOO_LITTLE_EVIDENCE"]),DuplicateAssetsSortSchema=external_exports.enum(["MEMBERS_DESC","NAME","TYPE"]),DuplicateMatchedBySchema=external_exports.discriminatedUnion("kind",[external_exports.object({kind:external_exports.literal("NAME")}),external_exports.object({kind:external_exports.literal("PROPERTY"),code:PropertyCodeSchema})]),MatchPropertyCodeSchema=PropertyCodeSchema.regex(/^[^\u0000\ud800-\udfff]*$/u,"a property code cannot hold a NUL character or an unpaired surrogate"),DuplicateAssetsInputSchema=external_exports.strictObject({search:external_exports.string().trim().min(1).max(DUPLICATE_ASSETS_SEARCH_MAX).optional(),assetType:AssetTypeIdSchema.optional(),lifecycle:AssetLifecycleStatusSchema.optional(),externalIdSystem:ExternalIdSystemSchema.optional(),minMembers:external_exports.number().int().min(DUPLICATE_ASSETS_MIN_MEMBERS_DEFAULT).optional(),evidence:DuplicateEvidenceKindSchema.optional(),sort:DuplicateAssetsSortSchema.optional(),page:external_exports.number().int().min(1).optional(),pageSize:external_exports.number().int().min(1).max(DUPLICATE_ASSETS_PAGE_SIZE_MAX).optional(),matchProperty:MatchPropertyCodeSchema.optional()}),DuplicateAssetMemberSchema=SubtreeNodeSchema.extend({externalIdSystems:external_exports.array(ExternalIdSystemSchema),matchedValue:external_exports.string().optional()}),DuplicateAssetGroupSchema=external_exports.object({nameKey:external_exports.string(),name:external_exports.string().min(1),matchedBy:DuplicateMatchedBySchema,sharedValue:external_exports.string().min(1),evidence:DuplicateEvidenceKindSchema,memberCount:external_exports.number().int().min(2),members:external_exports.array(DuplicateAssetMemberSchema).min(2).max(DUPLICATE_ASSETS_GROUP_MEMBERS_MAX)}).refine(group=>group.members.length===Math.min(group.memberCount,DUPLICATE_ASSETS_GROUP_MEMBERS_MAX),{message:"members must be the group\u2019s first members up to the cap",path:["members"]}),DuplicateAssetsReportSchema=external_exports.object({total:external_exports.number().int().min(0),groups:external_exports.array(DuplicateAssetGroupSchema)});var EdgeWriteDeadlockDataSchema=external_exports.object({reason:external_exports.literal("deadlock")});var DATED_STATUS_CODE="@status";var TemplateDefinitionIssueSchema=external_exports.strictObject({code:external_exports.string().min(1),message:external_exports.string().min(1)});var RESERVED_STATUS_CODE_MESSAGE=`property code "${DATED_STATUS_CODE}" is reserved for the asset's status`;var RECEIVED_VALUE_MAX_LENGTH=120,PropertyValueIssueSchema=external_exports.strictObject({code:external_exports.string().min(1),message:external_exports.string().min(1),expected:external_exports.string().min(1).optional(),received:external_exports.string().min(1).optional(),receivedValue:external_exports.string().max(RECEIVED_VALUE_MAX_LENGTH+1).optional()});var DatedLinkReasonSchema=external_exports.enum(["already-holds","kept-recorded","multiple-parents"]),DatedLinkEndSchema=external_exports.enum(["until","next-change","current-link","open"]),InstantSchema=external_exports.iso.datetime({precision:6}),DatedLinkStretchSchema=external_exports.strictObject({from:InstantSchema,until:InstantSchema.nullable(),parentAssetIds:external_exports.array(AssetIdSchema)}),DatedLinkKeptSchema=DatedLinkStretchSchema.extend({reason:DatedLinkReasonSchema}),DatedLinkReplacedSchema=external_exports.strictObject({relationshipId:external_exports.uuid(),parentAssetId:AssetIdSchema,from:InstantSchema,until:InstantSchema}),DatedLinkResultSchema=external_exports.strictObject({verdict:external_exports.enum(["written","unchanged"]),reason:DatedLinkReasonSchema.optional(),from:InstantSchema,until:InstantSchema.nullable(),endsAt:DatedLinkEndSchema,written:external_exports.array(DatedLinkStretchSchema),replaced:external_exports.array(DatedLinkReplacedSchema),kept:external_exports.array(DatedLinkKeptSchema),startMoved:external_exports.boolean().optional()}),LIST_PARENT_LINKS_PAGE_MAX=500;var ListParentLinksInputSchema=external_exports.strictObject({assetId:AssetIdSchema,hierarchy:HierarchyScopeSchema,limit:external_exports.number().int().min(1).max(LIST_PARENT_LINKS_PAGE_MAX).optional(),cursor:external_exports.string().min(1).max(512).optional()}),PARENT_LINK_REPLACED_MAX=20,ParentLinkReplacedSchema=external_exports.strictObject({parentAssetId:AssetIdSchema,from:external_exports.iso.datetime(),until:external_exports.iso.datetime()}),ParentLinkRowSchema=external_exports.strictObject({id:external_exports.uuid(),relationshipId:external_exports.uuid(),relationshipType:HierarchyRelationshipTypeSchema,parentAssetId:AssetIdSchema,effectiveFrom:external_exports.iso.datetime(),effectiveTo:external_exports.iso.datetime().nullable(),recordedAt:external_exports.iso.datetime().nullable(),recordId:external_exports.uuid().nullable(),statedBy:external_exports.strictObject({principal:external_exports.string(),onBehalfOf:external_exports.string().optional()}).nullable(),statedAt:external_exports.iso.datetime().nullable(),replaced:external_exports.array(ParentLinkReplacedSchema).max(PARENT_LINK_REPLACED_MAX),replacedTotal:external_exports.number().int().min(0)}),ListParentLinksOutputSchema=external_exports.strictObject({items:external_exports.array(ParentLinkRowSchema),nextCursor:external_exports.string().nullable()}),DatedLinkDryRunSchema=external_exports.strictObject({dryRun:external_exports.literal(!0),dated:DatedLinkResultSchema}),DATED_CREATE_FIELDS={replaceRecorded:external_exports.boolean().optional(),dryRun:external_exports.boolean().optional()},previewsADatedLink=input2=>input2.dryRun!==!0||input2.effectiveFrom!==void 0&&(input2.relationshipType===void 0||HierarchyRelationshipTypeSchema.safeParse(input2.relationshipType).success),DATED_DRY_RUN_ISSUE={message:"A dry run needs an effectiveFrom and a hierarchy relationship type.",path:["dryRun"]};var DATED_VALUES_MAX_ITEMS=1e3,DatedValueCodeSchema=external_exports.string().min(1).max(64),DatedValueScalarSchema=external_exports.union([external_exports.string(),external_exports.number(),external_exports.boolean()]).nullable(),DatedInstantSchema=external_exports.iso.datetime({precision:3}).describe("UTC instant, Z-only, millisecond precision. Never in the future."),DatedValueItemSchema=external_exports.strictObject({assetId:AssetIdSchema,code:DatedValueCodeSchema,value:DatedValueScalarSchema,from:DatedInstantSchema,until:external_exports.union([DatedInstantSchema,external_exports.literal("today")]).optional()}),SetDatedValuesInputSchema=external_exports.strictObject({items:external_exports.array(DatedValueItemSchema).min(1).max(DATED_VALUES_MAX_ITEMS),idempotencyKey:IdempotencyKeySchema,dryRun:external_exports.boolean().optional(),replaceRecorded:external_exports.boolean().optional()});var DatedValueVerdictSchema=external_exports.enum(["written","unchanged","refused"]),DatedValueReasonSchema=external_exports.enum(["already-holds","outside-asset-life","kept-recorded","future-date","invalid-range","unknown-property","invalid-value","asset-fails-template","unknown-asset","lifecycle-transition","lifecycle-gated-transition"]),DatedValueEndSchema=external_exports.enum(["next-change","deletion","today","until"]),DatedValueReplacedSchema=external_exports.strictObject({value:DatedValueScalarSchema,from:external_exports.iso.datetime(),until:external_exports.iso.datetime(),covered:external_exports.boolean()}),DatedStatusMoveSchema=external_exports.strictObject({from:AssetLifecycleStatusSchema,to:AssetLifecycleStatusSchema,at:external_exports.iso.datetime()}),DatedValueItemResultSchema=external_exports.strictObject({assetId:AssetIdSchema,code:DatedValueCodeSchema,verdict:DatedValueVerdictSchema,reason:DatedValueReasonSchema.optional(),from:external_exports.iso.datetime().optional(),until:external_exports.iso.datetime().optional(),endsAt:DatedValueEndSchema.optional(),startMoved:external_exports.boolean().optional(),replaced:external_exports.array(DatedValueReplacedSchema),kept:external_exports.array(DatedValueReplacedSchema),todayChanged:external_exports.boolean(),issues:external_exports.array(PropertyValueIssueSchema).optional(),move:DatedStatusMoveSchema.optional()}),SetDatedValuesOutputSchema=external_exports.strictObject({dryRun:external_exports.boolean(),results:external_exports.array(DatedValueItemResultSchema)}),AppliedDatedValueIdsSchema=external_exports.record(DatedValueCodeSchema,external_exports.uuid()),LIST_DATED_VALUES_PAGE_MAX=500;var ListDatedValuesInputSchema=external_exports.strictObject({assetId:AssetIdSchema,limit:external_exports.number().int().min(1).max(LIST_DATED_VALUES_PAGE_MAX).optional(),cursor:external_exports.string().min(1).max(512).optional()}),DatedValueStatedBySchema=external_exports.strictObject({principal:external_exports.string(),onBehalfOf:external_exports.string().optional()}),DatedValueRowSchema=external_exports.strictObject({id:external_exports.uuid(),code:DatedValueCodeSchema,value:DatedValueScalarSchema,replacedValue:DatedValueScalarSchema,replacedCovered:external_exports.boolean(),effectiveFrom:external_exports.iso.datetime(),effectiveTo:external_exports.iso.datetime(),recordedAt:external_exports.iso.datetime(),recordedTo:external_exports.iso.datetime().nullable(),recordId:external_exports.uuid(),statedBy:DatedValueStatedBySchema.nullable(),statedAt:external_exports.iso.datetime().nullable()}),ListDatedValuesOutputSchema=external_exports.strictObject({items:external_exports.array(DatedValueRowSchema),nextCursor:external_exports.string().nullable()}),DATED_VALUE_CHANGES_MAX_WINDOWS=200,DATED_VALUE_CHANGES_MAX_CODES=200,DATED_VALUE_CHANGES_MAX_ASSET_IDS=2e5,DATED_VALUE_CHANGES_MAX_TREES=200,DATED_VALUE_CHANGES_PAGE_MAX=1e3;var DatedValueChangeWindowSchema=external_exports.strictObject({from:AsOfSchema,to:AsOfSchema,knownAt:AsOfSchema}),ListDatedValueChangesInputSchema=external_exports.strictObject({codes:external_exports.array(DatedValueCodeSchema).min(1).max(DATED_VALUE_CHANGES_MAX_CODES),windows:external_exports.array(DatedValueChangeWindowSchema).min(1).max(DATED_VALUE_CHANGES_MAX_WINDOWS),assetIds:external_exports.array(AssetIdSchema).min(1).max(DATED_VALUE_CHANGES_MAX_ASSET_IDS).optional(),trees:external_exports.array(HierarchyScopeSchema).min(1).max(DATED_VALUE_CHANGES_MAX_TREES).optional(),limit:external_exports.number().int().min(1).max(DATED_VALUE_CHANGES_PAGE_MAX).optional(),cursor:external_exports.string().min(1).max(512).optional()}),DatedValueChangeSchema=external_exports.strictObject({kind:external_exports.literal("dated-value").default("dated-value"),id:external_exports.uuid(),assetId:AssetIdSchema,code:DatedValueCodeSchema,value:DatedValueScalarSchema,effectiveFrom:external_exports.iso.datetime(),effectiveTo:external_exports.iso.datetime(),recordedAt:external_exports.iso.datetime(),recordedTo:external_exports.iso.datetime().nullable(),windows:external_exports.array(external_exports.number().int().min(0)).min(1)}),DatedLinkChangeSchema=external_exports.strictObject({kind:external_exports.literal("link"),change:external_exports.enum(["recorded","retired","closed"]),id:external_exports.uuid(),relationshipId:external_exports.uuid(),relationshipType:external_exports.string(),childAssetId:AssetIdSchema,parentAssetId:AssetIdSchema,hierarchyId:external_exports.uuid().nullable(),effectiveFrom:external_exports.iso.datetime(),effectiveTo:external_exports.iso.datetime().nullable(),windows:external_exports.array(external_exports.number().int().min(0)).min(1)}),VersionChangeSchema=external_exports.strictObject({kind:external_exports.literal("version"),id:external_exports.uuid(),assetId:AssetIdSchema,codes:external_exports.array(DatedValueCodeSchema).min(1),effectiveFrom:external_exports.iso.datetime(),effectiveTo:external_exports.iso.datetime().nullable(),writtenAt:external_exports.iso.datetime(),windows:external_exports.array(external_exports.number().int().min(0)).min(1)}),DatedValueChangesItemSchema=external_exports.discriminatedUnion("kind",[DatedValueChangeSchema,VersionChangeSchema,DatedLinkChangeSchema]),ListDatedValueChangesOutputSchema=external_exports.strictObject({items:external_exports.array(DatedValueChangesItemSchema),nextCursor:external_exports.string().nullable()});var RevertDatedValuesInputSchema=external_exports.strictObject({importId:external_exports.uuid(),idempotencyKey:IdempotencyKeySchema}),RevertSkippedSchema=external_exports.strictObject({assetId:AssetIdSchema,code:DatedValueCodeSchema,from:external_exports.iso.datetime(),until:external_exports.iso.datetime()}),RevertDatedValuesOutputSchema=external_exports.strictObject({importId:external_exports.uuid(),retired:external_exports.number().int().nonnegative(),restored:external_exports.number().int().nonnegative(),skipped:external_exports.number().int().nonnegative(),skippedSample:external_exports.array(RevertSkippedSchema).max(20)});var ProjectedEffectiveFromSchema=external_exports.discriminatedUnion("from",[external_exports.object({from:external_exports.literal("column"),column:external_exports.string().min(1)}),external_exports.object({from:external_exports.literal("constant"),value:InitialEffectiveFromSchema}),external_exports.object({from:external_exports.literal("asset-start")})]).describe("WHEN each row takes effect. ABSENT: at the moment of the write. A `constant` applies one instant to every row (UTC, Z-only, millisecond precision). A `column` is read per row and must hold an ISO-8601 UTC calendar date `YYYY-MM-DD` (midnight UTC) or a full instant `YYYY-MM-DDTHH:MM:SS[.sss]Z`; anything else, a blank cell, a future date or a date that does not exist fails its row `template-validation`. `asset-start` dates each matched row from its asset's start (its first version's date) and a created asset from the import. A CREATED asset first exists at this instant, and so do its placement edges. A MATCHED row dated after the asset's current version is an ordinary dated update. A matched row dated at or before it is BACK-DATED: its property values are set over `[its date, the next row for that asset with a value for that column, or now)`, filling stretches with no value, writing nothing where the value already holds, and keeping a different recorded value unless `replaceRecorded` or `replaceColumns` says otherwise; a blank cell states nothing, and only the values a row writes are validated. Its name, status and location changes apply today. In a dated mode a file may carry several contiguous rows for one asset (its history), processed oldest first; a later non-contiguous row or a second row on the same date fails `identity-conflict`, and a history over the row bound fails `history-too-long`."),ProjectedReplaceFields={replaceRecorded:external_exports.boolean().optional().describe("Back-dated rows only: `true` replaces a different recorded value over the row's range with the file's value (\"Use the file's values\"). Absent or `false`: recorded values are kept and counted."),replaceColumns:external_exports.array(external_exports.string().min(1)).max(1e3).optional().describe("Back-dated rows only: the dataset columns whose different recorded values are replaced, the per-column form of `replaceRecorded`.")},RefusedValueSchema=external_exports.object({code:external_exports.string().min(1),message:external_exports.string().min(1)}),BackDatedRowFields={backDated:external_exports.literal(!0).optional(),valuesKept:external_exports.number().int().positive().optional(),refusedValues:external_exports.array(RefusedValueSchema).optional(),appliedToday:external_exports.literal(!0).optional()},DatedImportCountFields={backDated:external_exports.number().int().positive().optional(),valuesDated:external_exports.number().int().positive().optional(),valuesKept:external_exports.number().int().positive().optional(),valuesRefused:external_exports.number().int().positive().optional(),statusesDated:external_exports.number().int().positive().optional(),statusesKept:external_exports.number().int().positive().optional(),statusesRefused:external_exports.number().int().positive().optional(),parentsDated:external_exports.number().int().positive().optional(),parentsKept:external_exports.number().int().positive().optional(),parentsRefused:external_exports.number().int().positive().optional(),appliedToday:external_exports.number().int().positive().optional()},DatedImportPreviewFields={willBackDate:external_exports.number().int().nonnegative().optional(),matchedColumnDifferences:external_exports.number().int().nonnegative().optional()};var AssetDistinctValuesInputSchema=external_exports.strictObject({field:ConditionFieldSchema,get filter(){return AssetListFilterSchema.describe("The rest of the list filter the suggestions are over, verbatim (asOf included).")},prefix:external_exports.string().min(1).max(CONDITION_VALUE_MAX).optional().describe('Only values of a group where ANY member spelling starts with this, ignoring case, taken literally (`%`, `_` and `\\` match themselves). The returned `value` is the most common spelling of that group, so it may not start with the prefix itself (members `42` and `"42.0"`, prefix `42.`, returns `42`). REQUIRED for `asset:name` and `ext:` fields, which hold about one value per asset.'),limit:external_exports.number().int().min(1).max(DISTINCT_VALUES_LIMIT_MAX).optional().describe("How many values to return, 1 to 20; defaults to 20. There is no next page."),values:PropertyFilterValuesSchema.optional().describe('Count exactly these values instead of suggesting: JSON-typed and case-exact, the `propertyFilters` equality (42 is not "42", "Sold" is not "SOLD"). A `prop:` field only, with no `prefix`; refused INVALID_CONDITION `values-not-allowed` otherwise. Each listed value some selected asset holds comes back once, as listed, in list order; a value no selected asset holds is absent. `limit` does not apply. With a `search` that reached one of its caps, each count is a floor and says so (`countAtLeast`, `capReached`).')}),AssetDistinctValueSchema=external_exports.strictObject({value:ConditionScalarSchema,count:external_exports.number().int().min(1),countAtLeast:external_exports.literal(!0).optional(),capReached:SearchCapReachedSchema.optional()}),AssetDistinctValuesOutputSchema=external_exports.array(AssetDistinctValueSchema);var QUALITY_SCAN_TIMEOUT_REASON="timeout",QUALITY_SCAN_BUSY_REASON="busy",QualityScanRefusalDataSchema=external_exports.object({reason:external_exports.enum([QUALITY_SCAN_TIMEOUT_REASON,QUALITY_SCAN_BUSY_REASON])}),UnparentedScopeSchema=external_exports.strictObject({by:external_exports.literal("hierarchy"),hierarchyId:HierarchyIdSchema,relationshipType:HierarchyRelationshipTypeSchema});var ReadTxBudgetOverrunDataSchema=external_exports.object({budgetMs:external_exports.number().int().positive()}),LONG_READ_BUSY_REASON="long-read-busy",LongReadBusyDataSchema=external_exports.object({reason:external_exports.literal(LONG_READ_BUSY_REASON)}),RUNNER_ONLY_REASON="runner-only",NO_LONG_READ_REASON="no-long-read",RunnerOnlyDataSchema=external_exports.object({reason:external_exports.literal(RUNNER_ONLY_REASON)}),NoLongReadDataSchema=external_exports.object({reason:external_exports.literal(NO_LONG_READ_REASON)});var OBSERVED_PROPERTY_CATALOG_ENTRIES=[{observedProperty:"pressure",uom:"kPa"},{observedProperty:"temperature",uom:"degC"},{observedProperty:"flow_rate",uom:"m3/h"}];var ReturnResultsSchema=external_exports.enum(["all","failures","summary"]).describe("How much of the per-row `results` array to return on THIS call. `summary` (the counts object) rides on the wire in EVERY mode \u2014 this controls `results` alone. `all` (default) returns every row; `failures` returns only rows that did not succeed; `summary` returns no rows at all. Response-shaping only: the persisted governance Record keeps the FULL results array regardless, so a later replay of the same idempotencyKey can still return every row.");var MoveManyItemSchema=external_exports.strictObject({get assetId(){return AssetIdSchema},get fromParentAssetId(){return AssetIdSchema.nullable()}}),MOVE_MANY_MAX_ITEMS=100,MoveManyInputSchema=external_exports.strictObject({get relationshipType(){return HierarchyRelationshipTypeSchema},get targetAssetId(){return AssetIdSchema},items:external_exports.array(MoveManyItemSchema).min(1).max(MOVE_MANY_MAX_ITEMS),hierarchy:HierarchyScopeSchema.optional(),idempotencyKey:IdempotencyKeySchema,returnResults:ReturnResultsSchema.optional()}),MoveManyRefusalReasonSchema=external_exports.enum(["self-parent","asset-not-found","already-under-target","edge-changed","would-cycle"]),MoveManyItemResultSchema=external_exports.discriminatedUnion("status",[external_exports.strictObject({get assetId(){return AssetIdSchema},status:external_exports.literal("moved"),get relationshipId(){return AssetRelationshipIdSchema}}),external_exports.strictObject({get assetId(){return AssetIdSchema},status:external_exports.literal("attached"),get relationshipId(){return AssetRelationshipIdSchema}}),external_exports.strictObject({get assetId(){return AssetIdSchema},status:external_exports.literal("refused"),reason:MoveManyRefusalReasonSchema})]),MoveManyOutputSchema=external_exports.object({summary:external_exports.object({requested:external_exports.number().int().min(0),moved:external_exports.number().int().min(0),attached:external_exports.number().int().min(0),refused:external_exports.number().int().min(0)}),results:external_exports.array(MoveManyItemResultSchema)}),MoveManyResponseSchema=MoveManyOutputSchema.extend({accessUpdate:AccessUpdateStateSchema});var AssetSortFieldSchema=external_exports.enum(["name","lifecycleStatus","effectiveFrom"]),SortDirectionSchema=external_exports.enum(["asc","desc"]),AssetOrderBySchema=external_exports.strictObject({field:AssetSortFieldSchema,direction:SortDirectionSchema});var ASSETS_LIST_ROW_SOURCE_ID="assets.list",LIFECYCLE_OPTION_LABEL={PRE_PRODUCTION:"Pre-production",ACTIVE:"Active",INACTIVE:"Inactive",SHUT_IN:"Shut in",DECOMMISSIONED:"Decommissioned"},assetsListRowSource={id:ASSETS_LIST_ROW_SOURCE_ID,label:"Assets",description:"Every current asset in the tenant, with its category, type, lifecycle status and last update.",rowKind:{domain:"assets",type:"asset"},pageScope:{facets:[ASSETS_SUBTREE_FILTER_KIND,ASSETS_TYPE_FILTER_KIND]},columns:[{key:"name",label:"Name",type:"text",sortable:!0,shownByDefault:!0},{key:"category",label:"Category",type:"text",sortable:!1,shownByDefault:!0},{key:"type",label:"Type",type:"text",sortable:!1,shownByDefault:!0},{key:"lifecycle",label:"Lifecycle",type:"enum",sortable:!0,shownByDefault:!0},{key:"updated",label:"Last updated",type:"datetime",sortable:!0,shownByDefault:!0}],filters:[{key:"name",label:"Name",valueType:"text",operators:["contains"]},{key:"lifecycleStatus",label:"Lifecycle",valueType:"enum",operators:["eq","in"],options:AssetLifecycleStatusSchema.options.map(status=>({value:status,label:LIFECYCLE_OPTION_LABEL[status]}))},{key:"categoryId",label:"Category",valueType:"text",operators:["eq","in"]},{key:"assetTypeId",label:"Type",valueType:"text",operators:["eq","in"]},{key:"subtree",label:"Under asset (<tree>~<relationshipType>~<assetId>)",valueType:"text",operators:["eq"]}],defaultSort:{field:"name",direction:"asc"},limit:{default:20,max:200}};var ASSET_EXTERNAL_ID_DATASET_NAME="asset_external_id",ASSET_CURRENT_DATASET_NAME="asset_current",ASSET_CURRENT_PARENT_DATASET_NAME="asset_current_parent",ASSET_HIERARCHY_DATASET_NAME="asset_hierarchy";var ASSET_DIRECTORY_COLUMN_TYPES={[ASSET_EXTERNAL_ID_DATASET_NAME]:{asset_id:"VARCHAR",system:"VARCHAR",external_id:"VARCHAR",valid_from:"TIMESTAMPTZ",valid_to:"TIMESTAMPTZ",is_current:"BOOLEAN",as_of:"TIMESTAMPTZ"},[ASSET_CURRENT_DATASET_NAME]:{asset_id:"VARCHAR",asset_code:"VARCHAR",kind:"VARCHAR",name:"VARCHAR",parent_id:"VARCHAR",as_of:"TIMESTAMPTZ",location_wkt:"VARCHAR",location_type:"VARCHAR",latitude:"DOUBLE",longitude:"DOUBLE",location_from:"VARCHAR",kind_id:"VARCHAR"},[ASSET_CURRENT_PARENT_DATASET_NAME]:{asset_id:"VARCHAR",hierarchy_id:"VARCHAR",parent_id:"VARCHAR",as_of:"TIMESTAMPTZ",relationship_type:"VARCHAR"},[ASSET_HIERARCHY_DATASET_NAME]:{hierarchy_id:"VARCHAR",name:"VARCHAR",created_at:"TIMESTAMPTZ",as_of:"TIMESTAMPTZ"}},ASSET_DIRECTORY_COLUMN_ENTITIES={[ASSET_EXTERNAL_ID_DATASET_NAME]:{asset_id:ASSET_ENTITY_HINT},[ASSET_CURRENT_DATASET_NAME]:{asset_id:ASSET_ENTITY_HINT,parent_id:ASSET_ENTITY_HINT,location_from:ASSET_ENTITY_HINT,kind_id:ASSET_TYPE_ENTITY_HINT},[ASSET_CURRENT_PARENT_DATASET_NAME]:{asset_id:ASSET_ENTITY_HINT,parent_id:ASSET_ENTITY_HINT},[ASSET_HIERARCHY_DATASET_NAME]:{}};var ASSET_DIRECTORY_TYPED_COLUMNS={[ASSET_EXTERNAL_ID_DATASET_NAME]:["asset_id","system","external_id"],[ASSET_CURRENT_DATASET_NAME]:["asset_id"],[ASSET_CURRENT_PARENT_DATASET_NAME]:["asset_id"],[ASSET_HIERARCHY_DATASET_NAME]:[]};var DIRECTORY_SCHEDULE_MIN_INTERVAL_SECONDS=3600,DirectoryScheduleSchema=external_exports.object({intervalSeconds:external_exports.number().int().min(DIRECTORY_SCHEDULE_MIN_INTERVAL_SECONDS).nullable()}),DirectoryScheduleReadSchema=DirectoryScheduleSchema.nullable(),SetDirectoryScheduleInputSchema=external_exports.strictObject({intervalSeconds:external_exports.number().int().min(DIRECTORY_SCHEDULE_MIN_INTERVAL_SECONDS).nullable(),idempotencyKey:IdempotencyKeySchema});var DatasetColumnTypeSchema=external_exports.enum(["STRING","NUMBER","BOOLEAN"]),DatasetCellValueSchema=external_exports.union([external_exports.string(),external_exports.number(),external_exports.boolean(),external_exports.null()]);var COLUMN_MAP_WIRE_MAX=8192,SOURCE_TRANSFORMATION_RUN_INPUTS_MAX=128,SOURCE_TRANSFORMATION_RUN_PARAMS_MAX=200,SOURCE_TRANSFORMATION_OUTPUTS_MAX=64,SOURCE_TRANSFORMATION_OUTPUT_COLUMN_TYPES_MAX=COLUMN_MAP_WIRE_MAX,QUALITY_CHECKS_TABLES_WIRE_MAX=128,DESCRIBE_EXPECTED_KEYWORDS_MAX=1e3,WIRE_BOUNDED_RECORDS3=[];function boundedRecord2(key,value2,max2,noun,published4={}){let bounded4=external_exports.record(key,value2).refine(candidate=>Object.keys(candidate).length<=max2,{message:`name at most ${String(max2)} ${noun}`}),schema=published4.description===void 0?bounded4:bounded4.describe(published4.description);return WIRE_BOUNDED_RECORDS3.push({schema,max:max2,...published4.min===void 0?{}:{min:published4.min}}),schema}var DatasetColumnEntitySchema=external_exports.object({entity:external_exports.object({domain:external_exports.string().min(1).max(64),type:external_exports.string().min(1).max(64)}),pickerResource:external_exports.string().min(1).max(64).optional()}).describe('What the values of this column are the ids of, e.g. `{"entity": {"domain": "assets", "type": "asset"}, "pickerResource": "assets"}` for a column of asset ids.'),ASSET_COLUMN_ENTITY={entity:{domain:"assets",type:"asset"}},DatasetColumnEntitiesSchema=external_exports.record(external_exports.string().min(1),DatasetColumnEntitySchema),DatasetColumnEntitiesPatchSchema=boundedRecord2(external_exports.string().min(1),DatasetColumnEntitySchema.nullable(),COLUMN_MAP_WIRE_MAX,"column tags",{description:"Tag or untag columns, by column name: a tag sets it, `null` removes it, and columns not named keep theirs. Only a kind of thing Studio can show by name is accepted."}),DatasetColumnEntitiesWireSchema=boundedRecord2(external_exports.string().min(1),DatasetColumnEntitySchema,COLUMN_MAP_WIRE_MAX,"column tags"),COLUMN_ENTITIES_DESCRIPTION='Tag columns with what their values are the ids of, by column name (e.g. `{"site_id": {"entity": {"domain": "assets", "type": "asset"}}}`). The tag belongs to the dataset, so later versions keep it: a later land that omits this keeps every tag, and one that sends it sets the named columns and leaves the rest. A name that is not a column of the landed data is refused.',columnEntitiesWireFacet={columnEntities:DatasetColumnEntitiesWireSchema.optional().describe(COLUMN_ENTITIES_DESCRIPTION)},columnEntitiesFacet={columnEntities:DatasetColumnEntitiesSchema.optional().describe(COLUMN_ENTITIES_DESCRIPTION)};var DatasetColumnSchema2=external_exports.object({name:external_exports.string().min(1),type:DatasetColumnTypeSchema,refersTo:DatasetColumnEntitySchema.optional(),wholeNumbers:external_exports.literal(!0).optional()}),DatasetRowSchema=external_exports.record(external_exports.string(),DatasetCellValueSchema);var DATASET_LABEL_MAX_LENGTH=200,NO_CONTROL_CHARACTERS=/^[^\p{Cc}]*$/u,SHOWS_SOMETHING=/[^\s\p{Cf}\u115F\u1160\u2800\u3164\uFFA0]/u,DatasetLabelSchema=external_exports.string().trim().min(1).max(DATASET_LABEL_MAX_LENGTH).regex(NO_CONTROL_CHARACTERS,{message:"A label cannot hold control characters."}).regex(SHOWS_SOMETHING,{message:"A label needs at least one character that shows."}).describe("The readable name shown for the dataset. It never changes how the dataset is found."),labelFacet={label:DatasetLabelSchema.optional().describe('The readable name to show for this dataset, e.g. "Results \xB7 GHG \xB7 2025 \xB7 Totals". Set only when the dataset has no label yet, so a label a person chose is never overwritten. The dataset is still found by `name`.')};var datasetReadabilityFields={label:external_exports.string().min(1).optional(),category:external_exports.string().min(1).optional(),dataOwner:external_exports.string().min(1).optional()};var DATASET_ENTITY_HINT={entity:{domain:"datasets",type:"dataset"},pickerResource:"datasets",pinsTo:{path:"versionId",picker:"dataset-version"}},DatasetIdSchema=external_exports.string().min(1).brand().meta(DATASET_ENTITY_HINT),DatasetVersionIdSchema=external_exports.string().min(1).brand(),DatasetRefSchema=external_exports.object({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema.optional()}).describe("How every consumer addresses a dataset. `versionId` absent = whatever load is current; present = pin that exact load in single-version reads (`versionStatus`/`read`/`getLiveDefinition`), which is what makes a read reproducible; the `versions` history read ignores `versionId` and lists every load. A consumer wanting the latest PROMOTED load computes it from `versions`' `promotedAt`. PROMOTE-BEFORE-CONSUME gates governed CONSUMPTION, not reading: `datasets.read` and composition validation resolve an unpromoted version by design, so a successful read proves nothing about promotion. What refuses one is a governed consumer that turns dataset rows into domain state \u2014 `assets.composition.createMany` and the source-transformation inputs. The pipeline is land \u2192 promote \u2192 consume. Check a version's state with `datasets.versionStatus`; resolve a human name to a ref with `datasets.resolveName`.");var DATASET_REPLACED_CODE="DATASET_REPLACED";var RUN_CONNECTED_SYNCHRONOUS_UNSUPPORTED_CODE="RUN_CONNECTED_SYNCHRONOUS_UNSUPPORTED",DatasetReplacedBySchema=external_exports.object({get datasetId(){return DatasetIdSchema},name:external_exports.string().min(1),label:external_exports.string().min(1).optional()});var FORGE_DATASET_SLUG_PATTERN=/^[a-z0-9]+(?:-[a-z0-9]+)*(?:\/[a-z0-9]+(?:-[a-z0-9]+)*)*$/,SDP_CATALOG_SLUG_PATTERN=/^[a-z][a-z0-9_-]{0,62}[a-z0-9]$/,datasetSlugArm=pattern=>external_exports.string().min(1).max(200).regex(pattern),DatasetSlugSchema=external_exports.union([datasetSlugArm(FORGE_DATASET_SLUG_PATTERN),datasetSlugArm(SDP_CATALOG_SLUG_PATTERN)]).brand();var VERSION_PRODUCER_STATES=["failed","in-flight","abandoned"],DatasetVersionProducerSchema=external_exports.object({kind:external_exports.literal("corrections-apply"),applyRecordId:external_exports.string().min(1),state:external_exports.enum(VERSION_PRODUCER_STATES)});var ANALYTICS_MAX_PROFILE_COLUMNS=50;var ANALYTICS_MAX_TOP_VALUES=100;var ANALYTICS_MAX_HISTOGRAM_BUCKETS=100;var ANALYTICS_MAX_GROUP_LIMIT=1e3;var ANALYTICS_CURSOR_MAX_LENGTH=16384,ANALYTICS_MAX_SERIES=20;var DatasetProfileInputSchema=DatasetRefSchema.extend({columns:external_exports.array(external_exports.string().min(1)).min(1).max(ANALYTICS_MAX_PROFILE_COLUMNS).optional(),topValues:external_exports.number().int().min(1).max(ANALYTICS_MAX_TOP_VALUES).optional(),buckets:external_exports.number().int().min(1).max(ANALYTICS_MAX_HISTOGRAM_BUCKETS).optional()}),DatasetTemporalGrammarSchema=external_exports.enum(["iso-datetime","iso-date","year-month","year"]),DatasetColumnTemporalSchema=external_exports.object({grammar:DatasetTemporalGrammarSchema,min:external_exports.string().min(1),max:external_exports.string().min(1),minInstant:external_exports.iso.datetime(),maxInstant:external_exports.iso.datetime(),rangeDays:external_exports.number().int().nonnegative()}),DatasetTopValueSchema=external_exports.object({value:external_exports.string(),count:external_exports.number().int().nonnegative()}),DatasetHistogramBucketSchema=external_exports.object({bucketMin:external_exports.number(),bucketMax:external_exports.number(),count:external_exports.number().int().nonnegative()}),columnProfileBase={name:external_exports.string().min(1),rows:external_exports.number().int().nonnegative(),nonNull:external_exports.number().int().nonnegative(),nulls:external_exports.number().int().nonnegative(),blanks:external_exports.number().int().nonnegative(),distinct:external_exports.number().int().nonnegative()},DatasetStringColumnProfileSchema=external_exports.object({...columnProfileBase,type:external_exports.literal("STRING"),minLength:external_exports.number().int().nonnegative().nullable(),maxLength:external_exports.number().int().nonnegative().nullable(),topValues:external_exports.array(DatasetTopValueSchema),topValuesTruncated:external_exports.boolean(),temporal:DatasetColumnTemporalSchema.optional()}),DatasetNumberColumnProfileSchema=external_exports.object({...columnProfileBase,type:external_exports.literal("NUMBER"),numericKind:external_exports.enum(["integer","decimal"]).nullable(),min:external_exports.string().nullable(),max:external_exports.string().nullable(),mean:external_exports.string().nullable(),stddev:external_exports.string().nullable(),sum:external_exports.string().nullable(),p25:external_exports.string().nullable(),median:external_exports.string().nullable(),p75:external_exports.string().nullable(),quantilesExact:external_exports.boolean(),histogram:external_exports.array(DatasetHistogramBucketSchema)}),DatasetBooleanColumnProfileSchema=external_exports.object({...columnProfileBase,type:external_exports.literal("BOOLEAN"),trueCount:external_exports.number().int().nonnegative(),falseCount:external_exports.number().int().nonnegative()}),DatasetColumnProfileSchema=external_exports.discriminatedUnion("type",[DatasetStringColumnProfileSchema,DatasetNumberColumnProfileSchema,DatasetBooleanColumnProfileSchema]),DatasetProfileSchema=external_exports.object({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,producedBy:DatasetVersionProducerSchema.optional(),totalRows:external_exports.number().int().nonnegative(),totalColumns:external_exports.number().int().nonnegative(),columnsTruncated:external_exports.boolean(),columns:external_exports.array(DatasetColumnProfileSchema)}),DatasetMeasureAggSchema=external_exports.enum(["sum","avg","min","max"]),DatasetMeasureSchema=external_exports.discriminatedUnion("kind",[external_exports.object({kind:external_exports.literal("count")}),external_exports.object({kind:external_exports.literal("column"),column:external_exports.string().min(1),agg:DatasetMeasureAggSchema,castAs:external_exports.literal("number").optional()})]),DatasetAggregateInputSchema=DatasetRefSchema.extend({dimension:external_exports.string().min(1),measure:DatasetMeasureSchema,splitBy:external_exports.string().min(1).optional(),limit:external_exports.number().int().min(1).max(ANALYTICS_MAX_GROUP_LIMIT).optional(),cursor:external_exports.string().min(1).max(ANALYTICS_CURSOR_MAX_LENGTH).optional()}),DatasetMeasureStatsSchema=external_exports.object({sum:external_exports.string().nullable(),min:external_exports.string().nullable(),max:external_exports.string().nullable(),avg:external_exports.string().nullable()}),DatasetAggregateRowSchema=external_exports.object({dimension:external_exports.string().nullable(),series:external_exports.string().nullable().optional(),value:external_exports.string().nullable(),rowCount:external_exports.number().int().nonnegative(),stats:DatasetMeasureStatsSchema.nullable(),uncastCount:external_exports.number().int().nonnegative().optional()}),DatasetAggregateSchema=external_exports.object({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,producedBy:DatasetVersionProducerSchema.optional(),rows:external_exports.array(DatasetAggregateRowSchema),groupCount:external_exports.number().int().nonnegative(),seriesCount:external_exports.number().int().nonnegative(),truncated:external_exports.boolean(),omittedGroupCount:external_exports.number().int().nonnegative(),omittedSeriesCount:external_exports.number().int().nonnegative(),totalRows:external_exports.number().int().nonnegative(),nextCursor:external_exports.string().nullable(),uncastCellCount:external_exports.number().int().nonnegative().optional()}),DatasetSeriesBucketSchema=external_exports.enum(["day","month","quarter","year"]);var DatasetSeriesInputSchema=DatasetRefSchema.extend({timeColumn:external_exports.string().min(1),measure:DatasetMeasureSchema,bucket:DatasetSeriesBucketSchema,splitBy:external_exports.string().min(1).optional(),splitValues:external_exports.array(external_exports.string()).min(1).max(ANALYTICS_MAX_SERIES).optional()}),DatasetSeriesPointSchema=external_exports.object({t:external_exports.iso.datetime(),value:external_exports.string().nullable(),rowCount:external_exports.number().int().nonnegative()}),DatasetSeriesStatsSchema=external_exports.object({min:external_exports.string().nullable(),max:external_exports.string().nullable(),avg:external_exports.string().nullable(),first:external_exports.string().nullable(),last:external_exports.string().nullable(),lastT:external_exports.iso.datetime().nullable()}),DatasetSeriesEntrySchema=external_exports.object({key:external_exports.string().nullable().optional(),points:external_exports.array(DatasetSeriesPointSchema),stats:DatasetSeriesStatsSchema.nullable()}),DatasetSeriesSchema=external_exports.object({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,producedBy:DatasetVersionProducerSchema.optional(),timeColumn:external_exports.string().min(1),grammar:DatasetTemporalGrammarSchema,bucket:DatasetSeriesBucketSchema,bucketRequested:DatasetSeriesBucketSchema,bucketAdjusted:external_exports.boolean(),zeroFilled:external_exports.boolean(),series:external_exports.array(DatasetSeriesEntrySchema),droppedBucketCount:external_exports.number().int().nonnegative().optional(),totalRows:external_exports.number().int().nonnegative()});var DatasetStatusSchema=external_exports.enum(["active","paused","archived"]),DatasetMaturitySchema=external_exports.enum(["experimental","active","deprecated"]);var DatasetLifecycleReasonSchema=external_exports.string().min(1).max(500),ChangeDatasetStatusInputSchema=external_exports.strictObject({datasetId:external_exports.string().min(1).meta(DATASET_ENTITY_HINT),status:DatasetStatusSchema,reason:DatasetLifecycleReasonSchema.optional(),idempotencyKey:IdempotencyKeySchema}),ChangeDatasetMaturityInputSchema=external_exports.strictObject({datasetId:external_exports.string().min(1),maturity:DatasetMaturitySchema,reason:DatasetLifecycleReasonSchema.optional(),idempotencyKey:IdempotencyKeySchema});var DATASET_DESCRIPTION_MAX_LENGTH=2e3,DATASET_NOTES_MAX_LENGTH=4e3,DATASET_THEMES_MAX=100,DATASET_KEYWORD_MAX_LENGTH=64,DATASET_KEYWORDS_MAX=32,DATASET_GRAINS=["annual","quarterly","monthly","weekly","daily","hourly","irregular","unknown"],DatasetGrainSchema=external_exports.enum(DATASET_GRAINS),DATASET_TABLE_ROLES=["fact","dimension","relation"],DatasetTableRoleSchema=external_exports.enum(DATASET_TABLE_ROLES),DatasetTimeCoveredSchema=external_exports.strictObject({start:external_exports.iso.datetime({offset:!0}).nullable(),end:external_exports.iso.datetime({offset:!0}).nullable()}),DatasetTimeCoveredReadSchema=external_exports.object({start:external_exports.iso.datetime().nullable(),end:external_exports.iso.datetime().nullable()}),DATASET_DESCRIBE_FIELDS=["description","notes","keywords","themes","grain","timeCovered","tableRole"],DatasetDescribeFieldSchema=external_exports.enum(DATASET_DESCRIBE_FIELDS),DescribeDatasetExpectedSchema=external_exports.strictObject({description:external_exports.string().nullable().optional(),notes:external_exports.string().nullable().optional(),keywords:external_exports.array(external_exports.string()).max(DESCRIBE_EXPECTED_KEYWORDS_MAX).nullable().optional(),themes:external_exports.array(external_exports.string()).nullable().optional(),grain:DatasetGrainSchema.nullable().optional(),timeCovered:external_exports.strictObject({start:external_exports.string().nullable(),end:external_exports.string().nullable()}).nullable().optional(),tableRole:DatasetTableRoleSchema.nullable().optional(),versionId:external_exports.string().min(1).nullable()}),DescribeDatasetInputSchema=external_exports.strictObject({datasetId:external_exports.string().min(1),description:external_exports.string().min(1).max(DATASET_DESCRIPTION_MAX_LENGTH).nullable().optional().describe("Prose a reader needs to decide whether this dataset answers their question."),notes:external_exports.string().min(1).max(DATASET_NOTES_MAX_LENGTH).nullable().optional().describe("What a naive reading of this data gets wrong \u2014 a unit that is not what the column name suggests, timestamps that are really reporting periods, rows that double-count."),keywords:external_exports.array(external_exports.string().min(1).max(DATASET_KEYWORD_MAX_LENGTH)).max(DATASET_KEYWORDS_MAX).nullable().optional().describe("Search terms a reader would plausibly type looking for this dataset."),themes:external_exports.array(external_exports.string().regex(CATALOG_CONCEPT_REF_PATTERN,"a theme is 'scheme/slug'")).max(DATASET_THEMES_MAX).nullable().optional().describe("What this dataset is about, as terms from the tenant's own vocabulary, each 'scheme/slug'. Pick them with datasets.vocabulary.list \u2014 a term that is not there is refused, never created."),grain:DatasetGrainSchema.nullable().optional().describe("How often the data underneath changes. Derive it from how far apart the timestamps actually are, never from how precise they look: a yearly total stamped with a midnight timestamp is annual, not daily."),timeCovered:DatasetTimeCoveredSchema.nullable().optional().describe("The window the rows cover; either bound may be null for an open end."),tableRole:DatasetTableRoleSchema.nullable().optional().describe("What one row IS: a measurement (fact), a thing (dimension), or a link (relation)."),get expected(){return DescribeDatasetExpectedSchema.describe('What you believe each field you are about to write holds RIGHT NOW, so a value somebody edited since you read it is refused instead of overwritten. Every field this call writes must appear here; use null for "believed empty", which is a real assertion and not a default. Add versionId to state which load you read \u2014 the receipt then names the evidence you actually had. Beliefs about description, notes, keywords and themes are judged against the shared data platform, which owns them; the rest are judged against this server. Themes compare as a set. A wrong belief refuses the WHOLE call and names every field that moved, so one round trip builds the corrective retry.')},reason:DatasetLifecycleReasonSchema.optional(),get idempotencyKey(){return IdempotencyKeySchema}}),DescribeCandidatesInputSchema=DatasetRefSchema.extend({}),DatasetTimeCoveredCandidateSchema=external_exports.object({column:external_exports.string().min(1),start:external_exports.iso.datetime(),end:external_exports.iso.datetime(),evidence:external_exports.object({grammar:DatasetTemporalGrammarSchema,minValue:external_exports.string(),maxValue:external_exports.string(),rows:external_exports.number().int().nonnegative(),nonNull:external_exports.number().int().nonnegative()})}),DATASET_GRAIN_BASES=["grammar","spacing"],DatasetGrainBasisSchema=external_exports.enum(DATASET_GRAIN_BASES),DatasetGrainCandidateSchema=external_exports.object({column:external_exports.string().min(1),grain:DatasetGrainSchema,evidence:external_exports.object({basis:DatasetGrainBasisSchema,grammar:DatasetTemporalGrammarSchema,distinctValues:external_exports.number().int().nonnegative(),spanDays:external_exports.number().int().nonnegative(),averageSpacingDays:external_exports.number().nonnegative().nullable()})}),DatasetKeyFieldCandidateSchema=external_exports.object({column:external_exports.string().min(1),evidence:external_exports.object({rows:external_exports.number().int().nonnegative(),nonNull:external_exports.number().int().nonnegative(),distinct:external_exports.number().int().nonnegative()})}),DatasetDescribeCandidatesSchema=external_exports.object({get datasetId(){return DatasetIdSchema},get versionId(){return DatasetVersionIdSchema},rowCount:external_exports.number().int().nonnegative(),totalColumns:external_exports.number().int().nonnegative(),columnsProfiled:external_exports.number().int().nonnegative(),columnsTruncated:external_exports.boolean(),timeCovered:external_exports.array(DatasetTimeCoveredCandidateSchema),grain:external_exports.array(DatasetGrainCandidateSchema),keyFields:external_exports.array(DatasetKeyFieldCandidateSchema)});var REJECTED_CONFIG_SOURCE="`config.path` is not accepted by `datasets.inspectUpload`: this is a read-tier verb where the caller supplies the bytes, so admitting a server-filesystem path would widen it into a (confined) file-read primitive. Send the file inline as `content` (csv/json text) or `contentBase64` (any format); for a file too large to send inline, stage it with `datasets.beginUpload` and inspect the `uploadRef` it issues \u2014 that channel IS accepted here and is the one to reach for. Or use `datasets.land`, which does take `config.path`.",INSPECT_SHEET_DESCRIPTION='Which worksheet to inspect, for `format: "xlsx"` only \u2014 supplying it with any other format is refused. Omitted = the first NON-EMPTY sheet, in workbook order. ONE sheet is PARSED per call, but the response lists every sheet in the workbook, so a picker can show them all and inspect another by naming it here. A name that is not in the workbook is refused, listing the sheets that are. Nothing is landed either way \u2014 this verb persists nothing.\n\nWITH `uploadRef` IT DOES NOTHING: a staged xlsx cannot be inspected through a ref at all, so the whole call is refused (that refusal names your two options), and with every other format supplying `sheet` is the refused mistake above. To choose a worksheet, inspect a sample of the workbook INLINE as `contentBase64` to read its sheet list, then pass the sheet you picked to `datasets.land` together with your ref.',INSPECT_CONTENT_DESCRIPTION="The file itself, as inline UTF-8 TEXT. csv and json only \u2014 a UTF-8 string cannot carry arbitrary bytes losslessly, so xlsx/parquet are refused on this channel and must use `contentBase64`. Exactly one of `content` / `contentBase64` / `uploadRef` may be supplied. `config.path` is NOT a channel here (see `config`) \u2014 the caller supplies the bytes; use `datasets.land` for a file the server already holds.",INSPECT_CONTENT_BASE64_DESCRIPTION="The file itself, as inline BASE64 bytes. Works for EVERY format, and is the only channel here for the binary ones (xlsx, parquet). The size cap is checked on the base64 length BEFORE decoding, so an over-cap upload is refused without ever being allocated. Exactly one of `content` / `contentBase64` / `uploadRef` may be supplied. `config.path` is NOT a channel here (see `config`) \u2014 use `datasets.land` for a file the server already holds.",INSPECT_COLUMN_TYPES_DESCRIPTION='Declare a column\'s type and PREVIEW what that declaration would do, by column name (e.g. `{"asset_tag": "STRING"}`) \u2014 the same map `datasets.land` takes, checked by the same rule against the same full pass over every value. TWO DIFFERENCES from the land, both because this verb persists nothing: a declared NUMBER/BOOLEAN the values cannot carry is REPORTED in `castReport` (how many values fail, and a few of them) rather than refusing the call, and the previewed `columns` then keep the INFERRED type \u2014 so the preview never shows a type the land would refuse to declare. A name that is not a column of the source is still REFUSED, exactly as on `land`: a silently dropped declaration is how a caller ends up believing a column is text when it landed NUMBER. Not accepted on the `objectRef` arm, where the engine reads a bounded sample rather than every value and no honest count exists.',INSPECT_UPLOAD_REF_DESCRIPTION="A sealed staged-upload handle from `completeUpload` \u2014 how a file you STAGED gets PREVIEWED before it is landed (and, for a csv, how a file too large to send inline gets previewed at all). This is the channel to reach for whenever you staged the bytes: inspecting a ref is what lets you choose a `keyColumn` from real columns, and `keyColumn` is fixed AT land and cannot be changed afterwards.\n\nRecipe: `beginUpload` \u2192 `appendUploadChunk` \xD7 N \u2192 `completeUpload` (issues this ref) \u2192 `inspectUpload` with the ref \u2192 `land` with the SAME ref plus the `keyColumn` you chose. The ref must be SEALED, not yet captured into custody, and yours \u2014 each failure is refused by name, exactly as on `land`.\n\nA READ NEVER RELEASES: inspecting does NOT release or consume the slot, so the same ref is still there to `land` afterwards (and still counts toward your open-slot cap until you `abortUpload` it). It also does not EXTEND the slot: unlike `land`, a preview leaves the expiry where it was, because this is a read-tier call and cannot write to the slot at all. So inspect and then land without a long pause between them; if the slot expires in between, the land is refused and you re-stage. In the same vein, a preview does not hold the slot against a concurrent reclaim \u2014 if it expires mid-read you get a named, retryable refusal, never damaged data.\n\nWhich formats, and how big: csv is read INCREMENTALLY, so a staged csv far larger than the inline channels can carry previews fine (up to the streamed bound). json/geojson/parquet are read WHOLE, exactly as `land` reads them \u2014 so those are bound by the same 10 MiB whole-read cap as an inline body, and a staged one over that is refused by size. A staged XLSX is REFUSED outright \u2014 preview a small sample of the workbook inline instead. Exactly one of `content` / `contentBase64` / `uploadRef` may be supplied.";var CAPTURE_POLICY_CLASSES=["interactive","bulk"],CapturePolicyClassSchema=external_exports.enum(CAPTURE_POLICY_CLASSES),CONTENT_ENCODINGS=["identity","gzip"],ContentEncodingSchema=external_exports.enum(CONTENT_ENCODINGS),INTERACTIVE_MAX_CAPTURE_BYTES=1024*1024*1024,BULK_MAX_CAPTURE_BYTES=2*1024*1024*1024;var CaptureSourceIdSchema=external_exports.string().min(1).brand(),CaptureSourceViewSchema=external_exports.object({sourceId:external_exports.string().min(1),displayName:external_exports.string().min(1),policyClass:CapturePolicyClassSchema,maxBytes:external_exports.number().int().positive(),contentEncoding:ContentEncodingSchema,registeredAt:external_exports.iso.datetime().optional(),recordId:external_exports.string().min(1).optional()});var SourceKeySchema=external_exports.string().min(1).max(64).regex(/^[a-z][a-z0-9-]*$/,"source key must be kebab-case starting with a letter"),registrationFields={key:SourceKeySchema,displayName:external_exports.string().min(1).max(200),maxBytes:external_exports.number().int().positive(),idempotencyKey:IdempotencyKeySchema},RegisterSourceInputSchema=external_exports.discriminatedUnion("policyClass",[external_exports.strictObject({...registrationFields,policyClass:external_exports.literal("interactive"),contentEncoding:external_exports.literal("identity").default("identity")}),external_exports.strictObject({...registrationFields,policyClass:external_exports.literal("bulk"),contentEncoding:ContentEncodingSchema.default("identity")})]);var OBJECT_REF_PREFIX="obr_",OBJECT_REF_HEX_LENGTH=32,ObjectRefSchema=external_exports.string().regex(new RegExp(`^${OBJECT_REF_PREFIX}[0-9a-f]{${OBJECT_REF_HEX_LENGTH}}$`),"not an ObjectRef (obr_ + 32 hex characters)").brand();var ResolvedObjectSchema=external_exports.object({uri:external_exports.string().min(1),captureId:external_exports.string().min(1),sizeBytes:external_exports.number().int().nonnegative(),contentType:external_exports.string().min(1),contentEncoding:external_exports.enum(["identity","gzip"]),policyClass:CapturePolicyClassSchema});var CaptureIdSchema=external_exports.uuid().brand(),CAPTURE_STATES=["PENDING","COMPLETED","EXPIRED"],CaptureStateSchema=external_exports.enum(CAPTURE_STATES),CHECKSUM_VERIFICATION_GRADES=["STORE_VERIFIED"],ChecksumVerificationGradeSchema=external_exports.enum(CHECKSUM_VERIFICATION_GRADES),QUARANTINE_WINDOW_MS=1440*60*1e3,Sha256Base64Schema=external_exports.string().regex(/^[A-Za-z0-9+/]{43}=$/,"not a base64-encoded sha256 digest");var BeginCaptureInputSchema=external_exports.strictObject({sourceId:external_exports.string().min(1).optional(),filename:external_exports.string().min(1).max(1024),contentType:external_exports.string().min(1).max(255),sizeBytes:external_exports.number().int().positive(),sha256:Sha256Base64Schema,contentEncoding:ContentEncodingSchema.default("identity"),idempotencyKey:IdempotencyKeySchema}),WriteGrantSchema=external_exports.object({url:external_exports.url(),method:external_exports.literal("PUT"),headers:external_exports.record(external_exports.string(),external_exports.string()),expiresAt:external_exports.iso.datetime()}),CaptureViewSchema=external_exports.object({captureId:CaptureIdSchema,objectRef:ObjectRefSchema,sourceId:external_exports.string().min(1),policyClass:CapturePolicyClassSchema,state:CaptureStateSchema,filename:external_exports.string().min(1),contentType:external_exports.string().min(1),contentEncoding:ContentEncodingSchema,sizeBytes:external_exports.number().int().nonnegative(),declaredSha256:Sha256Base64Schema,verificationGrade:ChecksumVerificationGradeSchema.optional(),capturedBy:external_exports.string().min(1),expiresAt:external_exports.iso.datetime(),completedAt:external_exports.iso.datetime().optional(),createdAt:external_exports.iso.datetime(),recordId:external_exports.string().min(1).optional()}),BeginCaptureResultSchema=external_exports.object({capture:CaptureViewSchema,grants:external_exports.array(WriteGrantSchema)}),CompleteCaptureInputSchema=external_exports.strictObject({captureId:CaptureIdSchema,idempotencyKey:IdempotencyKeySchema}),GetCaptureInputSchema=external_exports.strictObject({captureId:CaptureIdSchema});var CONNECTOR_KINDS=["delta-sharing","snowflake"],ConnectorKindSchema=external_exports.enum(CONNECTOR_KINDS,{error:`connectorKind must be one of: ${CONNECTOR_KINDS.join(", ")} \u2014 the SDP catalog's own data_service_type slug. "delta-share" is the retired spelling and is refused.`});var SNOWFLAKE_ACCOUNT_URL_HINT="Must look like https://<account>.snowflakecomputing.com (<org>-<account> or an account locator) \u2014 lower-case, the account\u2019s own URL, with no path, port or login in it.";var SNOWFLAKE_ACCOUNT_URL_RE=/^https:\/\/[a-z0-9]+(-[a-z0-9]+)*\.snowflakecomputing\.com\/?$/,trimSnowflakeAccountUrlSlash=url2=>url2.endsWith("/")?url2.slice(0,-1):url2,SnowflakeAccountUrlSchema=external_exports.string().min(1).max(2048).regex(SNOWFLAKE_ACCOUNT_URL_RE,SNOWFLAKE_ACCOUNT_URL_HINT).transform(trimSnowflakeAccountUrlSlash),ConnectionIdSchema=external_exports.string().min(1).max(200).brand(),ConnectionRefSchema=external_exports.object({connectionId:ConnectionIdSchema}),TITLE_REQUIRED_HINT="Enter a name for this connection.";var ENDPOINT_URL_HINT="Must be an https:// URL, with no username or password in the URL itself.",SECRET_ARN_HINT="Must be a Secrets Manager ARN (arn:aws:secretsmanager:\u2026).";var MAX_CONNECTION_TITLE_LENGTH=200,ConnectionTitleSchema=external_exports.string().min(1).max(MAX_CONNECTION_TITLE_LENGTH).regex(/\S/,TITLE_REQUIRED_HINT),HTTPS_URL_RE=/^https:\/\/(?![^/?#]*@)[^\s/?#]+[^\s]*$/,ConnectionEndpointUrlSchema=external_exports.string().min(1).max(2048).regex(HTTPS_URL_RE,ENDPOINT_URL_HINT),SECRET_ARN_RE=/^arn:aws:secretsmanager:[a-z0-9-]{1,32}:[0-9]{12}:secret:[A-Za-z0-9/_+=.@-]{1,512}$/,CredentialReferenceSchema=external_exports.string().min(1).max(2048).regex(SECRET_ARN_RE,SECRET_ARN_HINT),CreateConnectionInputSchema=external_exports.strictObject({connectorKind:ConnectorKindSchema,title:ConnectionTitleSchema,endpointUrl:ConnectionEndpointUrlSchema,secretArn:CredentialReferenceSchema.optional(),idempotencyKey:IdempotencyKeySchema}),ConfigureConnectionInputSchema=external_exports.strictObject({connectionId:ConnectionIdSchema,title:ConnectionTitleSchema.optional(),endpointUrl:ConnectionEndpointUrlSchema.optional(),secretArn:CredentialReferenceSchema.optional(),idempotencyKey:IdempotencyKeySchema});var ConnectionDeclarationSchema=external_exports.object({connectionId:ConnectionIdSchema,title:external_exports.string().min(1),connectorKind:external_exports.string().min(1),endpointUrl:external_exports.string().min(1),credentialConfigured:external_exports.boolean()}),TestConnectionInputSchema=external_exports.strictObject({connectionId:ConnectionIdSchema}),RetireConnectionInputSchema=external_exports.strictObject({connectionId:ConnectionIdSchema,idempotencyKey:IdempotencyKeySchema}),ConnectionRetirementSchema=external_exports.object({connectionId:ConnectionIdSchema,title:external_exports.string().min(1),connectorKind:external_exports.string().min(1)}),CONNECTION_PROBE_FAILURES=SDP_CONNECTION_PROBE_FAILURES,ConnectionProbeFailureSchema=external_exports.enum(CONNECTION_PROBE_FAILURES),ConnectionTestResultSchema=external_exports.discriminatedUnion("ok",[external_exports.object({ok:external_exports.literal(!0),durationMs:external_exports.number().int().nonnegative(),message:external_exports.string().min(1)}),external_exports.object({ok:external_exports.literal(!1),failure:ConnectionProbeFailureSchema,durationMs:external_exports.number().int().nonnegative(),message:external_exports.string().min(1),hint:external_exports.string().min(1)})]),MAX_CONNECTION_BROWSE_DEPTH=MAX_SDP_LISTING_DEPTH-1,BrowsePathSchema=external_exports.array(external_exports.string().min(1).max(512)).max(MAX_CONNECTION_BROWSE_DEPTH),ListConnectionContentsInputSchema=external_exports.strictObject({connectionId:ConnectionIdSchema,path:BrowsePathSchema.default([])}),ConnectionContentEntrySchema=external_exports.object({name:external_exports.string().min(1).max(512),path:external_exports.array(external_exports.string().min(1).max(512)).min(1),kind:external_exports.enum(["container","dataset"]),readable:external_exports.boolean()}),ConnectionContentsSchema=external_exports.object({path:BrowsePathSchema,entries:external_exports.array(ConnectionContentEntrySchema)});var ConnectionSourceSchema=external_exports.object({connectionId:ConnectionIdSchema,serviceSlug:external_exports.string().min(1),connectorKind:external_exports.string().min(1),endpointUrl:external_exports.string().min(1),secretArn:external_exports.string().min(1).optional()}),ResolveConnectionSourceInputSchema=external_exports.strictObject({connectionRef:ConnectionRefSchema});var SNOWFLAKE_IDENTIFIER_RE=/^[A-Za-z_][A-Za-z0-9_$]{0,254}$/,SNOWFLAKE_USER_RE=/^[A-Za-z0-9_][A-Za-z0-9_.@$-]{0,254}$/,SNOWFLAKE_IDENTIFIER_HINT="Use the plain Snowflake name \u2014 letters, digits, _ and $, starting with a letter or _, with no quotes.",SNOWFLAKE_USER_HINT="Use the Snowflake user name as it appears in Snowflake, with no quotes.";var MAX_SNOWFLAKE_KEY_PEM_LENGTH=16384,SnowflakeUserSchema=external_exports.string().regex(SNOWFLAKE_USER_RE,SNOWFLAKE_USER_HINT),SnowflakeIdentifierSchema=external_exports.string().regex(SNOWFLAKE_IDENTIFIER_RE,SNOWFLAKE_IDENTIFIER_HINT),SnowflakeKeyOptionsSchema=external_exports.strictObject({user:SnowflakeUserSchema,warehouse:SnowflakeIdentifierSchema,database:SnowflakeIdentifierSchema,role:SnowflakeIdentifierSchema.optional()}),SetSnowflakeKeyInputSchema=external_exports.strictObject({connectionId:ConnectionIdSchema,privateKeyPem:external_exports.string().min(1).max(MAX_SNOWFLAKE_KEY_PEM_LENGTH),passphrase:external_exports.string().min(1).max(1024).optional(),...SnowflakeKeyOptionsSchema.shape,idempotencyKey:IdempotencyKeySchema}),GetSnowflakeKeyInputSchema=external_exports.strictObject({connectionId:ConnectionIdSchema}),SnowflakeKeyStateSchema=external_exports.strictObject({connectionId:ConnectionIdSchema,keyOnFile:external_exports.boolean(),attached:external_exports.boolean().optional(),enabled:external_exports.boolean().optional(),options:SnowflakeKeyOptionsSchema.optional(),lastRefreshError:external_exports.string().optional()});var RawDataLandedDetailSchema=external_exports.strictObject({objectRef:ObjectRefSchema,captureId:external_exports.uuid(),sourceId:external_exports.string().min(1),policyClass:CapturePolicyClassSchema,checksumSha256:Sha256Base64Schema,verificationGrade:ChecksumVerificationGradeSchema,sizeBytes:external_exports.number().int().nonnegative(),contentType:external_exports.string().min(1),contentEncoding:ContentEncodingSchema,filename:external_exports.string().min(1),capturedBy:external_exports.string().min(1)});var STREAMABLE_LAND_FORMATS=Object.freeze(["csv","xlsx"]),MAX_LAND_BASE64_CHARS=Math.ceil(10485760/3)*4+8,LAND_BYTE_CAP_REFUSAL=`this file is over the ${String(10485760/(1024*1024))} MiB limit on landed content, which is the largest file this path reads whole \u2014 it is the number beginUpload reports as landMaxBytes. datasets.startImportJob does NOT lift it: running in the background changes WHEN an import happens, never how much of a file a whole-file read has to hold. A CSV or XLSX staged through datasets.beginUpload IS read incrementally and accepts up to ${String(50331648/(1024*1024))} MiB \u2014 so if this file is one of those, stage it instead of sending it inline and it will land whole. For every other format, and for anything sent inline, this is the limit. This is a size limit, not a time limit, so waiting or retrying will not change it. Splitting the file is the only option, and it is the right one HERE even though the smaller-import guidance warns against it \u2014 that warning applies when a background import can take the whole file, which at this size it cannot. Be aware of the cost it was warning about: each piece lands as its own dataset, so the key-column diff that makes a re-import update rows rather than duplicate them works only within each piece, not across them. Split on a boundary that keeps related rows together.`,STREAMED_LAND_CAP_REFUSAL=`this file is over the ${String(50331648/(1024*1024))} MiB limit for a streamed import, which is the largest source this platform accepts in ANY format \u2014 csv and xlsx are read incrementally and therefore accept more than every other format, and this file is past even that. Staging it again will not help: it is already on the channel that accepts the most, and datasets.startImportJob refuses the same size at accept rather than handing back a job that cannot finish. This is a size limit, not a time limit, so waiting or retrying will not change it. Splitting the file is the only option, and it is the right one HERE even though the smaller-import guidance warns against it \u2014 that warning applies when one import can take the whole file, which at this size it cannot. Be aware of the cost it was warning about: each piece lands as its own dataset, so the key-column diff that makes a re-import update rows rather than duplicate them works only within each piece, not across them. Split on a boundary that keeps related rows together.`;var MAX_STAGED_UPLOAD_BYTES=100*1024*1024,STAGED_UPLOAD_CHUNK_BYTES=512*1024,MAX_STAGED_CHUNK_BASE64_CHARS=Math.ceil(STAGED_UPLOAD_CHUNK_BYTES/3)*4+8,BASE64_CHUNK_PATTERN=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,MAX_UPLOAD_FILENAME_CHARS=255,STAGED_UPLOAD_IDEMPOTENCY_KEY_MAX_LENGTH=200,StagedUploadIdempotencyKeySchema=IdempotencyKeySchema.max(STAGED_UPLOAD_IDEMPOTENCY_KEY_MAX_LENGTH);var MAX_OPEN_UPLOAD_SLOTS_PER_TENANT_PRINCIPAL=8,OPEN_SLOT_CAP_REFUSAL=`you are holding ${String(MAX_OPEN_UPLOAD_SLOTS_PER_TENANT_PRINCIPAL)} open upload slots, which is the most one principal may hold at once (MAX_OPEN_UPLOAD_SLOTS_PER_TENANT_PRINCIPAL) \u2014 so this beginUpload is refused until one is released. RELEASE ONE WITH datasets.abortUpload, naming its uploadId. That is the remedy even when every one of your uploads SUCCEEDED: landing a ref does not release its slot (deliberately \u2014 the same uploadRef can be landed more than once until it expires), so a slot you have already imported is still counted here and only you know that you are done with it. Call datasets.abortUpload after your FINAL land of each ref. Completing an upload does NOT free its slot; a completed-but-unimported slot is exactly what this cap counts. Waiting also works, unlike the size limits: every slot expires on its own, and the next beginUpload reclaims your expired ones \u2014 so this refusal lifts by itself, and splitting or shrinking your file will not change it.`,UploadIdSchema=external_exports.uuid().brand(),UploadRefSchema=external_exports.uuid().brand(),BeginUploadInputSchema=external_exports.object({filename:external_exports.string().min(1).max(MAX_UPLOAD_FILENAME_CHARS),idempotencyKey:StagedUploadIdempotencyKeySchema}).strict(),BeginUploadResultSchema=external_exports.object({uploadId:UploadIdSchema,chunkSizeBytes:external_exports.number().int().positive(),maxBytes:external_exports.number().int().positive(),landMaxBytes:external_exports.number().int().positive().describe("The cap the `land` consumption arm enforces on a ref whose format is read WHOLE (json, geojson, parquet). A slot may STORE up to `maxBytes`, but a staged file of one of those formats may be at most `landMaxBytes`. Always <= `maxBytes`. For a format in `streamableFormats` the binding number is `streamedLandMaxBytes` instead."),streamedLandMaxBytes:external_exports.number().int().positive().describe("The cap for a ref whose format is read INCREMENTALLY \u2014 the formats listed in `streamableFormats`. Larger than `landMaxBytes`, because a streamed land never holds the file: its memory is a function of batch size, not file size. Always <= `maxBytes`."),streamableFormats:external_exports.array(external_exports.string().min(1)).describe("The land formats read incrementally, and therefore bounded by `streamedLandMaxBytes` rather than `landMaxBytes`. Sent as a LIST rather than resolved server-side because `beginUpload` is told a filename, not a format \u2014 the format is a `land` argument the caller has not made yet, and guessing it from an extension here would advertise a bound the land might not honour. A client that knows which format it will pass can pick the right bound before staging a byte."),expiresAt:external_exports.iso.datetime()}),AppendUploadChunkInputSchema=external_exports.object({uploadId:UploadIdSchema,sequence:external_exports.number().int().min(0),contentBase64:external_exports.string().min(4).max(MAX_STAGED_CHUNK_BASE64_CHARS).regex(BASE64_CHUNK_PATTERN,"contentBase64 must be canonical base64 of at least one byte")}).strict(),AppendUploadChunkResultSchema=external_exports.object({nextSequence:external_exports.number().int().min(0),receivedBytes:external_exports.number().int().min(0)}),CompleteUploadInputSchema=external_exports.object({uploadId:UploadIdSchema,sha256:external_exports.string().regex(/^[0-9a-f]{64}$/,"sha256 must be lowercase hex")}).strict(),CompleteUploadResultSchema=external_exports.object({uploadRef:UploadRefSchema,sha256:external_exports.string().min(1),byteSize:external_exports.number().int().min(0)}),AbortUploadInputSchema=external_exports.object({uploadId:UploadIdSchema.describe("The slot to release. PASS YOUR `uploadRef` HERE if that is what you are holding \u2014 a ref and the id it came from are the same value (the brands mark the lifecycle stage, not a different identifier), so a caller who only ever saw the ref needs nothing else. Releasing is how you end a SUCCESSFUL staged upload as well as an abandoned one: landing never releases the slot, and an unreleased slot counts against your open-slot cap until it expires. Idempotent \u2014 releasing an already-released slot succeeds with `released: false`. It frees staged BYTES only, and never touches anything you landed.")}).strict(),AbortUploadResultSchema=external_exports.object({released:external_exports.boolean()});var inlineTextSource={content:external_exports.string().min(1).max(10485760,LAND_BYTE_CAP_REFUSAL).describe("The file itself, as inline UTF-8 TEXT. csv and json only \u2014 a UTF-8 string cannot carry arbitrary bytes losslessly, so xlsx/parquet are refused on this channel and must use `contentBase64`, `config.path` or `uploadRef`. Best for small files a client already holds in memory. Exactly one of `content` / `contentBase64` / `config.path` / `uploadRef` may be supplied.")},inlineBase64Source={contentBase64:external_exports.string().min(1).max(MAX_LAND_BASE64_CHARS,LAND_BYTE_CAP_REFUSAL).describe("The file itself, as inline BASE64 bytes. Works for EVERY format, and is the only inline channel for the binary ones (xlsx, parquet). The size cap is checked on the base64 length BEFORE decoding, so an over-cap upload is refused without ever being allocated. A file too large to emit in one call goes through the staged-upload protocol instead (`beginUpload` \u2192 `appendUploadChunk` \u2192 `completeUpload`) and lands via `uploadRef`. Exactly one of `content` / `contentBase64` / `config.path` / `uploadRef` may be supplied.")},confinedFileSource={config:external_exports.object({path:external_exports.string().min(1).describe("A file the SERVER can already see, named relative to its configured ingest directory. This is the channel for LARGE loads \u2014 the inline channels cap at `MAX_LAND_CONTENT_BYTES`, while a csv supplied this way is landed by STREAMING it and is not bound by that cap at all (other formats are still parsed whole, so they keep the cap). Deliver the file into the ingest directory by whatever means the deployment provides, then name it here.\n\nCONFINED: the path is resolved against the ingest directory and refused if it escapes \u2014 `../` traversal, and an in-directory symlink pointing out, are both rejected before any read. An absolute path is accepted only when it lands inside that directory; it is not a way to read anywhere on the host.\n\nIt takes a PLAIN FILE (`.csv`, `.xlsx`, \u2026) \u2014 not an archive. The zip-shaped artifact intake is a different seam entirely (`registerSourceArtifact` + a source transformation); nothing about `land` unpacks anything.")}).strict().describe("The server-side file channel. Its only member is `path`. Exactly one of `content` / `contentBase64` / `config.path` / `uploadRef` may be supplied. A client that cannot write the server filesystem should stage bytes with the upload protocol and land via `uploadRef` instead.")},uploadRefSource={uploadRef:UploadRefSchema.describe("A sealed staged-upload handle from `completeUpload` \u2014 the byte channel for an agent or any client that cannot write the server filesystem and cannot emit a whole file inline. Recipe: `beginUpload` (returns the chunk size to use) \u2192 `appendUploadChunk` \xD7 N \u2192 `completeUpload` (verifies your declared sha-256 and issues this ref) \u2192 `land` with the ref plus the usual `format`/`sheet`/`keyColumn` facets. The staged bytes are read whole, so the inline land cap applies (`MAX_LAND_CONTENT_BYTES`); the ref must be SEALED, not yet captured into custody, and yours \u2014 each failure is refused by name. Landing does NOT release the ref (the same bytes can be landed again until the slot expires), and reading slides the slot TTL forward. Exactly one of `content` / `contentBase64` / `config.path` / `uploadRef` / `objectRef` may be supplied.")},csvDialectFacet={csvDialect:external_exports.strictObject({delimiter:external_exports.string().length(1).optional().describe("Field separator. Omitted = `,`. Exactly one character."),quote:external_exports.string().length(1).optional().describe('Quoting character. Omitted = `"`. Exactly one character.'),escape:external_exports.string().length(1).optional().describe('Escape character INSIDE a quoted field. Omitted = `"` (RFC4180 doubling). Set it to `\\` for a Spark/Hadoop-style export, which escapes an embedded quote as `\\"` rather than `""` \u2014 that export then lands AS DELIVERED, with no pre-translation.'),header:external_exports.boolean().optional().describe("Does the first record name the columns? Omitted = true. `false` is refused today: a headerless land has no column names to declare a version with.")}).optional().describe('CSV parse dialect for `format: "csv"` on the `objectRef` channel. Omitted = RFC4180 (`,` / `"` / doubled-quote escaping), which is what every other land channel parses unconditionally. The dialect is DECLARED, never sniffed \u2014 auto-detection samples only the head of the file and mistypes exactly the large files this channel exists for.')},objectRefSource={objectRef:ObjectRefSchema.describe("An opaque handle to an object captured through the Integrations capture seam (`integrations.beginCapture` \u2192 a direct-to-bucket PUT \u2192 `integrations.completeCapture`). This is the channel for LARGE loads: the server never reads the bytes \u2014 it resolves the ref server-side and the query engine reads the object directly from object storage \u2014 so no inline or streamed byte cap applies. What bounds it is the capture SOURCE CLASS's own size policy, and that bound already bit at `beginCapture`, before the object existed.\n\nACCEPTED ONLY BY `datasets.startImportJob` (mode `land`), which returns a job handle to poll. `datasets.land` refuses this channel at every size \u2014 landing by reference is always a background job, so the channel has exactly one execution shape.\n\nThe ref must name a capture of YOUR tenant that sealed COMPLETED. A ref belonging to another tenant is NOT_FOUND, indistinguishable from one that never existed; a capture still PENDING and a capture that EXPIRED are refused by name. The ref is opaque \u2014 it carries no bucket, no key and no URL, and nothing resolves one to a browser. Exactly one of `content` / `contentBase64` / `config.path` / `uploadRef` / `objectRef` may be supplied.")};var DatasetFormatSchema=external_exports.enum(["csv","json","geojson","xlsx","parquet"]),LoadStrategySchema=external_exports.enum(["full-refresh"]),LAND_IDEMPOTENCY_KEY_MAX_LENGTH=200,LandIdempotencyKeySchema=IdempotencyKeySchema.max(LAND_IDEMPOTENCY_KEY_MAX_LENGTH).describe("REQUIRED client-minted replay key for this load \u2014 YOU generate it (a UUID is fine), the server never does; omitting it is refused before anything lands. Once a load has COMPLETED, re-sending the same key returns that original DatasetRef and lands nothing \u2014 which is how a caller whose socket died retries a multi-GB load without landing a second copy. A load still IN FLIGHT under the key is refused CONFLICT (data.code LAND_IN_FLIGHT) rather than started again: wait for it, and if it never finishes, CALL datasets.get AND READ currentVersionId before minting a new key \u2014 a load can be complete and current with only its receipt left unsealed, and a new key would land the whole thing a second time. currentVersionId is the field that answers: it flips LAST, whereas a datasets.versions row already exists while the load is still streaming. A load that RAN and FAILED is the different case: its seal frees the base key, so re-sending that key starts a second real load \u2014 unless that failure seal ALSO failed, which leaves the Record in flight and the key claimed. A process that DIED without sealing either way leaves the key claimed indefinitely; nothing sweeps it. On BOTH the replay and in-flight paths the server compares the name, the parse facets, the key column and a digest of the source against what the key recorded, and refuses CONFLICT (data.code LAND_IDEMPOTENCY_KEY_REUSED, listing the differing fields) if they differ \u2014 so mint a new key whenever you change the inputs, including when you change them mid-load. WHAT THE SOURCE DIGEST COVERS depends on the channel: inline content/contentBase64 digests the payload STRING you sent, tagged with the channel \u2014 so the same file re-sent on the OTHER inline channel is refused rather than replayed \u2014 but a config.path source digests the PATH STRING and never reads the file. So replacing the staged file at the same path and re-sending the key REPLAYS \u2014 success is reported for bytes the server never read. Changed the file, kept the path? Mint a new key. An uploadRef source digests the REF, which is safe where the path is not: a ref names bytes sealed against their sha-256 at completeUpload and immutable thereafter, so the ref identifies the bytes transitively. Resuming a partially-streamed load is not something YOU can ask for: an in-flight key is refused, never continued. An import job is the one exception \u2014 it continues its own interrupted load on the next sweep, so a large import survives a deployment \u2014 but that rests on the job row remembering what it opened, which nothing on the wire can supply. So this refusal is unchanged for a direct caller. WHAT TO MINT: a key that is stable across a RE-SEND of one intent and different for a different intent \u2014 a UUID held for the lifetime of the attempt, or a digest of the inputs. A key minted fresh per attempt is accepted and files a Record, but protects nothing."),IMPORT_JOB_TRANSFORM_IDEMPOTENCY_KEY_MAX_LENGTH=512,IMPORT_JOB_KEY_DESCRIPTION="REQUIRED client-minted replay key for this background import \u2014 YOU generate it (a UUID is fine), the server never does. It is the JOB row\u2019s replay identity: re-sending the same key with the same request re-reads YOUR OWN JOB \u2014 and re-runs it if that job FAILED \u2014 rather than starting a second import. It is also what the underlying verb files its own Record under once the job runs, and what THIS verb files its own accept receipt under. Re-sending a key whose accept receipt names a DIFFERENT mode, or a different derived run key, is REFUSED (BAD_REQUEST, data.code KEY_PARAM_MISMATCH) rather than answered from the other request. Mint a NEW key whenever you change the request; reuse one only to re-send the identical intent. ",ImportJobTransformIdempotencyKeySchema=IdempotencyKeySchema.max(IMPORT_JOB_TRANSFORM_IDEMPOTENCY_KEY_MAX_LENGTH).describe(IMPORT_JOB_KEY_DESCRIPTION+'On mode "transform" the server appends `#attempt-1` when your key does not already carry an `#attempt-<n>` segment, so a key minted with `composeTransformRunKey` is used verbatim and a plain one still becomes a well-formed run key. Up to 512 characters \u2014 wider than mode "land" allows, because a composition runner mints this arm\u2019s key from the definition name and the step id, neither of which is length-bounded.'),ImportJobLandIdempotencyKeySchema=LandIdempotencyKeySchema.describe(IMPORT_JOB_KEY_DESCRIPTION+'On mode "land" the key is what the land files its Record under, VERBATIM, and a key beginning with the literal `transform:` or `declared:` is REFUSED (BAD_REQUEST, data.code LAND_KEY_RESERVED_PREFIX) \u2014 those prefixes name the other two arms\u2019 own job namespaces. Up to 200 characters, the SAME bound the synchronous datasets.land takes, so one minted key is legal at both doors however large the file turns out to be.'),ImportJobDeclaredIdempotencyKeySchema=IdempotencyKeySchema.max(IMPORT_JOB_TRANSFORM_IDEMPOTENCY_KEY_MAX_LENGTH).describe(IMPORT_JOB_KEY_DESCRIPTION+'On mode "declared" the key is what the declared transformation run files its Record under, VERBATIM \u2014 no attempt suffix is appended, because that run verb takes a plain caller-minted key and resolves a re-send against a still-running run by RESUMING it rather than starting a second one. Up to 512 characters, the same bound mode "transform" takes, because a composition runner mints this arm\u2019s key too.'),DatasetProvenanceSchema=external_exports.enum(["legacy","sdp","live"]);var DatasetSdpOriginSchema=external_exports.enum(["walkup_declare","replica_connection","transformation_output","catalog_adoption","studio_reference"]),UploadVersionsUnavailableReasonSchema=external_exports.enum(["awaiting-first-landing","connection-delivered"]);var parseFacets={format:DatasetFormatSchema.optional().describe("Which parser reads the bytes. Omitted = `csv` (back-compat, not a sniff \u2014 the format is never guessed from the filename or the content). The declared format is checked against the bytes' magic and a mismatch is refused by name, so a mislabelled file fails loudly rather than landing as garbage."),sheet:external_exports.string().min(1).optional().describe('Which worksheet to land, for `format: "xlsx"` only \u2014 supplying it with any other format is refused. Omitted = the first NON-EMPTY sheet, in workbook order. ONE sheet lands per call; the others are not landed, so a multi-sheet workbook takes one `land` per sheet. A name that is not in the workbook is refused, listing the sheets that are.')},keyColumnFacet={keyColumn:external_exports.string().min(1).optional().describe("The source column holding each row's identity \u2014 copied into `row_key` and used as the join for the load-to-load diff and for asset provenance. It ALWAYS lands as STRING whatever it holds, so a numeric-looking key keeps its exact source text and cannot be reshaped by type inference. Set on the FIRST load and fixed thereafter: a re-land of an established dataset may omit it (the stored value applies) but cannot change it.\n\nSEPARATE from an asset import's own row key. Assets decide the identity they stamp on each created asset in their projection (`keyColumn` / `keyColumns`), and the two settings do not feed each other: this one is not defaulted from that one, that one is not defaulted from this one, and neither is required for the other to work. They are worth pointing at the SAME column when the published rowKey-to-assetId directory has to join back to this dataset's `row_key` \u2014 that join is by rendered text, so a multi-column asset key can never match it.")},COLUMN_TYPES_DESCRIPTION='Declare a column\'s type instead of letting it be inferred, by column name (e.g. `{"asset_tag": "STRING"}`). Reach for it when a column of digits is really an IDENTIFIER: it would otherwise land NUMBER and be ineligible as an external-ID value. Quoting the field in CSV does NOT force text. Undeclared columns are still inferred. Declaring STRING always works. Declaring NUMBER or BOOLEAN applies only where EVERY value ALREADY carries that type \u2014 this land never rewrites a value to fit, so it is refused naming the first value that does not: in csv, `007` is not the number `7`; in json/xlsx/parquet, a value the source supplied as TEXT is not a number just because it looks like one. A name that is not a column of the source is refused rather than ignored.',columnTypesFacet={columnTypes:external_exports.record(external_exports.string().min(1),DatasetColumnTypeSchema).optional().describe(COLUMN_TYPES_DESCRIPTION)},columnTypesWireFacet={columnTypes:boundedRecord2(external_exports.string().min(1),DatasetColumnTypeSchema,COLUMN_MAP_WIRE_MAX,"column types").optional().describe(COLUMN_TYPES_DESCRIPTION)},createOnlyFacet={createOnly:external_exports.literal(!0).optional().describe('Refuse rather than join: this land is a FIRST load, so a name any dataset already holds is a CONFLICT (`LAND_NAME_TAKEN`) and nothing is created. Omit it \u2014 the default \u2014 to keep the ordinary behaviour, where the same `name` re-lands as a new full-refresh version of the dataset that holds it. Reach for it when the caller means "create", not "load again": a wizard minting a dataset from a file cannot otherwise tell a deliberate re-land from a name typo. A `raw` shell whose first load never succeeded is NOT taken \u2014 it holds no data to join and its name can never be freed, so retrying that load under the same name stays possible.')},LoopbackLandProducerSchema=external_exports.enum(["calculation-result","report","scenario-forecast"]),idempotencyKeyFacet={idempotencyKey:LandIdempotencyKeySchema},inlineTextLand=external_exports.object({name:external_exports.string().min(1),...keyColumnFacet,...columnTypesFacet,...columnEntitiesFacet,...labelFacet,...createOnlyFacet,...parseFacets,...inlineTextSource}).strict(),inlineBase64Land=external_exports.object({name:external_exports.string().min(1),...keyColumnFacet,...columnTypesFacet,...columnEntitiesFacet,...labelFacet,...createOnlyFacet,...parseFacets,...inlineBase64Source}).strict(),confinedFileLand=external_exports.object({name:external_exports.string().min(1),...keyColumnFacet,...columnTypesFacet,...columnEntitiesFacet,...labelFacet,...createOnlyFacet,...parseFacets,...confinedFileSource}).strict(),uploadRefLand=external_exports.object({name:external_exports.string().min(1),...keyColumnFacet,...columnTypesFacet,...columnEntitiesFacet,...labelFacet,...createOnlyFacet,...parseFacets,...uploadRefSource}).strict(),objectRefLand=external_exports.object({name:external_exports.string().min(1),...keyColumnFacet,...columnTypesFacet,...columnEntitiesFacet,...labelFacet,...createOnlyFacet,...parseFacets,...csvDialectFacet,...objectRefSource}).strict(),RawLandInputSchema=external_exports.union([inlineTextLand,inlineBase64Land,confinedFileLand,uploadRefLand,objectRefLand]),LandInputSchema=external_exports.union([inlineTextLand.extend(idempotencyKeyFacet),inlineBase64Land.extend(idempotencyKeyFacet),confinedFileLand.extend(idempotencyKeyFacet),uploadRefLand.extend(idempotencyKeyFacet),objectRefLand.extend(idempotencyKeyFacet)]),columnMapWireFacets={...columnTypesWireFacet,...columnEntitiesWireFacet},RawLandWireInputSchema=external_exports.union([inlineTextLand.extend(columnMapWireFacets),inlineBase64Land.extend(columnMapWireFacets),confinedFileLand.extend(columnMapWireFacets),uploadRefLand.extend(columnMapWireFacets),objectRefLand.extend(columnMapWireFacets)]),LandWireInputSchema=external_exports.union([inlineTextLand.extend(columnMapWireFacets).extend(idempotencyKeyFacet),inlineBase64Land.extend(columnMapWireFacets).extend(idempotencyKeyFacet),confinedFileLand.extend(columnMapWireFacets).extend(idempotencyKeyFacet),uploadRefLand.extend(columnMapWireFacets).extend(idempotencyKeyFacet),objectRefLand.extend(columnMapWireFacets).extend(idempotencyKeyFacet)]);var LandRawInputSchema=external_exports.union([inlineTextLand.extend({loadStrategy:LoadStrategySchema}),inlineBase64Land.extend({loadStrategy:LoadStrategySchema}),confinedFileLand.extend({loadStrategy:LoadStrategySchema}),uploadRefLand.extend({loadStrategy:LoadStrategySchema}),objectRefLand.extend({loadStrategy:LoadStrategySchema})]);var DatasetReadColumnNameSchema=external_exports.string().min(1).max(200),NO_CONTROL_CHARS=/^[^\p{Cc}]+$/u,FilterValueSchema=external_exports.string().min(1).max(256).regex(NO_CONTROL_CHARS,"a filter value may not contain control characters");var COMPARE_FILTER_MEMBERS=[external_exports.object({column:DatasetReadColumnNameSchema,op:external_exports.literal("gt"),value:FilterValueSchema}).strict(),external_exports.object({column:DatasetReadColumnNameSchema,op:external_exports.literal("lt"),value:FilterValueSchema}).strict(),external_exports.object({column:DatasetReadColumnNameSchema,op:external_exports.literal("between"),from:FilterValueSchema,to:FilterValueSchema}).strict()],EMPTY_FILTER_MEMBER=external_exports.object({column:DatasetReadColumnNameSchema,op:external_exports.literal("isEmpty")}).strict();var DatasetReadFilterSchema=external_exports.discriminatedUnion("op",[external_exports.object({column:DatasetReadColumnNameSchema,op:external_exports.literal("equals"),value:FilterValueSchema}).strict(),external_exports.object({column:DatasetReadColumnNameSchema,op:external_exports.literal("contains"),value:FilterValueSchema}).strict(),external_exports.object({column:DatasetReadColumnNameSchema,op:external_exports.literal("in"),values:external_exports.array(FilterValueSchema).max(5e5)}).strict(),...COMPARE_FILTER_MEMBERS,EMPTY_FILTER_MEMBER]),DatasetReadRangeSchema=external_exports.object({column:DatasetReadColumnNameSchema,from:external_exports.iso.datetime({offset:!0}).optional().describe("The first instant in range (inclusive): RFC 3339 with `Z` or an offset (seconds required)."),to:external_exports.iso.datetime({offset:!0}).optional().describe("The first instant past the range (exclusive): RFC 3339 with `Z` or an offset (seconds required).")}).strict().describe("Keep rows whose DATE or TIMESTAMP WITH TIME ZONE column falls in the half-open instant range from <= column < to, either end optional. NULL is never in range. At most six fraction digits; from after to is refused."),DatasetReadOrderBySchema=external_exports.object({column:DatasetReadColumnNameSchema,direction:external_exports.enum(["asc","desc"])}).strict();var RecipeResultSchema=external_exports.object({datasetId:DatasetIdSchema,name:external_exports.string().min(1),keyColumn:external_exports.string().min(1).nullable()}),RecipeSourcePinSchema=external_exports.object({versionId:DatasetVersionIdSchema,loadNumber:external_exports.number().int().positive().nullable(),promotedAt:external_exports.iso.datetime().nullable(),newerLoadCount:external_exports.number().int().nonnegative().nullable(),newestPromoted:external_exports.object({versionId:DatasetVersionIdSchema,loadNumber:external_exports.number().int().positive()}).nullable()});var EngineWaitSchema=external_exports.strictObject({since:external_exports.iso.datetime(),gaveUpAfterMs:external_exports.number().int().positive(),asOf:external_exports.iso.datetime()}).describe("The job is waiting for another large job on the same server to finish. `since` is when it started waiting; past `gaveUpAfterMs` it stops waiting and fails retryably, having changed nothing."),EngineBusySchema=external_exports.strictObject({gaveUpAfterMs:external_exports.number().int().positive().optional()}).describe("The job never started: another large job on the same server held the engine for the whole of its wait \u2014 `gaveUpAfterMs`, when the bound was recorded. Nothing was changed, and starting it again can succeed."),TRANSFORMATION_RUN_PHASES=["waiting-for-engine","exporting-inputs","running-sql","saving-outputs"],TransformationRunPhaseSchema=external_exports.enum(TRANSFORMATION_RUN_PHASES),TransformationRunInputProgressSchema=external_exports.strictObject({slot:external_exports.string().min(1),tilesDone:external_exports.number().int().nonnegative(),tilesTotal:external_exports.number().int().nonnegative().optional()}),TransformationRunStepSchema=external_exports.strictObject({phase:TransformationRunPhaseSchema,startedAt:external_exports.iso.datetime()}),TransformationRunPhaseDetailSchema=external_exports.strictObject({steps:external_exports.array(TransformationRunStepSchema).min(1),input:TransformationRunInputProgressSchema.optional()}),TransformationRunProgressSchema=TransformationRunPhaseDetailSchema.extend({phase:TransformationRunPhaseSchema,asOf:external_exports.iso.datetime(),lastActivityAt:external_exports.iso.datetime(),leaseExpiresAt:external_exports.iso.datetime().optional()});var ContentLocationSchema=external_exports.enum(["platform","external"]),EXTERNAL_URI_RE=/^https?:\/\/\S+$/i,ExternalContentUriSchema=external_exports.string().regex(EXTERNAL_URI_RE);var DUCKDB_ENGINE_VERSIONS=["1.5","2.0"],DuckdbEngineVersionSchema=external_exports.enum(DUCKDB_ENGINE_VERSIONS);var ZERO_ROW_OUTPUT_WARNING="zero-row-output",ZeroRowOutputWarningSchema=external_exports.object({kind:external_exports.literal(ZERO_ROW_OUTPUT_WARNING),output:external_exports.string().min(1),inputRows:external_exports.record(external_exports.string(),external_exports.number().int().nonnegative())}),OUTPUT_HELD_WARNING="output-held",OutputHeldWarningSchema=external_exports.object({kind:external_exports.literal(OUTPUT_HELD_WARNING),output:external_exports.string().min(1),datasetId:external_exports.string().min(1),versionId:external_exports.string().min(1)}),TransformationRunWarningSchema=external_exports.discriminatedUnion("kind",[ZeroRowOutputWarningSchema,OutputHeldWarningSchema]),TransformationRunWarningsSchema=external_exports.array(TransformationRunWarningSchema);var TRANSFORMATION_OUTPUT_KEY_PATTERN=JOB_FIELD_PATTERN,TRANSFORMATION_OUTPUT_KEY_MESSAGE="use a bare identifier a gate expression can address (letters, digits, `_`, `-`; no spaces or dots, and it must START with a letter or `_`)";var TransformationOutputEntityRefSchema=EntityRefSchema.extend({domain:external_exports.literal("datasets"),type:external_exports.literal("dataset-version"),version:external_exports.string().min(1)}),TransformationRunCompletionOutputSchema=external_exports.object({datasetId:external_exports.string().min(1).meta(DATASET_ENTITY_HINT),versionId:external_exports.string().min(1),ref:TransformationOutputEntityRefSchema.meta({entity:{domain:"datasets",type:"dataset-version"}})}),TransformationRunCompletionDetailSchema=external_exports.object({outputsByName:external_exports.record(external_exports.string().regex(TRANSFORMATION_OUTPUT_KEY_PATTERN,TRANSFORMATION_OUTPUT_KEY_MESSAGE),TransformationRunCompletionOutputSchema)});var TransformationDefinitionRefSchema=external_exports.discriminatedUnion("kind",[external_exports.strictObject({kind:external_exports.literal("transformation"),transformationId:external_exports.string().min(1),version:external_exports.number().int().positive()}),external_exports.strictObject({kind:external_exports.literal("spec"),specId:external_exports.string().min(1),version:external_exports.number().int().positive()})]);var TransformationEngineSchema=external_exports.enum(["duckdb-sql","declarative-steps"]);var BaseTransformRunKeySchema=external_exports.string().min(1).brand(),TransformRunKeySchema=external_exports.string().min(1).brand(),TransformRunKeyInputSchema=TransformRunKeySchema.regex(/#attempt-[1-9][0-9]*(?:\/|(?![\s\S]))/,"a transform run key must be attempt-scoped \u2014 mint it as `<base>#attempt-<n>` with `composeTransformRunKey`; a base key would be handed the FIRST run's Record and execute nothing").describe("Client-minted replay key \u2014 REQUIRED, and ATTEMPT-SCOPED. Mint it as `<base>#attempt-<n>` (`composeTransformRunKey`), one base per run intent and a new attempt each time you deliberately run again; a key carrying no `#attempt-<n>` segment is REFUSED at validation. Once a run has COMMITTED, reusing its key replays it: you get the original `DatasetRef` back and nothing executes a second time. A key whose run is still IN FLIGHT is refused CONFLICT `TRANSFORM_IN_FLIGHT` naming the run, never resumed \u2014 wait for it to settle rather than starting a second one. (A background import that is restarted DOES continue its own run, because the job row can name the Record as its own; a wire caller cannot, so it is refused.) A run that RAN and sealed FAILED consumed the key and uniquified it at seal, which frees the base key \u2014 so re-sending it after a failure starts a SECOND REAL RUN. To run the same spec again on purpose, bump the attempt. On both same-key paths the server compares what YOU SENT against what the record pinned \u2014 the spec id, the engine those two select, and the spec version IF YOU SENT ONE \u2014 and refuses CONFLICT if anything differs, so a key never silently answers for inputs you did not send. It does NOT compare anything the server resolved for itself: not the source version, and not the spec version when you omitted it (the server takes the latest). So neither a source that re-lands nor a spec that gains a version between your two calls turns a replay into a refusal, and a restarted background run still executes against the source version AND the spec version its Record names."),TransformAttemptSchema=external_exports.number().int().min(1).brand();var DEFAULT_UNSEALED_RECORD_TTL_MS=3600*1e3,UNSEALED_RECORD_CEILING_MS=1440*60*1e3,PinnedDatasetVersionRefSchema=external_exports.strictObject({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema});var SOURCE_ARTIFACT_ENTITY_HINT={entity:{domain:"datasets",type:"source-artifact"}},SourceArtifactIdSchema=external_exports.string().min(1).brand().meta(SOURCE_ARTIFACT_ENTITY_HINT),SourceTransformationIdSchema=external_exports.string().min(1).brand().meta({entity:{domain:"datasets",type:"source-transformation"}}),CitationSchema=external_exports.object({title:external_exports.string().trim().min(1),url:external_exports.string().trim().min(1)}),SourceArtifactSchema=external_exports.object({id:SourceArtifactIdSchema,filename:external_exports.string().min(1),byteSize:external_exports.number().int().nonnegative(),sha256:external_exports.string().regex(/^[0-9a-f]{64}$/),contentType:external_exports.string().min(1),originNote:external_exports.string().min(1),uploadedBy:external_exports.string().min(1),createdAt:external_exports.iso.datetime(),contentLocation:ContentLocationSchema.default("platform"),externalUri:ExternalContentUriSchema.optional()}),RegisterSourceArtifactInputSchema=external_exports.object({filename:external_exports.string().min(1),contentType:external_exports.string().min(1),originNote:external_exports.string().min(1),config:external_exports.object({path:external_exports.string().min(1)}),idempotencyKey:IdempotencyKeySchema}),RegisterSourceArtifactResultSchema=external_exports.object({artifact:SourceArtifactSchema,created:external_exports.boolean()}),TransformationMethodSchema=external_exports.enum(["duckdb-sql"]),SourceTransformationParamSchema=external_exports.object({type:external_exports.enum(["boolean","number","string"]),default:external_exports.union([external_exports.boolean(),external_exports.number(),external_exports.string()])}),TransformationInputFormatSchema=external_exports.enum(["csv","parquet"]),TransformationInputDescriptorSchema=external_exports.discriminatedUnion("kind",[external_exports.object({kind:external_exports.literal("artifact"),name:external_exports.string().min(1)}),external_exports.object({kind:external_exports.literal("dataset-version"),name:external_exports.string().min(1),format:TransformationInputFormatSchema.optional().describe("The file the slot is materialized as: `csv` (the default) exposes `<name>_csv`; `parquet` writes the version with its engine column types and exposes `<name>_parquet`. A Parquet slot reads only a connected dataset.")}),external_exports.object({kind:external_exports.literal("asset-mapping"),name:external_exports.string().min(1)}),external_exports.object({kind:external_exports.literal("identity-directory"),name:external_exports.string().min(1),system:external_exports.string().min(1)})]),DatasetVersionInputBindingSchema=external_exports.object({kind:external_exports.literal("dataset-version"),datasetId:external_exports.string().min(1).meta(DATASET_ENTITY_HINT),versionId:external_exports.string().min(1)}),TransformationInputBindingSchema=external_exports.discriminatedUnion("kind",[external_exports.object({kind:external_exports.literal("artifact"),artifactId:SourceArtifactIdSchema}),DatasetVersionInputBindingSchema,external_exports.object({kind:external_exports.literal("asset-mapping"),sourceDatasetId:external_exports.string().min(1).meta(DATASET_ENTITY_HINT)}),external_exports.strictObject({kind:external_exports.literal("identity-directory")})]),OBJECT_FORM_COLUMN_TYPES_DESCRIBE='Declare a column\'s type instead of letting it be inferred, by column name (e.g. `{"asset_tag": "STRING"}`). Reach for it when a column of digits is really an IDENTIFIER. Declaring STRING always holds. Declaring NUMBER or BOOLEAN is checked, and WHERE plus HOW depends on the output-storage election. On the `legacy` election the pins are applied at the output\'s own land with the same checked coercion a direct land makes \u2014 refused naming the first VALUE that does not already carry the type (in csv, `007` is not the number `7`). On the `connected` election the pins are written into the source read config the movement reader consumes, and a NUMBER/BOOLEAN pin is refused BEFORE delivery when a delivered value does not read as that type, naming the column and a value (a NUMBER refuses a leading zero, `007`; a BOOLEAN takes true, false, t, f, yes or no, in any case). A column of clean integers that was text passes there. A name that is not a column of the source is refused at the land. A `connected` output may instead pin a DuckDB type \u2014 VARCHAR, BIGINT, DOUBLE or TIMESTAMPTZ \u2014 which movement reads the column as; it is refused BEFORE delivery when a delivered value does not read as that type (BIGINT takes only integers as written, TIMESTAMPTZ only a time ending in Z or a numeric offset; named zones are refused), naming the column and the value. An empty column holds any of them. BOOLEAN is the land pin above on both elections. The `legacy` election refuses a DuckDB type.',SourceTransformationOutputColumnTypeSchema=external_exports.enum(["STRING","NUMBER","BOOLEAN","VARCHAR","BIGINT","DOUBLE","TIMESTAMPTZ"]);var SOURCE_TRANSFORMATION_OUTPUT_FORMATS=["csv","parquet"],SourceTransformationOutputFormatSchema=external_exports.enum(SOURCE_TRANSFORMATION_OUTPUT_FORMATS),SourceTransformationOutputKindSchema=external_exports.enum(["raw","result"]),SourceTransformationObjectOutputSchema=external_exports.strictObject({dataset:external_exports.string().min(1),columnTypes:external_exports.record(external_exports.string().min(1),SourceTransformationOutputColumnTypeSchema).optional().describe(OBJECT_FORM_COLUMN_TYPES_DESCRIBE),datasetId:DatasetIdSchema.optional().describe("Land each run of this output as a new version of this existing dataset, found by its id rather than by `dataset`, so it keeps receiving versions after a rename. A run whose id names no dataset it can land into fails, naming the output."),ownerDomain:external_exports.string().min(1).max(48).regex(LIVE_OWNER_DOMAIN_PATTERN).optional().describe("Not settable: a create carrying it is refused. Only the platform stamps a dataset s owner."),kind:SourceTransformationOutputKindSchema.optional().describe("The landed dataset's lineage kind, stamped on every landing. Absent means `raw`."),format:SourceTransformationOutputFormatSchema.optional().describe("The file the declaration writes for this output: `parquet` writes `<output>.parquet`, typed by the declaration itself; `csv` (LEGACY) writes `<output>.csv`. Omitted at create, it is the output's stored format when an append keeps the output, else `parquet` on connected storage \u2014 `csv` on legacy storage, or when the output pins columnTypes. A stored output with no format is `csv`. A create electing legacy storage, or pinning columnTypes, on a parquet output is refused RUN_OUTPUT_FORMAT_UNLANDABLE. A create or run whose SQL writes the other format fails RUN_OUTPUT_FILE_FORMAT_MISMATCH. Before anything is delivered, a parquet output with a nested or unknown column type fails RUN_OUTPUT_COLUMN_TYPE_UNSUPPORTED, and one holding NaN or infinity in a DOUBLE/FLOAT column fails RUN_OUTPUT_NON_FINITE_VALUE.")}),SourceTransformationOutputSchema=external_exports.union([external_exports.string().min(1),SourceTransformationObjectOutputSchema]),SourceTransformationOutputInputSchema=external_exports.union([external_exports.string().min(1),SourceTransformationObjectOutputSchema.extend({columnTypes:boundedRecord2(external_exports.string().min(1),SourceTransformationOutputColumnTypeSchema,SOURCE_TRANSFORMATION_OUTPUT_COLUMN_TYPES_MAX,"column types").optional().describe(OBJECT_FORM_COLUMN_TYPES_DESCRIBE)})]),SourceTransformationOutputsSchema=external_exports.record(external_exports.string().min(1),SourceTransformationOutputSchema);var SourceTransformationOutputsInputSchema=boundedRecord2(external_exports.string().regex(TRANSFORMATION_OUTPUT_KEY_PATTERN,TRANSFORMATION_OUTPUT_KEY_MESSAGE),SourceTransformationOutputInputSchema,SOURCE_TRANSFORMATION_OUTPUTS_MAX,"outputs");var OutputStorageSchema=external_exports.enum(["legacy","connected"]);var SourceTransformationSchema=external_exports.object({id:external_exports.string().min(1),transformationId:SourceTransformationIdSchema,version:external_exports.number().int().min(1),name:external_exports.string().min(1),method:TransformationMethodSchema,engineVersion:external_exports.string().min(1),sql:external_exports.string().min(1),paramsSchema:external_exports.record(external_exports.string().min(1),SourceTransformationParamSchema),inputs:external_exports.array(TransformationInputDescriptorSchema).min(1),outputs:SourceTransformationOutputsSchema,outputStorage:OutputStorageSchema.default("legacy"),citations:external_exports.array(CitationSchema),createdBy:external_exports.string().min(1),createdAt:external_exports.iso.datetime()}),SOURCE_TRANSFORMATION_INPUTS_MAX=64,SOURCE_TRANSFORMATION_CITATIONS_MAX=50,SOURCE_TRANSFORMATION_PARAMS_MAX=100,SourceTransformationParamsInputSchema=boundedRecord2(external_exports.string().min(1),SourceTransformationParamSchema,SOURCE_TRANSFORMATION_PARAMS_MAX,"parameters"),CreateSourceTransformationInputSchema=external_exports.object({transformationId:SourceTransformationIdSchema.optional(),name:external_exports.string().min(1),method:TransformationMethodSchema,engineVersion:external_exports.string().min(1),sql:external_exports.string().min(1),paramsSchema:SourceTransformationParamsInputSchema,inputs:external_exports.array(TransformationInputDescriptorSchema).min(1).max(SOURCE_TRANSFORMATION_INPUTS_MAX),outputs:SourceTransformationOutputsInputSchema,outputStorage:OutputStorageSchema.optional(),citations:external_exports.array(CitationSchema).max(SOURCE_TRANSFORMATION_CITATIONS_MAX).default([]),idempotencyKey:IdempotencyKeySchema}),CallerMintedKeySchema=IdempotencyKeySchema.describe("Client-minted replay key \u2014 REQUIRED. Mint ONE per intent (a UUID is fine) and reuse it only to re-send that identical intent. Once a call has COMPLETED, reusing its key returns the original receipt without re-executing; a call that was REFUSED consumed nothing, so the same key is free to run again. A run that RAN and sealed FAILED is neither: it consumed the key and uniquified it at seal (`<your key>#failed-<id>`), which frees the base key \u2014 so re-sending it after a failure starts a SECOND REAL RUN, never a replay. Recover from the receipt named by `data.runRecordId` instead. `runDeclaredTransformation` adds a third state, because it opens and seals across two transactions: a key whose run is still IN FLIGHT resumes that run rather than starting a second one. On BOTH of those paths the server compares your request against what the record holds \u2014 the declaration version, one digest per bound slot, and the resolved params \u2014 and refuses CONFLICT if anything differs, so a key never silently answers for inputs you did not send; mint a new key to run changed inputs. The values NOT compared are the as-of timestamps of asset-mapping and identity-directory slots: those subjects are temporal, so the stamp is taken per attempt and only the directory / system the slot names is matched. The key LIMITS but does not PREVENT double execution: two callers sending it at the same instant can both pass the in-flight check, so re-send sequentially, never in parallel.");var RUN_ENGINE_BUSY="RUN_ENGINE_BUSY",RUN_ENGINE_MISMATCH="RUN_ENGINE_MISMATCH",DIRECTORY_SLOT_UNAVAILABLE="DIRECTORY_SLOT_UNAVAILABLE",RunSourceTransformationInputSchema=external_exports.object({transformationId:SourceTransformationIdSchema,version:external_exports.number().int().min(1),inputs:external_exports.record(external_exports.string(),TransformationInputBindingSchema).default({}),params:external_exports.record(external_exports.string(),external_exports.union([external_exports.boolean(),external_exports.number(),external_exports.string()])).default({}),idempotencyKey:CallerMintedKeySchema}),DeclaredParamValueSchema=external_exports.union([external_exports.boolean(),external_exports.number(),external_exports.string()]),RunSourceTransformationWireInputSchema=RunSourceTransformationInputSchema.extend({inputs:boundedRecord2(external_exports.string(),TransformationInputBindingSchema,SOURCE_TRANSFORMATION_RUN_INPUTS_MAX,"input bindings").default({}),params:boundedRecord2(external_exports.string(),DeclaredParamValueSchema,SOURCE_TRANSFORMATION_RUN_PARAMS_MAX,"parameter values").default({})}),StartImportJobDeclaredRequestSchema=RunSourceTransformationWireInputSchema.omit({idempotencyKey:!0}).strict(),SourceTransformationRunOutputOutcomeSchema=external_exports.enum(["landed","landing","failed","unconfirmed","unchanged"]),SourceTransformationRunOutputSchema=external_exports.object({output:external_exports.string().min(1),datasetId:external_exports.string().min(1),versionId:external_exports.string().min(1),outcome:SourceTransformationRunOutputOutcomeSchema.optional(),message:external_exports.string().min(1).optional()}),SourceTransformationRunLandingOutputSchema=external_exports.object({output:external_exports.string().min(1),datasetId:external_exports.string().min(1),outcome:SourceTransformationRunOutputOutcomeSchema,message:external_exports.string().min(1).optional()}),RunSourceTransformationAcceptedSchema=external_exports.object({runRecordId:external_exports.string().min(1),running:external_exports.literal(!0).optional(),jobId:external_exports.string().min(1).optional()}),SourceTransformationRunEngineSchema=external_exports.object({declared:external_exports.string().min(1),actual:external_exports.string().min(1).nullable(),requested:DuckdbEngineVersionSchema.optional()}),PreviewSourceTransformationInputBindingSchema=external_exports.strictObject({kind:external_exports.literal("dataset-version"),datasetId:external_exports.string().min(1),versionId:external_exports.string().min(1),format:TransformationInputFormatSchema.optional()}),PreviewSourceTransformationInputSchema=external_exports.strictObject({sql:external_exports.string().min(1),inputs:boundedRecord2(external_exports.string().min(1),PreviewSourceTransformationInputBindingSchema,SOURCE_TRANSFORMATION_RUN_INPUTS_MAX,"input bindings"),resultOutput:external_exports.string().min(1),resultFormat:SourceTransformationOutputFormatSchema.optional(),params:boundedRecord2(external_exports.string(),DeclaredParamValueSchema,SOURCE_TRANSFORMATION_RUN_PARAMS_MAX,"parameter values").optional()}),SourceTransformationPreviewSchema=external_exports.object({rows:external_exports.array(external_exports.record(external_exports.string(),external_exports.string())),rowCount:external_exports.number().int().nonnegative()}),SourceTransformationRunStatusSchema=external_exports.object({runRecordId:external_exports.string().min(1),status:external_exports.enum(["in-flight","landing","committed","failed"]),outputs:external_exports.array(SourceTransformationRunOutputSchema),landingOutputs:external_exports.array(SourceTransformationRunLandingOutputSchema).optional(),stats:external_exports.record(external_exports.string(),external_exports.number()),warnings:TransformationRunWarningsSchema.optional(),summary:external_exports.string().optional(),detail:external_exports.string().optional(),engine:SourceTransformationRunEngineSchema.optional().describe("The engine this run declared beside the engine that actually ran it. ABSENT on a receipt sealed before the engine was recorded; `actual` is null when the run failed before its engine was identified."),actor:external_exports.string().min(1).optional(),openedAt:external_exports.iso.datetime().optional(),failureCode:external_exports.literal(RUN_ENGINE_BUSY).optional(),engineBusy:EngineBusySchema.optional(),engineWait:EngineWaitSchema.optional(),progress:TransformationRunProgressSchema.optional(),queued:external_exports.literal(!0).optional(),stopped:external_exports.literal(!0).optional(),stoppedReason:external_exports.string().optional(),transformation:external_exports.object({transformationId:SourceTransformationIdSchema,version:external_exports.number().int().min(1)}).describe('The EXACT declaration version this run pinned, projected off the run Record own reads \u2014 the walk-back hop. ABSENT rather than guessed when the pin cannot be read, so treat its absence as "this receipt does not name what it ran", never as "version 1".').optional(),bindings:external_exports.object({inputs:external_exports.record(external_exports.string(),TransformationInputBindingSchema),params:external_exports.record(external_exports.string(),external_exports.union([external_exports.boolean(),external_exports.number(),external_exports.string()]))}).describe('What this run BOUND \u2014 one binding per declared slot plus the declared params it resolved, projected off the run Record own input digests and reads. ABSENT rather than guessed, and absence carries THREE indistinguishable causes: the pinned declaration could not be read back, no declared slot resolved at all, or the reads this projection needs FAILED. Read an absent `bindings` as "this receipt cannot name what it bound", never as "this run bound nothing". An individual slot that cannot be resolved faithfully is OMITTED from `inputs` rather than approximated, so treat a missing slot the same way \u2014 the run bound every declared slot or it never opened.').optional()}),GetSourceTransformationRunInputSchema=external_exports.object({runRecordId:external_exports.string().min(1)}),SourceTransformationRunSummarySchema=external_exports.object({runRecordId:external_exports.string().min(1),status:external_exports.enum(["in-flight","landing","committed","failed"]),actor:external_exports.string().min(1),at:external_exports.iso.datetime(),summary:external_exports.string().optional(),outputs:external_exports.array(SourceTransformationRunOutputSchema),landingOutputs:external_exports.array(SourceTransformationRunLandingOutputSchema).optional(),elapsedMs:external_exports.number().int().nonnegative().optional(),phase:external_exports.enum(["queued","stopped",...TRANSFORMATION_RUN_PHASES]).optional(),restarts:external_exports.number().int().nonnegative().optional()}),ListSourceTransformationRunsInputSchema=external_exports.object({datasetId:external_exports.string().min(1).optional(),transformationId:external_exports.string().min(1).optional(),take:external_exports.number().int().min(1).max(1e3).optional().describe(`Rows this call may return, 1\u2013${1e3}; defaults to ${100}. An ask above the maximum is REFUSED, not clamped (a clamp hands back a page the caller did not request and cannot tell apart from the one it did). The list is newest-first, so a bounded answer is the most recent runs. There is NO continuation token: this read cannot page past its own bound today, and it does not pretend to \u2014 asking for more means asking for a larger \`take\`.`)});var MAX_TRANSFORM_STEPS=200,MAX_STEP_INPUT_COLUMNS=200,MAX_LOOKUP_ENTRIES=100,MAX_LOOKUP_VALUE_LENGTH=512,MapStepSchema=external_exports.object({kind:external_exports.literal("map"),source:external_exports.string().min(1),target:external_exports.string().min(1)}),UnitConvertStepSchema=external_exports.object({kind:external_exports.literal("unitConvert"),source:external_exports.string().min(1),target:external_exports.string().min(1),factor:external_exports.number()}),ConstStepSchema=external_exports.object({kind:external_exports.literal("const"),target:external_exports.string().min(1),value:DatasetCellValueSchema}),ExpressionStepSchema=external_exports.object({kind:external_exports.literal("expression"),target:external_exports.string().min(1),expression:external_exports.string().min(1),inputs:external_exports.array(external_exports.string().min(1)).max(MAX_STEP_INPUT_COLUMNS)}),CastStepSchema=external_exports.object({kind:external_exports.literal("cast"),source:external_exports.string().min(1),target:external_exports.string().min(1),to:DatasetColumnTypeSchema}),LookupMapEntrySchema=external_exports.object({from:external_exports.string().min(1).max(MAX_LOOKUP_VALUE_LENGTH),to:external_exports.string().max(MAX_LOOKUP_VALUE_LENGTH)}),LookupMapStepSchema=external_exports.object({kind:external_exports.literal("lookupMap"),source:external_exports.string().min(1),target:external_exports.string().min(1),entries:external_exports.array(LookupMapEntrySchema).min(1).max(MAX_LOOKUP_ENTRIES),onMiss:external_exports.enum(["passthrough","null"])}),FilterRowsStepSchema=external_exports.object({kind:external_exports.literal("filterRows"),predicate:external_exports.string().min(1),inputs:external_exports.array(external_exports.string().min(1)).max(MAX_STEP_INPUT_COLUMNS)}),TransformStepSchema=external_exports.discriminatedUnion("kind",[MapStepSchema,UnitConvertStepSchema,ConstStepSchema,ExpressionStepSchema,CastStepSchema,LookupMapStepSchema,FilterRowsStepSchema]);var DATASET_SNAPSHOT_TYPES=["dataset-version","reference-table"];var SnapshotUuidAskSchema=external_exports.guid(),SnapshotAskSchema=external_exports.object({domain:external_exports.literal("datasets"),type:external_exports.enum(DATASET_SNAPSHOT_TYPES).describe("Which kind of datasets entity to snapshot: 'dataset-version', one load of a dataset, or 'reference-table', a reference table whose snapshot is one of its versions; anything else is refused, and the refusal names the accepted values."),id:SnapshotUuidAskSchema.brand(),version:SnapshotUuidAskSchema.brand().optional()}),SnapshotResultSchema=EntitySnapshotRefSchema;var DELIVERY_CADENCE_MIN_SECONDS=60,DELIVERY_CADENCE_MAX_SECONDS=366*24*60*60,DeliveryCadenceSecondsSchema=external_exports.number().int().min(DELIVERY_CADENCE_MIN_SECONDS).max(DELIVERY_CADENCE_MAX_SECONDS);var DatasetsDeliveryLateDetailSchema=external_exports.strictObject({datasetId:DatasetIdSchema,dueBy:external_exports.iso.datetime(),expectedEverySeconds:DeliveryCadenceSecondsSchema,lastDeliveredAt:external_exports.iso.datetime().optional()});var LOAD_RECONCILIATION_VERDICTS=["matches","short","over","not-stated","not-counted"],LoadReconciliationVerdictSchema=external_exports.enum(LOAD_RECONCILIATION_VERDICTS);var LoadReconciliationSchema=external_exports.object({versionId:DatasetVersionIdSchema,loadNumber:external_exports.number().int().positive(),landedRows:external_exports.number().int().nonnegative().optional(),declaredRows:external_exports.number().int().nonnegative().optional(),verdict:LoadReconciliationVerdictSchema,difference:external_exports.number().int().positive().optional()}),ListLoadReconciliationsInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema}),ListLoadReconciliationsOutputSchema=external_exports.object({items:external_exports.array(LoadReconciliationSchema)});var GetLandReceiptInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema.optional()}),ReceiptFactsShape={datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,loadNumber:external_exports.number().int().positive(),loadedAt:external_exports.iso.datetime(),actor:external_exports.string().min(1),openedAt:external_exports.iso.datetime()},LandReceiptSchema=external_exports.discriminatedUnion("kind",[external_exports.object({kind:external_exports.literal("land"),...ReceiptFactsShape,rowCount:external_exports.number().int().nonnegative(),captureId:external_exports.string().min(1).optional()}),external_exports.object({kind:external_exports.literal("scheduled-delivery"),...ReceiptFactsShape,landedAt:external_exports.iso.datetime().optional()}),external_exports.object({kind:external_exports.literal("connection-observe"),...ReceiptFactsShape})]);var ValidationRulesetIdSchema=external_exports.string().min(1).brand(),ValidationRuleKindSchema=external_exports.enum(["required","regex","numeric","range","uniqueness","allowedValues","sourceFlag"]);var VALIDATION_RULES_MAX=50,MAX_ALLOWED_VALUES=200,MAX_ALLOWED_VALUE_LENGTH=200;var MAX_RULE_REASON_LENGTH=280,RuleReasonSchema=external_exports.string().min(1).max(MAX_RULE_REASON_LENGTH).optional(),RuleOnBreakSchema=external_exports.enum(["fails","questions","notes"]),LEGACY_RULE_ON_BREAK="fails",RuleConditionSchema=external_exports.strictObject({column:external_exports.string().min(1),equals:external_exports.string().min(1)}),RequiredRuleSchema=external_exports.object({kind:external_exports.literal("required"),column:external_exports.string().min(1),when:RuleConditionSchema.optional(),onBreak:RuleOnBreakSchema,reason:RuleReasonSchema}),RegexRuleSchema=external_exports.object({kind:external_exports.literal("regex"),column:external_exports.string().min(1),pattern:external_exports.string().min(1),onBreak:RuleOnBreakSchema,reason:RuleReasonSchema}),NumericRuleSchema=external_exports.object({kind:external_exports.literal("numeric"),column:external_exports.string().min(1),onBreak:RuleOnBreakSchema,reason:RuleReasonSchema}),RangeRuleSchema=external_exports.object({kind:external_exports.literal("range"),column:external_exports.string().min(1),min:external_exports.number().optional(),max:external_exports.number().optional(),inclusive:external_exports.boolean(),onBreak:RuleOnBreakSchema,reason:RuleReasonSchema}),UniquenessRuleSchema=external_exports.object({kind:external_exports.literal("uniqueness"),column:external_exports.string().min(1),onBreak:RuleOnBreakSchema,reason:RuleReasonSchema}),AllowedValuesRuleSchema=external_exports.object({kind:external_exports.literal("allowedValues"),column:external_exports.string().min(1),values:external_exports.array(external_exports.string().min(1).max(MAX_ALLOWED_VALUE_LENGTH)).min(1).max(MAX_ALLOWED_VALUES),onBreak:RuleOnBreakSchema,reason:RuleReasonSchema});var SourceFlagRuleSchema=external_exports.object({kind:external_exports.literal("sourceFlag"),column:external_exports.string().min(1),values:external_exports.array(external_exports.string().trim().min(1).max(MAX_ALLOWED_VALUE_LENGTH)).min(1).max(MAX_ALLOWED_VALUES),reasonColumn:external_exports.string().min(1).optional(),onBreak:RuleOnBreakSchema,reason:RuleReasonSchema}),ValidationRuleSchema=external_exports.discriminatedUnion("kind",[RequiredRuleSchema,RegexRuleSchema,NumericRuleSchema,RangeRuleSchema,UniquenessRuleSchema,AllowedValuesRuleSchema,SourceFlagRuleSchema]),StoredValidationRuleSchema=external_exports.preprocess(value2=>typeof value2=="object"&&value2!==null&&!("onBreak"in value2)?{...value2,onBreak:LEGACY_RULE_ON_BREAK}:value2,ValidationRuleSchema);var ValidationRulesetSchema=external_exports.object({rulesetId:ValidationRulesetIdSchema,version:external_exports.number().int().positive(),name:external_exports.string().min(1),datasetId:DatasetIdSchema,rules:external_exports.array(StoredValidationRuleSchema),savedAt:external_exports.iso.datetime()}),SaveValidationRulesetInputSchema=external_exports.object({rulesetId:ValidationRulesetIdSchema.optional(),name:external_exports.string().min(1).max(200),datasetId:DatasetIdSchema,rules:external_exports.array(ValidationRuleSchema).min(1).max(VALIDATION_RULES_MAX),idempotencyKey:IdempotencyKeySchema}),ListValidationRulesetsInputSchema=external_exports.object({datasetId:DatasetIdSchema}),ListValidationRulesetVersionsInputSchema=external_exports.object({rulesetId:ValidationRulesetIdSchema}),VALIDATION_WINDOW_START_MAX=2147483647,ValidationViolationWindowSchema=external_exports.strictObject({start:external_exports.number().int().nonnegative().max(VALIDATION_WINDOW_START_MAX),take:external_exports.number().int().min(1).max(1e3),ruleIndex:external_exports.number().int().nonnegative().optional()}),ValidateInputSchema=external_exports.strictObject({rulesetId:ValidationRulesetIdSchema,rulesetVersion:external_exports.number().int().positive().optional(),versionId:DatasetVersionIdSchema.optional(),violations:ValidationViolationWindowSchema.optional()}),ValidationViolationSchema=external_exports.object({rowId:external_exports.string().min(1),rowIndex:external_exports.number().int().nonnegative().optional(),rowKey:external_exports.string().min(1).optional(),column:external_exports.string().min(1),rule:ValidationRuleKindSchema,ruleIndex:external_exports.number().int().nonnegative().optional(),message:external_exports.string().min(1),evaluated:external_exports.literal(!1).optional()}),ValidationRecordClassificationSchema=external_exports.enum(["good","uncertain","failed"]),ValidationRuleTallySchema=external_exports.object({ruleIndex:external_exports.number().int().nonnegative(),cellsFlagged:external_exports.number().int().nonnegative(),rowsAffected:external_exports.number().int().nonnegative(),cellsNotEvaluated:external_exports.number().int().nonnegative(),conditionRowsSelected:external_exports.number().int().nonnegative().optional(),onBreak:RuleOnBreakSchema});var ValidationRecordDistributionSchema=external_exports.object({good:external_exports.number().int().nonnegative(),uncertain:external_exports.number().int().nonnegative(),failed:external_exports.number().int().nonnegative()}),ValidationPageRecordSchema=external_exports.object({rowId:external_exports.string().min(1),rowIndex:external_exports.number().int().nonnegative().optional(),rowKey:external_exports.string().min(1).optional(),classification:ValidationRecordClassificationSchema});var ValidationPreviewSchema=external_exports.object({rowLimit:external_exports.number().int().positive(),rowsInLoad:external_exports.number().int().nonnegative().optional()}),StoredFindingsPageSchema=external_exports.object({state:external_exports.enum(["kept","expired"]),matching:external_exports.number().int().nonnegative(),perRuleLimit:external_exports.number().int().positive()}),ValidationReportSchema=external_exports.object({rulesetId:ValidationRulesetIdSchema,rulesetVersion:external_exports.number().int().positive(),datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,rowsChecked:external_exports.number().int().nonnegative(),violations:external_exports.array(ValidationViolationSchema).max(1e3),window:ValidationViolationWindowSchema,violationsMatching:external_exports.number().int().nonnegative(),rowsWithViolation:external_exports.number().int().nonnegative(),cellsFlagged:external_exports.number().int().nonnegative(),cellsNotEvaluated:external_exports.number().int().nonnegative(),recordDistribution:ValidationRecordDistributionSchema,pageRecords:external_exports.array(ValidationPageRecordSchema).max(1e3),perRule:external_exports.array(ValidationRuleTallySchema).max(VALIDATION_RULES_MAX),preview:ValidationPreviewSchema.optional(),loadInFlight:external_exports.literal(!0).optional(),findingsStored:StoredFindingsPageSchema.optional()});var LiveOwnerDomainSchema=external_exports.string().min(1).max(48).regex(LIVE_OWNER_DOMAIN_PATTERN);var LIVE_SAMPLE_MAX_ROWS=100;var LIVE_READ_MAX_ROWS=1e3,SaveLiveDefinitionInputSchema=external_exports.strictObject({slug:DatasetSlugSchema,name:external_exports.string().min(1),description:external_exports.string().min(1).optional(),ownerDomain:LiveOwnerDomainSchema,sql:external_exports.string().min(1),idempotencyKey:IdempotencyKeySchema}),LiveDefinitionViewSchema=external_exports.object({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,definitionVersion:external_exports.number().int().positive(),slug:DatasetSlugSchema,ownerDomain:LiveOwnerDomainSchema,sql:external_exports.string().min(1),columns:external_exports.array(DatasetColumnSchema2),broken:external_exports.boolean()}),CheckLiveDefinitionInputSchema=external_exports.strictObject({slug:DatasetSlugSchema,ownerDomain:LiveOwnerDomainSchema,sql:external_exports.string().min(1),sampleRows:external_exports.number().int().min(0).max(LIVE_SAMPLE_MAX_ROWS).optional()}),LiveDefinitionCheckSchema=external_exports.object({slug:DatasetSlugSchema,ownerDomain:LiveOwnerDomainSchema,columns:external_exports.array(DatasetColumnSchema2),rowCount:external_exports.number().int().nonnegative(),sampleRows:external_exports.array(DatasetRowSchema),sampleTruncated:external_exports.boolean(),durationMs:external_exports.number().int().nonnegative(),engine:external_exports.string().min(1),role:external_exports.string().min(1)}),ReadLiveInputSchema=DatasetRefSchema.extend({take:external_exports.number().int().min(1).max(LIVE_READ_MAX_ROWS).optional()});var DATASET_COLUMN_MEANING_MAX_LENGTH=2e3,DATASET_COLUMN_NOTE_URI_MAX_LENGTH=2048,DATASET_COLUMN_NOTE_COLUMN_MAX_LENGTH=255,DATASET_COLUMN_NOTES_PER_CALL_MAX=25,DATASET_COLUMN_NOTE_FIELDS=["meaning","unit","term","uri"],DatasetColumnNoteFieldSchema=external_exports.enum(DATASET_COLUMN_NOTE_FIELDS),DatasetColumnNoteSchema=external_exports.object({meaning:external_exports.string().optional(),unit:external_exports.string().optional(),term:external_exports.string().optional(),uri:external_exports.string().optional(),orphaned:external_exports.boolean(),typeChanged:external_exports.boolean(),profileVersion:external_exports.number().int().optional()}),DatasetColumnNotesInputSchema=external_exports.strictObject({datasetId:external_exports.string().min(1)}),DatasetColumnNotesSchema=external_exports.object({datasetId:external_exports.string().min(1),recordSet:external_exports.string().min(1).optional(),columns:external_exports.array(external_exports.object({name:external_exports.string().min(1),type:external_exports.string().min(1),note:DatasetColumnNoteSchema.optional()})),unmatched:external_exports.array(external_exports.object({column:external_exports.string().min(1),note:DatasetColumnNoteSchema}))}),meaning=external_exports.string().min(1).max(DATASET_COLUMN_MEANING_MAX_LENGTH),unit=external_exports.string().regex(CATALOG_QUDT_UNIT_PATTERN,"a unit is a QUDT unit, e.g. 'unit:M'"),term=external_exports.string().regex(CATALOG_CONCEPT_REF_PATTERN,"a term is 'scheme/slug'"),uri=external_exports.string().min(1).max(DATASET_COLUMN_NOTE_URI_MAX_LENGTH),columnName=external_exports.string().min(1).max(DATASET_COLUMN_NOTE_COLUMN_MAX_LENGTH),DatasetColumnNotePatchSchema=external_exports.strictObject({meaning:meaning.nullable().optional().describe("What the values in this column mean."),unit:unit.nullable().optional().describe("The column's unit as a QUDT unit, e.g. 'unit:M3-PER-HR'."),term:term.nullable().optional().describe("A term from the tenant's vocabulary, 'scheme/slug' \u2014 pick it with datasets.vocabulary.list."),uri:uri.nullable().optional().describe("A term reference outside the vocabulary, as an absolute IRI (e.g. https://\u2026); javascript:, data: and vbscript: are refused.")}),DatasetColumnNoteBeliefSchema=external_exports.strictObject({meaning:external_exports.string().nullable().optional(),unit:external_exports.string().nullable().optional(),term:external_exports.string().nullable().optional(),uri:external_exports.string().nullable().optional()}).nullable(),DescribeColumnsInputSchema=external_exports.strictObject({datasetId:external_exports.string().min(1),columns:external_exports.record(columnName,DatasetColumnNotePatchSchema.nullable()).describe(`Column name \u2192 what to change in its note, or null to remove the note. At most ${String(DATASET_COLUMN_NOTES_PER_CALL_MAX)} columns per call.`),get expected(){return external_exports.strictObject({versionId:external_exports.string().min(1).nullable(),columns:external_exports.record(external_exports.string().min(1),DatasetColumnNoteBeliefSchema)}).describe(`What you believe each column's note holds RIGHT NOW, read from datasets.columnNotes: every column this call writes must appear, null for "no note", and every field written must be stated (null for "believed empty"). Judged against the shared data platform; a wrong belief refuses the WHOLE call and names every column and field that moved. versionId is the load you read (null for none).`)},reason:DatasetLifecycleReasonSchema.optional(),get idempotencyKey(){return IdempotencyKeySchema}}),DatasetVocabularyInputSchema=external_exports.strictObject({scheme:external_exports.string().regex(CATALOG_SLUG_PATTERN,"a scheme is a catalog slug").optional().describe("Narrow to one concept scheme by its slug; omit to list every scheme.")}),DATASET_VOCABULARY_SCOPES=["tenant","shared"],DatasetVocabularyTermSchema=external_exports.object({term:external_exports.string().min(1),label:external_exports.string().min(1),definition:external_exports.string().optional(),uri:external_exports.string().optional(),scope:external_exports.enum(DATASET_VOCABULARY_SCOPES)}),DatasetVocabularySchemeSchema=external_exports.object({scheme:external_exports.string().min(1),name:external_exports.string().min(1),description:external_exports.string().optional(),uri:external_exports.string().optional(),scope:external_exports.enum(DATASET_VOCABULARY_SCOPES),terms:external_exports.array(DatasetVocabularyTermSchema)}),DatasetVocabularySchema=external_exports.object({schemes:external_exports.array(DatasetVocabularySchemeSchema)});var DESCRIPTION_PROPOSAL_DATASET_FIELDS=["description","notes","themes"],DESCRIPTION_PROPOSAL_COLUMN_FIELDS=["meaning","unit","term","uri","refersTo"],DESCRIPTION_PROPOSAL_REFERS_TO_VALUES=["assets/asset","assets/asset-type"],DESCRIPTION_PROPOSAL_REFERS_TO={"assets/asset":{...ASSET_COLUMN_ENTITY,pickerResource:"assets"},"assets/asset-type":{entity:{domain:"assets",type:"asset-type"}}};var DESCRIPTION_PROPOSAL_FIELDS=[...DESCRIPTION_PROPOSAL_DATASET_FIELDS,...DESCRIPTION_PROPOSAL_COLUMN_FIELDS],DescriptionProposalFieldSchema=external_exports.enum(DESCRIPTION_PROPOSAL_FIELDS),DESCRIPTION_PROPOSAL_COLUMNS_MAX=250,DESCRIPTION_PROPOSAL_VALUES_MAX=DESCRIPTION_PROPOSAL_DATASET_FIELDS.length+DESCRIPTION_PROPOSAL_COLUMN_FIELDS.length*DESCRIPTION_PROPOSAL_COLUMNS_MAX;var slot2=DescribeDatasetInputSchema.shape,note=DatasetColumnNotePatchSchema.shape,ProposedColumnNoteSchema=external_exports.strictObject({meaning:note.meaning.unwrap().unwrap().optional().describe("What the values in this column mean."),unit:note.unit.unwrap().unwrap().optional().describe("A QUDT unit, e.g. 'unit:M3-PER-HR'."),term:note.term.unwrap().unwrap().optional().describe("A term from datasets.vocabulary.list, 'scheme/slug'."),uri:note.uri.unwrap().unwrap().optional().describe("A term outside the vocabulary, as an absolute IRI \u2014 never beside a term."),refersTo:external_exports.string().optional().describe(`What the column's values are the ids of: ${DESCRIPTION_PROPOSAL_REFERS_TO_VALUES.map(value2=>`'${value2}'`).join(" or ")}. Propose it only when the sampled values match; leave it out otherwise.`)}),ProposeDescriptionInputSchema=external_exports.strictObject({datasetId:external_exports.string().min(1),versionId:external_exports.string().min(1).nullable().describe("The load you read \u2014 the dataset's currentVersionId when you read it, null for a dataset with no load yet. A load that is no longer current is refused."),description:slot2.description.unwrap().unwrap().optional().describe("A proposed description."),notes:slot2.notes.unwrap().unwrap().optional().describe("Proposed notes: what a naive reading gets wrong."),themes:slot2.themes.unwrap().unwrap().optional().describe("Proposed themes, each 'scheme/slug' from datasets.vocabulary.list."),columns:external_exports.record(external_exports.string().min(1).max(DATASET_COLUMN_NOTE_COLUMN_MAX_LENGTH),ProposedColumnNoteSchema).optional().describe(`Column name \u2192 the note you propose for it; leave out what you cannot support. At most ${String(DESCRIPTION_PROPOSAL_COLUMNS_MAX)} columns.`),reason:DatasetLifecycleReasonSchema.optional().describe("Why you propose this, for the person deciding."),get idempotencyKey(){return IdempotencyKeySchema}}),DescriptionProposalValueDataSchema=external_exports.union([external_exports.string(),external_exports.array(external_exports.string())]),DESCRIPTION_PROPOSAL_VALUE_STATUSES=["pending","applied","rejected","replaced"],DescriptionProposalValueStatusSchema=external_exports.enum(DESCRIPTION_PROPOSAL_VALUE_STATUSES),DESCRIPTION_PROPOSAL_DECISIONS=["accept","edit","reject"],DescriptionProposalDecisionKindSchema=external_exports.enum(DESCRIPTION_PROPOSAL_DECISIONS),DESCRIPTION_PROPOSAL_APPLIED_NOTES=["landed-before-refusal","already-in-place","cache-behind"],DescriptionProposalAppliedNoteSchema=external_exports.enum(DESCRIPTION_PROPOSAL_APPLIED_NOTES),DescriptionProposalAttemptSchema=external_exports.discriminatedUnion("outcome",[external_exports.object({outcome:external_exports.literal("superseded"),was:DescriptionProposalValueDataSchema.nullable(),at:external_exports.iso.datetime()}),external_exports.object({outcome:external_exports.literal("not-applied"),code:external_exports.string(),collateral:external_exports.literal(!0).optional(),at:external_exports.iso.datetime()}),external_exports.object({outcome:external_exports.literal("may-have-landed"),code:external_exports.string(),at:external_exports.iso.datetime()}),external_exports.object({outcome:external_exports.literal("applied"),note:DescriptionProposalAppliedNoteSchema,code:external_exports.string().optional(),at:external_exports.iso.datetime()})]),DescriptionProposalValueSchema=external_exports.object({valueId:external_exports.string(),field:DescriptionProposalFieldSchema,column:external_exports.string().nullable(),proposed:DescriptionProposalValueDataSchema,current:DescriptionProposalValueDataSchema.nullable(),status:DescriptionProposalValueStatusSchema,lastAttempt:DescriptionProposalAttemptSchema.nullable(),decision:DescriptionProposalDecisionKindSchema.nullable(),applied:DescriptionProposalValueDataSchema.nullable(),decidedBy:external_exports.string().nullable(),decidedAt:external_exports.iso.datetime().nullable(),decisionRecordId:external_exports.string().nullable()}),DESCRIPTION_PROPOSAL_STATUSES=["open","decided","replaced"],DescriptionProposalStatusSchema=external_exports.enum(DESCRIPTION_PROPOSAL_STATUSES),DescriptionProposalActorSchema=external_exports.object({principal:external_exports.string(),onBehalfOf:external_exports.string().optional()}),DescriptionProposalSchema=external_exports.object({proposalId:external_exports.string(),datasetId:external_exports.string(),versionId:external_exports.string().nullable(),proposedBy:DescriptionProposalActorSchema,proposedAt:external_exports.iso.datetime(),recordId:external_exports.string(),reason:external_exports.string().optional(),status:DescriptionProposalStatusSchema,values:external_exports.array(DescriptionProposalValueSchema)}),DescriptionProposalsInputSchema=external_exports.strictObject({datasetId:external_exports.string().min(1)}),DescriptionProposalsSchema=external_exports.object({proposals:external_exports.array(DescriptionProposalSchema),capped:external_exports.boolean()}),OpenDescriptionProposalsInputSchema=external_exports.strictObject({}),OpenDescriptionProposalSchema=external_exports.object({proposalId:external_exports.string(),datasetId:external_exports.string(),datasetName:external_exports.string(),proposedBy:DescriptionProposalActorSchema,proposedAt:external_exports.iso.datetime(),pending:external_exports.number().int().nonnegative(),total:external_exports.number().int().nonnegative()}),OpenDescriptionProposalsSchema=external_exports.object({proposals:external_exports.array(OpenDescriptionProposalSchema),capped:external_exports.boolean()}),DescriptionProposalDecisionSchema=external_exports.strictObject({valueId:external_exports.string().min(1),decision:DescriptionProposalDecisionKindSchema,value:DescriptionProposalValueDataSchema.optional().describe("Your own value, for `edit` only \u2014 typed as the field is.")}),DecideDescriptionProposalInputSchema=external_exports.strictObject({datasetId:external_exports.string().min(1),proposalId:external_exports.string().min(1),expected:external_exports.strictObject({versionId:external_exports.string().min(1).nullable().describe("The dataset's current load as you read it; null for a dataset with no load.")}),decisions:external_exports.array(DescriptionProposalDecisionSchema).min(1).max(DESCRIPTION_PROPOSAL_VALUES_MAX),reason:DatasetLifecycleReasonSchema.optional(),get idempotencyKey(){return IdempotencyKeySchema}}),DESCRIPTION_PROPOSAL_OUTCOMES=["applied","rejected","superseded","not-applied","may-have-landed"],DescriptionProposalOutcomeSchema=external_exports.object({valueId:external_exports.string(),outcome:external_exports.enum(DESCRIPTION_PROPOSAL_OUTCOMES),code:external_exports.string().optional(),collateral:external_exports.literal(!0).optional(),note:DescriptionProposalAppliedNoteSchema.optional()}),DecideDescriptionProposalSchema=external_exports.object({proposal:DescriptionProposalSchema,outcomes:external_exports.array(DescriptionProposalOutcomeSchema)});var DatasetColumnTermMatchesInputSchema=external_exports.strictObject({datasetId:external_exports.string().min(1)});var term2=external_exports.string().regex(CATALOG_CONCEPT_REF_PATTERN,"a term is 'scheme/slug'"),DatasetColumnTermMatchesSchema=external_exports.discriminatedUnion("state",[external_exports.object({state:external_exports.literal("unavailable")}),external_exports.object({state:external_exports.literal("available"),terms:external_exports.number().int().nonnegative(),truncated:external_exports.boolean(),datasets:external_exports.array(external_exports.object({datasetId:external_exports.string().min(1),name:external_exports.string().min(1),matches:external_exports.array(external_exports.object({term:term2,column:external_exports.string().min(1),ownColumns:external_exports.array(external_exports.string().min(1)).min(1)}))}))})]);var CORRECTION_METHODS=["replace","percent","revert","drop-row"],CorrectionMethodSchema=external_exports.enum(CORRECTION_METHODS);var MAX_CORRECTION_PERCENT=1e3,CorrectionChangeSchema=external_exports.discriminatedUnion("method",[external_exports.strictObject({method:external_exports.literal("replace"),value:DatasetCellValueSchema}),external_exports.strictObject({method:external_exports.literal("percent"),percent:external_exports.number().finite().min(0).max(MAX_CORRECTION_PERCENT)}),external_exports.strictObject({method:external_exports.literal("revert")}),external_exports.strictObject({method:external_exports.literal("drop-row")})]),CorrectionFromSchema=external_exports.strictObject({logicalId:external_exports.string().min(1).max(200),value:DatasetCellValueSchema}),MAX_CORRECTION_COLUMN_LENGTH=255,MAX_CORRECTION_ACT_ROWS=500,ReplaceEachChangeSchema=external_exports.strictObject({method:external_exports.literal("replace-each")}),CorrectionCellFromSchema=CorrectionFromSchema.extend({to:DatasetCellValueSchema}),CELL_KEEP_TAKE=["keep","take"],CellKeepTakeSchema=external_exports.enum(CELL_KEEP_TAKE),CHANGE_CORRECTION_FIELDS={column:external_exports.string().min(1).max(MAX_CORRECTION_COLUMN_LENGTH),change:CorrectionChangeSchema,from:external_exports.array(CorrectionFromSchema).max(MAX_CORRECTION_ACT_ROWS),undoes:external_exports.string().min(1).optional(),resolves:external_exports.strictObject({actId:external_exports.string().min(1),deliveryVersionId:external_exports.string().min(1),resolution:external_exports.enum(["keep","use-delivered"])}).optional(),countedOnVersionId:external_exports.string().min(1).optional()},ChangeCorrectionSchema=external_exports.strictObject(CHANGE_CORRECTION_FIELDS),PastedCorrectionSchema=external_exports.strictObject({column:external_exports.string().min(1).max(MAX_CORRECTION_COLUMN_LENGTH),change:ReplaceEachChangeSchema,from:external_exports.array(CorrectionCellFromSchema).min(1).max(MAX_CORRECTION_ACT_ROWS),keepTake:external_exports.record(external_exports.string().min(1).max(200),CellKeepTakeSchema).optional()}),ReviewCorrectionSchema=external_exports.union([ChangeCorrectionSchema,PastedCorrectionSchema]);var REQUEST_ROWS_LISTED_MAX=20,REQUEST_PREVIEW_ROWS_MAX=5;var RequestRowSchema=external_exports.object({logicalId:external_exports.string().min(1),key:external_exports.string().min(1),problems:external_exports.array(external_exports.string().min(1)),line:external_exports.string().min(1)}),RequestCorrectionDetailSchema=external_exports.object({datasetName:external_exports.string(),deliveryNumber:external_exports.number().int().nonnegative(),rows:external_exports.number().int().nonnegative(),selectionWords:external_exports.string(),filterWords:external_exports.string(),listed:external_exports.array(RequestRowSchema).max(REQUEST_ROWS_LISTED_MAX),moreLine:external_exports.string(),problemsComplete:external_exports.boolean().optional(),incompleteLine:external_exports.string().optional(),requesterName:external_exports.string(),requesterEmail:external_exports.string(),requestedAt:external_exports.iso.datetime(),expectedLine:external_exports.string().optional(),requesterLine:external_exports.string().optional(),subjectPath:external_exports.string().min(1)}),RequestCorrectionPreviewSchema=external_exports.object({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,rows:external_exports.number().int().nonnegative(),selectionWords:external_exports.string(),listed:external_exports.array(RequestRowSchema).max(REQUEST_PREVIEW_ROWS_MAX),moreLine:external_exports.string(),problemsComplete:external_exports.boolean(),incompleteLine:external_exports.string()});var REVIEW_ACT_KINDS=["flag","comment","dismiss","request","correct","withdraw"],ReviewActKindSchema=external_exports.enum(REVIEW_ACT_KINDS),REVIEW_SEVERITIES=["blocking","warning"],ReviewSeveritySchema=external_exports.enum(REVIEW_SEVERITIES),MAX_REVIEW_SELECTION_RECORDS=500,MAX_REVIEW_SELECTION_FILTERS=20,MAX_REVIEW_ID_LENGTH=200,ReviewRecordRefSchema=external_exports.strictObject({logicalId:external_exports.string().min(1).max(MAX_REVIEW_ID_LENGTH),recordId:external_exports.string().min(1).max(MAX_REVIEW_ID_LENGTH)}),ReviewSelectionSchema=external_exports.discriminatedUnion("kind",[external_exports.strictObject({kind:external_exports.literal("records"),records:external_exports.array(ReviewRecordRefSchema).min(1).max(MAX_REVIEW_SELECTION_RECORDS)}),external_exports.strictObject({kind:external_exports.literal("filter"),filters:external_exports.array(DatasetReadFilterSchema).min(1).max(MAX_REVIEW_SELECTION_FILTERS)})]),RULE_FINDING_RESOLUTIONS=["correction"],RuleFindingResolutionSchema=external_exports.enum(RULE_FINDING_RESOLUTIONS),ReviewRuleFindingSchema=external_exports.strictObject({kind:external_exports.literal("rule-finding"),rulesetId:external_exports.string().min(1).max(255).optional(),rulesetVersion:external_exports.number().int().positive().optional(),ruleIndex:external_exports.number().int().nonnegative(),column:external_exports.string().min(1).max(255),resolvedBy:RuleFindingResolutionSchema.optional()}),ReviewRuleFindingInputSchema=ReviewRuleFindingSchema.required({rulesetId:!0,rulesetVersion:!0}),ReviewFlagFindingSchema=external_exports.strictObject({kind:external_exports.literal("flag"),flagActId:external_exports.string().min(1)}),ReviewFindingRefSchema=external_exports.discriminatedUnion("kind",[ReviewRuleFindingSchema,ReviewFlagFindingSchema]),ReviewFindingRefInputSchema=external_exports.discriminatedUnion("kind",[ReviewRuleFindingInputSchema,ReviewFlagFindingSchema]),REVIEW_TEXT_PATTERN=/^[^\0-\x08\x0B\x0C\x0E-\x1F\x7F-\x9F\p{Cs}]*$/u,REVIEW_TEXT_HINT="may not contain control characters other than a line break or a tab";var reviewText=max2=>external_exports.string().trim().min(1).max(max2).regex(REVIEW_TEXT_PATTERN,REVIEW_TEXT_HINT),MAX_REVIEW_BODY_LENGTH=4e3,ReviewBodySchema=reviewText(MAX_REVIEW_BODY_LENGTH),ReviewDimensionSchema=reviewText(80),ACT_BASE={datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,selection:ReviewSelectionSchema,idempotencyKey:IdempotencyKeySchema.max(200)},flagColumn=external_exports.string().min(1).max(255).regex(REVIEW_TEXT_PATTERN,REVIEW_TEXT_HINT),FlagRecordsInputSchema=external_exports.strictObject({...ACT_BASE,severity:ReviewSeveritySchema,dimension:ReviewDimensionSchema.optional(),column:flagColumn.optional(),body:ReviewBodySchema.optional()}),CommentRecordsInputSchema=external_exports.strictObject({...ACT_BASE,body:ReviewBodySchema}),DismissFindingInputSchema=external_exports.strictObject({...ACT_BASE,finding:ReviewFindingRefInputSchema,body:ReviewBodySchema.optional()}),REVIEW_REQUEST_CHANNELS=["notification","manual"],ReviewRequestChannelSchema=external_exports.enum(REVIEW_REQUEST_CHANNELS),RequestCorrectionInputSchema=external_exports.strictObject({...ACT_BASE,body:ReviewBodySchema,expected:reviewText(1e3).optional(),channel:ReviewRequestChannelSchema.optional()}),REVIEW_REQUEST_RESOLUTIONS=["pending","resolved"],ReviewRequestResolutionSchema=external_exports.enum(REVIEW_REQUEST_RESOLUTIONS),ReviewActSchema=external_exports.object({actId:external_exports.string().min(1),kind:ReviewActKindSchema,datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,selection:ReviewSelectionSchema,severity:ReviewSeveritySchema.optional(),dimension:external_exports.string().min(1).optional(),column:external_exports.string().min(1).optional(),finding:ReviewFindingRefSchema.optional(),body:external_exports.string().min(1).optional(),expected:external_exports.string().min(1).optional(),channel:ReviewRequestChannelSchema.optional(),correction:ReviewCorrectionSchema.optional(),matchedCount:external_exports.number().int().positive().optional(),withdraws:external_exports.string().min(1).optional(),withdrawn:external_exports.object({whole:external_exports.boolean(),logicalIds:external_exports.array(external_exports.string().min(1))}).optional(),request:RequestCorrectionDetailSchema.optional(),actor:external_exports.string().min(1),at:external_exports.iso.datetime(),receiptId:external_exports.string().min(1)}),ReviewActsInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema});var ReviewActsSchema=external_exports.object({acts:external_exports.array(ReviewActSchema),truncated:external_exports.boolean()}),RECORD_REVIEW_STATES=["fine","warning","blocking","at-source","check-again"],RecordReviewStateKindSchema=external_exports.enum(RECORD_REVIEW_STATES),CHANGES_SINCE_REVIEW=["unchanged","updated","deleted"],ChangeSinceReviewSchema=external_exports.enum(CHANGES_SINCE_REVIEW),SinceReviewSchema=external_exports.discriminatedUnion("state",[external_exports.object({state:external_exports.literal("current")}),external_exports.object({state:external_exports.literal("compared"),currentVersionId:DatasetVersionIdSchema}),external_exports.object({state:external_exports.literal("not-comparable"),currentVersionId:DatasetVersionIdSchema,reason:external_exports.enum(["unkeyed","unreadable"])})]),RecordReviewStateInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,logicalIds:external_exports.array(external_exports.string().min(1).max(MAX_REVIEW_ID_LENGTH)).min(1).max(MAX_REVIEW_SELECTION_RECORDS)}),RecordReviewEntrySchema=external_exports.object({logicalId:external_exports.string().min(1),state:RecordReviewStateKindSchema,openFlags:external_exports.array(external_exports.string().min(1)),requests:external_exports.array(external_exports.object({actId:external_exports.string().min(1),resolution:ReviewRequestResolutionSchema})),dismissedRuleFindings:external_exports.array(external_exports.object({rulesetId:external_exports.string().min(1),rulesetVersion:external_exports.number().int().positive(),ruleIndex:external_exports.number().int().nonnegative(),column:external_exports.string().min(1)})),thread:external_exports.array(external_exports.string().min(1)),changeSinceReview:ChangeSinceReviewSchema.nullable(),carriedFrom:external_exports.number().int().nonnegative().optional(),checkAgain:external_exports.array(external_exports.string().min(1)).optional(),earlier:external_exports.array(external_exports.object({actId:external_exports.string().min(1),delivery:external_exports.number().int().nonnegative(),outcome:external_exports.enum(["carried","reopened"])})).optional()}),CarryFailureSchema=external_exports.object({code:external_exports.string().min(1),message:external_exports.string(),attempts:external_exports.number().int().positive().optional()}),RecordReviewStateSchema=external_exports.object({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,records:external_exports.array(RecordReviewEntrySchema),acts:external_exports.array(ReviewActSchema),truncated:external_exports.boolean(),sinceReview:SinceReviewSchema,carryPending:external_exports.literal(!0).optional(),carryFailure:CarryFailureSchema.optional(),carryRetrying:CarryFailureSchema.optional()}),REVIEWED_RECORDS_FILTERS=["blocking","warning","at-source","needs-attention","check-again","carried"],ReviewedRecordsFilterSchema=external_exports.enum(REVIEWED_RECORDS_FILTERS),MAX_REVIEWED_RECORDS=1e4;var ReviewedRecordsInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,filter:ReviewedRecordsFilterSchema}),CHECKS_UNLISTED_REASONS=["not-stored","too-many-acts","version-unreadable","row-not-found"],ChecksUnlistedReasonSchema=external_exports.enum(CHECKS_UNLISTED_REASONS),ReviewedRecordsSchema=external_exports.object({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,filter:ReviewedRecordsFilterSchema,logicalIds:external_exports.array(external_exports.string().min(1)).max(MAX_REVIEWED_RECORDS),counts:external_exports.object({blocking:external_exports.number().int().nonnegative(),warning:external_exports.number().int().nonnegative(),atSource:external_exports.number().int().nonnegative(),checkAgain:external_exports.number().int().nonnegative().optional(),carried:external_exports.number().int().nonnegative().optional()}),carriedFrom:external_exports.array(external_exports.number().int().nonnegative()).optional(),carryPending:external_exports.literal(!0).optional(),carryFailure:CarryFailureSchema.optional(),carryRetrying:CarryFailureSchema.optional(),truncated:external_exports.boolean(),checksUnlisted:external_exports.array(ChecksUnlistedReasonSchema).min(1).optional()}),REVIEW_REASON_RULES=["blocking","always"],ReviewReasonRuleSchema=external_exports.enum(REVIEW_REASON_RULES);var ReviewSettingsSchema=external_exports.strictObject({labels:external_exports.strictObject({blocking:reviewText(40),warning:reviewText(40)}),dimensions:external_exports.array(ReviewDimensionSchema).max(50),dimensionRequired:external_exports.boolean(),reasonRequiredOnFlag:ReviewReasonRuleSchema,reasonRequiredOnDismissal:ReviewReasonRuleSchema});var ReviewSettingsInputSchema=external_exports.strictObject({}),SaveReviewSettingsInputSchema=external_exports.strictObject({settings:ReviewSettingsSchema,idempotencyKey:IdempotencyKeySchema.max(200)}),FILTER_SELECTION_SAMPLE_MAX=5,PreviewFilterSelectionInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,filters:external_exports.array(DatasetReadFilterSchema).min(1).max(MAX_REVIEW_SELECTION_FILTERS),withOpenChecks:external_exports.boolean().optional()}),OpenCheckOnColumnSchema=external_exports.object({rulesetId:external_exports.string().min(1),rulesetVersion:external_exports.number().int().positive(),ruleIndex:external_exports.number().int().nonnegative(),column:external_exports.string().min(1),rulesetNames:external_exports.array(external_exports.string()),rows:external_exports.number().int().positive()}),FilterSelectionPreviewSchema=external_exports.object({matched:external_exports.number().int().nonnegative(),sample:external_exports.array(external_exports.record(external_exports.string(),DatasetCellValueSchema)).max(FILTER_SELECTION_SAMPLE_MAX),openChecks:external_exports.array(OpenCheckOnColumnSchema).optional()}),PreviewRequestCorrectionInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,selection:ReviewSelectionSchema});var CORRECTION_MODES=["update","persist"],CorrectionModeSchema=external_exports.enum(CORRECTION_MODES),CorrectionSettingsSchema=external_exports.strictObject({mode:CorrectionModeSchema,notifyOnOverwrite:external_exports.boolean(),conflictSeverity:ReviewSeveritySchema});var CORRECTION_REAPPLY_STEPS=["bound","not-bound"],CorrectionSettingsInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema}),CorrectedCopyFailureSchema=external_exports.object({reason:external_exports.string().min(1),failedAt:external_exports.iso.datetime()}),CorrectionSettingsViewSchema=external_exports.object({datasetId:DatasetIdSchema,settings:CorrectionSettingsSchema,saved:external_exports.boolean(),reapplyStep:external_exports.enum(CORRECTION_REAPPLY_STEPS),correctedCopyFailure:CorrectedCopyFailureSchema.optional()}),RetryCorrectedCopyInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema,idempotencyKey:IdempotencyKeySchema.max(200)}),RetryCorrectedCopyResultSchema=external_exports.object({datasetId:DatasetIdSchema,retried:external_exports.boolean()}),SaveCorrectionSettingsInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema,settings:CorrectionSettingsSchema,idempotencyKey:IdempotencyKeySchema.max(200)}),CORRECTIONS_CURRENCY_STATES=["no-corrections","current","not-reapplied"],CorrectionsCurrencySchema=external_exports.object({datasetId:DatasetIdSchema,state:external_exports.enum(CORRECTIONS_CURRENCY_STATES),mode:CorrectionModeSchema,holdsReadiness:external_exports.boolean(),currentVersionId:external_exports.string().min(1).optional(),builtFromVersionId:external_exports.string().min(1).optional(),currentLoadNumber:external_exports.number().int().positive().optional(),builtFromLoadNumber:external_exports.number().int().positive().optional(),builtInMode:CorrectionModeSchema.optional(),raisedConflicts:external_exports.number().int().nonnegative()}),CorrectionsCurrencyInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema}),CORRECTION_CONFLICT_CASES=["adopted","overwritten-unchanged","overwritten-changed","conflict","absent"],CORRECTION_CONFLICT_SEVERITIES=["blocking","warning","none"];var FILTER_CONFLICT_SAMPLE_MAX=5,FILTER_RESOLUTIONS=["keep","use-delivered"],FilterResolutionSchema=external_exports.enum(FILTER_RESOLUTIONS),FilterResolvesSchema=external_exports.strictObject({actId:external_exports.string().min(1),deliveryVersionId:external_exports.string().min(1),resolution:FilterResolutionSchema}),FilterCorrectionSchema=external_exports.object({actId:external_exports.string().min(1),at:external_exports.iso.datetime(),column:external_exports.string().min(1).max(MAX_CORRECTION_COLUMN_LENGTH),change:CorrectionChangeSchema,filters:external_exports.array(DatasetReadFilterSchema).min(1),rowsVersionId:external_exports.string().min(1),baseVersionId:external_exports.string().min(1),onlyChanged:external_exports.boolean(),matched:external_exports.number().int().nonnegative()}),FilterConflictSampleSchema=external_exports.object({logicalId:external_exports.string().min(1),delivered:external_exports.string().nullable(),corrected:external_exports.string().nullable()}),FilterConflictGroupSchema=external_exports.object({actId:external_exports.string().min(1),deliveryVersionId:external_exports.string().min(1),case:external_exports.enum(CORRECTION_CONFLICT_CASES),severity:external_exports.enum(CORRECTION_CONFLICT_SEVERITIES),rows:external_exports.number().int().positive(),sample:external_exports.array(FilterConflictSampleSchema).max(FILTER_CONFLICT_SAMPLE_MAX)}),FILTER_SIT_OUT_REASONS=["rows-version-unreadable","value-unfit"],FilterAppliedSchema=external_exports.object({actId:external_exports.string().min(1),rows:external_exports.number().int().nonnegative(),unapplied:external_exports.number().int().nonnegative(),reasons:external_exports.record(external_exports.string(),external_exports.number().int().positive()).optional(),later:external_exports.number().int().positive().optional(),sitOut:external_exports.enum(FILTER_SIT_OUT_REASONS).optional()});var FILTER_CORRECTION_STATES=["staged","applied","undone"],StagedFilterCorrectionSchema=external_exports.object({actId:external_exports.string().min(1),column:external_exports.string().min(1),change:CorrectionChangeSchema,filters:external_exports.array(DatasetReadFilterSchema).min(1),versionId:external_exports.string().min(1),matched:external_exports.number().int().nonnegative(),actor:external_exports.string().min(1),at:external_exports.iso.datetime(),reason:external_exports.string().min(1),state:external_exports.enum(FILTER_CORRECTION_STATES),resolves:FilterResolvesSchema.optional(),undoneBy:external_exports.string().min(1).optional(),undoTaken:external_exports.literal(!0).optional(),applied:FilterAppliedSchema.optional(),groups:external_exports.array(FilterConflictGroupSchema)});var CorrectRecordsInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,selection:ReviewSelectionSchema,column:external_exports.string().min(1).max(MAX_CORRECTION_COLUMN_LENGTH),change:CorrectionChangeSchema,from:external_exports.array(CorrectionFromSchema).min(1).max(500).optional(),undoes:external_exports.string().min(1).max(200).optional(),resolves:FilterResolvesSchema.optional(),confirmCount:external_exports.number().int().positive().optional(),resolveChecks:external_exports.boolean().optional(),body:ReviewBodySchema,idempotencyKey:IdempotencyKeySchema.max(200)}),ResolvedCheckSchema=external_exports.object({rulesetId:external_exports.string().min(1),rulesetVersion:external_exports.number().int().positive(),ruleIndex:external_exports.number().int().nonnegative(),column:external_exports.string().min(1),rows:external_exports.number().int().nonnegative(),act:ReviewActSchema}),CorrectRecordsResultSchema=ReviewActSchema.extend({resolvedChecks:external_exports.array(ResolvedCheckSchema).optional()}),STAGED_CORRECTION_STATES=["staged","applied","conflict","superseded","adopted","stale"],StagedCorrectionStateSchema=external_exports.enum(STAGED_CORRECTION_STATES),CORRECTION_UNAPPLIED_REASONS=["row-absent","from-mismatch","not-numeric","column-absent","unrepresentable","value-unfit"],CorrectionUnappliedReasonSchema=external_exports.enum(CORRECTION_UNAPPLIED_REASONS),CorrectionFindingSchema=external_exports.object({case:external_exports.enum(CORRECTION_CONFLICT_CASES),severity:external_exports.enum(CORRECTION_CONFLICT_SEVERITIES),delivered:external_exports.string().nullable(),corrected:external_exports.string().nullable()}),StagedCorrectionSchema=external_exports.object({logicalId:external_exports.string().min(1),recordId:external_exports.string().min(1),column:external_exports.string().min(1),change:CorrectionChangeSchema,from:DatasetCellValueSchema,actId:external_exports.string().min(1),versionId:DatasetVersionIdSchema,actor:external_exports.string().min(1),at:external_exports.iso.datetime(),reason:external_exports.string().min(1),state:StagedCorrectionStateSchema,finding:CorrectionFindingSchema.optional(),gone:external_exports.enum(["row","column"]).optional(),keptOver:external_exports.array(external_exports.string().min(1)).optional(),supersededBy:external_exports.string().min(1).optional(),unappliedReason:CorrectionUnappliedReasonSchema.optional(),heldByFilter:external_exports.string().min(1).optional()}),CORRECTION_APPLY_STATUSES=["in-flight","committed","failed"],LastCorrectionApplySchema=external_exports.object({applyRecordId:external_exports.string().min(1),status:external_exports.enum(CORRECTION_APPLY_STATUSES),sourceVersionId:external_exports.string().min(1),at:external_exports.iso.datetime(),sourceLoadNumber:external_exports.number().int().positive().optional(),correctedVersionId:external_exports.string().min(1).optional(),correctionsVersionId:external_exports.string().min(1).optional(),conflictsVersionId:external_exports.string().min(1).optional(),detail:external_exports.string().optional(),code:external_exports.string().min(1).optional(),job:external_exports.enum(["queued","landing"]).optional(),correctionCount:external_exports.number().int().nonnegative().optional(),corrections:external_exports.number().int().nonnegative().optional(),reason:external_exports.string().min(1).optional(),link:external_exports.object({url:external_exports.string().min(1),title:external_exports.string().min(1)}).optional()}),StagedCorrectionsInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema}),CORRECTION_OUTPUT_LABELS=["corrections","corrected","conflicts"],CorrectionOutputInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema}),CorrectionOutputSchema=external_exports.object({source:external_exports.object({datasetId:DatasetIdSchema,name:external_exports.string().min(1),output:external_exports.enum(CORRECTION_OUTPUT_LABELS),builtFrom:external_exports.object({versionId:external_exports.string().min(1),loadNumber:external_exports.number().int().positive()}).optional(),sourceCurrent:external_exports.object({versionId:external_exports.string().min(1),loadNumber:external_exports.number().int().positive()}).optional(),corrections:external_exports.number().int().nonnegative().optional(),currentApply:external_exports.object({applyRecordId:external_exports.string().min(1),status:external_exports.enum(CORRECTION_APPLY_STATUSES),at:external_exports.iso.datetime()}).optional()}).optional()}),CORRECTED_ROWS_MAX=1e3,CorrectedRowsInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,logicalIds:external_exports.array(external_exports.string().min(1).max(200)).max(CORRECTED_ROWS_MAX)}),CORRECTED_ROWS_UNAVAILABLE_REASONS=["no-corrected-dataset","apply-not-committed","unreadable"],CORRECTED_ROW_STATES=["in-corrected","left-out","not-yet"],CorrectedRowsSchema=external_exports.discriminatedUnion("state",[external_exports.object({state:external_exports.literal("aligned"),correctedDatasetId:DatasetIdSchema,correctedName:external_exports.string().min(1),correctedVersionId:DatasetVersionIdSchema,builtFrom:external_exports.object({versionId:DatasetVersionIdSchema,loadNumber:external_exports.number().int().positive()}),keyFields:external_exports.array(external_exports.string().min(1)).min(1),rows:external_exports.array(external_exports.object({logicalId:external_exports.string().min(1),state:external_exports.enum(CORRECTED_ROW_STATES),changed:external_exports.record(external_exports.string(),external_exports.object({value:external_exports.string().nullable(),delivered:external_exports.string().nullable()})),reason:external_exports.string().min(1).optional(),reasonSource:external_exports.enum(["correction","apply"]).optional(),moreReasons:external_exports.number().int().nonnegative().optional()})),repeated:external_exports.array(external_exports.string().min(1))}),external_exports.object({state:external_exports.literal("unavailable"),reason:external_exports.enum(CORRECTED_ROWS_UNAVAILABLE_REASONS),message:external_exports.string().min(1).optional()})]);var APPLY_IN_FLIGHT_HOLD_MS=3600*1e3,StagedCorrectionsSchema=external_exports.object({datasetId:DatasetIdSchema,cells:external_exports.array(StagedCorrectionSchema),pending:external_exports.number().int().nonnegative(),undosPending:external_exports.number().int().nonnegative().default(0),correctedDatasetId:external_exports.string().min(1).optional(),correctedName:external_exports.string().min(1).optional(),correctedArchived:external_exports.literal(!0).optional(),correctionsDatasetId:external_exports.string().min(1).optional(),conflictsDatasetId:external_exports.string().min(1).optional(),lastApply:LastCorrectionApplySchema.optional(),lastAttempt:LastCorrectionApplySchema.optional(),outputsBehind:external_exports.boolean(),raisedConflicts:external_exports.number().int().nonnegative(),truncated:external_exports.boolean(),filterCorrections:external_exports.array(StagedFilterCorrectionSchema).default([])}),ApplyCorrectionsKeySchema=IdempotencyKeySchema.max(200).describe("Client-minted replay key for an Apply of corrections \u2014 REQUIRED. Mint ONE per Apply (a UUID is fine) and reuse it only to re-send that Apply. Once it has COMPLETED, reusing the key returns its receipt without landing anything again; a call REFUSED before its Record opened consumed nothing. An Apply opens and seals across two transactions, so a key whose Apply is still in flight is refused CONFLICT (CORRECTIONS_IN_FLIGHT) rather than starting a second; re-sent while in flight, the server compares the request with what the receipt holds \u2014 the raw version and every correction it carried \u2014 and refuses CONFLICT (CORRECTIONS_KEY_INPUT_MISMATCH) on any difference. CORRECTIONS_IN_FLIGHT carries the receipt id (data.applyRecordId), so a caller that lost the answer can poll stagedCorrections. A COMPLETED key answers its receipt whatever was staged since: corrections staged since need a new key. An Apply that RAN and sealed FAILED freed its key, so re-sending it starts a second Apply."),APPLY_LINK_URL=/^https?:\/\/\S+$/i,ApplyLinkSchema=external_exports.strictObject({url:external_exports.string().trim().min(1).max(2e3).regex(APPLY_LINK_URL,"a link must start with http:// or https://"),title:external_exports.string().trim().min(1).max(200).optional()}),ApplyCorrectionsInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,link:ApplyLinkSchema.optional(),idempotencyKey:ApplyCorrectionsKeySchema});var ApplyCorrectionsAcceptedSchema=external_exports.object({applyRecordId:external_exports.string().min(1)}),AppliedCorrectionSchema=external_exports.object({actId:external_exports.string().min(1),logicalId:external_exports.string().min(1),recordId:external_exports.string().min(1),column:external_exports.string().min(1),change:CorrectionChangeSchema,from:DatasetCellValueSchema,versionId:external_exports.string().min(1)}),RetiredCorrectionSchema=external_exports.object({actId:external_exports.string().min(1),logicalId:external_exports.string().min(1),column:external_exports.string().min(1)});var SEED_CORRECTED_COPY_FAULT_VERB="seedCorrectedCopyFault",SEED_CORRECTED_COPY_FAULT_ACTION_NAME=`datasets.${SEED_CORRECTED_COPY_FAULT_VERB}`;var CorrectionApplyTriggerSchema=external_exports.object({kind:external_exports.literal("automatic-reapply"),deliveryVersionId:external_exports.string().min(1),deliveryLoadNumber:external_exports.number().int().nonnegative(),reapplyId:external_exports.string().min(1)}),ApplyCorrectionsRecordParamsSchema=external_exports.object({datasetId:external_exports.string().min(1),sourceVersionId:external_exports.string().min(1),reason:external_exports.string().min(1),citations:external_exports.array(CitationSchema),trigger:CorrectionApplyTriggerSchema.optional(),keyFields:external_exports.array(external_exports.string().min(1)).min(1),settings:CorrectionSettingsSchema,corrections:external_exports.array(AppliedCorrectionSchema),retired:external_exports.array(RetiredCorrectionSchema).optional(),retiredBefore:external_exports.iso.datetime().optional(),raised:external_exports.array(RetiredCorrectionSchema.extend(CorrectionFindingSchema.shape)).optional(),filterCorrections:external_exports.array(FilterCorrectionSchema).optional(),filterRetired:external_exports.array(external_exports.string().min(1)).optional()});var DatasetSortFieldSchema=external_exports.enum(["name","kind","updatedAt","rowCount","category"]),DatasetSortDirectionSchema=external_exports.enum(["asc","desc"]),DatasetOrderBySchema=external_exports.object({field:DatasetSortFieldSchema,direction:DatasetSortDirectionSchema}),DATASET_CATALOG_MAX_LIMIT=200;var DATASET_OWNER_FILTER_MAX=50,DATASET_OWNER_FILTER_NAME_MAX=100,DATASET_SEARCH_MAX=200,DATASET_NAME_CONTAINS_MAX=DATASET_SEARCH_MAX,SearchTermSchema=external_exports.string().min(1).max(DATASET_SEARCH_MAX).regex(/^[^\p{Cc}]*$/u,{message:"Search cannot hold control characters."}),DATASET_KEYWORD_FILTER_MAX=50;var DATASET_THEME_FILTER_MAX=50,DATASET_ID_FILTER_MAX=1e3,DATASET_NARROWING_MARKS_MAX=16,DatasetNarrowingSchemeSchema=external_exports.string().regex(/^[a-z][a-z0-9-]*\.[a-z][a-z0-9-]*$/).max(64),DatasetNarrowingMarkSchema=external_exports.string().regex(/^[a-z0-9][a-z0-9:._-]*$/).max(64),DatasetNarrowedBySchema=external_exports.strictObject({scheme:DatasetNarrowingSchemeSchema,anyOf:external_exports.array(DatasetNarrowingMarkSchema).max(DATASET_NARROWING_MARKS_MAX).optional(),noneOf:external_exports.array(DatasetNarrowingMarkSchema).max(DATASET_NARROWING_MARKS_MAX).optional()});var DatasetPromotionSchema=external_exports.enum(["promoted","unpromoted"]);var DatasetTimeCoveredFilterSchema=external_exports.strictObject({start:external_exports.iso.datetime({offset:!0}).optional(),end:external_exports.iso.datetime({offset:!0}).optional()}).refine(window=>window.start!==void 0||window.end!==void 0,"timeCovered cannot be open at both ends").refine(window=>window.start===void 0||window.end===void 0||Date.parse(window.start)<=Date.parse(window.end),"timeCovered ends before it starts"),ListDatasetsInputSchema=external_exports.strictObject({get kind(){return external_exports.array(DatasetKindSchema).max(DatasetKindSchema.options.length).optional()},status:external_exports.array(DatasetStatusSchema).max(DatasetStatusSchema.options.length).optional(),maturity:external_exports.array(DatasetMaturitySchema).max(DatasetMaturitySchema.options.length).optional(),ownerDomain:external_exports.array(external_exports.string().min(1).max(DATASET_OWNER_FILTER_NAME_MAX)).max(DATASET_OWNER_FILTER_MAX).optional(),promotion:DatasetPromotionSchema.optional(),get grain(){return external_exports.array(DatasetGrainSchema).max(DatasetGrainSchema.options.length).optional()},keyword:external_exports.array(external_exports.string().min(1).max(DATASET_KEYWORD_MAX_LENGTH)).max(DATASET_KEYWORD_FILTER_MAX).optional(),theme:external_exports.array(external_exports.string().regex(CATALOG_CONCEPT_REF_PATTERN,"a theme is 'scheme/slug'")).max(DATASET_THEME_FILTER_MAX).optional(),get timeCovered(){return DatasetTimeCoveredFilterSchema.optional()},search:SearchTermSchema.optional(),nameContains:SearchTermSchema.max(DATASET_NAME_CONTAINS_MAX).optional().describe("DEPRECATED \u2014 use `search` instead; this name is kept for one release. It is now an ALIAS of `search` rather than its old behaviour: it matches the dataset LABEL, DESCRIPTION and KEYWORDS as well as the NAME, so the same ask can only return MORE rows than it used to, never fewer. Sending both is not an error \u2014 they are OR'd."),provenance:DatasetProvenanceSchema.optional(),datasetIds:external_exports.array(external_exports.uuid()).max(DATASET_ID_FILTER_MAX).optional(),narrowedBy:DatasetNarrowedBySchema.optional(),includeArchived:external_exports.boolean().optional(),orderBy:DatasetOrderBySchema.optional(),offset:external_exports.number().int().min(0).optional(),limit:external_exports.number().int().min(1).max(DATASET_CATALOG_MAX_LIMIT).optional()}),DatasetSummarySchema=external_exports.object({get datasetId(){return DatasetIdSchema},name:external_exports.string().min(1),label:external_exports.string().min(1).optional(),createdAt:external_exports.iso.datetime().optional(),get kind(){return DatasetKindSchema},status:DatasetStatusSchema,maturity:DatasetMaturitySchema,get slug(){return DatasetSlugSchema},ownerDomain:external_exports.string().min(1).optional(),category:external_exports.string().min(1).optional(),dataOwner:external_exports.string().min(1).optional(),openIssues:external_exports.number().int().nonnegative().optional(),producedByRecordId:external_exports.string().min(1).optional(),description:external_exports.string().min(1).optional(),notes:external_exports.string().min(1).optional(),keywords:external_exports.array(external_exports.string().min(1)).optional(),themes:external_exports.array(external_exports.string().min(1)).optional(),get grain(){return DatasetGrainSchema.optional()},get timeCovered(){return DatasetTimeCoveredReadSchema.optional()},get tableRole(){return DatasetTableRoleSchema.optional()},get currentVersionId(){return DatasetVersionIdSchema.optional()},rowCount:external_exports.number().int().nonnegative().optional(),updatedAt:external_exports.iso.datetime().optional(),promoted:external_exports.boolean(),hasPromotedVersion:external_exports.boolean().optional(),provenance:DatasetProvenanceSchema,get replacedBy(){return DatasetReplacedBySchema.optional()},get correctionOf(){return external_exports.object({datasetId:DatasetIdSchema,name:external_exports.string().min(1),output:external_exports.enum(CORRECTION_OUTPUT_LABELS),status:DatasetStatusSchema.optional()}).optional()},get bundle(){return external_exports.object({correctedDatasetId:DatasetIdSchema,correctionsDatasetId:DatasetIdSchema.optional(),conflictsDatasetId:DatasetIdSchema.optional(),notYetReviewed:external_exports.boolean()}).optional()},correctedUnavailable:external_exports.enum(["archived","gone"]).optional(),held:external_exports.boolean().optional()}).describe("One dataset as the catalog and `datasets.list` report it: identity (`datasetId`, and `versionId` is deliberately absent \u2014 a summary describes the CURRENT load, so pin a load by building a `DatasetRef` yourself) plus the current load's size and state. PROMOTE-BEFORE-CONSUME gates governed CONSUMPTION, not reading: `datasets.read` and composition validation resolve an unpromoted version by design, so a successful read proves nothing about promotion. What refuses one is a governed consumer that turns dataset rows into domain state \u2014 `assets.composition.createMany` and the source-transformation inputs. The pipeline is land \u2192 promote \u2192 consume, and `promoted` here is that gate's answer for the current load. `rowCount` is ABSENT when nothing has landed and for every `live` dataset (a live version pins a definition, not rows) \u2014 absent means \"no size is knowable here\", never zero."),DatasetCatalogPageSchema=external_exports.object({items:external_exports.array(DatasetSummarySchema),total:external_exports.number().int().nonnegative(),nextCursor:external_exports.string().min(1).nullable()}),DatasetFacetBucketSchema=external_exports.object({value:external_exports.string().min(1),count:external_exports.number().int().nonnegative()}),DatasetFacetsSchema=external_exports.object({total:external_exports.number().int().nonnegative(),byKind:external_exports.array(DatasetFacetBucketSchema),byStatus:external_exports.array(DatasetFacetBucketSchema),byMaturity:external_exports.array(DatasetFacetBucketSchema),byOwnerDomain:external_exports.array(DatasetFacetBucketSchema),byPromotion:external_exports.array(DatasetFacetBucketSchema),byGrain:external_exports.array(DatasetFacetBucketSchema),byKeyword:external_exports.array(DatasetFacetBucketSchema),byTheme:external_exports.array(DatasetFacetBucketSchema)});var DATASET_USES_MAX_DATASETS=20,DatasetUseDatasetSchema=external_exports.object({datasetId:external_exports.string().min(1),name:external_exports.string().min(1)}),ListedDatasetSchema=DatasetUseDatasetSchema.extend({correctedDatasetId:external_exports.string().min(1).optional()}),ListDatasetUsesInputSchema=external_exports.object({datasets:external_exports.array(ListedDatasetSchema).min(1).max(DATASET_USES_MAX_DATASETS)}),DatasetUseReadsVersionSchema=external_exports.discriminatedUnion("mode",[external_exports.object({mode:external_exports.literal("follow")}),external_exports.object({mode:external_exports.literal("pinned"),versionId:external_exports.string().min(1)}),external_exports.object({mode:external_exports.literal("current")})]),DatasetUseStateSchema=external_exports.discriminatedUnion("status",[external_exports.object({status:external_exports.literal("generating"),versionId:external_exports.string().min(1),version:external_exports.number().int().min(1)}),external_exports.object({status:external_exports.literal("failed"),versionId:external_exports.string().min(1),version:external_exports.number().int().min(1),failure:external_exports.object({message:external_exports.string().min(1),nextStep:external_exports.enum(["retry","narrow-inputs","fix-template","fix-dataset","contact-support"])})})]),DatasetUseSchema=external_exports.object({useId:external_exports.string().min(1),datasetId:external_exports.string().min(1),kind:external_exports.string().min(1),name:external_exports.string().min(1),where:external_exports.array(external_exports.string().min(1)),href:external_exports.string().regex(/^\/(?!\/)/).optional(),canSwitch:external_exports.boolean(),cannotSwitchReason:external_exports.string().min(1).optional(),note:external_exports.string().min(1).optional(),readsVersion:DatasetUseReadsVersionSchema.optional(),readsKeys:external_exports.array(external_exports.string().min(1)).optional(),state:DatasetUseStateSchema.optional()}),ListDatasetUsesOutputSchema=external_exports.object({uses:external_exports.array(DatasetUseSchema)}),SwitchDatasetUseInputSchema=external_exports.object({useId:external_exports.string().min(1),from:DatasetUseDatasetSchema,to:DatasetUseDatasetSchema,idempotencyKey:external_exports.string().min(1).max(200).describe("Client-minted replay key for this governed write \u2014 the switch runs the owning domain's own revise under it. Mint ONE key per (item, from, to) and reuse it on every retry: a retry after a lost answer replays what the first attempt answered (a report whose switch is generating answers `switching` for the same version again), and an item that already reads `to` answers `switched` without changing anything.")}),SwitchDatasetUseResultSchema=external_exports.discriminatedUnion("outcome",[external_exports.object({useId:external_exports.string().min(1),outcome:external_exports.enum(["switched","left-as-draft"]),message:external_exports.string().min(1)}),external_exports.object({useId:external_exports.string().min(1),outcome:external_exports.literal("switching"),message:external_exports.string().min(1),versionId:external_exports.string().min(1),version:external_exports.number().int().min(1)})]);var ViewScopeSchema=external_exports.enum(["assets-list","datasets-list","events-list","scenarios-list","work-list","scenarios-workbench"]),SavedViewIdSchema=external_exports.string().min(1).brand(),SAVED_VIEW_NAME_MAX=100,VIEW_COLUMNS_MAX=100;function createViewPreferenceShapes(config2){let ScopeSchema2=external_exports.literal(config2.scope),SavedViewSchema3=external_exports.object({id:SavedViewIdSchema,scope:ScopeSchema2,name:external_exports.string().min(1).max(SAVED_VIEW_NAME_MAX),payload:config2.view,createdAt:external_exports.iso.datetime(),updatedAt:external_exports.iso.datetime()}),TablePreferencesSchema3=external_exports.object({scope:ScopeSchema2,preferences:config2.preferences,createdAt:external_exports.iso.datetime(),updatedAt:external_exports.iso.datetime()});return{ScopeSchema:ScopeSchema2,SavedViewSchema:SavedViewSchema3,TablePreferencesSchema:TablePreferencesSchema3,CreateSavedViewInputSchema:external_exports.strictObject({scope:ScopeSchema2,name:external_exports.string().min(1).max(SAVED_VIEW_NAME_MAX),payload:config2.view}),UpdateSavedViewInputSchema:external_exports.strictObject({id:SavedViewIdSchema,name:external_exports.string().min(1).max(SAVED_VIEW_NAME_MAX).optional(),payload:config2.view.optional()}),ListSavedViewsInputSchema:external_exports.strictObject({scope:ScopeSchema2}),DeleteSavedViewInputSchema:external_exports.strictObject({id:SavedViewIdSchema}),GetTablePreferencesInputSchema:external_exports.strictObject({scope:ScopeSchema2}),SetTablePreferencesInputSchema:external_exports.strictObject({scope:ScopeSchema2,preferences:config2.preferences})}}var DATASETS_LIST_VIEW_SCOPE="datasets-list",DatasetsListViewFiltersSchema=external_exports.looseObject({get kind(){return external_exports.array(DatasetKindSchema).max(DatasetKindSchema.options.length).optional()},status:external_exports.array(DatasetStatusSchema).max(DatasetStatusSchema.options.length).optional(),maturity:external_exports.array(DatasetMaturitySchema).max(DatasetMaturitySchema.options.length).optional(),ownerDomain:external_exports.array(external_exports.string().min(1).max(DATASET_OWNER_FILTER_NAME_MAX)).max(DATASET_OWNER_FILTER_MAX).optional(),promotion:DatasetPromotionSchema.optional(),search:external_exports.string().min(1).max(DATASET_SEARCH_MAX).optional(),nameContains:external_exports.string().min(1).max(DATASET_NAME_CONTAINS_MAX).optional().describe("DEPRECATED \u2014 use `search` instead; this name is kept for one release. It is now an ALIAS of `search` rather than its old behaviour: it matches the dataset DESCRIPTION and KEYWORDS as well as the NAME, so the same ask can only return MORE rows than it used to, never fewer. Sending both is not an error \u2014 they are OR'd."),get grain(){return external_exports.array(DatasetGrainSchema).max(DatasetGrainSchema.options.length).optional()},keyword:external_exports.array(external_exports.string().min(1).max(DATASET_KEYWORD_MAX_LENGTH)).max(DATASET_KEYWORD_FILTER_MAX).optional(),theme:external_exports.array(external_exports.string().regex(CATALOG_CONCEPT_REF_PATTERN,"a theme is 'scheme/slug'")).max(DATASET_THEME_FILTER_MAX).optional(),get timeCovered(){return DatasetTimeCoveredFilterSchema.optional()},includeArchived:external_exports.boolean().optional()}),DatasetsListViewSchema=external_exports.looseObject({filters:DatasetsListViewFiltersSchema.optional(),orderBy:DatasetOrderBySchema.optional(),columns:external_exports.array(external_exports.string().min(1)).max(VIEW_COLUMNS_MAX).optional()}),DatasetsTablePreferencesSchema=external_exports.looseObject({columns:external_exports.array(external_exports.string().min(1)).max(VIEW_COLUMNS_MAX).optional(),pageSize:external_exports.number().int().min(1).max(DATASET_CATALOG_MAX_LIMIT).optional()}),datasetsViewShapes=createViewPreferenceShapes({scope:DATASETS_LIST_VIEW_SCOPE,view:DatasetsListViewSchema,preferences:DatasetsTablePreferencesSchema}),SavedViewSchema=datasetsViewShapes.SavedViewSchema,CreateSavedViewInputSchema=datasetsViewShapes.CreateSavedViewInputSchema,UpdateSavedViewInputSchema=datasetsViewShapes.UpdateSavedViewInputSchema,ListSavedViewsInputSchema=datasetsViewShapes.ListSavedViewsInputSchema,DeleteSavedViewInputSchema=datasetsViewShapes.DeleteSavedViewInputSchema,GetTablePreferencesInputSchema=datasetsViewShapes.GetTablePreferencesInputSchema,SetTablePreferencesInputSchema=datasetsViewShapes.SetTablePreferencesInputSchema,TablePreferencesSchema=datasetsViewShapes.TablePreferencesSchema;var DATASET_CATEGORY_MAX_LENGTH=80,DATASET_DATA_OWNER_MAX_LENGTH=200,DatasetCategorySchema=external_exports.string().trim().min(1).max(DATASET_CATEGORY_MAX_LENGTH).regex(NO_CONTROL_CHARACTERS,{message:"A category cannot hold control characters."}).regex(SHOWS_SOMETHING,{message:"A category needs at least one character that shows."}).describe('The group the Datasets page lists this dataset under, e.g. "Emissions factors". Free text; a dataset with none is listed as Uncategorised.'),DatasetDataOwnerSchema=external_exports.string().trim().min(1).max(DATASET_DATA_OWNER_MAX_LENGTH).regex(NO_CONTROL_CHARACTERS,{message:"A member id cannot hold control characters."}).describe("The user id of the tenant member who is this dataset\u2019s data owner \u2014 the person its questions are sent to. Not the publishing module (`ownerDomain`)."),SetDatasetCatalogDetailsInputSchema=external_exports.strictObject({datasetId:external_exports.string().min(1),category:DatasetCategorySchema.nullable().optional(),dataOwner:DatasetDataOwnerSchema.nullable().optional(),reason:DatasetLifecycleReasonSchema.optional(),idempotencyKey:IdempotencyKeySchema});var SetDatasetColumnEntitiesInputSchema=external_exports.strictObject({datasetId:external_exports.string().min(1),columnEntities:DatasetColumnEntitiesPatchSchema,reason:DatasetLifecycleReasonSchema.optional(),idempotencyKey:IdempotencyKeySchema});var TENANT_LAKEHOUSES=["dedicated","shared","hybrid"],TenantLakehouseSchema=external_exports.enum(TENANT_LAKEHOUSES);var TenantLakehouseViewSchema=external_exports.object({lakehouse:TenantLakehouseSchema,hasConnectedLake:external_exports.boolean(),hasLegacyData:external_exports.boolean()});var DatasetsPromotedDetailSchema=external_exports.strictObject({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema});var REFERENCE_TABLE_SUBJECT_TYPE="reference-table",OBSERVE_REFERENCE_VERSION_VERB="observeReferenceVersion",OBSERVE_REFERENCE_VERSION_ACTION_NAME=`datasets.${OBSERVE_REFERENCE_VERSION_VERB}`;var HoldsSchema=external_exports.strictObject({holds:external_exports.boolean()}),ReferenceVersionFactsSchema=external_exports.strictObject({datesAbut:HoldsSchema,coverageKept:HoldsSchema,unitsKnown:HoldsSchema,saveSealed:HoldsSchema}),REFERENCE_APPROVAL_SETUPS=["covered","none"],ReferenceApprovalSetupSchema=external_exports.enum(REFERENCE_APPROVAL_SETUPS),ReferenceVersionFactDetailSchema=external_exports.object({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,facts:ReferenceVersionFactsSchema,clean:external_exports.boolean(),approval:ReferenceApprovalSetupSchema}),StepKeySchema=IdempotencyKeySchema.max(512),AssertReferenceVersionSignableInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema,idempotencyKey:StepKeySchema,requires:external_exports.array(external_exports.string().max(ENTITY_REF_MAX_IDENTITY_CHARS)).max(16).optional(),factRecordId:external_exports.uuid().max(ENTITY_REF_MAX_IDENTITY_CHARS).optional()}),ReferenceVersionSignableSchema=external_exports.object({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,facts:ReferenceVersionFactsSchema}),ActivateReferenceVersionInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema.optional(),idempotencyKey:StepKeySchema}),ReferenceVersionInUseSchema=external_exports.object({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,changed:external_exports.boolean(),held:external_exports.object({reason:external_exports.string().min(1).optional(),message:external_exports.string().min(1)}).optional()}),REFERENCE_VERSION_APPROVED_IN_APPROVALS="REFERENCE_VERSION_APPROVED_IN_APPROVALS",REFERENCE_VERSION_NOT_SIGNABLE="REFERENCE_VERSION_NOT_SIGNABLE",REFERENCE_VERSION_SUPERSEDED="REFERENCE_VERSION_SUPERSEDED";var REFERENCE_SAVE_STAGES=["checking-approval-setup","sent-for-approval","ready-to-send","approved","approved-outside-sign-off","rejected","withdrawn","approval-status-unknown","in-use","not-sent"],ReferenceSaveStageSchema=external_exports.enum(REFERENCE_SAVE_STAGES),REFERENCE_NOT_SENT_REASONS=["saver-cannot-save","approval-set-up-since","saved-before-approval"],ReferenceNotSentSchema=external_exports.object({reason:external_exports.enum(REFERENCE_NOT_SENT_REASONS),saver:external_exports.string().min(1),at:external_exports.iso.datetime()});var ReferenceCitationSchema=external_exports.object({title:external_exports.string().trim().min(1).max(300),url:external_exports.string().trim().min(1).max(2e3)}),REFERENCE_CITATIONS_MAX=20,ReferenceGovernanceSchema=external_exports.strictObject({authority:external_exports.string().trim().min(1).max(200).optional(),citations:external_exports.array(ReferenceCitationSchema).max(REFERENCE_CITATIONS_MAX).default([]),authorityEdition:external_exports.string().trim().min(1).max(100).optional(),notes:external_exports.string().trim().min(1).max(4e3).optional()});var REFERENCE_EDIT_ROWS_MAX=1e4,REFERENCE_EDIT_COLUMNS_MAX=100,ReferenceColumnSchema=external_exports.object({name:external_exports.string().trim().min(1).max(128),type:external_exports.enum(["text","number"])}),REFERENCE_CHANGE_TYPES=["new-edition","publisher-errata","local-correction"],ReferenceChangeTypeSchema=external_exports.enum(REFERENCE_CHANGE_TYPES),ReferenceCellSchema=external_exports.union([external_exports.string().max(4e3),external_exports.number(),external_exports.null()]),ReferenceEditRowSchema=external_exports.record(external_exports.string(),ReferenceCellSchema),SaveCommonShape={columns:external_exports.array(ReferenceColumnSchema).min(1).max(REFERENCE_EDIT_COLUMNS_MAX),rows:external_exports.array(ReferenceEditRowSchema).max(REFERENCE_EDIT_ROWS_MAX),reason:external_exports.string().trim().min(1).max(500),idempotencyKey:IdempotencyKeySchema.max(200)},SaveReferenceVersionInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema,baseVersionId:DatasetVersionIdSchema,authorityEdition:ReferenceGovernanceSchema.shape.authorityEdition,changeType:ReferenceChangeTypeSchema,...SaveCommonShape}),CreateReferenceTableInputSchema=external_exports.strictObject({name:external_exports.string().trim().min(1).max(200),keyFields:external_exports.array(external_exports.string().trim().min(1).max(128)).min(1).max(10),source:ReferenceGovernanceSchema.optional(),...SaveCommonShape}),SaveReferenceVersionAcceptedSchema=external_exports.object({saveRecordId:external_exports.string().min(1),datasetId:DatasetIdSchema.optional()}),REFERENCE_SAVE_FAILURE_CODES=["REFERENCE_BASE_MOVED","REFERENCE_SAVE_NOT_SAVABLE","REFERENCE_SAVE_UNCHANGED","REFERENCE_SAVE_SUPERSEDED","LAND_NAME_TAKEN","REFERENCE_SAVE_ABANDONED","REFERENCE_SAVE_FAILED"];var ReferenceSaveStatusInputSchema=external_exports.strictObject({saveRecordId:external_exports.string().min(1).max(ENTITY_REF_MAX_IDENTITY_CHARS)}),ReferenceSaveStatusSchema=external_exports.object({saveRecordId:external_exports.string().min(1),state:external_exports.enum(["saving","saved","failed"]),stage:ReferenceSaveStageSchema.optional(),notSent:ReferenceNotSentSchema.optional(),rejectedReason:external_exports.string().min(1).optional(),datasetId:DatasetIdSchema.optional(),versionId:DatasetVersionIdSchema.optional(),code:external_exports.enum(REFERENCE_SAVE_FAILURE_CODES).optional(),message:external_exports.string().min(1).optional()});var DatasetVersionSchema=external_exports.object({versionId:DatasetVersionIdSchema,datasetId:DatasetIdSchema,loadNumber:external_exports.number().int().positive(),rowCount:external_exports.number().int().nonnegative().optional(),loadedAt:external_exports.string().min(1),promotedAt:external_exports.iso.datetime().nullable(),completedAt:external_exports.iso.datetime().nullable().optional(),asOf:external_exports.iso.datetime().optional(),producedByRecordId:external_exports.string().min(1).optional(),save:external_exports.object({by:external_exports.string().min(1),reason:external_exports.string().min(1),changeType:ReferenceChangeTypeSchema.optional()}).optional(),governance:ReferenceGovernanceSchema.optional()}),ListDatasetVersionsInputSchema=DatasetRefSchema.extend({completeOnly:external_exports.boolean().optional().describe("true lists only loads that finished landing (`completedAt` set), plus the dataset\u2019s current load, which is finished by definition; omitted or false lists every load, one still importing included, whose climbing `rowCount` is its progress.")}).describe(DatasetRefSchema.description??""),DatasetVersionDiffUnkeyedSideSchema=external_exports.enum(["from","to","both"]),DatasetVersionDiffSchema=external_exports.discriminatedUnion("comparable",[external_exports.object({comparable:external_exports.literal(!0),fromVersionId:DatasetVersionIdSchema,toVersionId:DatasetVersionIdSchema,added:external_exports.number().int().nonnegative(),removed:external_exports.number().int().nonnegative(),changed:external_exports.number().int().nonnegative()}),external_exports.object({comparable:external_exports.literal(!1),fromVersionId:DatasetVersionIdSchema,toVersionId:DatasetVersionIdSchema,unkeyedSide:DatasetVersionDiffUnkeyedSideSchema})]);var MAX_REPLICA_TABLES=64,REPLICA_SLUG_SUFFIX_RESERVE=7,CATALOG_SLUG_CEILING=64,MAX_REPLICA_SLUG_LENGTH=CATALOG_SLUG_CEILING-REPLICA_SLUG_SUFFIX_RESERVE,REPLICA_SLUG_HINT='Lowercase letters, digits, "-" or "_"; starts with a letter, ends with a letter or digit.',ReplicaSlugSchema=external_exports.string().min(2).max(MAX_REPLICA_SLUG_LENGTH).regex(CATALOG_SLUG_PATTERN,REPLICA_SLUG_HINT),REPLICA_RECORD_SET_ORIENTATIONS=["fact","dimension","relation"],ReplicaRecordSetOrientationSchema=external_exports.enum(REPLICA_RECORD_SET_ORIENTATIONS),REMOTE_NAME_HINT="table names may not contain / or control characters",REMOTE_NAME_PATTERN=/^(?!\.\.?$)[^/\\\u0000-\u001f]+$/,RemoteNameSchema=external_exports.string().min(1).max(255).regex(REMOTE_NAME_PATTERN,REMOTE_NAME_HINT),MAX_REPLICA_KEY_FIELDS=32,MAX_REPLICA_KEY_FIELD_LENGTH=255,ReplicaTableSelectionSchema=external_exports.strictObject({name:RemoteNameSchema,keyFields:external_exports.array(external_exports.string().min(1).max(MAX_REPLICA_KEY_FIELD_LENGTH)).max(MAX_REPLICA_KEY_FIELDS).optional(),orientation:ReplicaRecordSetOrientationSchema.optional()}),REPLICA_TITLE_REQUIRED_HINT="Enter a name for this replica.",MAX_REPLICA_TITLE_LENGTH=200,DeclareReplicaBase={connectionRef:ConnectionRefSchema,tables:external_exports.array(ReplicaTableSelectionSchema).min(1).max(MAX_REPLICA_TABLES),replicaSlug:ReplicaSlugSchema,title:external_exports.string().min(1).max(MAX_REPLICA_TITLE_LENGTH).regex(/\S/,REPLICA_TITLE_REQUIRED_HINT),idempotencyKey:IdempotencyKeySchema},DeclareReplicaInputSchema=external_exports.union([external_exports.strictObject({...DeclareReplicaBase,share:RemoteNameSchema,schema:RemoteNameSchema}),external_exports.strictObject({...DeclareReplicaBase,schema:RemoteNameSchema})]),CatalogDatasetIdSchema=external_exports.string().regex(/^dataset:[a-z][a-z0-9_-]{0,62}[a-z0-9]$/),ReplicaLocatorSchema=external_exports.union([external_exports.strictObject({share:RemoteNameSchema,schema:RemoteNameSchema,tables:external_exports.array(RemoteNameSchema).min(1)}),external_exports.strictObject({schema:RemoteNameSchema,tables:external_exports.array(RemoteNameSchema).min(1)})]),ReplicaDeclarationSchema=external_exports.object({connectionRef:ConnectionRefSchema,replica:external_exports.object({datasetId:CatalogDatasetIdSchema,slug:ReplicaSlugSchema,title:external_exports.string().min(1)}),externalDataset:external_exports.object({datasetId:CatalogDatasetIdSchema,slug:external_exports.string().min(1),title:external_exports.string().min(1)}),importOperation:external_exports.object({slug:external_exports.string().min(1),enabled:external_exports.literal(!0),loadStrategy:external_exports.literal("full-refresh")}),locator:ReplicaLocatorSchema,recordSets:external_exports.array(external_exports.object({slug:external_exports.string().min(1),layerName:external_exports.string().min(1)})),distributions:external_exports.array(external_exports.object({distributionId:external_exports.string().min(1),table:RemoteNameSchema,accessURL:external_exports.string().min(1),accessService:external_exports.string().min(1)})),declaredAt:external_exports.iso.datetime()}),REPLICA_RECORD_SET_STATES=["declared","processing","landed"],ReplicaRecordSetStateSchema=external_exports.enum(REPLICA_RECORD_SET_STATES),ReplicaRecordSetViewSchema=external_exports.object({slug:external_exports.string().min(1),layerName:external_exports.string().min(1).optional(),loadStrategy:external_exports.string().min(1),keyFields:external_exports.array(external_exports.string()).optional(),state:ReplicaRecordSetStateSchema,sourceName:external_exports.string().min(1).optional(),landedVersion:external_exports.number().int().nonnegative().optional(),rowCount:external_exports.number().int().nonnegative().optional(),landedAt:external_exports.string().optional()}),ReplicaLandingsReadSchema=external_exports.enum(["ok","unavailable"]),ReplicaViewSchema=external_exports.object({datasetId:CatalogDatasetIdSchema,slug:external_exports.string().min(1),title:external_exports.string().min(1),importOperation:external_exports.object({slug:external_exports.string().min(1),enabled:external_exports.boolean()}).optional(),landingsRead:ReplicaLandingsReadSchema,recordSets:external_exports.array(ReplicaRecordSetViewSchema)}),ExternalDatasetViewSchema=external_exports.object({externalDatasetId:CatalogDatasetIdSchema,title:external_exports.string().min(1),connectionRef:ConnectionRefSchema,locator:ReplicaLocatorSchema.optional(),locatorUnreadable:external_exports.literal(!0).optional(),replicas:external_exports.array(ReplicaViewSchema)}),ListConnectionReplicasInputSchema=external_exports.strictObject({connectionRef:ConnectionRefSchema}),ConnectionReplicasSchema=external_exports.object({connectionRef:ConnectionRefSchema,externalDatasets:external_exports.array(ExternalDatasetViewSchema)}),REPLICA_REFUSAL_CODES={REPLICA_CONFLICT:"REPLICA_CONFLICT",REPLICA_VALIDATION:"REPLICA_VALIDATION",SERVICE_NOT_FOUND:"SERVICE_NOT_FOUND",PARTIAL_DECLARE:"PARTIAL_DECLARE",REPLICA_RETIRE_BLOCKED:"REPLICA_RETIRE_BLOCKED",PARTIAL_RETIRE:"PARTIAL_RETIRE",REPLICA_NOT_FOUND:"REPLICA_NOT_FOUND",REPLICA_CATALOG_UNAVAILABLE:"REPLICA_CATALOG_UNAVAILABLE",REPLICA_FILL_UNREADABLE:"REPLICA_FILL_UNREADABLE",REPLICA_FILL_PENDING:"REPLICA_FILL_PENDING"},REPLICA_DECLARE_STEPS=["external-dataset","distributions","replica-dataset","record-sets","import-operation","link-operation"],ReplicaDeclareStepSchema=external_exports.enum(REPLICA_DECLARE_STEPS),PartialDeclareDataSchema=external_exports.object({code:external_exports.literal(REPLICA_REFUSAL_CODES.PARTIAL_DECLARE),completed:external_exports.array(ReplicaDeclareStepSchema),failed:ReplicaDeclareStepSchema,written:external_exports.array(external_exports.string().min(1))}),REPLICA_RETIRE_STEPS=["disable-operation","detach-dataset","delete-operation","delete-external","archive-studio-rows"],ReplicaRetireStepSchema=external_exports.enum(REPLICA_RETIRE_STEPS),REPLICA_RETIRE_STEP_OUTCOMES=["done","already-gone"],ReplicaRetireStepOutcomeSchema=external_exports.enum(REPLICA_RETIRE_STEP_OUTCOMES),RetireReplicaInputSchema=external_exports.strictObject({replicaSlug:ReplicaSlugSchema,connectionRef:ConnectionRefSchema.optional(),idempotencyKey:IdempotencyKeySchema}),ReplicaRetirementSchema=external_exports.object({replicaSlug:ReplicaSlugSchema,retained:external_exports.object({datasetId:CatalogDatasetIdSchema,status:external_exports.literal("deprecated")}).optional(),steps:external_exports.array(external_exports.object({step:ReplicaRetireStepSchema,outcome:ReplicaRetireStepOutcomeSchema})).length(REPLICA_RETIRE_STEPS.length),archived:external_exports.array(external_exports.string().min(1)),retiredAt:external_exports.iso.datetime()}),ReplicaRetireBlockedDataSchema=external_exports.object({code:external_exports.literal(REPLICA_REFUSAL_CODES.REPLICA_RETIRE_BLOCKED),step:ReplicaRetireStepSchema,blockers:external_exports.array(external_exports.string().min(1)).min(1),completed:external_exports.array(ReplicaRetireStepSchema),hint:external_exports.string().min(1)}),PartialRetireDataSchema=external_exports.object({code:external_exports.literal(REPLICA_REFUSAL_CODES.PARTIAL_RETIRE),completed:external_exports.array(ReplicaRetireStepSchema),failed:ReplicaRetireStepSchema,remaining:external_exports.array(ReplicaRetireStepSchema),written:external_exports.array(external_exports.string().min(1))});var deltaSharingAccessUrlOf=(share,schema,table)=>`delta-sharing://${share}/${schema}/${table}`,DELTA_SHARING_ACCESS_URL=/^delta-sharing:\/\/([^/]+)\/([^/]+)\/([^/]+)$/,parseDeltaSharingAccessUrl=accessURL=>{let match=DELTA_SHARING_ACCESS_URL.exec(accessURL);if(match===null)return;let[,share,schema,table]=match;return share===void 0||schema===void 0||table===void 0?void 0:{share,schema,table}};var ObserveReplicaDatasetInputSchema=external_exports.strictObject({replicaDatasetId:CatalogDatasetIdSchema,idempotencyKey:IdempotencyKeySchema}),ReplicaDatasetObservationSchema=external_exports.discriminatedUnion("state",[external_exports.object({state:external_exports.literal("processing")}),external_exports.object({state:external_exports.literal("ready"),datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,rowCount:external_exports.number().int().nonnegative().optional(),landedAt:external_exports.string().optional()})]),ReplicaLandingFactSchema=external_exports.object({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema}),MAX_RESOLVE_SDP_REFS=100,ResolveSdpDatasetRefsInputSchema=external_exports.strictObject({refs:external_exports.array(CatalogDatasetIdSchema).min(1).max(MAX_RESOLVE_SDP_REFS)}),SdpDatasetLinkSchema=external_exports.object({sdpDatasetRef:CatalogDatasetIdSchema,datasetId:DatasetIdSchema}),SdpDatasetLinksSchema=external_exports.array(SdpDatasetLinkSchema);var RECORD_ENVELOPE_COLUMNS=["record_id","logical_id","manifest_id","valid_from","valid_to","system_from","system_to","is_current"],ENVELOPE_PATTERN=new RegExp(`^(${RECORD_ENVELOPE_COLUMNS.join("|")})(_\\d+)?$`);var DatasetTargetSchema=external_exports.strictObject({datasetId:DatasetIdSchema}),ReplicaTargetSchema=external_exports.strictObject({connectionRef:ConnectionRefSchema,replicaSlug:ReplicaSlugSchema,recordSetSlug:external_exports.string().min(1)}),SetKeyFieldsTargetSchema=external_exports.union([DatasetTargetSchema,ReplicaTargetSchema]),SET_KEY_FIELDS_WIRE_MAX=MAX_REPLICA_KEY_FIELDS*4,SetKeyFieldsInputSchema=external_exports.strictObject({target:SetKeyFieldsTargetSchema,keyFields:external_exports.array(external_exports.string()).max(SET_KEY_FIELDS_WIRE_MAX),idempotencyKey:IdempotencyKeySchema}),SetKeyFieldsResultSchema=external_exports.object({recordSetId:external_exports.string().min(1),keyFields:external_exports.array(external_exports.string().min(1)).min(1)}),KEY_FIELDS_ISSUE_REASONS=["empty","blank","padded","envelope","repeated","control-character","too-long","too-many"];var ReplicaRecordSetColumnsInputSchema=external_exports.strictObject({connectionRef:ConnectionRefSchema,replicaSlug:ReplicaSlugSchema,recordSetSlug:external_exports.string().regex(CATALOG_SLUG_PATTERN,"a record set slug is the catalog slug grammar")}),ReplicaRecordSetColumnsSchema=external_exports.discriminatedUnion("profiled",[external_exports.object({profiled:external_exports.literal(!0),columns:external_exports.array(external_exports.object({name:external_exports.string().min(1),type:external_exports.string()})).min(1),version:external_exports.number().int().nonnegative().optional()}),external_exports.object({profiled:external_exports.literal(!1),columns:external_exports.tuple([])})]);var DELTA_SHARING_KIND="delta-sharing",DELTA_SHARING_SCHEME="delta-sharing://",deltaPathOf=containerPath=>{let[share,schema]=containerPath;if(containerPath.length!==2||share===void 0||schema===void 0)throw new Error(`a delta-sharing container path is [share, schema]; got ${String(containerPath.length)} segment(s)`);return{share,schema}},deltaSharingBuilder={connectorKind:DELTA_SHARING_KIND,accessUrlScheme:DELTA_SHARING_SCHEME,accessUrlOf:(containerPath,table)=>{let{share,schema}=deltaPathOf(containerPath);return deltaSharingAccessUrlOf(share,schema,table)},parseAccessUrl:accessUrl=>{let parsed=parseDeltaSharingAccessUrl(accessUrl);return parsed===void 0?void 0:{containerPath:[parsed.share,parsed.schema],table:parsed.table}},declarationOf:({locator,secretName})=>{let{share,schema}=deltaPathOf(locator.containerPath);return{tablestore:"delta-sharing",share,schema,tables:[...locator.tables],secretName}},usesShare:!0,declaringDistributionNeedsAccessService:!1,declaringDistributionFirst:!1,disjointnessScopedToConnection:!1,locatorRefusalOf:locator=>locator.containerPath.length===2?void 0:{reason:`a delta-sharing replica is read from a share and a schema; got ${String(locator.containerPath.length)} path segment(s)`},externalDescriptionOf:(containerPath,connectionId)=>{let{share,schema}=deltaPathOf(containerPath);return`External Delta Share tables ${share}/${schema} reached through connection ${connectionId}`},distributionTitleOf:(containerPath,table)=>{let{share,schema}=deltaPathOf(containerPath);return`${share}.${schema}.${table}`},credentialRequiredReason:"a delta-sharing import names the secret the engine reads the share with",wireLocatorOf:locator=>{let{share,schema}=deltaPathOf(locator.containerPath);return{share,schema,tables:[...locator.tables]}}},SNOWFLAKE_KIND="snowflake",SNOWFLAKE_SCHEME="snowflake://",snowflakePathOf=containerPath=>{let[schema]=containerPath;if(containerPath.length!==1||schema===void 0)throw new Error(`a snowflake container path is [schema]; got ${String(containerPath.length)} segment(s)`);return{schema}},snowflakeSegment=segment=>encodeURIComponent(segment),decodeSnowflakeSegment=raw=>{if(raw!=="")try{let decoded=decodeURIComponent(raw);return decoded!==""&&snowflakeSegment(decoded)===raw?decoded:void 0}catch{return}},SELECTOR_DELIMITERS=/[./*]/,isSnowflakeNameAddressable=name2=>!SELECTOR_DELIMITERS.test(name2),snowflakeUnaddressableReason=name2=>`"${name2}" cannot be declared from a Snowflake connection \u2014 a schema or table name may not contain ".", "/" or "*"`,isEncodable=name2=>{try{return encodeURIComponent(name2),!0}catch{return!1}},snowflakeBuilder={connectorKind:SNOWFLAKE_KIND,accessUrlScheme:SNOWFLAKE_SCHEME,accessUrlOf:(containerPath,table)=>{let{schema}=snowflakePathOf(containerPath);return`${SNOWFLAKE_SCHEME}${snowflakeSegment(schema)}/${snowflakeSegment(table)}`},parseAccessUrl:accessUrl=>{if(!accessUrl.startsWith(SNOWFLAKE_SCHEME))return;let parts=accessUrl.slice(SNOWFLAKE_SCHEME.length).split("/");if(parts.length!==2)return;let[schema,table]=parts.map(decodeSnowflakeSegment);return schema===void 0||table===void 0?void 0:{containerPath:[schema],table}},declarationOf:({locator})=>{let{schema}=snowflakePathOf(locator.containerPath);return{tablestore:SNOWFLAKE_KIND,tables:locator.tables.map(table=>`${schema}.${table}`)}},externalDescriptionOf:(containerPath,connectionId)=>{let{schema}=snowflakePathOf(containerPath);return`External Snowflake tables ${schema} reached through connection ${connectionId}`},distributionTitleOf:(containerPath,table)=>{let{schema}=snowflakePathOf(containerPath);return`${schema}.${table}`},credentialRequiredReason:void 0,usesShare:!1,declaringDistributionNeedsAccessService:!0,declaringDistributionFirst:!0,disjointnessScopedToConnection:!0,locatorRefusalOf:locator=>{if(locator.containerPath.length!==1)return{reason:`a snowflake replica is read from a schema; got ${String(locator.containerPath.length)} path segment(s)`};let[schema]=locator.containerPath,unencodableReason="a Snowflake schema or table name must be well-formed text (it contains an unpaired surrogate character)";if(!isEncodable(schema??""))return{reason:unencodableReason,field:"schema"};let unencodableTable=locator.tables.find(name2=>!isEncodable(name2));if(unencodableTable!==void 0)return{reason:unencodableReason,field:"tables",table:unencodableTable};if(!isSnowflakeNameAddressable(schema??""))return{reason:snowflakeUnaddressableReason(schema??""),field:"schema"};let unaddressableTable=locator.tables.find(name2=>!isSnowflakeNameAddressable(name2));return unaddressableTable===void 0?void 0:{reason:snowflakeUnaddressableReason(unaddressableTable),field:"tables",table:unaddressableTable}},wireLocatorOf:locator=>{let{schema}=snowflakePathOf(locator.containerPath);return{schema,tables:[...locator.tables]}}},REPLICA_KIND_BUILDERS=new Map([[deltaSharingBuilder.connectorKind,deltaSharingBuilder],[snowflakeBuilder.connectorKind,snowflakeBuilder]]);var ReplicaCursorEntrySchema=external_exports.object({recordSet:external_exports.string().min(1).regex(/^[^,@]+$/,'a record-set slug may not contain "," or "@" \u2014 see the injectivity guard'),landed:external_exports.boolean(),landedVersion:external_exports.number().int().nonnegative().max(2147483647).optional(),landedAt:external_exports.string().optional(),manifestId:external_exports.string().min(1).optional(),landingName:external_exports.string().min(1).optional()}),ReplicaCursorVectorSchema=external_exports.array(ReplicaCursorEntrySchema);var ReplicaDeliveryVersionSchema=external_exports.object({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema}),ReplicaDeliveryFactSchema=external_exports.object({versions:external_exports.array(ReplicaDeliveryVersionSchema).min(1),cursor:ReplicaCursorVectorSchema}),OBSERVE_REPLICA_DELIVERY_VERB="observeReplicaDelivery",OBSERVE_REPLICA_DELIVERY_ACTION=`datasets.${OBSERVE_REPLICA_DELIVERY_VERB}`;var LANDED_ORIGINS=["delivery","upload","output"],LandedOriginSchema=external_exports.enum(LANDED_ORIGINS),VersionLandedFactSchema=external_exports.strictObject({origin:LandedOriginSchema,datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,captureId:external_exports.string().min(1).optional(),sourceId:external_exports.string().min(1).optional(),filename:external_exports.string().min(1).optional()}),OBSERVE_VERSION_LANDED_VERB="observeVersionLanded",OBSERVE_VERSION_LANDED_ACTION=`datasets.${OBSERVE_VERSION_LANDED_VERB}`;var ImportJobIdSchema=external_exports.uuid().brand(),ImportJobStateSchema=external_exports.enum(["PENDING","RUNNING","COMPLETED","FAILED"]);var ImportJobRefSchema=external_exports.strictObject({jobId:ImportJobIdSchema,state:ImportJobStateSchema});var ImportJobStatusInputSchema=external_exports.strictObject({jobId:ImportJobIdSchema});var ImportJobStatusSchema=external_exports.strictObject({jobId:ImportJobIdSchema,state:ImportJobStateSchema,attempt:external_exports.number().int().positive(),datasetId:DatasetIdSchema.optional(),versionId:DatasetVersionIdSchema.optional(),rowsLoaded:external_exports.number().int().nonnegative().optional(),outputs:external_exports.array(SourceTransformationRunOutputSchema).optional(),landingOutputs:external_exports.array(SourceTransformationRunLandingOutputSchema).optional(),runRecordId:external_exports.string().min(1).optional(),failureDetail:external_exports.string().optional(),failureCode:external_exports.enum([RUN_ENGINE_BUSY,DIRECTORY_SLOT_UNAVAILABLE]).optional(),engineBusy:EngineBusySchema.optional(),engineWait:EngineWaitSchema.optional(),progress:TransformationRunProgressSchema.optional(),restartReason:external_exports.string().optional(),startedAt:external_exports.iso.datetime(),updatedAt:external_exports.iso.datetime()}),DEFAULT_MAX_SYNCHRONOUS_LAND_ROWS=25e3,DEFAULT_MAX_SYNCHRONOUS_LAND_BYTES=1536*1024,DEFAULT_MAX_SYNCHRONOUS_TRANSFORM_ROWS=8e3,DEFAULT_MAX_SYNCHRONOUS_TRANSFORM_BYTES=512*1024,IMPORT_JOB_MODES=["land","transform","declared"],ImportJobModeSchema=external_exports.enum(IMPORT_JOB_MODES);var DEFAULT_SYNCHRONOUS_IMPORT_LIMITS=Object.freeze({land:Object.freeze({rows:DEFAULT_MAX_SYNCHRONOUS_LAND_ROWS,bytes:DEFAULT_MAX_SYNCHRONOUS_LAND_BYTES}),transform:Object.freeze({rows:DEFAULT_MAX_SYNCHRONOUS_TRANSFORM_ROWS,bytes:DEFAULT_MAX_SYNCHRONOUS_TRANSFORM_BYTES})});var GetDatasetTransformationInputSchema=external_exports.object({datasetId:DatasetIdSchema}),DatasetTransformationSummarySchema=external_exports.object({get specId(){return TransformSpecIdSchema},name:external_exports.string().min(1),version:external_exports.number().int().positive(),savedAt:external_exports.iso.datetime(),get sources(){return external_exports.array(RecipeSourceSchema).min(1)},get result(){return RecipeResultSchema}}),ListDatasetTransformationsInputSchema=external_exports.object({take:external_exports.number().int().min(1).max(1e3).optional()});var CorrectionCellValueSchema=DatasetCellValueSchema,CorrectionEditSchema=external_exports.discriminatedUnion("kind",[external_exports.object({kind:external_exports.literal("set-cell"),rowKey:external_exports.string().min(1),column:external_exports.string().min(1),from:CorrectionCellValueSchema,to:CorrectionCellValueSchema}),external_exports.object({kind:external_exports.literal("drop-row"),rowKey:external_exports.string().min(1)})]),CORRECTION_MAX_EDITS=500,CorrectionRecordParamsSchema=external_exports.object({datasetId:external_exports.string().min(1),sourceVersionId:external_exports.string().min(1),keyColumn:external_exports.string().min(1),reason:external_exports.string().min(1),citations:external_exports.array(CitationSchema).min(1),edits:external_exports.array(CorrectionEditSchema).min(1).max(CORRECTION_MAX_EDITS)}),GetCorrectionReceiptInputSchema=external_exports.object({correctionRecordId:external_exports.string().min(1)}),CorrectionReceiptSchema=external_exports.object({correctionRecordId:external_exports.string().min(1),status:external_exports.enum(["in-flight","committed","failed"]),datasetId:external_exports.string().min(1),sourceVersionId:external_exports.string().min(1),correctedVersionId:external_exports.string().min(1).optional(),keyColumn:external_exports.string().min(1),reason:external_exports.string().min(1),citations:external_exports.array(CitationSchema).min(1),edits:external_exports.array(CorrectionEditSchema).min(1).max(CORRECTION_MAX_EDITS),actor:external_exports.string().min(1).optional(),openedAt:external_exports.iso.datetime().optional(),detail:external_exports.string().optional(),engine:SourceTransformationRunEngineSchema.optional().describe("The engine this correction declared beside the engine that actually ran it. ABSENT on a receipt sealed before the engine was recorded; `actual` is null when no engine answered in the attempt that sealed. A correction always declares `cli`, so this pair names the engine rather than detecting drift from a declaration.")});var RunQualityCheckInputSchema=external_exports.strictObject({rulesetId:ValidationRulesetIdSchema,rulesetVersion:external_exports.number().int().positive(),datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,idempotencyKey:IdempotencyKeySchema});var QualityRunStoredFindingsSchema=external_exports.object({perRuleLimit:external_exports.number().int().positive(),cappedRuleIndexes:external_exports.array(external_exports.number().int().nonnegative()).max(VALIDATION_RULES_MAX)}),QualityRunSummarySchema=external_exports.object({rowsChecked:external_exports.number().int().nonnegative(),rowsWithFinding:external_exports.number().int().nonnegative(),cellsFlagged:external_exports.number().int().nonnegative(),cellsNotEvaluated:external_exports.number().int().nonnegative(),recordDistribution:ValidationRecordDistributionSchema,perRule:external_exports.array(ValidationRuleTallySchema).max(VALIDATION_RULES_MAX),storedFindings:QualityRunStoredFindingsSchema.optional()}),QualityRunRecordParamsSchema=external_exports.object({rulesetId:external_exports.string().min(1),rulesetVersion:external_exports.number().int().positive(),datasetId:external_exports.string().min(1),versionId:external_exports.string().min(1),reason:external_exports.string().min(1).max(500).optional()}),GetQualityRunInputSchema=external_exports.object({qualityRunId:external_exports.string().min(1)}),QualityRunRefusalSchema=external_exports.object({code:external_exports.string().min(1),message:external_exports.string().min(1).max(500)}),QualityRunReceiptSchema=external_exports.object({qualityRunId:external_exports.string().min(1),status:external_exports.enum(["in-flight","committed","failed"]),rulesetId:external_exports.string().min(1),rulesetVersion:external_exports.number().int().positive(),datasetId:external_exports.string().min(1).meta(DATASET_ENTITY_HINT),versionId:external_exports.string().min(1),summary:QualityRunSummarySchema.optional(),refusal:QualityRunRefusalSchema.optional(),actor:external_exports.string().min(1).optional(),reason:external_exports.string().min(1).optional(),ranAt:external_exports.iso.datetime().optional()}),RunQualityCheckResultSchema=QualityRunReceiptSchema.extend({replayed:external_exports.boolean()}),QualityRunExecutionSchema=external_exports.enum(["background","synchronous"]),ListQualityRunsInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,rulesetId:ValidationRulesetIdSchema.optional(),rulesetVersion:external_exports.number().int().positive().optional(),execution:QualityRunExecutionSchema.optional(),take:external_exports.number().int().min(1).max(1e3).optional().describe(`How many runs to return, 1\u2013${1e3}; defaults to ${100}. An ask above the maximum is REFUSED, not clamped.`),cursor:external_exports.string().min(1).optional()}),QualityRunPageSchema=external_exports.object({items:external_exports.array(QualityRunReceiptSchema),nextCursor:external_exports.string().min(1).nullable()}),ListQualityRunFindingsInputSchema=external_exports.strictObject({qualityRunId:external_exports.string().min(1),findings:ValidationViolationWindowSchema.optional()});var StartQualityRunInputSchema=RunQualityCheckInputSchema,QualityRunJobStateSchema=external_exports.enum(["PENDING","RUNNING","COMPLETED","FAILED"]);var StartQualityRunResultSchema=external_exports.strictObject({qualityRunId:external_exports.string().min(1),state:QualityRunJobStateSchema,joined:external_exports.boolean(),replayed:external_exports.boolean()});var QualityRunStatusInputSchema=external_exports.strictObject({qualityRunId:external_exports.string().min(1)}),QualityRunStatusSchema=external_exports.strictObject({qualityRunId:external_exports.string().min(1),state:QualityRunJobStateSchema,execution:QualityRunExecutionSchema,rowsChecked:external_exports.number().int().nonnegative(),rowsTotal:external_exports.number().int().nonnegative().optional(),attempt:external_exports.number().int().positive().optional(),runRecordId:external_exports.string().min(1).optional(),summary:QualityRunSummarySchema.optional(),refusal:QualityRunRefusalSchema.optional(),engineWait:EngineWaitSchema.optional(),engineBusy:EngineBusySchema.optional(),startedAt:external_exports.iso.datetime(),updatedAt:external_exports.iso.datetime()}),QualityRunCompletionDetailSchema=QualityRunSummarySchema.pick({rowsChecked:!0,rowsWithFinding:!0,cellsFlagged:!0,cellsNotEvaluated:!0,recordDistribution:!0});var INPUT_MARKER_SCOPE_MAX_LENGTH=128,InputMarkerScopeSchema=external_exports.string().max(INPUT_MARKER_SCOPE_MAX_LENGTH).regex(/^[A-Za-z0-9_][A-Za-z0-9_.:-]*$/,"a scope is a letter, digit or underscore, then letters, digits, underscores, dots, colons or hyphens"),InputFingerprintSchema=external_exports.string().regex(/^[0-9a-f]{64}$/,"a fingerprint is the 64-character hex a lookup step answers"),InputMarkerInputSchema=external_exports.strictObject({scope:InputMarkerScopeSchema,fingerprint:InputFingerprintSchema,idempotencyKey:IdempotencyKeySchema}),CheckInputsChangedInputSchema=InputMarkerInputSchema,MarkInputsProcessedInputSchema=InputMarkerInputSchema,BuiltDefinitionSchema=external_exports.strictObject({type:external_exports.enum(["source-transformation","transform-spec"]),id:external_exports.string().min(1),version:external_exports.number().int().min(1),newest:external_exports.number().int().min(1),pinned:external_exports.boolean()}),RunBuildsShape={built:external_exports.array(BuiltDefinitionSchema),builds:external_exports.array(external_exports.string().min(1)),pendingJobs:external_exports.array(external_exports.string().min(1))},InputMarkerSchema=external_exports.strictObject({recordId:external_exports.string(),fingerprint:InputFingerprintSchema,definitionVersion:external_exports.number().int().min(1).nullable().optional(),built:RunBuildsShape.built.optional(),builds:RunBuildsShape.builds.optional(),pendingJobs:RunBuildsShape.pendingJobs.optional(),markedAt:external_exports.iso.datetime()}),CheckInputsChangedResultSchema=external_exports.strictObject({changed:external_exports.boolean(),scope:InputMarkerScopeSchema,fingerprint:InputFingerprintSchema,lastProcessed:InputMarkerSchema.nullable()});var MarkInputsProcessedResultSchema=external_exports.strictObject({scope:InputMarkerScopeSchema,fingerprint:InputFingerprintSchema,...RunBuildsShape});var DATASET_NO_PROMOTED_VERSION="DATASET_NO_PROMOTED_VERSION",DATASET_ARCHIVED="DATASET_ARCHIVED",RESOLVE_PROMOTED_VERSIONS_MAX_SLOTS=64,ResolveSlotNameSchema=external_exports.string().regex(/^[A-Za-z_][A-Za-z0-9_-]*$/,"a slot name must be a flow path segment: a letter or underscore, then letters, digits, underscores or hyphens"),RESOLVE_PROMOTED_VERSIONS_MAX_DATASET_ID_LENGTH=128,ResolvePromotedVersionsDatasetsSchema=external_exports.record(ResolveSlotNameSchema,DatasetIdSchema.max(RESOLVE_PROMOTED_VERSIONS_MAX_DATASET_ID_LENGTH,`a dataset id is at most ${String(RESOLVE_PROMOTED_VERSIONS_MAX_DATASET_ID_LENGTH)} characters`)).refine(datasets=>Object.keys(datasets).length>=1,"name at least one dataset to resolve").refine(datasets=>Object.keys(datasets).length<=RESOLVE_PROMOTED_VERSIONS_MAX_SLOTS,`resolve at most ${String(RESOLVE_PROMOTED_VERSIONS_MAX_SLOTS)} datasets per call`),ResolvePromotedVersionsInputSchema=external_exports.strictObject({datasets:ResolvePromotedVersionsDatasetsSchema,idempotencyKey:IdempotencyKeySchema}),PinnedDatasetRefSchema=DatasetRefSchema.required(),ResolvedPromotedVersionSchema=external_exports.object({slot:ResolveSlotNameSchema,...PinnedDatasetRefSchema.shape,loadNumber:external_exports.number().int().positive(),promotedAt:external_exports.iso.datetime()}),ResolveUnresolvedReasonSchema=external_exports.enum([DATASET_NO_PROMOTED_VERSION]),UnresolvedPromotedVersionSchema=external_exports.strictObject({slot:ResolveSlotNameSchema,datasetId:DatasetIdSchema,reason:ResolveUnresolvedReasonSchema}),ResolvedPromotedVersionsAnswerSchema=external_exports.strictObject({status:external_exports.literal("resolved"),inputs:external_exports.record(ResolveSlotNameSchema,DatasetVersionInputBindingSchema),refs:external_exports.record(ResolveSlotNameSchema,PinnedDatasetRefSchema),resolved:external_exports.array(ResolvedPromotedVersionSchema),fingerprint:InputFingerprintSchema.optional()}),UnresolvedPromotedVersionsAnswerSchema=external_exports.strictObject({status:external_exports.literal("unresolved"),unresolved:external_exports.array(UnresolvedPromotedVersionSchema).min(1),resolved:external_exports.array(ResolvedPromotedVersionSchema)}),ResolvePromotedVersionsResultSchema=external_exports.discriminatedUnion("status",[ResolvedPromotedVersionsAnswerSchema,UnresolvedPromotedVersionsAnswerSchema]);var REFUSAL_SENTENCES={DATASET_NOT_FOUND:slot3=>`slot "${slot3}": dataset not found`,DATASET_READ_LIVE_UNSUPPORTED:slot3=>`slot "${slot3}" names a live dataset \u2014 its rows are computed when they are read rather than stored here, so there is no promoted load to pin; capture it to a frozen dataset and name that`,[DATASET_ARCHIVED]:slot3=>`slot "${slot3}" names an archived dataset \u2014 it is retired and its last promoted load is no longer current; name its replacement, or restore it first`};var DATASET_NO_VERSION="DATASET_NO_VERSION",DATASET_POINTER_DANGLING="DATASET_POINTER_DANGLING",DATASET_VERSION_UNSETTLED="DATASET_VERSION_UNSETTLED",ResolveLatestVersionsInputSchema=ResolvePromotedVersionsInputSchema,ResolvedLatestVersionSchema=ResolvedPromotedVersionSchema.extend({promoted:external_exports.boolean(),promotedAt:external_exports.iso.datetime().nullable()}),UnresolvedLatestVersionSchema=UnresolvedPromotedVersionSchema.extend({reason:external_exports.enum([DATASET_NO_VERSION,DATASET_POINTER_DANGLING,DATASET_VERSION_UNSETTLED])}),ResolvedLatestVersionsAnswerSchema=ResolvedPromotedVersionsAnswerSchema.extend({resolved:external_exports.array(ResolvedLatestVersionSchema)}),UnresolvedLatestVersionsAnswerSchema=UnresolvedPromotedVersionsAnswerSchema.extend({unresolved:external_exports.array(UnresolvedLatestVersionSchema).min(1),resolved:external_exports.array(ResolvedLatestVersionSchema)}),ResolveLatestVersionsResultSchema=external_exports.discriminatedUnion("status",[ResolvedLatestVersionsAnswerSchema,UnresolvedLatestVersionsAnswerSchema]);var QUALITY_CHECKS_VERB="runQualityChecks",QUALITY_CHECKS_ACTION_NAME=`datasets.${QUALITY_CHECKS_VERB}`;var QUALITY_CHECKS_RUNS_MAX=128;var QualityChecksSlotSchema=external_exports.string().max(64).regex(JOB_FIELD_PATTERN,"a table slot must be a walkable name: a letter or _, then letters, digits, _ or -"),QualityChecksTableSchema=external_exports.object({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema}),QualityChecksTablesSchema=external_exports.record(QualityChecksSlotSchema,QualityChecksTableSchema),QualityChecksTablesWireSchema=boundedRecord2(QualityChecksSlotSchema,QualityChecksTableSchema,QUALITY_CHECKS_TABLES_WIRE_MAX,"tables",{min:1}),StartQualityChecksInputSchema=external_exports.strictObject({tables:QualityChecksTablesWireSchema,idempotencyKey:IdempotencyKeySchema}),QualityCheckPinSchema=external_exports.object({slot:QualityChecksSlotSchema,datasetId:external_exports.string().min(1),versionId:external_exports.string().min(1),rulesetId:external_exports.string().min(1),rulesetVersion:external_exports.number().int().positive(),qualityRunId:external_exports.string().min(1),joined:external_exports.boolean()}),StartQualityChecksResultSchema=external_exports.strictObject({qualityChecksId:external_exports.string().min(1),state:QualityRunJobStateSchema,replayed:external_exports.boolean(),checks:external_exports.array(QualityCheckPinSchema).max(QUALITY_CHECKS_RUNS_MAX)}),QualityChecksCountsSchema=external_exports.object({rulesetsChecked:external_exports.number().int().nonnegative(),rowsChecked:external_exports.number().int().nonnegative(),failedRecords:external_exports.number().int().nonnegative(),uncertainRecords:external_exports.number().int().nonnegative(),rulesNeverApplied:external_exports.number().int().nonnegative()}),QualityChecksTotalsSchema=external_exports.object({tablesChecked:external_exports.number().int().nonnegative(),tablesWithoutRulesets:external_exports.number().int().nonnegative(),tablesWithNoRows:external_exports.number().int().nonnegative(),...QualityChecksCountsSchema.shape});var QualityChecksTotalsWithVerdictSchema=QualityChecksTotalsSchema.extend({passed:external_exports.boolean()}),QualityChecksRulesetResultSchema=external_exports.object({rulesetId:external_exports.string().min(1),rulesetVersion:external_exports.number().int().positive(),qualityRunId:external_exports.string().min(1),recordDistribution:ValidationRecordDistributionSchema}),QualityChecksTableResultSchema=external_exports.object({datasetId:external_exports.string().min(1),versionId:external_exports.string().min(1),...QualityChecksCountsSchema.shape,rulesets:external_exports.array(QualityChecksRulesetResultSchema).max(QUALITY_CHECKS_RUNS_MAX)}),QualityChecksResultSchema=QualityChecksTotalsWithVerdictSchema.extend({tables:external_exports.record(QualityChecksSlotSchema,QualityChecksTableResultSchema)}),QualityChecksCompletionDetailSchema=QualityChecksTotalsWithVerdictSchema.extend({tables:external_exports.record(QualityChecksSlotSchema,QualityChecksTableResultSchema.omit({rulesets:!0}))}),QualityChecksFailureSchema=external_exports.object({slot:QualityChecksSlotSchema,rulesetId:external_exports.string().min(1),rulesetVersion:external_exports.number().int().positive(),qualityRunId:external_exports.string().min(1),code:external_exports.string().min(1)}),QualityChecksRefusalSchema=external_exports.object({code:external_exports.string().min(1),message:external_exports.string().min(1).max(500),failures:external_exports.array(QualityChecksFailureSchema).min(1).max(QUALITY_CHECKS_RUNS_MAX)}),QualityChecksStatusInputSchema=external_exports.strictObject({qualityChecksId:external_exports.string().min(1)}),QualityChecksStatusSchema=external_exports.strictObject({qualityChecksId:external_exports.string().min(1),state:QualityRunJobStateSchema,runsTotal:external_exports.number().int().nonnegative(),runsFinished:external_exports.number().int().nonnegative(),runRecordId:external_exports.string().min(1).optional(),result:QualityChecksResultSchema.optional(),refusal:QualityChecksRefusalSchema.optional(),startedAt:external_exports.iso.datetime(),updatedAt:external_exports.iso.datetime()});var StartSourceTransformationDryRunInputSchema=PreviewSourceTransformationInputSchema,SourceTransformationDryRunStateSchema=external_exports.enum(["queued","running","succeeded","failed"]);var SourceTransformationDryRunPhaseSchema=external_exports.enum(["materializing-inputs","running","collecting-result"]),SourceTransformationDryRunSlotProgressSchema=external_exports.strictObject({rowsCopied:external_exports.number().int().nonnegative(),rowsTotal:external_exports.number().int().nonnegative().optional(),done:external_exports.boolean()}),SourceTransformationDryRunProgressSchema=external_exports.record(external_exports.string().min(1),SourceTransformationDryRunSlotProgressSchema),SourceTransformationDryRunResultSchema=external_exports.strictObject({columns:external_exports.array(external_exports.string()),rows:external_exports.array(external_exports.record(external_exports.string(),external_exports.string())),rowCount:external_exports.number().int().nonnegative()}),SourceTransformationDryRunFailureSchema=external_exports.strictObject({code:external_exports.string().min(1),message:external_exports.string().min(1)}),StartSourceTransformationDryRunResultSchema=external_exports.strictObject({dryRunId:external_exports.string().min(1),state:SourceTransformationDryRunStateSchema,joined:external_exports.boolean()}),SourceTransformationDryRunStatusInputSchema=external_exports.strictObject({dryRunId:external_exports.string().min(1)}),SourceTransformationDryRunStatusSchema=external_exports.strictObject({dryRunId:external_exports.string().min(1),state:SourceTransformationDryRunStateSchema,phase:SourceTransformationDryRunPhaseSchema.optional(),progress:SourceTransformationDryRunProgressSchema,attempt:external_exports.number().int().positive().optional(),result:SourceTransformationDryRunResultSchema.optional(),failure:SourceTransformationDryRunFailureSchema.optional(),startedAt:external_exports.iso.datetime(),updatedAt:external_exports.iso.datetime(),finishedAt:external_exports.iso.datetime().optional(),expiresAt:external_exports.iso.datetime()}),SOURCE_TRANSFORMATION_DRY_RUN_RETENTION_MS=10080*60*1e3;var SOURCE_TRANSFORMATION_DRY_RUN_RESULT_MAX_BYTES=64*1024*1024;var SOURCE_TRANSFORMATION_DRY_RUN_RESULT_MAX_HELD_BYTES=32*1024*1024;var StartProfileRunInputSchema=DatasetRefSchema,DatasetProfileRunStateSchema=external_exports.enum(["queued","running","succeeded","failed"]);var StartProfileRunResultSchema=external_exports.strictObject({runId:external_exports.string().min(1),datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,state:DatasetProfileRunStateSchema,joined:external_exports.boolean()}),GetProfileRunInputSchema=DatasetRefSchema,DatasetProfileRunProgressSchema=external_exports.strictObject({rowsTotal:external_exports.number().int().nonnegative().optional(),columnsTotal:external_exports.number().int().nonnegative().optional(),columnsProfiled:external_exports.number().int().nonnegative()}),DatasetProfileRunFailureSchema=external_exports.strictObject({code:external_exports.string().min(1),reason:external_exports.string().min(1).optional(),message:external_exports.string().min(1)}),DatasetProfileRunSchema=external_exports.strictObject({runId:external_exports.string().min(1),state:DatasetProfileRunStateSchema,attempt:external_exports.number().int().positive().optional(),progress:DatasetProfileRunProgressSchema,failure:DatasetProfileRunFailureSchema.optional(),startedAt:external_exports.iso.datetime(),updatedAt:external_exports.iso.datetime(),finishedAt:external_exports.iso.datetime().optional()}),StoredDatasetProfileSchema=external_exports.strictObject({computedAt:external_exports.iso.datetime(),topValues:external_exports.number().int().positive(),buckets:external_exports.number().int().positive(),profile:DatasetProfileSchema}),EarlierStoredProfileSchema=external_exports.strictObject({versionId:DatasetVersionIdSchema,loadNumber:external_exports.number().int().positive(),loadedAt:external_exports.iso.datetime(),computedAt:external_exports.iso.datetime()}),DatasetProfileRunStatusSchema=external_exports.strictObject({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,loadNumber:external_exports.number().int().positive(),run:DatasetProfileRunSchema.optional(),profile:StoredDatasetProfileSchema.optional(),previous:EarlierStoredProfileSchema.optional()});var MovementFormatSchema=external_exports.enum(["csv","xlsx"]),MovementMediaTypeSchema=external_exports.enum(["text/csv","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/gzip"]);var MovementFilterSchema=external_exports.strictObject({search:external_exports.string().min(1).max(256).optional(),columnFilters:external_exports.array(DatasetReadFilterSchema).max(8).default([])}),MovementAssetColumnsSchema=external_exports.strictObject({column:DatasetReadColumnNameSchema,system:external_exports.string().min(1).max(64).regex(NO_CONTROL_CHARS,"an ID system may not contain control characters").optional()}),MovementEstimateInputSchema=external_exports.strictObject({ref:DatasetRefSchema,filters:MovementFilterSchema.optional(),assetColumns:MovementAssetColumnsSchema.optional()}),MovementEstimateSchema=external_exports.object({rowCount:external_exports.number().int().nonnegative(),promoted:external_exports.boolean(),versionId:DatasetVersionIdSchema,maxRows:external_exports.number().int().positive().optional(),assetColumns:external_exports.object({unmatchedRows:external_exports.number().int().nonnegative()}).optional()}),MovementRowOrderSchema=external_exports.enum(["none","shown"]),MovementExportInputSchema=external_exports.strictObject({ref:DatasetRefSchema,format:MovementFormatSchema,filters:MovementFilterSchema.optional(),order:MovementRowOrderSchema.optional(),orderBy:DatasetReadOrderBySchema.optional(),assetColumns:MovementAssetColumnsSchema.optional(),idempotencyKey:IdempotencyKeySchema.describe("Client-minted replay key for this export authorization \u2014 unique per (tenant, caller, key). A retry with the same key and the same selection replays the ONE recorded authorization and returns a FRESH grant (a new URL with a future expiry) \u2014 never the first call's possibly-expired URL, and never a second Record. A reused key with a DIFFERENT version, format or filter is refused, as is another caller's key. Mint a new key per intended export.")}),MovementGrantSchema=external_exports.object({url:external_exports.url(),headers:external_exports.record(external_exports.string(),external_exports.string()),expiresAt:external_exports.iso.datetime(),mediaType:MovementMediaTypeSchema,filename:external_exports.string().min(1),rowCount:external_exports.number().int().nonnegative()}),EXPORT_ENGINE_BUSY="EXPORT_ENGINE_BUSY",DatasetExportJobStateSchema=external_exports.enum(["PENDING","RUNNING","READY","FAILED"]);var MovementExportHandleSchema=external_exports.object({exportId:external_exports.string().min(1),state:DatasetExportJobStateSchema,rowCount:external_exports.number().int().nonnegative()}),MovementExportStatusInputSchema=external_exports.strictObject({exportId:external_exports.string().min(1)}),MovementExportStatusSchema=external_exports.discriminatedUnion("state",[external_exports.object({state:external_exports.literal("pending"),rowCount:external_exports.number().int().nonnegative(),engineWait:EngineWaitSchema.optional(),tilesDone:external_exports.number().int().nonnegative().optional(),tilesTotal:external_exports.number().int().nonnegative().optional()}),external_exports.object({state:external_exports.literal("ready"),grant:MovementGrantSchema,byteSize:external_exports.number().int().nonnegative()}),external_exports.object({state:external_exports.literal("failed"),reason:external_exports.string().min(1),retryable:external_exports.boolean(),code:external_exports.literal(EXPORT_ENGINE_BUSY).optional(),engineBusy:EngineBusySchema.optional()})]);var EXPORT_STORE_UNAVAILABLE="EXPORT_STORE_UNAVAILABLE",EXPORT_PRICING_TIMED_OUT="EXPORT_PRICING_TIMED_OUT",ExportServiceUnavailableDataSchema=external_exports.object({code:external_exports.enum([EXPORT_STORE_UNAVAILABLE,EXPORT_PRICING_TIMED_OUT])}),ExportStoreUnavailableDataSchema=external_exports.object({code:external_exports.literal(EXPORT_STORE_UNAVAILABLE)});var ImportRunStateSchema=external_exports.enum(["never-run","queued","running","succeeded","failed","canceled"]);var ImportRunFailureReasonSchema=external_exports.enum(["UnreadableTableError","UnsafePartitionKeyError","ReadLocationError","CustodyRefusedError","UnknownImportOperationError","DisabledImportOperationError","LaneMismatchError","UndescribedDatasetError","UndescribableDatasetError","UnknownShareTableError","VersionTagRefusedError","unassigned","ambiguous","unknown"]),ImportRunFailureSchema=external_exports.object({reason:ImportRunFailureReasonSchema,table:external_exports.string().min(1).optional(),code:external_exports.string().min(1).optional(),detail:external_exports.string().optional(),wireReason:external_exports.string().min(1).optional()}),ImportRunLandedRecordSetSchema=external_exports.object({recordSet:external_exports.string().min(1),manifestId:external_exports.string().min(1).optional(),sourceName:external_exports.string().min(1).optional(),rowCount:external_exports.number().int().nonnegative().optional()}),ImportRunSchema=external_exports.object({state:ImportRunStateSchema,runId:external_exports.string().min(1).optional(),partitionKey:external_exports.string().min(1).optional(),startedAt:external_exports.string().optional(),endedAt:external_exports.string().optional(),triggeredVia:external_exports.string().min(1).optional(),rowCount:external_exports.number().int().nonnegative().optional(),landed:external_exports.number().int().nonnegative().optional(),skipped:external_exports.number().int().nonnegative().optional(),replayed:external_exports.number().int().nonnegative().optional(),recordSets:external_exports.array(ImportRunLandedRecordSetSchema).optional(),failure:ImportRunFailureSchema.optional()}),OperationImportRunsSchema=external_exports.object({operationSlug:external_exports.string().min(1),summary:ImportRunSchema,runs:external_exports.array(ImportRunSchema)}),ImportRecordSetLandingSchema=external_exports.object({sourceName:external_exports.string().min(1).optional(),rowCount:external_exports.number().int().nonnegative().optional(),landedAt:external_exports.string().optional()}),DatasetImportRecordSetSchema=external_exports.object({recordSet:external_exports.string().min(1),operationSlug:external_exports.string().min(1).optional(),lastLanded:ImportRecordSetLandingSchema.optional(),lastRun:ImportRunSchema.optional()}),DatasetImportRunsSchema=external_exports.object({recordSets:external_exports.array(DatasetImportRecordSetSchema)}),IMPORT_RUNS_LIMIT_DEFAULT=5,IMPORT_RUNS_LIMIT_MAX=25,IMPORT_RUNS_LIMIT_MIN=1;var ListImportOperationRunsInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema,operationSlug:external_exports.string().min(1),limit:external_exports.number().int().min(IMPORT_RUNS_LIMIT_MIN).max(IMPORT_RUNS_LIMIT_MAX).optional().default(IMPORT_RUNS_LIMIT_DEFAULT)}),GetDatasetImportRunsInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema});var GetWalkupLandingStatusInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema}),WalkupLandingStateSchema=external_exports.object({state:external_exports.enum(["processing","ready","no-data-yet","stalled"]),rowCount:external_exports.number().int().nonnegative().optional(),landedAt:external_exports.string().optional()}),WalkupLayerLandingStatusSchema=WalkupLandingStateSchema.extend({datasetId:DatasetIdSchema}),WalkupLandingStatusSchema=WalkupLandingStateSchema.extend({layers:external_exports.array(WalkupLayerLandingStatusSchema).optional()}),WALKUP_LANDING_STALL_MS=3600*1e3,WalkupLandingAmbiguousDataSchema=external_exports.object({recordSets:external_exports.array(external_exports.string())});var WALKUP_COLUMN_TYPES=["VARCHAR","BIGINT","DOUBLE","BOOLEAN","DATE","TIMESTAMP"],WalkupColumnTypeSchema=external_exports.enum(WALKUP_COLUMN_TYPES),MAX_PINNED_COLUMN_NAME_LENGTH=255,MAX_PINNED_COLUMNS=512,PINNED_COLUMN_NAME=/^[^\p{Cc}\p{Cf}"'\\]{1,255}$/u,WalkupPinnedColumnNameSchema=external_exports.string().min(1).max(MAX_PINNED_COLUMN_NAME_LENGTH).regex(PINNED_COLUMN_NAME,"column name may not contain quotes, backslashes or control characters");var WalkupColumnTypesSchema=external_exports.record(WalkupPinnedColumnNameSchema,WalkupColumnTypeSchema).refine(types=>Object.keys(types).length<=MAX_PINNED_COLUMNS,{message:`at most ${MAX_PINNED_COLUMNS} column type pins may ride one declare`}),MAX_WALKUP_KEY_FIELDS=32,WalkupKeyFieldsSchema=external_exports.array(WalkupPinnedColumnNameSchema).min(1).max(MAX_WALKUP_KEY_FIELDS),CONNECTED_OUTPUT_COLUMN_TYPES=["VARCHAR","BIGINT","DOUBLE","BOOLEAN","TIMESTAMPTZ"],ConnectedOutputColumnTypeSchema=external_exports.enum(CONNECTED_OUTPUT_COLUMN_TYPES),ConnectedOutputColumnTypesSchema=external_exports.record(WalkupPinnedColumnNameSchema,ConnectedOutputColumnTypeSchema).refine(types=>Object.keys(types).length<=MAX_PINNED_COLUMNS,{message:`at most ${MAX_PINNED_COLUMNS} column type pins may ride one output`}),WalkupColumnTimezonesSchema=external_exports.record(WalkupPinnedColumnNameSchema,external_exports.string().min(1).max(64)).refine(zones=>Object.keys(zones).length<=MAX_PINNED_COLUMNS,{message:`at most ${MAX_PINNED_COLUMNS} column timezone declarations may ride one declare`}),WALKUP_FILE_FORMATS=["csv","parquet","json","geojson","filegdb","xlsx"],WalkupFileFormatSchema=external_exports.enum(WALKUP_FILE_FORMATS),DialectCharacterSchema=external_exports.string().length(1).regex(/^[^\p{Cc}\p{Cf}\p{Cs}\p{Cn}]$/u,"must be one printable character"),WalkupCsvDialectSchema=external_exports.strictObject({quote:DialectCharacterSchema.optional(),escape:DialectCharacterSchema.optional()}),MAX_LAYER_NAME_LENGTH=160,MAX_WALKUP_LAYERS=64,WalkupLayerNamesSchema=external_exports.array(external_exports.string().min(1).max(MAX_LAYER_NAME_LENGTH).regex(/^[^\p{Cc}\p{Cf}\p{Cs}]+$/u,"must not contain control characters")).min(1).max(MAX_WALKUP_LAYERS),WALKUP_DECLARE_KEY_MAX_LENGTH=200,WalkupDeclareIdempotencyKeySchema=IdempotencyKeySchema.max(WALKUP_DECLARE_KEY_MAX_LENGTH).describe("REQUIRED client-minted key for this import \u2014 YOU generate it (a UUID is fine), once per file you mean to import, and send the SAME key on every retry of that import. A retry under the same key resumes the same declare, and once it has declared it replays that answer: it never creates a second dataset. A key is pinned to the declaration it first carried; declaring anything else under it is refused (data.code KEY_PARAM_MISMATCH), so mint a new key for a new file or changed options."),WalkupDeclareInputSchema=external_exports.strictObject({idempotencyKey:WalkupDeclareIdempotencyKeySchema,fileName:external_exports.string().min(1),displayName:external_exports.string().min(1).optional(),columnTypes:WalkupColumnTypesSchema.optional(),columnTimezones:WalkupColumnTimezonesSchema.optional(),keyFields:WalkupKeyFieldsSchema.optional().describe("Optional. The ordered column names that identify one row across every upload of this dataset \u2014 its key fields. Set ONLY when the dataset is created and never changeable: without them, rows cannot be reviewed or corrected across uploads. Refused beside intoDatasetId (data.code WALKUP_DECLARE_KEY_FIELDS_ON_NEW_VERSION \u2014 a new version keeps its dataset's key), for a FileGDB or an Excel workbook (WALKUP_DECLARE_KEY_FIELDS_NOT_FOR_FORMAT), and when a name repeats (WALKUP_DECLARE_KEY_FIELDS_DUPLICATED)."),format:WalkupFileFormatSchema.optional(),csv:WalkupCsvDialectSchema.optional(),layers:WalkupLayerNamesSchema.optional().describe("A FileGDB (format filegdb) or an Excel workbook (format xlsx) only, and required for both: the layers, or the SHEET names, to import \u2014 each becomes its own dataset. Refused for any other format (data.code WALKUP_DECLARE_LAYERS_NOT_FOR_FORMAT)."),intoDatasetId:DatasetIdSchema.optional().describe("Optional. The id of an existing connected dataset that was created by uploading a file (`get` answers `acceptsUploadedVersions: true`). When set, the file lands as that dataset's NEXT VERSION instead of creating a new dataset: `fileName` names only the file, never the dataset. Refused for any other dataset (data.code WALKUP_UPLOAD_VERSION_NOT_UPLOADED), an archived one (WALKUP_UPLOAD_VERSION_ARCHIVED), an unknown id (WALKUP_UPLOAD_VERSION_UNKNOWN_DATASET), a geodatabase (WALKUP_UPLOAD_VERSION_FORMAT_UNSUPPORTED). A dataset `get` names a `sheetName` for is one sheet of an Excel workbook: its next version is format xlsx with layers naming that sheet alone \u2014 another sheet is refused WALKUP_UPLOAD_VERSION_SHEET_MISMATCH, another format (or a workbook into a single file's dataset) WALKUP_UPLOAD_VERSION_FORMAT_MISMATCH. Refused too: one with no landed version to follow yet (WALKUP_UPLOAD_VERSION_NO_LANDED_VERSION, CONFLICT \u2014 retry once its upload lands), and one with another new version still being declared (WALKUP_UPLOAD_VERSION_BUSY, CONFLICT \u2014 retry once that finishes); a resume under a key a newer upload has replaced is refused WALKUP_UPLOAD_VERSION_SUPERSEDED (CONFLICT, final \u2014 start again under a new key). Columns may differ from the previous version. Poll getWalkupLandingStatus as for a new import, then promote."),replaceStalledUpload:external_exports.boolean().optional().describe("Optional, with intoDatasetId only. The person has confirmed uploading a new version while the dataset's previous upload has STALLED (uploaded longer than the landing stall window ago and not landed): admitting the new version may lose that upload. Without it such a declare is refused CONFLICT (data.code WALKUP_PREVIOUS_UPLOAD_STALLED, with data.fileName when known and data.startedAt). An upload still within the window is refused WALKUP_UPLOAD_VERSION_PREVIOUS_LANDING whatever this says."),referenceChange:external_exports.strictObject({reason:external_exports.string().trim().min(1).max(500),changeType:ReferenceChangeTypeSchema}).optional().describe("Required with intoDatasetId when the dataset is a reference table (kind constant), and refused otherwise: the reason the values change and the change type (new-edition, publisher-errata or local-correction), stamped on the version this upload lands. Missing for a reference table: BAD_REQUEST (data.code REFERENCE_UPLOAD_CHANGE_REQUIRED); given for any other upload: BAD_REQUEST (REFERENCE_UPLOAD_CHANGE_NOT_REFERENCE).")}),WalkupDeclaredLayerSchema=external_exports.object({layerName:external_exports.string().min(1),datasetId:DatasetIdSchema,datasetSlug:external_exports.string().min(1),recordSet:external_exports.string().min(1),datasetName:external_exports.string().min(1).optional()}),WalkupDeclareResultSchema=external_exports.object({datasetId:DatasetIdSchema,datasetSlug:external_exports.string().min(1),operationSlug:external_exports.string().min(1),sdpDatasetRef:external_exports.string().min(1),reused:external_exports.boolean(),layers:external_exports.array(WalkupDeclaredLayerSchema).min(1).optional()}),WalkupDeclareOutputSchema=external_exports.discriminatedUnion("state",[WalkupDeclareResultSchema.extend({state:external_exports.literal("declared"),attemptId:external_exports.string().min(1)}),external_exports.object({state:external_exports.literal("declaring"),attemptId:external_exports.string().min(1)})]),WalkupDeclareAttemptStateSchema=external_exports.enum(["declaring","declared","refused"]),WALKUP_DECLARE_LEASE_MS=5*6e4,WALKUP_DECLARE_INTERRUPTED="WALKUP_DECLARE_INTERRUPTED",WALKUP_DECLARE_ERRORS={[WALKUP_DECLARE_INTERRUPTED]:{status:503,message:"The import is still being set up \u2014 try the same import again, and it continues where it stopped"}};var RecordIdentityInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema}),connected={recordSet:external_exports.string().min(1),loadStrategy:external_exports.string().min(1)},RecordIdentitySchema=external_exports.discriminatedUnion("state",[external_exports.object({state:external_exports.literal("keyed"),...connected,keyFields:external_exports.array(external_exports.string().min(1)).min(1)}),external_exports.object({state:external_exports.literal("keyless"),...connected}),external_exports.object({state:external_exports.literal("not-connected")})]);var REVIEW_READINESS_NOTICES=["none","live-feed","reloading","upload-again","run-again","produced-again"],ReviewReadinessInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema}),ReviewReadinessSchema=external_exports.object({notice:external_exports.enum(REVIEW_READINESS_NOTICES)});var MAX_WITHDRAW_REASON_LENGTH=500,WithdrawReviewActInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,withdraws:external_exports.string().min(1).max(200),records:external_exports.array(ReviewRecordRefSchema).min(1).max(MAX_REVIEW_SELECTION_RECORDS).optional(),body:ReviewBodySchema.max(MAX_WITHDRAW_REASON_LENGTH).optional(),idempotencyKey:IdempotencyKeySchema.max(200)});var MAX_CORRECT_CELLS=MAX_CORRECTION_ACT_ROWS,MAX_CORRECT_CELLS_SENT=10*MAX_CORRECT_CELLS,MAX_CORRECT_CELLS_COLUMNS=10,CorrectCellSchema=external_exports.strictObject({logicalId:external_exports.string().min(1).max(200),recordId:external_exports.string().min(1).max(200),column:external_exports.string().min(1).max(MAX_CORRECTION_COLUMN_LENGTH),from:DatasetCellValueSchema,value:DatasetCellValueSchema,keepTake:CellKeepTakeSchema.optional()}),CorrectCellsInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,cells:external_exports.array(CorrectCellSchema).min(1).max(MAX_CORRECT_CELLS_SENT),body:ReviewBodySchema,dryRun:external_exports.boolean().optional(),idempotencyKey:IdempotencyKeySchema.max(200)}),CORRECT_CELL_REFUSALS=["VALUE_NOT_STORABLE","KEY_COLUMN","LAKE_WRITTEN_COLUMN","COLUMN_NOT_IN_VERSION","NOT_A_NUMBER","ROW_NOT_IN_VERSION","FROM_UNREPRESENTABLE","VALUE_DOES_NOT_FIT","OVER_LIMIT"],CorrectCellRefusalSchema=external_exports.enum(CORRECT_CELL_REFUSALS),OUTCOME_CELL={logicalId:external_exports.string().min(1),column:external_exports.string().min(1)},RefusedCellOutcomeSchema=external_exports.discriminatedUnion("code",[external_exports.strictObject({...OUTCOME_CELL,result:external_exports.literal("refused"),code:external_exports.literal("VALUE_DOES_NOT_FIT"),type:external_exports.string().min(1)}),external_exports.strictObject({...OUTCOME_CELL,result:external_exports.literal("refused"),code:external_exports.enum(CORRECT_CELL_REFUSALS.filter(code2=>code2!=="VALUE_DOES_NOT_FIT"))})]),CorrectCellOutcomeSchema=external_exports.discriminatedUnion("result",[external_exports.strictObject({...OUTCOME_CELL,result:external_exports.literal("changed")}),external_exports.strictObject({...OUTCOME_CELL,result:external_exports.literal("unchanged")}),RefusedCellOutcomeSchema]),CorrectCellsResultSchema=external_exports.object({cells:external_exports.array(CorrectCellOutcomeSchema),acts:external_exports.array(ReviewActSchema),laterApply:external_exports.number().int().nonnegative(),checkedTypes:external_exports.array(external_exports.string().min(1)),lakeRead:external_exports.boolean()}),CORRECT_CELLS_REFUSED="CORRECT_CELLS_REFUSED",CorrectCellsRefusedDataSchema=external_exports.object({code:external_exports.literal(CORRECT_CELLS_REFUSED),cells:external_exports.array(RefusedCellOutcomeSchema),count:external_exports.number().int().positive()});var CORRECTED_DIFFERENCES_MAX=1e4;var CorrectedDifferencesInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema}),CORRECTED_DIFFERENCE_KINDS=["changed","left-out"],CorrectedDifferencesSchema=external_exports.discriminatedUnion("state",[external_exports.object({state:external_exports.literal("listed"),correctedDatasetId:DatasetIdSchema,correctedName:external_exports.string().min(1),builtFrom:external_exports.object({versionId:DatasetVersionIdSchema,loadNumber:external_exports.number().int().positive()}),rows:external_exports.array(external_exports.object({logicalId:external_exports.string().min(1),kind:external_exports.enum(CORRECTED_DIFFERENCE_KINDS)})).max(CORRECTED_DIFFERENCES_MAX),counts:external_exports.object({changed:external_exports.number().int().nonnegative(),leftOut:external_exports.number().int().nonnegative(),repeated:external_exports.number().int().nonnegative()})}),external_exports.object({state:external_exports.literal("unavailable"),reason:external_exports.enum(CORRECTED_ROWS_UNAVAILABLE_REASONS),message:external_exports.string().min(1).optional()})]);var LATER_CORRECTIONS_MAX_REFS=200;var LaterCorrectionsRefSchema=external_exports.strictObject({datasetId:external_exports.string().min(1),versionId:external_exports.string().min(1),producedAt:external_exports.iso.datetime()}),LaterCorrectionsInputSchema=external_exports.strictObject({refs:external_exports.array(LaterCorrectionsRefSchema).min(1).max(LATER_CORRECTIONS_MAX_REFS)}),VersionPointerSchema=external_exports.object({datasetId:external_exports.string().min(1),versionId:external_exports.string().min(1)}),CORRECTIONS_PIN_KINDS=["delivered","corrected"],LATER_CORRECTION_REASONS=["applied-after","newer-version"],LaterCorrectionsEntrySchema=external_exports.object({datasetId:external_exports.string().min(1),versionId:external_exports.string().min(1),producedAt:external_exports.iso.datetime(),applied:external_exports.boolean(),reason:external_exports.enum(LATER_CORRECTION_REASONS).optional(),unsure:external_exports.boolean().optional(),pinned:external_exports.enum(CORRECTIONS_PIN_KINDS).optional(),delivery:external_exports.object({datasetId:external_exports.string().min(1),name:external_exports.string().min(1),versionId:external_exports.string().min(1),loadNumber:external_exports.number().int().positive().optional()}).optional(),correctedDataset:external_exports.object({datasetId:external_exports.string().min(1),name:external_exports.string().min(1)}).optional(),newerDelivery:external_exports.object({versionId:external_exports.string().min(1),loadNumber:external_exports.number().int().positive().optional()}).optional(),rowsChanged:external_exports.number().int().nonnegative().optional(),reasons:external_exports.array(external_exports.string()),corrections:VersionPointerSchema.optional(),repin:VersionPointerSchema.optional()}),LaterCorrectionsSchema=external_exports.object({refs:external_exports.array(LaterCorrectionsEntrySchema)});var ReviewDeliverySchema=external_exports.object({versionId:DatasetVersionIdSchema,loadNumber:external_exports.number().int().nonnegative()}),ReviewBaselineMarkSchema=ReviewDeliverySchema.extend({markedBy:external_exports.string().min(1),markedAt:external_exports.iso.datetime()}),ReviewBaselineInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema}),ReviewBaselineSchema=external_exports.object({datasetId:DatasetIdSchema,baseline:ReviewBaselineMarkSchema.nullable(),current:ReviewDeliverySchema.nullable(),notYetReviewed:external_exports.number().int().nonnegative(),applyNotStarted:external_exports.object({code:external_exports.string().min(1),message:external_exports.string().min(1),remaining:external_exports.number().int().positive().optional()}).optional()}),MarkDeliveryReviewedInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,idempotencyKey:IdempotencyKeySchema.max(200)});var ChangesSinceReviewedInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema}),ChangesSinceReviewedSchema=external_exports.discriminatedUnion("state",[external_exports.object({state:external_exports.literal("never-marked"),datasetId:DatasetIdSchema}),external_exports.object({state:external_exports.literal("no-current-delivery"),datasetId:DatasetIdSchema,baseline:ReviewBaselineMarkSchema}),external_exports.object({state:external_exports.literal("current"),datasetId:DatasetIdSchema,baseline:ReviewBaselineMarkSchema}),external_exports.object({state:external_exports.literal("compared"),datasetId:DatasetIdSchema,baseline:ReviewBaselineMarkSchema,current:ReviewDeliverySchema,added:external_exports.number().int().nonnegative(),removed:external_exports.number().int().nonnegative(),changed:external_exports.number().int().nonnegative(),unidentifiedRows:external_exports.object({from:external_exports.number().int().nonnegative(),to:external_exports.number().int().nonnegative()})}),external_exports.object({state:external_exports.literal("not-comparable"),datasetId:DatasetIdSchema,baseline:ReviewBaselineMarkSchema,current:ReviewDeliverySchema,unkeyedSide:DatasetVersionDiffUnkeyedSideSchema})]);var SetReviewEnabledInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema,enabled:external_exports.boolean(),idempotencyKey:IdempotencyKeySchema.max(200)}),REVIEW_CORRECTED_COPY_STATES=["ready","creating","catching-up","behind","waiting","failed","archived","no-delivery","at-first-apply","retired","none"],ReviewCorrectedCopySchema=external_exports.enum(REVIEW_CORRECTED_COPY_STATES),ReviewEnabledViewSchema=external_exports.object({datasetId:DatasetIdSchema,reviewEnabled:external_exports.boolean(),correctedCopy:ReviewCorrectedCopySchema});var ReapplyCorrectionsKeySchema=IdempotencyKeySchema.max(512),ReapplyCorrectionsInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,idempotencyKey:ReapplyCorrectionsKeySchema}),REAPPLY_OUTCOMES=["started","joined","current","no-corrections","deferred","not-current","not-applicable"],ReapplyOutcomeSchema=external_exports.enum(REAPPLY_OUTCOMES),REAPPLY_STATES=["queued","running","completed","failed"],ReapplyStateSchema=external_exports.enum(REAPPLY_STATES),ReapplyCorrectionsResultSchema=external_exports.object({reapplyId:external_exports.string().min(1),state:ReapplyStateSchema,outcome:ReapplyOutcomeSchema,applyRecordId:external_exports.string().min(1).optional(),message:external_exports.string().min(1).optional(),replayed:external_exports.boolean()}),ReapplyCorrectionsAcceptDetailSchema=external_exports.object({reapplyId:external_exports.string().min(1),state:ReapplyStateSchema,outcome:ReapplyOutcomeSchema,datasetId:external_exports.string().min(1),sourceVersionId:external_exports.string().min(1),applyRecordId:external_exports.string().min(1).optional(),correctedVersionId:external_exports.string().min(1).optional(),message:external_exports.string().min(1).optional()}),ReapplyCorrectionsStatusInputSchema=external_exports.strictObject({reapplyId:external_exports.string().min(1)}),ReapplyCorrectionsStatusSchema=external_exports.strictObject({reapplyId:external_exports.string().min(1),state:ReapplyStateSchema,outcome:ReapplyOutcomeSchema,completionRecordId:external_exports.string().min(1).optional(),code:external_exports.string().min(1).optional(),error:external_exports.string().min(1).optional(),message:external_exports.string().min(1).optional()}),ReapplyCorrectionsCompletionDetailSchema=external_exports.object({outcome:ReapplyOutcomeSchema.optional(),datasetId:external_exports.string().min(1),sourceVersionId:external_exports.string().min(1),correctedVersionId:external_exports.string().min(1).optional()});var MAX_VERSION_CHANGES_PAGE=500;var MAX_VERSION_CHANGE_ID_LENGTH=200,VERSION_CHANGE_TYPES=["insert","delete","update"],VersionChangeTypeSchema=external_exports.enum(VERSION_CHANGE_TYPES),ListVersionChangesInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema,fromVersionId:DatasetVersionIdSchema,toVersionId:DatasetVersionIdSchema,cursor:external_exports.string().min(1).max(MAX_VERSION_CHANGE_ID_LENGTH).optional(),limit:external_exports.number().int().min(1).max(MAX_VERSION_CHANGES_PAGE).optional()}),VersionChangeImageSchema=external_exports.object({recordId:external_exports.string().min(1),values:external_exports.record(external_exports.string(),external_exports.unknown())}),VersionChangeSchema2=external_exports.object({logicalId:external_exports.string().min(1),changeType:VersionChangeTypeSchema,before:VersionChangeImageSchema.nullable(),after:VersionChangeImageSchema.nullable(),changedColumns:external_exports.array(external_exports.string())}),VersionChangesSchema=external_exports.discriminatedUnion("comparable",[external_exports.object({comparable:external_exports.literal(!0),fromVersionId:DatasetVersionIdSchema,toVersionId:DatasetVersionIdSchema,changes:external_exports.array(VersionChangeSchema2),nextCursor:external_exports.string().min(1).nullable(),unidentifiedRows:external_exports.object({from:external_exports.number().int().nonnegative(),to:external_exports.number().int().nonnegative()})}),external_exports.object({comparable:external_exports.literal(!1),fromVersionId:DatasetVersionIdSchema,toVersionId:DatasetVersionIdSchema,unkeyedSide:DatasetVersionDiffUnkeyedSideSchema})]);var REFERENCE_VALIDITY_COLUMNS={validFrom:"validFrom",validTo:"validTo"},REFERENCE_PROBLEMS_SHOWN_MAX=20,BoundTextSchema=external_exports.string().nullable(),ReferenceGroupSchema=external_exports.record(external_exports.string(),external_exports.string().nullable()),ReferenceRowBoundsSchema=external_exports.object({validFrom:BoundTextSchema,validTo:BoundTextSchema}),REFERENCE_WINDOW_PROBLEM_KINDS=["bad-bound","inverted","open-start","open-end","overlap","gap"],ReferenceWindowProblemSchema=external_exports.object({kind:external_exports.enum(REFERENCE_WINDOW_PROBLEM_KINDS),group:ReferenceGroupSchema,rows:external_exports.array(ReferenceRowBoundsSchema).min(1).max(2),column:external_exports.enum(["validFrom","validTo"]).optional(),from:external_exports.iso.date().optional(),to:external_exports.iso.date().optional()}),ReferenceSpanSchema=external_exports.object({from:external_exports.iso.date().nullable(),to:external_exports.iso.date().nullable()});var VALIDITY=new Set(Object.values(REFERENCE_VALIDITY_COLUMNS));var ReferenceCodelistNameSchema=external_exports.string().trim().min(3).max(128).regex(/^[a-z][a-z0-9_-]*(\.[a-z0-9_-]+)+$/);var ReferenceKeyCodelistsSchema=external_exports.record(external_exports.string().trim().min(1).max(128),ReferenceCodelistNameSchema),ReferenceCodelistProblemSchema=external_exports.object({group:ReferenceGroupSchema,row:ReferenceRowBoundsSchema,column:external_exports.string().min(1),code:external_exports.string(),codelist:external_exports.string().min(1),reason:external_exports.enum(["not-found","retired"]),suggestion:external_exports.string().min(1).optional()});var SetReferenceKeyCodelistsInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema,keyCodelists:ReferenceKeyCodelistsSchema,idempotencyKey:IdempotencyKeySchema.max(200)}),ReferenceKeyCodelistsAnswerSchema=external_exports.object({datasetId:DatasetIdSchema,keyCodelists:ReferenceKeyCodelistsSchema});var ReferenceCoverageProblemSchema=external_exports.object({group:ReferenceGroupSchema,from:external_exports.iso.date().nullable(),to:external_exports.iso.date().nullable()});var REFERENCE_ROW_SOURCE_COLUMN="source",REFERENCE_ROW_SOURCE_LINK_COLUMN="source_link",REFERENCE_ROW_SOURCE_COLUMNS=[REFERENCE_ROW_SOURCE_COLUMN,REFERENCE_ROW_SOURCE_LINK_COLUMN],RESERVED=new Set(REFERENCE_ROW_SOURCE_COLUMNS);var ReferenceSourceLinkProblemSchema=external_exports.object({group:ReferenceGroupSchema,row:ReferenceRowBoundsSchema,link:external_exports.string().min(1),message:external_exports.string().min(1)});var DECIMAL_TEXT=/^([+-]?)([0-9]*)(?:\.([0-9]*))?(?:[eE]([+-]?[0-9]+))?$/;function scaledOf(text){if(text.length>2016)throw new RangeError("decimal text is longer than 2000 digits");let match=DECIMAL_TEXT.exec(text);if(match===null)return;let[,sign="",whole="",fraction="",exponent="0"]=match;if(whole===""&&fraction==="")return;if(whole.length+fraction.length>2e3)throw new RangeError(`"${text.slice(0,24)}\u2026" has more than 2000 digits`);if(Math.abs(Number(exponent))>400)throw new RangeError(`exponent ${exponent.slice(0,24)} is outside \xB1400`);let magnitude=BigInt(whole+fraction),shift=Number(exponent)-fraction.length,units=sign==="-"?-magnitude:magnitude;return shift>=0?{units:units*10n**BigInt(shift),scale:0}:{units,scale:-shift}}function stripTrailingZeros(text){let end=text.length;for(;end>0&&text.charCodeAt(end-1)===48;)end-=1;return text.slice(0,end)}function formatScaled(units,scale){if(units===0n)return"0";let digits=(units<0n?-units:units).toString().padStart(scale+1,"0"),whole=digits.slice(0,digits.length-scale),fraction=stripTrailingZeros(digits.slice(digits.length-scale));return`${units<0n?"-":""}${whole}${fraction===""?"":`.${fraction}`}`}function canonicalDecimal(text){let scaled=scaledOf(text);return scaled===void 0?void 0:formatScaled(scaled.units,scaled.scale)}function gcd(a,b){let[x2,y]=[a<0n?-a:a,b<0n?-b:b];for(;y!==0n;)[x2,y]=[y,x2%y];return x2}function rational(num,den){if(den===0n)throw new RangeError("Rational with a zero denominator");let divisor=gcd(num,den)||1n,sign=den<0n?-1n:1n;return{num:sign*num/divisor,den:sign*den/divisor}}function rationalOfDecimal(text){let scaled=scaledOf(text);if(scaled===void 0)throw new RangeError(`"${text}" is not a decimal number`);return rational(scaled.units,10n**BigInt(scaled.scale))}function mul(a,b){return rational(a.num*b.num,a.den*b.den)}function div(a,b){return rational(a.num*b.den,a.den*b.num)}function pow(a,n){let magnitude=BigInt(Math.abs(n)),[num,den]=n>=0?[a.num,a.den]:[a.den,a.num];return rational(num**magnitude,den**magnitude)}var BASE_QUANTITIES=["L","M","T","I","\u0398","N","J"],DIMENSIONLESS=[0,0,0,0,0,0,0];function dim(partial2){let[L=0,M=0,T=0,I=0,\u0398=0,N=0,J=0]=BASE_QUANTITIES.map(q=>partial2[q]??0);return[L,M,T,I,\u0398,N,J]}function zip2(a,f){let[L=0,M=0,T=0,I=0,\u0398=0,N=0,J=0]=a.map(f);return[L,M,T,I,\u0398,N,J]}function mulDim(a,b){return zip2(a,(x2,i2)=>x2+(b[i2]??0))}function powDim(a,n){return zip2(a,x2=>x2*n)}function dimEquals(a,b){return a.every((x2,i2)=>x2===b[i2])}var NAMED_DIMENSIONS={dimensionless:DIMENSIONLESS,length:dim({L:1}),area:dim({L:2}),volume:dim({L:3}),mass:dim({M:1}),time:dim({T:1}),temperature:dim({\u0398:1}),speed:dim({L:1,T:-1}),flowRate:dim({L:3,T:-1}),massFlowRate:dim({M:1,T:-1}),pressure:dim({M:1,L:-1,T:-2}),energy:dim({M:1,L:2,T:-2}),power:dim({M:1,L:2,T:-3}),concentration:dim({M:1,L:-3}),amount:dim({N:1})};function isNamedDimension(name2){return name2 in NAMED_DIMENSIONS}var NAMED_DIMENSION_NAMES=Object.keys(NAMED_DIMENSIONS).filter(isNamedDimension);function dimensionName(v){return NAMED_DIMENSION_NAMES.find(name2=>dimEquals(NAMED_DIMENSIONS[name2],v))}function vectorText(v){let parts=BASE_QUANTITIES.flatMap((q,i2)=>{let e=v[i2]??0;return e===0?[]:[e===1?q:`${q}^${e}`]});return parts.length===0?"1":parts.join(" ")}function clean(entries){return Object.fromEntries([...entries].filter(([,e])=>e!==0))}function mulBasis(a,b){let out=new Map(Object.entries(a));for(let[name2,e]of Object.entries(b))out.set(name2,(out.get(name2)??0)+e);return clean(out)}function powBasis(a,n){return clean(Object.entries(a).map(([name2,e])=>[name2,e*n]))}var FRACTION_KIND="-fraction";function fractionKind(v){let leading=v.find(e=>e!==0)??0,inverse=powDim(v,-1),name2=dimensionName(v)??dimensionName(inverse),positive=leading<0?inverse:v;return`${name2??vectorText(positive).replaceAll(" ","\xB7")}${FRACTION_KIND}`}var SI="SI Brochure 9th ed. (BIPM, 2019, with the 2022 prefix update)",NIST="NIST SP 811 (2008) App. B.8",SP811_RATIOS="NIST SP 811 (2008) \xA77.10.3",BARE_BTU="Bare Btu and MMBtu name no one energy, so they never convert to joules: 40 CFR 98.6 defines the Btu at \u201Cabout 39.2 degrees Fahrenheit\u201D, while Part 98 Subpart A Table A-2 converts joules to Btu by 9.47817\xD710\u207B\u2074 (the International Table Btu, rounded); Alberta Quantification Methodologies give 1 Btu = 1,055.056 J and 1 mmBtu = 1.055 GJ, the Canada Energy Regulator 1 MMBtu = 1.0551 GJ, and Statistics Canada and Measurement Canada 1 Btu = 1,054.615 J. Use Btu_IT, MMBtu_IT, Btu_th or MMBtu_th for a stated Btu.",MASS=dim({M:1}),VOLUME=dim({L:3}),TIME=dim({T:1}),ENERGY=dim({M:1,L:2,T:-2}),DEFINITIONS=[{kind:"atomic",id:"ppm",dimension:DIMENSIONLESS,factor:"0.000001",cite:`${SI} \xA75.4.7 (parts per million, 10\u207B\u2076)`},{kind:"atomic",id:"%",dimension:DIMENSIONLESS,factor:"0.01",cite:`${SI} \xA75.4.7 (percent, 10\u207B\xB2)`},{kind:"atomic",id:"fraction",dimension:DIMENSIONLESS,factor:"1",cite:`${SI} \xA72.3.3 (quantities of dimension one)`},{kind:"atomic",id:"g",dimension:MASS,factor:"0.001",prefixable:!0,cite:`${SI} ch. 3 (the kilogram is the only coherent SI unit that includes a prefix; the gram is 10\u207B\xB3 kg)`},{kind:"derived",id:"kg",expression:"kg"},{kind:"atomic",id:"t",dimension:MASS,factor:"1000",prefixable:"kilo-and-larger",cite:`${SI} Table 8 (tonne = 1 Mg = 10\xB3 kg)`},{kind:"atomic",id:"lb",dimension:MASS,factor:"0.45359237",cite:`${NIST} (avoirdupois pound = 0.45359237 kg exactly)`},{kind:"derived",id:"t CH4",expression:"t",basis:"CH4"},{kind:"derived",id:"t CO2",expression:"t",basis:"CO2"},{kind:"derived",id:"t CO2e",expression:"t",basis:"CO2e"},{kind:"derived",id:"kg CH4",expression:"kg",basis:"CH4"},{kind:"atomic",id:"Sm3",dimension:VOLUME,factor:"1",basis:"Sm3",cite:"One cubic metre of gas at the reference conditions of the framework that names it; which conditions is that framework\u2019s choice (AER Directive 017 and the BC Measurement Guideline use 15 \xB0C and 101.325 kPa; programs differ), so the basis is the id itself"},{kind:"vocabulary",id:"MSm3",dimension:VOLUME,basis:"Sm3",reason:"`M` is a thousand in oilfield usage and a million in Norwegian (Sodir) reporting, so its multiplier is not established and no factor to Sm3 is asserted"},{kind:"vocabulary",id:"e3m3",dimension:VOLUME,basis:"Sm3",reason:'Thousand cubic metres, the gas-volume unit Canadian regulators require (BC Measurement Guideline v2.4 \xA74.2: monthly gas volumes "must be reported in units of e3m3", at 101.325 kPa and 15 \xB0C); `e3m3 \u2192 Sm3` is \xD71000 only when both sit at the same base conditions, which is the framework\u2019s choice, so no factor is asserted'},{kind:"vocabulary",id:"MBOE",dimension:VOLUME,basis:"boe",reason:"`M` is thousand in oilfield usage, but the OGCI reporting framework writes \u201CMboe/day\u201D for million barrels of oil equivalent per day, so the multiplier is 10\xB3 or 10\u2076 by source; no factor to boe is asserted"},{kind:"derived",id:"kg CO2e/boe",expression:"kg CO2e / boe",dimensionLabel:"intensity"},{kind:"derived",id:"t CH4/1000 hp",expression:"t CH4 / (1000 hp)",dimensionLabel:"intensity"},{kind:"atomic",id:"h",dimension:TIME,factor:"3600",cite:`${SI} Table 8 (hour = 3600 s)`},{kind:"atomic",id:"s",dimension:TIME,factor:"1",prefixable:!0,cite:`${SI} Table 2 (second)`},{kind:"atomic",id:"hp",dimension:dim({M:1,L:2,T:-3}),factor:"745.69987158227022",cite:`${NIST} (mechanical horsepower = 550 ft\xB7lbf/s; standard gravity 9.80665 m/s\xB2, 3rd CGPM 1901)`},{kind:"derived",id:"kW",expression:"kW"},{kind:"atomic",id:"count",dimension:DIMENSIONLESS,factor:"1",basis:"count",cite:"A tally of items; dimension one, never a ratio"},{kind:"atomic",id:"J",dimension:ENERGY,factor:"1",prefixable:!0,cite:`${SI} Table 4 (joule)`},{kind:"derived",id:"kJ",expression:"kJ"},{kind:"derived",id:"MJ",expression:"MJ"},{kind:"derived",id:"GJ",expression:"GJ"},{kind:"derived",id:"TJ",expression:"TJ"},{kind:"derived",id:"kWh",expression:"kWh"},{kind:"derived",id:"\xB5g/L",expression:"\xB5g/L"},{kind:"derived",id:"mg/L",expression:"mg/L"},{kind:"derived",id:"g/L",expression:"g/L"},{kind:"atomic",id:"NTU",dimension:DIMENSIONLESS,factor:"1",basis:"NTU",dimensionLabel:"turbidity",cite:"EPA Method 180.1 (white-light nephelometric turbidity unit); factor 1 is an identity within the basis NTU, not a physical SI factor"},{kind:"atomic",id:"FNU",dimension:DIMENSIONLESS,factor:"1",basis:"FNU",dimensionLabel:"turbidity",cite:"ISO 7027 (near-infrared formazin nephelometric unit); factor 1 is an identity within the basis FNU, not a physical SI factor"},{kind:"atomic",id:"\xB0C",dimension:dim({\u0398:1}),factor:"1",offset:"273.15",cite:`${SI} \xA72.3.1 (degree Celsius: t/\xB0C = T/K \u2212 273.15)`},{kind:"atomic",id:"pH",dimension:DIMENSIONLESS,factor:"1",basis:"pH",cite:"IUPAC Gold Book (pH = \u2212log\u2081\u2080 a(H\u207A)); logarithmic; factor 1 is an identity within the basis pH, not a physical SI factor"},{kind:"derived",id:"kg CO2",expression:"kg",basis:"CO2"},{kind:"atomic",id:"scf",dimension:VOLUME,factor:"0.028316846592",basis:"scf",cite:`${NIST} (cubic foot = 0.3048\xB3 m\xB3 exactly); 40 CFR 98.6 (standard conditions are \u201Ceither 60 or 68 degrees Fahrenheit and 14.7 pounds per square inch absolute\u201D, the choice of the program, so scf-family conversions assume one program\u2019s reference conditions)`},{kind:"atomic",id:"Mcf",dimension:VOLUME,factor:"28.316846592",cite:`40 CFR 98.6 (Mcf means thousand cubic feet); ${NIST} (cubic foot = 0.3048\xB3 m\xB3 exactly). 98.6 gives Mcf no reference conditions and the abbreviation alone does not establish them, so it carries no basis and the package refuses Mcf \u2192 scf rather than assume`},{kind:"atomic",id:"boe",dimension:VOLUME,factor:"1",basis:"boe",cite:"A barrel of oil equivalent is a convention\u2019s reference unit; its energy and gas equivalence are data in the program that chose it. Factor 1 is an identity within the basis boe, not a physical SI factor"},{kind:"atomic",id:"MMBtu",dimension:ENERGY,factor:"1000000",basis:"Btu",cite:`${BARE_BTU} 40 CFR Part 98 Subpart A Table A-2 converts Btu to MMBtu by 10\u207B\u2076`},{kind:"atomic",id:"m",dimension:dim({L:1}),factor:"1",prefixable:!0,cite:`${SI} Table 2 (metre)`},{kind:"atomic",id:"L",dimension:VOLUME,factor:"0.001",prefixable:!0,cite:`${SI} Table 8 (litre = 10\u207B\xB3 m\xB3)`},{kind:"atomic",id:"Pa",dimension:dim({M:1,L:-1,T:-2}),factor:"1",prefixable:!0,cite:`${SI} Table 4 (pascal)`},{kind:"atomic",id:"W",dimension:dim({M:1,L:2,T:-3}),factor:"1",prefixable:!0,cite:`${SI} Table 4 (watt)`},{kind:"atomic",id:"Wh",dimension:ENERGY,factor:"3600",prefixable:!0,cite:`${SI} Table 8 (hour = 3600 s) and Table 4 (watt = J/s), so 1 Wh = 3600 J`},{kind:"atomic",id:"K",dimension:dim({\u0398:1}),factor:"1",prefixable:!0,cite:`${SI} Table 2 (kelvin)`},{kind:"atomic",id:"\xB0F",dimension:dim({\u0398:1}),factor:{num:"5",den:"9"},offset:"459.67",cite:`${NIST} (T/K = (t/\xB0F + 459.67) \xD7 5/9)`},{kind:"atomic",id:"min",dimension:TIME,factor:"60",cite:`${SI} Table 8 (minute = 60 s)`},{kind:"atomic",id:"d",dimension:TIME,factor:"86400",cite:`${SI} Table 8 (day = 86400 s)`},{kind:"atomic",id:"ft",dimension:dim({L:1}),factor:"0.3048",cite:`${NIST} (international foot = 0.3048 m exactly)`},{kind:"atomic",id:"psi",dimension:dim({M:1,L:-1,T:-2}),factor:{num:"8896443230521",den:"1290320000"},cite:`${NIST} (pound-force per square inch = 0.45359237 kg \xD7 9.80665 m/s\xB2 \xF7 (0.0254 m)\xB2)`},{kind:"derived",id:"kPa",expression:"kPa"},{kind:"derived",id:"kg CO2e",expression:"kg",basis:"CO2e"},{kind:"atomic",id:"Btu",dimension:ENERGY,factor:"1",basis:"Btu",cite:BARE_BTU},{kind:"atomic",id:"Btu_IT",dimension:ENERGY,factor:"1055.05585262",cite:`${NIST} (the International Table Btu, Btu_IT, is 1.055 055 852 62 kJ exactly, from the International Table calorie of 4.1868 J)`},{kind:"atomic",id:"MMBtu_IT",dimension:ENERGY,factor:"1055055852.62",cite:`${NIST} (Btu_IT = 1055.05585262 J exactly); MMBtu_IT is 10\u2076 Btu_IT`},{kind:"atomic",id:"Btu_th",dimension:ENERGY,factor:{num:"23722880951",den:"22500000"},cite:`${NIST} (Btu_th is based on the thermochemical calorie, 4.184 J exactly): 453.59237 g (lb) \xD7 4.184 J/g/K \xD7 5/9 K`},{kind:"vocabulary",id:"Btu_39",dimension:ENERGY,basis:"Btu_39",reason:"40 CFR 98.6 defines the Btu at \u201Cabout 39.2 degrees Fahrenheit\u201D; UCUM [Btu_39] is the Btu at 39 \xB0F, about 1.05967 kJ. The registry holds the id as vocabulary only: it refuses every other Btu, and no factor to joules is asserted"},{kind:"atomic",id:"Mscf",dimension:VOLUME,factor:"28.316846592",basis:"scf",cite:"40 CFR 98.6 (Mscf means thousand standard cubic feet)"},{kind:"atomic",id:"MMscf",dimension:VOLUME,factor:"28316.846592",basis:"scf",cite:"40 CFR 98.6 (Mscf means thousand standard cubic feet); 40 CFR Part 98 Subpart Y writes \u201Cmillion (MM) standard cubic feet per year, MMscf/year\u201D"},{kind:"atomic",id:"cf",dimension:VOLUME,factor:"0.028316846592",cite:`${NIST} (international cubic foot = 0.3048\xB3 m\xB3 exactly)`},{kind:"atomic",id:"MMcf",dimension:VOLUME,factor:"28316.846592",cite:`${NIST} (international cubic foot = 0.3048\xB3 m\xB3 exactly); MMcf is 10\u2076 cf`},{kind:"atomic",id:"ppb",dimension:DIMENSIONLESS,factor:"0.000000001",cite:`${SI} \xA75.4.7 (ppb: meanings are language dependent; the package reads the US-English 10\u207B\u2079); ${SP811_RATIOS} (ppm, ppb and ppt are not acceptable for use with the SI, and a law or regulation may require them). Names no kind of fraction`},{kind:"atomic",id:"mol",dimension:dim({N:1}),factor:"1",prefixable:!0,cite:`${SI} Table 2 (mole)`},{kind:"derived",id:"ppmv",expression:"\xB5L/L",cite:`Package definition: ppm by volume, a volume fraction of 10\u207B\u2076 written \xB5L/L (${SP811_RATIOS} does not accept ppm in SI use and defines no ppmv)`},{kind:"derived",id:"ppmw",expression:"mg/kg",cite:`Package definition: ppm by mass, a mass fraction of 10\u207B\u2076 written mg/kg (${SP811_RATIOS} does not accept ppm in SI use and defines no ppmw)`},{kind:"derived",id:"MMBtu_th",expression:"1000000 Btu_th",cite:`${NIST} (Btu_th, the thermochemical Btu, from the thermochemical calorie of 4.184 J exactly); MMBtu_th is 10\u2076 Btu_th`}];var ALIASES={mmBtu:"MMBtu","million Btu":"MMBtu",scfh:"scf/h","scf/hr":"scf/h",degC:"\xB0C"};var SI_PREFIXES={Q:30,R:27,Y:24,Z:21,E:18,P:15,T:12,G:9,M:6,k:3,h:2,da:1,d:-1,c:-2,m:-3,\u00B5:-6,n:-9,p:-12,f:-15,a:-18,z:-21,y:-24,r:-27,q:-30},PREFIX_ALIASES=new Map([["u","\xB5"],["\u03BC","\xB5"]]),canonicalPrefix=prefix=>PREFIX_ALIASES.get(prefix)??prefix;function prefixExponent(prefix){let canonical=canonicalPrefix(prefix);return Object.hasOwn(SI_PREFIXES,canonical)?SI_PREFIXES[canonical]:void 0}function splitPrefix(token,isPrefixable){for(let length of[2,1]){let prefix=token.slice(0,length),rest=token.slice(length);if(rest!==""&&prefixExponent(prefix)!==void 0&&isPrefixable(rest,prefix))return{prefix:canonicalPrefix(prefix),rest}}}var fail=(code2,message,part2)=>({ok:!1,code:code2,message,...part2===void 0?{}:{part:part2}}),ok=unit2=>({ok:!0,unit:unit2}),SUPERSCRIPT=new Map([["\xB2",2],["\xB3",3]]),NUMBER_PREFIX=/^(\d{1,12}(?:\.\d{1,12})?)\s+(\S.*)$/,MAX_EXPRESSION_LENGTH=64,MAX_EXPONENT=12,MAX_PRODUCT_TERMS=8,EXPONENT_SUFFIX=/^(.+?)(?:\^(-?\d+)|([²³])|([23]))$/;function refuseAffine(unit2){if(unit2.offset!==void 0)throw new RangeError(`"${unit2.text}" is a temperature scale with an offset; it stands alone, never with a multiplier, an exponent, a product or a ratio`)}var numeratorOf=u=>u.numerator??u.vector,denominatorOf=u=>u.denominator??DIMENSIONLESS;function kinded(unit2){let numerator=numeratorOf(unit2);return dimEquals(unit2.vector,DIMENSIONLESS)&&!dimEquals(numerator,DIMENSIONLESS)?{...unit2,basis:mulBasis(unit2.basis,{[fractionKind(numerator)]:1})}:unit2}function combine(a,b,text,sign){refuseAffine(a),refuseAffine(b);let factor=a.factor===void 0||b.factor===void 0?void 0:sign===1?mul(a.factor,b.factor):div(a.factor,b.factor),vector=mulDim(a.vector,sign===1?b.vector:powDim(b.vector,-1)),basis=mulBasis(a.basis,sign===1?b.basis:powBasis(b.basis,-1)),[bNum,bDen]=sign===1?[numeratorOf(b),denominatorOf(b)]:[denominatorOf(b),numeratorOf(b)];return{text,vector,basis,numerator:mulDim(numeratorOf(a),bNum),denominator:mulDim(denominatorOf(a),bDen),...factor===void 0?{}:{factor},citations:[...new Set([...a.citations,...b.citations])]}}function raised(unit2,exponent,text){if(!Number.isInteger(exponent)||Math.abs(exponent)>MAX_EXPONENT)throw new RangeError(`exponent ${exponent} is outside \xB1${MAX_EXPONENT}`);refuseAffine(unit2);let[numerator,denominator]=exponent>0?[numeratorOf(unit2),denominatorOf(unit2)]:[denominatorOf(unit2),numeratorOf(unit2)];return{text,vector:powDim(unit2.vector,exponent),basis:powBasis(unit2.basis,exponent),numerator:powDim(numerator,Math.abs(exponent)),denominator:powDim(denominator,Math.abs(exponent)),...unit2.factor===void 0?{}:{factor:pow(unit2.factor,exponent)},citations:unit2.citations}}function suffixed(text,exponent){return(exponent===2||exponent===3)&&!/\d$/.test(text)?`${text}${exponent}`:`${text}^${exponent}`}function prefixed(prefix,atom){let exponent=prefixExponent(prefix);if(exponent===void 0||atom.factor===void 0)return;let scale=rational(10n**BigInt(Math.abs(exponent)),1n);return{text:`${prefix}${atom.text}`,vector:atom.vector,basis:atom.basis,numerator:numeratorOf(atom),denominator:denominatorOf(atom),factor:exponent>=0?mul(atom.factor,scale):div(atom.factor,scale),citations:atom.citations}}function resolveToken(token,lookup2){let name2=lookup2.alias(token)??token,registered=lookup2.byId(name2);if(registered!==void 0)return registered;let split=splitPrefix(name2,(id,prefix)=>lookup2.prefixable(id,prefix)!==void 0),atom=split&&lookup2.prefixable(split.rest,split.prefix);return split&&atom?prefixed(split.prefix,atom):void 0}function resolvePiece(piece,lookup2){let text=piece.trim(),whole=resolveToken(text,lookup2);if(whole!==void 0)return ok(whole);let match=EXPONENT_SUFFIX.exec(text);if(match!==null){let[,base="",caret,superscript,digit]=match,exponent=caret!==void 0?Number(caret):SUPERSCRIPT.get(superscript??"")??Number(digit),unit2=resolveToken(base.trim(),lookup2);if(unit2!==void 0)return!Number.isInteger(exponent)||exponent===0||Math.abs(exponent)>MAX_EXPONENT?fail("UNIT_MALFORMED",`Exponent of "${text}" must be a non-zero whole number within \xB1${MAX_EXPONENT}.`):ok(raised(unit2,exponent,suffixed(unit2.text,exponent)))}return fail("UNIT_UNKNOWN",`Unknown unit "${text}".`,text)}function resolveSide(side,lookup2,allowMultiplier=!0){let text=side.trim(),wrapped=/^\((.*)\)$/.exec(text);wrapped!==null&&(text=(wrapped[1]??"").trim());let whole=resolveToken(text,lookup2);if(whole!==void 0)return ok(whole);let multiplier=allowMultiplier?NUMBER_PREFIX.exec(text):null;if(multiplier!==null){let[,number4="",rest=""]=multiplier,scale=rationalOfDecimal(number4);if(scale.num<=0n)return fail("UNIT_MALFORMED",`Multiplier "${number4}" must be greater than zero.`);let inner=resolveSide(rest,lookup2,!1);if(!inner.ok)return inner;let scaled=raised(inner.unit,1,`${canonicalDecimal(number4)} ${inner.unit.text}`);return ok(inner.unit.factor===void 0?scaled:{...scaled,factor:mul(inner.unit.factor,scale)})}let pieces=text.split(/[·*]/);if(pieces.length>MAX_PRODUCT_TERMS)return fail("UNIT_MALFORMED",`"${text}" has more than ${MAX_PRODUCT_TERMS} terms.`);let result;for(let piece of pieces){let resolved=resolvePiece(piece,lookup2);if(!resolved.ok)return resolved;result=result===void 0?resolved.unit:combine(result,resolved.unit,`${result.text}\xB7${resolved.unit.text}`,1)}return result===void 0?fail("UNIT_UNKNOWN",`Unknown unit "${text}".`,text):ok(result)}function resolveExpression2(input2,lookup2){if(input2.length>MAX_EXPRESSION_LENGTH)return fail("UNIT_MALFORMED",`A unit is at most ${MAX_EXPRESSION_LENGTH} characters.`);try{return resolveBounded(input2,lookup2)}catch(error62){if(error62 instanceof RangeError)return fail("UNIT_MALFORMED",`"${input2.trim()}" is not a usable unit: ${error62.message}.`);throw error62}}function resolveBounded(input2,lookup2){let trimmed=input2.trim();if(trimmed==="")return fail("UNIT_EMPTY","Unit is empty.");let text=lookup2.alias(trimmed)??trimmed,whole=lookup2.byId(text);if(whole!==void 0)return ok(whole);let parts=text.split("/");if(parts.length===1){let side=resolveSide(text,lookup2);return side.ok?ok(kinded(side.unit)):side}if(parts.length>2)return fail("UNIT_MALFORMED",`"${text}" has more than one "/".`);let[left="",right=""]=parts.map(p=>p.trim());if(left===""||right==="")return fail("UNIT_MALFORMED",`"${text}" has an empty side around "/".`);if(/[·*]/.test(right)&&!/^\(.*\)$/.test(right))return fail("UNIT_MALFORMED",`"${text}" has a product after "/"; "/" binds only to the term after it, so write the denominator in parentheses ("kg/(m\xB7s)").`);let numerator=resolveSide(left,lookup2);if(!numerator.ok)return numerator;let denominator=resolveSide(right,lookup2);if(!denominator.ok)return denominator;let ratio=combine(numerator.unit,denominator.unit,`${numerator.unit.text}/${denominator.unit.text}`,-1);return ok(lookup2.byId(ratio.text)??kinded(ratio))}function rationalOfFactor(factor){return typeof factor=="string"?rationalOfDecimal(factor):rational(BigInt(factor.num),BigInt(factor.den))}var resolvedById=new Map,prefixPolicies=new Map;function admits(policy,prefix){return policy===void 0?!1:policy===!0||prefix===void 0||(prefixExponent(prefix)??0)>=3}var lookup={byId:id=>resolvedById.get(id),prefixable:(id,prefix)=>admits(prefixPolicies.get(id),prefix)?resolvedById.get(id):void 0,alias:text=>Object.hasOwn(ALIASES,text)?ALIASES[text]:void 0};for(let def of DEFINITIONS){if(def.kind==="derived")continue;let basis={[def.basis??""]:1};resolvedById.set(def.id,{text:def.id,vector:def.dimension,basis:def.basis===void 0?{}:basis,...def.kind==="atomic"?{factor:rationalOfFactor(def.factor)}:{},...def.kind==="atomic"&&def.offset!==void 0?{offset:def.offset}:{},citations:def.kind==="atomic"?[def.cite]:[],registeredId:def.id,...def.kind==="atomic"&&def.dimensionLabel!==void 0?{dimensionLabel:def.dimensionLabel}:{}}),def.kind==="atomic"&&def.prefixable!==void 0&&prefixPolicies.set(def.id,def.prefixable)}var pending=DEFINITIONS.filter(def=>def.kind==="derived");for(;pending.length>0;){let stillPending=pending.filter(def=>{if(def.kind!=="derived")return!1;let result=resolveExpression2(def.expression,lookup);if(!result.ok)return!0;let{unit:unit2}=result;return resolvedById.set(def.id,{...unit2,text:def.id,basis:def.basis===void 0?unit2.basis:mulBasis(unit2.basis,{[def.basis]:1}),citations:def.cite===void 0?unit2.citations:[...unit2.citations,def.cite],registeredId:def.id,...def.basis===void 0?{}:{declaredBasis:def.basis},...def.dimensionLabel===void 0?{}:{dimensionLabel:def.dimensionLabel}}),!1});if(stillPending.length===pending.length)throw new Error(`units: unresolvable derived definitions: ${stillPending.map(d=>d.id).join(", ")}`);pending=stillPending}for(let def of DEFINITIONS){let policy=def.kind==="derived"?prefixPolicies.get(def.expression):void 0;def.kind==="derived"&&def.basis!==void 0&&policy!==void 0&&prefixPolicies.set(def.id,policy)}var dimensionOfResolved=resolved=>resolved.dimensionLabel??dimensionName(resolved.vector)??"derived";function toUnit(resolved){let{factor,offset}=resolved;return{id:resolved.text,dimension:dimensionOfResolved(resolved),vector:resolved.vector,basis:resolved.basis,...factor===void 0?{}:{factor:{num:factor.num.toString(),den:factor.den.toString()}},...offset===void 0?{}:{offset},citations:resolved.citations}}var UNITS=DEFINITIONS.flatMap(def=>{let resolved=resolvedById.get(def.id);return resolved===void 0?[]:[toUnit(resolved)]}),UNIT_BY_ID=new Map(UNITS.map(u=>[u.id,u]));var NONZERO_INTEGER=new RegExp(`^-?[1-9][0-9]{0,${1999}}$`);var INT128_MAX=2n**127n-1n;var c=(value2,from,to,places,expected)=>({name:`${value2} ${from} to ${to} at ${places}`,value:value2,from,to,places,expected}),UNIT_CONFORMANCE_CASES=[c("1000","kg","t",9,"1"),c("1","kWh","MJ",9,"3.6"),c("5","kg","lb",9,"11.023113109"),c("1","lb","g",9,"453.59237"),c("1","kW","hp",9,"1.34102209"),c("7200","s","h",9,"2"),c("1","s","h",9,"0.000277778"),c("100","\xB0C","K",9,"373.15"),c("-40","\xB0C","\xB0F",9,"-40"),c("212","\xB0F","\xB0C",9,"100"),c("0","K","\xB0C",9,"-273.15"),c("32","\xB0F","\xB0C",0,"0"),c("212","\xB0F","\xB0C",0,"100"),c("0","\xB0C","\xB0F",0,"32"),c("100","\xB0C","\xB0F",0,"212"),c("-40","\xB0C","\xB0F",0,"-40"),c("98.6","\xB0F","\xB0C",2,"37"),c("100","\xB0F","\xB0C",2,"37.78"),c("0","\xB0F","\xB0C",0,"-18"),c("0","\xB0F","\xB0C",2,"-17.78"),c("100.5","\xB0C","\xB0F",0,"213"),c("2.5","mg/L","g/L",9,"0.0025"),c("1","mg/L","kg/m3",9,"0.001"),c("1","Mscf","scf",9,"1000"),c("1","Mcf","m3",9,"28.316846592"),c("1","MMBtu_IT","GJ",9,"1.055055853"),c("1","MMBtu_th","GJ",9,"1.054350264"),c("0.5","fraction","%",9,"50"),c("10000","ppm","%",9,"1"),c("3","mg/kg","ppmw",9,"3"),c("1","kg CH4","t CH4",9,"0.001"),c("1","t CH4/1000 hp","kg CH4/hp",9,"1"),c("101.325","kPa","psi",9,"14.695948776"),c("1","m3/h","L/min",9,"16.666666667"),c("0.5","g","kg",3,"0.001"),c("-0.5","g","kg",3,"-0.001"),c("1.5","g","kg",3,"0.002"),c("99999999999999999999","g","kg",3,"99999999999999999.999"),c("5000","kW","hp",9,"6705.110447975"),c("5000","hp","kW",9,"3728.499357911"),c("1000000","kW","hp",9,"1341022.089595028"),c("0.000000005","kg","g",9,"0.000005"),c("123456789.123456789","kg","t",9,"123456.789123457"),c("50000000000000000000000000","kW","W",9,"50000000000000000000000000000")];var REFERENCE_UNIT_REFUSAL_CODES=["UNIT_EMPTY","UNIT_UNKNOWN","UNIT_MALFORMED"],ReferenceUnitProblemSchema=external_exports.object({group:ReferenceGroupSchema,row:ReferenceRowBoundsSchema,unit:external_exports.string().nullable(),code:external_exports.enum(REFERENCE_UNIT_REFUSAL_CODES),message:external_exports.string().min(1)});var REFERENCE_VERDICT_STATES=["passed","failed","too-large"],REFERENCE_VERDICT_SHAPE="reference-values/v2",ReferenceVerdictSchema=external_exports.object({shape:external_exports.literal(REFERENCE_VERDICT_SHAPE),state:external_exports.enum(REFERENCE_VERDICT_STATES),rowCount:external_exports.number().int().nonnegative(),span:ReferenceSpanSchema.nullable(),window:external_exports.array(ReferenceWindowProblemSchema).max(REFERENCE_PROBLEMS_SHOWN_MAX),windowCount:external_exports.number().int().nonnegative(),coverage:external_exports.array(ReferenceCoverageProblemSchema).max(REFERENCE_PROBLEMS_SHOWN_MAX),coverageCount:external_exports.number().int().nonnegative(),unit:external_exports.array(ReferenceUnitProblemSchema).max(REFERENCE_PROBLEMS_SHOWN_MAX),unitCount:external_exports.number().int().nonnegative(),codelist:external_exports.array(ReferenceCodelistProblemSchema).max(REFERENCE_PROBLEMS_SHOWN_MAX),codelistCount:external_exports.number().int().nonnegative(),sourceLink:external_exports.array(ReferenceSourceLinkProblemSchema).max(REFERENCE_PROBLEMS_SHOWN_MAX),sourceLinkCount:external_exports.number().int().nonnegative(),codelists:ReferenceKeyCodelistsSchema,comparedVersionId:DatasetVersionIdSchema.nullable()});var ReferenceCheckFailureSchema=external_exports.object({code:external_exports.string().min(1),message:external_exports.string().min(1),tries:external_exports.number().int().positive(),at:external_exports.iso.datetime()});var VERSION_READINESS_STATES=["ready","blocked","not-evaluated","stale"],VersionReadinessStateSchema=external_exports.enum(VERSION_READINESS_STATES),REFERENCE_READINESS_REASONS=["save-not-sealed","save-failed","reference-unchecked","reference-window","reference-coverage","reference-unit","reference-codelist","reference-source-link"],VERSION_READINESS_STALE_REASONS=["ruleset-changed","quality-run-on-another-pin","corrections-not-reapplied","review-not-carried",...REFERENCE_READINESS_REASONS],VersionReadinessStaleReasonSchema=external_exports.enum(VERSION_READINESS_STALE_REASONS),VersionReadinessInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema}),RuleResultDecidedSchema=external_exports.object({by:external_exports.string().min(1),at:external_exports.iso.datetime(),reason:external_exports.string().min(1)}),CappedRuleSchema=external_exports.object({rulesetId:ValidationRulesetIdSchema,rulesetVersion:external_exports.number().int().positive(),rulesetName:external_exports.string(),ruleIndex:external_exports.number().int().nonnegative(),decided:RuleResultDecidedSchema.nullable()});var UnlineagedDismissalSchema=external_exports.object({actId:external_exports.string().min(1),ruleIndex:external_exports.number().int().nonnegative(),column:external_exports.string().min(1),selection:ReviewSelectionSchema,body:external_exports.string().optional(),ambiguous:external_exports.boolean(),candidates:external_exports.array(external_exports.object({rulesetId:ValidationRulesetIdSchema,rulesetVersion:external_exports.number().int().positive(),rulesetName:external_exports.string()})).min(1),lineages:external_exports.array(external_exports.object({rulesetId:ValidationRulesetIdSchema,rulesetVersion:external_exports.number().int().positive(),rulesetName:external_exports.string()})).min(1)}),VersionReadinessQualityRunPendingSchema=external_exports.object({qualityRunId:external_exports.string().min(1),state:external_exports.enum(["PENDING","RUNNING"])}),VersionReadinessQualityRunFailureSchema=external_exports.object({qualityRunId:external_exports.string().min(1),code:external_exports.string().min(1),message:external_exports.string().min(1),retryAt:external_exports.iso.datetime().optional()}),VersionReadinessSchema=external_exports.object({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,state:VersionReadinessStateSchema,reason:VersionReadinessStaleReasonSchema.optional(),blocking:external_exports.number().int().nonnegative(),blockingFlags:external_exports.number().int().nonnegative().optional(),blockingRuleFailures:external_exports.number().int().nonnegative().optional(),warnings:external_exports.number().int().nonnegative(),open:external_exports.number().int().nonnegative(),qualityRunId:external_exports.string().min(1).nullable(),rulesetDeclared:external_exports.boolean(),dismissalsUnaccounted:external_exports.boolean(),dismissalsUnlineaged:external_exports.array(UnlineagedDismissalSchema).optional(),cappedRules:external_exports.array(CappedRuleSchema),carryFailure:CarryFailureSchema.optional(),carryRetrying:CarryFailureSchema.optional(),qualityRunPending:VersionReadinessQualityRunPendingSchema.optional(),qualityRunFailure:VersionReadinessQualityRunFailureSchema.optional(),qualityRunOwed:external_exports.literal(!0).optional(),reference:ReferenceVerdictSchema.optional(),referenceCheckFailure:ReferenceCheckFailureSchema.optional()}),RetryReviewCarryInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,idempotencyKey:IdempotencyKeySchema.max(200)}),RetryReviewCarryResultSchema=external_exports.object({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,retried:external_exports.boolean()});var DecideRuleResultInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,rulesetId:ValidationRulesetIdSchema,rulesetVersion:external_exports.number().int().positive(),ruleIndex:external_exports.number().int().nonnegative(),reason:external_exports.string().trim().min(1).max(2e3),idempotencyKey:IdempotencyKeySchema.max(200)}),RuleResultDecisionSchema=CappedRuleSchema.extend({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,decided:RuleResultDecidedSchema,receiptId:external_exports.string().min(1),alreadyDecided:external_exports.literal(!0).optional()});var PublishOverridesSchema=external_exports.object({apply:external_exports.enum(["in-flight","failed","couldnt-apply"]),applyRecordId:external_exports.string().min(1).optional(),started:external_exports.boolean().optional(),waiting:external_exports.number().int().nonnegative().optional(),failureCode:external_exports.string().optional(),column:external_exports.string().min(1).optional(),remaining:external_exports.number().int().positive().optional(),transient:external_exports.boolean().optional(),columns:external_exports.array(external_exports.string().min(1)).optional()}),PromoteIfReadyInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,idempotencyKey:IdempotencyKeySchema.max(512)}),PROMOTE_IF_READY_OUTCOMES=["promoted","held"],PromoteIfReadyResultSchema=external_exports.object({outcome:external_exports.enum(PROMOTE_IF_READY_OUTCOMES),readiness:VersionReadinessSchema}),RowCheckFindingsInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,recordIds:external_exports.array(external_exports.string().min(1).max(200)).min(1).max(500)}),RowCheckFindingSchema=external_exports.object({recordId:external_exports.string().min(1),rulesetId:external_exports.string().min(1),rulesetVersion:external_exports.number().int().positive(),rulesetName:external_exports.string(),ruleIndex:external_exports.number().int().nonnegative(),column:external_exports.string().min(1),onBreak:RuleOnBreakSchema,evaluated:external_exports.boolean(),atSource:external_exports.boolean()}),RowCheckFindingsSchema=external_exports.object({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,findings:external_exports.array(RowCheckFindingSchema),unaccounted:external_exports.boolean(),decidedCappedWarnings:external_exports.boolean().optional(),checksNotCurrent:external_exports.enum(["not-run","stale"]).optional()});var DATASET_HISTORY_KINDS=["data-version","full-check","override","accepted","asked-source","flag","flag-cleared","conflict","undone"],DatasetHistoryKindSchema=external_exports.enum(DATASET_HISTORY_KINDS);var DATASET_HISTORY_FACETS_MAX=500;var hasNoNul=value2=>!value2.includes("\0"),DatasetHistoryInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema,kinds:external_exports.array(DatasetHistoryKindSchema).min(1).max(DATASET_HISTORY_KINDS.length).optional(),column:external_exports.string().min(1).max(MAX_CORRECTION_COLUMN_LENGTH).refine(hasNoNul,{message:"A column cannot hold a NUL character."}).optional(),actor:external_exports.string().min(1).max(255).refine(hasNoNul,{message:"An actor cannot hold a NUL character."}).optional(),search:external_exports.string().min(1).max(256).refine(hasNoNul,{message:"Search cannot hold a NUL character."}).optional(),take:external_exports.number().int().min(1).max(1e3).optional(),cursor:external_exports.string().min(1).max(1e3).optional()}),DatasetHistorySelectionSchema=external_exports.discriminatedUnion("kind",[external_exports.object({kind:external_exports.literal("rows"),rows:external_exports.number().int().nonnegative()}),external_exports.object({kind:external_exports.literal("filter"),filters:external_exports.array(DatasetReadFilterSchema),matched:external_exports.number().int().nonnegative()})]);var OverrideCellCountsSchema=external_exports.partialRecord(StagedCorrectionStateSchema,external_exports.number().int().positive());var DATA_VERSION_HISTORY_STATES=["in-use","on-hold"],EntryBase={id:external_exports.string().min(1),at:external_exports.iso.datetime(),actor:external_exports.string().min(1).nullable(),versionId:external_exports.string().min(1).nullable(),loadNumber:external_exports.number().int().nullable()},ColumnNameSchema=external_exports.string().min(1).max(MAX_CORRECTION_COLUMN_LENGTH),DatasetHistoryPastedValueSchema=external_exports.strictObject({logicalId:CorrectionFromSchema.shape.logicalId,column:ColumnNameSchema.optional(),from:DatasetCellValueSchema,to:DatasetCellValueSchema}),DatasetHistoryReplaceEachChangeSchema=ReplaceEachChangeSchema.extend({values:external_exports.array(DatasetHistoryPastedValueSchema).min(1).max(MAX_CORRECTION_ACT_ROWS)}),DatasetHistoryOverrideChangeSchema=external_exports.discriminatedUnion("method",[...CorrectionChangeSchema.options,DatasetHistoryReplaceEachChangeSchema]),DATASET_HISTORY_UNDONE_KINDS=["accepted","asked-source","flag-cleared"],DatasetHistoryEntrySchema=external_exports.discriminatedUnion("kind",[external_exports.object({...EntryBase,kind:external_exports.literal("data-version"),rows:external_exports.number().int().nonnegative(),state:external_exports.enum(DATA_VERSION_HISTORY_STATES).optional()}),external_exports.object({...EntryBase,kind:external_exports.literal("full-check"),status:external_exports.enum(["in-flight","committed","failed"]),rulesetId:external_exports.string().min(1),rulesetVersion:external_exports.number().int().positive(),rowsChecked:external_exports.number().int().nonnegative().optional(),rowsWithFinding:external_exports.number().int().nonnegative().optional(),reason:external_exports.string().min(1).optional()}),external_exports.object({...EntryBase,kind:external_exports.literal("override"),column:external_exports.string().min(1).optional(),change:DatasetHistoryOverrideChangeSchema,undoes:external_exports.string().min(1).optional(),resolves:external_exports.string().min(1).optional(),selection:DatasetHistorySelectionSchema,oldValue:DatasetCellValueSchema.optional(),pasted:external_exports.array(external_exports.strictObject({actId:external_exports.string().min(1),column:ColumnNameSchema})).min(2).max(MAX_CORRECT_CELLS_COLUMNS).optional(),reason:external_exports.string(),state:StagedCorrectionStateSchema,cells:OverrideCellCountsSchema}),external_exports.object({...EntryBase,kind:external_exports.literal("accepted"),scope:external_exports.enum(["rows","rule"]),column:external_exports.string().min(1).optional(),rulesetId:external_exports.string().min(1).optional(),rulesetVersion:external_exports.number().int().positive().optional(),ruleIndex:external_exports.number().int().nonnegative(),selection:DatasetHistorySelectionSchema.optional(),reason:external_exports.string().min(1).optional()}),external_exports.object({...EntryBase,kind:external_exports.literal("asked-source"),selection:DatasetHistorySelectionSchema,reason:external_exports.string().min(1),expected:external_exports.string().min(1).optional(),channel:ReviewRequestChannelSchema}),external_exports.object({...EntryBase,kind:external_exports.literal("flag"),selection:DatasetHistorySelectionSchema,severity:ReviewSeveritySchema,dimension:external_exports.string().min(1).optional(),reason:external_exports.string().min(1).optional(),state:external_exports.enum(["open","cleared"])}),external_exports.object({...EntryBase,kind:external_exports.literal("flag-cleared"),selection:DatasetHistorySelectionSchema,flagActId:external_exports.string().min(1),reason:external_exports.string().min(1).optional()}),external_exports.object({...EntryBase,kind:external_exports.literal("undone"),undid:external_exports.string().min(1),undidKind:external_exports.enum(DATASET_HISTORY_UNDONE_KINDS),selection:DatasetHistorySelectionSchema,reason:external_exports.string().min(1).optional()}),external_exports.object({...EntryBase,kind:external_exports.literal("conflict"),rows:external_exports.number().int().positive()})]),DatasetHistoryPageSchema=external_exports.object({entries:external_exports.array(DatasetHistoryEntrySchema).max(1e3),nextCursor:external_exports.string().min(1).nullable()}),DatasetHistoryFacetsInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema}),DatasetHistoryFacetsSchema=external_exports.object({columns:external_exports.array(external_exports.string().min(1)).max(DATASET_HISTORY_FACETS_MAX),actors:external_exports.array(external_exports.string().min(1)).max(DATASET_HISTORY_FACETS_MAX),automatic:external_exports.boolean(),truncated:external_exports.boolean()});var DATASET_HISTORY_KIND_LABELS={"data-version":"Data version","full-check":"Full check",override:"Override",accepted:"Accepted as is","asked-source":"Asked the source",flag:"Flag","flag-cleared":"Flag cleared",conflict:"Conflict",undone:"Undone"},DATASET_HISTORY_KIND_FILTER_LABELS={...DATASET_HISTORY_KIND_LABELS,undone:"Undone or reopened"};var NEWER_DELIVERY_REASONS=["blocker-flags","failing-checks","checks-not-finished","corrections-not-reapplied","at-source","other","not-published"],NewerDeliveryReasonCodeSchema=external_exports.enum(NEWER_DELIVERY_REASONS),NewerDeliveryInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema,readVersionId:DatasetVersionIdSchema.optional(),periodColumns:external_exports.array(external_exports.string().min(1).max(200)).max(20),datePublished:external_exports.boolean().optional()}),NewerDeliveryLoadSchema=external_exports.object({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,loadNumber:external_exports.number().int().positive()}),NewerDeliveryReasonSchema=external_exports.object({reason:NewerDeliveryReasonCodeSchema,rows:external_exports.number().int().nonnegative()}),NewerDeliveryCellsSchema=external_exports.record(external_exports.string(),external_exports.array(external_exports.string().nullable())),NewerDeliverySchema=external_exports.object({read:external_exports.object({versionId:DatasetVersionIdSchema,loadNumber:external_exports.number().int().positive(),publishedSource:external_exports.boolean(),delivery:NewerDeliveryLoadSchema.nullable(),reasons:external_exports.array(NewerDeliveryReasonSchema)}).nullable(),newer:external_exports.object({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,loadNumber:external_exports.number().int().positive(),state:external_exports.enum(["blocked","published"]),reasons:external_exports.array(NewerDeliveryReasonSchema),rows:external_exports.number().int().nonnegative(),cells:NewerDeliveryCellsSchema,undated:external_exports.number().int().nonnegative(),changed:external_exports.object({rows:external_exports.number().int().nonnegative(),cells:NewerDeliveryCellsSchema,undated:external_exports.number().int().nonnegative()}).nullable()}).nullable(),newerPublished:external_exports.object({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,loadNumber:external_exports.number().int().positive(),rows:external_exports.number().int().nonnegative(),cells:NewerDeliveryCellsSchema,undated:external_exports.number().int().nonnegative()}).nullable(),atSource:external_exports.object({rows:external_exports.number().int().nonnegative(),cells:NewerDeliveryCellsSchema,undated:external_exports.number().int().nonnegative()}),blockingLabel:external_exports.string().min(1)});var GRANT_URL_PATTERN=/^(?:https:\/\/|http:\/\/(?:localhost|127\.0\.0\.1|\[::1\]|[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.localhost)(?::\d+)?(?:[/?#]|$))/,WALKUP_MAX_UPLOAD_BYTES=5*1024**3,WalkupUploadGrantInputSchema=external_exports.strictObject({sdpDatasetRef:external_exports.string().min(1),fileName:external_exports.string().min(1),contentType:external_exports.string().min(1),byteLength:external_exports.number().int().positive().max(WALKUP_MAX_UPLOAD_BYTES),sha256:external_exports.string().min(1).describe("Base64 of the raw 32-byte SHA-256 digest \u2014 S3's `x-amz-checksum-sha256` convention, NOT hex. A hex digest is 64 characters, which is itself legal base64 and decodes to 48 bytes; send the base64 encoding of the raw digest bytes instead."),idempotencyKey:external_exports.string().min(1).max(200).optional().describe("The idempotencyKey of the walkupDeclare this upload is for. It names that import rather than replaying anything: a reused key never replays an earlier grant, and every call mints a new one for the import the key names. Send it whenever you have it.")}),WalkupUploadGrantRefusalDataSchema=external_exports.object({code:external_exports.string(),detail:external_exports.string().optional()}),WalkupUploadGrantResultSchema=external_exports.object({url:external_exports.url().refine(value2=>GRANT_URL_PATTERN.test(value2),{message:"upload grant URL must be https (http is admitted for loopback only)"}),headers:external_exports.record(external_exports.string(),external_exports.string()),expiresAt:external_exports.iso.datetime()});var DATASET_ROW_KIND={domain:"datasets",type:"dataset-version"},datasetCountComponentContract={name:"dataset-count",binds:"collection",bindsToResource:"datasets",configVersion:"1",configSchema:external_exports.object({}),description:"Single-number tile: how many datasets the tenant has, under a sublabel.",grain:"widget",defaultLayout:{spanCol:4,spanRow:4},rowKind:DATASET_ROW_KIND},datasetManagerComponentContract={name:"dataset-manager",binds:"collection",bindsToResource:"datasets",configVersion:"1",configSchema:external_exports.object({}),description:"The tenant's datasets as a searchable, filterable catalog; a row opens that dataset's own page where the frame offers one. The import wizard, and the artifacts, transformations and runs surfaces, are separate Studio surfaces and are not part of it.",grain:"page",rowKind:DATASET_ROW_KIND},referenceTableManagerComponentContract={name:"reference-table-manager",binds:"collection",bindsToResource:"datasets",configVersion:"1",configSchema:external_exports.object({}),description:"The tenant's reference tables, the dated values calculations read: each with where it came from, the version in use, the dates its rows cover and its cited source; a row opens that table's own page where the frame offers one.",grain:"page",rowKind:DATASET_ROW_KIND},datasetCatalogComponentContract={name:"dataset-catalog",binds:"none",configVersion:"1",configSchema:external_exports.object({}).strict(),description:"The tenant's datasets grouped by category, with search and Category and Kind filters: name, kind, the run that produced it, owner, maturity, rows, open issues and when it last loaded. A row opens the dataset where the frame offers it. New dataset uploads files or a folder, each file its own dataset; New pipeline opens the Solution's pipelines page.",grain:"page"},datasetViewConfigSchema=external_exports.object({});var datasetProfileComponentContract={name:"dataset-profile",binds:"entity",bindsToResource:"datasets",entity:{domain:"datasets",type:"dataset-version"},configVersion:"1",configSchema:external_exports.object({}),description:"One load's column profile, a card per column: how much is empty, how many distinct values, and its top values or distribution \u2014 at whichever version the reference pins.",grain:"widget",defaultLayout:{spanCol:12,spanRow:3}},datasetRuleEditorComponentContract={name:"dataset-rule-editor",binds:"entity",bindsToResource:"datasets",entity:{domain:"datasets",type:"dataset-version"},configVersion:"1",configSchema:external_exports.object({}),description:"Author a dataset's validation ruleset: rules proposed from the pinned load's profile, each kept, edited or dropped with the violations it would raise on that load, then saved as a new ruleset version.",grain:"widget",defaultLayout:{spanCol:12,spanRow:8}},datasetRowsComponentContract={name:"dataset-rows",binds:"entity",bindsToResource:"datasets",entity:{domain:"datasets",type:"dataset-version"},configVersion:"1",configSchema:external_exports.object({}),description:"A working data view of one load, for inspecting a pipeline step's output: paged rows with the automatic checks' problems marked on the cells they flag, a column profile, and an Open issues filter that appears only when a row has an issue, with Full screen as its one size control. Unlike dataset-view, the read-only viewer that shows the first rows of a load as a reference embed, it reads the checks, narrows to issues and pages through the load.",grain:"widget",defaultLayout:{spanCol:12,spanRow:8}},editorTransformationId=SourceTransformationIdSchema.check(external_exports.regex(/\S/,"A transformation id cannot be blank.")).meta(SourceTransformationIdSchema.meta()??{}),datasetTransformationEditorComponentContract={name:"dataset-transformation-editor",binds:"none",configVersion:"2",configSchema:external_exports.object({transformationId:editorTransformationId.optional().describe("The transformation to revise. Set, the editor opens that transformation prefilled from its current version and saving appends the next version; unset, it authors a new transformation.")}).strict(),description:"Author a source transformation from pasted SQL: the input slots it reads are matched by name to the tenant's datasets, with a chooser for the rest; the outputs are read from its COPY \u2026 TO statements; saving mints a new transformation version, which a later run step references by id and version. With a transformationId set it revises that transformation instead, saving its next version.",grain:"widget",defaultLayout:{spanCol:12,spanRow:10}},referenceTableReviewComponentContract={name:"reference-table-review",binds:"entity",bindsToResource:"datasets",entity:{domain:"datasets",type:REFERENCE_TABLE_SUBJECT_TYPE},configVersion:"1",configSchema:external_exports.object({}),description:"One version of a reference table as its approver reviews it: the checks it passed or what holds it, its rows changed against the version in use, and which projects' next run approving it changes.",grain:"widget",viewer:!0,defaultLayout:{spanCol:12,spanRow:6}},datasetExportComponentContract={name:"dataset-export",binds:"entity",bindsToResource:"datasets",entity:{domain:"datasets",type:"dataset-version"},acceptsKinds:"any",configVersion:"1",configSchema:external_exports.object({}).strict(),description:"The dataset versions behind the bound record, found by walking what the record was made from, in two groups, decided from the step that produced each version: Raw data (landed from a source) and Transposed data (produced by a transformation or a calculation). Each row has its own Export, which downloads that version. Bind it to any record; it lists the dataset versions that record was made from.",grain:"widget",defaultLayout:{spanCol:12,spanRow:6}};var RELAND_REQUEST_KEY_MAX=512,RequestRelandInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema,idempotencyKey:IdempotencyKeySchema.max(RELAND_REQUEST_KEY_MAX)}),RelandRequestSchema=external_exports.object({requestId:external_exports.uuid(),datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema});var RELAND_LANDING_VERB="relandCurrentLoad",RELAND_LANDING_ACTION_NAME=`datasets.${RELAND_LANDING_VERB}`;var SetHoistedColumnsInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema,enabled:external_exports.boolean(),idempotencyKey:IdempotencyKeySchema.max(200)}),HOISTED_COLUMNS_TAKES_EFFECT=["next-full-refresh","next-run","recorded-only"],HoistedColumnsTakesEffectSchema=external_exports.enum(HOISTED_COLUMNS_TAKES_EFFECT),HoistedColumnsViewSchema=external_exports.object({datasetId:DatasetIdSchema,enabled:external_exports.boolean(),declaredColumns:external_exports.array(external_exports.string()),takesEffect:HoistedColumnsTakesEffectSchema,runStarted:external_exports.literal(!1),ignoredUntilFullRefresh:external_exports.boolean().optional(),startRunWith:external_exports.string().optional(),unchanged:external_exports.boolean()});var ReferenceOriginSchema=external_exports.discriminatedUnion("kind",[external_exports.object({kind:external_exports.literal("studio"),via:external_exports.enum(["create","mark"]),by:external_exports.string().min(1),at:external_exports.iso.datetime()}),external_exports.object({kind:external_exports.literal("pack"),pack:external_exports.string().min(1),itemKey:external_exports.string().min(1),version:external_exports.number().int().positive()})]);var SetReferenceSourceInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema,source:ReferenceGovernanceSchema.omit({authorityEdition:!0}),expectedUpdatedAt:external_exports.iso.datetime().nullable(),reason:external_exports.string().trim().min(1).max(500),idempotencyKey:IdempotencyKeySchema.max(200)}),ReferenceSourceInputSchema=external_exports.strictObject({datasetId:DatasetIdSchema}),ReferenceTableSourceSchema=external_exports.object({datasetId:DatasetIdSchema,source:ReferenceGovernanceSchema.nullable(),updatedAt:external_exports.iso.datetime().nullable(),keyCodelists:ReferenceKeyCodelistsSchema.optional()}),REFERENCE_TABLES_MAX=200,ReferenceLastSaveSchema=external_exports.object({saveRecordId:external_exports.string().min(1),by:external_exports.string().min(1),reason:external_exports.string().min(1),at:external_exports.iso.datetime(),state:external_exports.enum(["saving","saved","failed"])}),ReferenceTableSchema=external_exports.object({datasetId:DatasetIdSchema,name:external_exports.string().min(1),label:external_exports.string().min(1).nullable(),origin:ReferenceOriginSchema.nullable(),currentVersionId:DatasetVersionIdSchema.nullable(),promotedVersionId:DatasetVersionIdSchema.nullable(),span:ReferenceSpanSchema.nullable(),source:ReferenceGovernanceSchema.nullable(),lastSave:ReferenceLastSaveSchema.nullable(),keyCodelists:ReferenceKeyCodelistsSchema.optional()}),ReferenceTablesInputSchema=external_exports.strictObject({}),ReferenceTablesSchema=external_exports.object({tables:external_exports.array(ReferenceTableSchema).max(REFERENCE_TABLES_MAX),more:external_exports.boolean()});var MarkReferenceValuesInputSchema=external_exports.discriminatedUnion("marked",[external_exports.strictObject({datasetId:DatasetIdSchema,marked:external_exports.literal(!0),source:ReferenceGovernanceSchema.optional(),idempotencyKey:IdempotencyKeySchema.max(200)}),external_exports.strictObject({datasetId:DatasetIdSchema,marked:external_exports.literal(!1),idempotencyKey:IdempotencyKeySchema.max(200)})]),MarkReferenceValuesResultSchema=external_exports.object({datasetId:DatasetIdSchema,kind:external_exports.enum(["raw","constant"]),changed:external_exports.boolean(),verdict:ReferenceVerdictSchema.optional()});var TransformSpecIdSchema=external_exports.string().min(1).brand(),DatasetKindSchema=external_exports.enum(["raw","constant","result","live"]),TransformStepKindSchema=external_exports.enum(["map","unitConvert","const","expression","cast","lookupMap","filterRows"]),DatasetReadInputSchema=DatasetRefSchema.extend({rows:external_exports.object({start:external_exports.number().int().nonnegative(),take:external_exports.number().int().min(1).max(1e3)}).optional(),offset:external_exports.number().int().nonnegative().optional().describe(`Rows to skip, in load order; defaults to 0. Sent WITHOUT \`limit\`, the page size defaults to ${100}. Mutually exclusive with \`rows\` \u2014 sending both is refused with \`DATASET_READ_WINDOW_AMBIGUOUS\`, never reconciled.`),limit:external_exports.number().int().min(1).max(1e3).optional().describe(`Page size, 1\u2013${1e3}; defaults to ${100}. Sent WITHOUT \`offset\`, the page starts at row 0. An ask above the maximum is REFUSED, not clamped. Mutually exclusive with \`rows\` \u2014 sending both is refused with \`DATASET_READ_WINDOW_AMBIGUOUS\`. Read \`totalRows\` for the full count.`),search:external_exports.string().min(1).max(256).optional(),cursor:external_exports.string().min(1).optional(),orderBy:DatasetReadOrderBySchema.optional(),filters:external_exports.array(DatasetReadFilterSchema).min(1).max(8).optional(),range:DatasetReadRangeSchema.optional(),includeTotal:external_exports.boolean().optional().describe("Send `false` to skip the exact total: the page omits `totalRows` (absent, never 0), no count runs, and `nextCursor` still marks the end \u2014 follow it until it is `null`. A window past the last row answers an empty page rather than `DATASET_READ_WINDOW_OUT_OF_RANGE`, which needs the total to decide. Default `true`.")}).strict(),DatasetVersionStatusSchema=external_exports.object({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,promoted:external_exports.boolean(),promotedAt:external_exports.iso.datetime().optional(),get columns(){return external_exports.array(DatasetColumnSchema2).optional()},loadNumber:external_exports.number().int().positive().optional(),rowCount:external_exports.number().int().nonnegative().optional(),loadedAt:external_exports.string().min(1).optional()}),ResolveDatasetNameInputSchema=external_exports.strictObject({name:external_exports.string().min(1),kind:DatasetKindSchema.optional()}),PromoteDatasetInputSchema=external_exports.strictObject({ref:DatasetRefSchema,idempotencyKey:IdempotencyKeySchema,reason:DatasetLifecycleReasonSchema.optional()}),RenameDatasetInputSchema=external_exports.strictObject({datasetId:external_exports.string().min(1),name:external_exports.string().min(1).optional().describe("The new system name. Omit it to leave the name as it is."),label:DatasetLabelSchema.nullable().optional().describe("The readable name to show; `null` clears it, so the dataset shows its `name` again. Never changes how the dataset is found."),ifUnlabeled:external_exports.literal(!0).optional().describe("Write `label` only while the dataset has no label; otherwise a no-op is recorded. Needs `label`; refused with `name`."),reason:DatasetLifecycleReasonSchema.optional(),idempotencyKey:IdempotencyKeySchema}),DatasetNameTakenDataSchema=external_exports.object({code:external_exports.literal("DATASET_NAME_TAKEN"),suggestedName:external_exports.string().min(1)}),SetDatasetKeyColumnInputSchema=external_exports.strictObject({datasetId:external_exports.string().min(1),keyColumn:external_exports.string().min(1),reason:DatasetLifecycleReasonSchema.optional(),idempotencyKey:IdempotencyKeySchema}),DatasetSchema=external_exports.object({datasetId:DatasetIdSchema,name:external_exports.string().min(1),...datasetReadabilityFields,kind:DatasetKindSchema,columns:external_exports.array(DatasetColumnSchema2),outdatedColumnTags:external_exports.array(external_exports.string().min(1)).optional(),createdAt:external_exports.iso.datetime().optional(),currentVersionId:DatasetVersionIdSchema.optional(),rowCount:external_exports.number().int().nonnegative().optional(),promoted:external_exports.boolean(),currentVersionAsOf:external_exports.iso.datetime().optional(),status:DatasetStatusSchema,maturity:DatasetMaturitySchema,slug:DatasetSlugSchema,ownerDomain:external_exports.string().min(1).optional(),description:external_exports.string().min(1).optional(),keyColumn:external_exports.string().min(1).optional(),notes:external_exports.string().min(1).optional(),keywords:external_exports.array(external_exports.string().min(1)).optional(),themes:external_exports.array(external_exports.string().min(1)).optional(),get grain(){return DatasetGrainSchema.optional()},get timeCovered(){return DatasetTimeCoveredReadSchema.optional()},get tableRole(){return DatasetTableRoleSchema.optional()},isDerived:external_exports.boolean().optional(),hasSourceRuns:external_exports.boolean().optional(),acceptsUploadedVersions:external_exports.boolean().optional(),importRunsAvailable:external_exports.boolean().optional(),uploadVersionsUnavailableReason:UploadVersionsUnavailableReasonSchema.optional(),sheetName:external_exports.string().min(1).optional(),reviewEnabled:external_exports.boolean().optional(),provenance:DatasetProvenanceSchema,get replacedBy(){return DatasetReplacedBySchema.optional()}}),DatasetPageSchema=external_exports.object({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,columns:external_exports.array(DatasetColumnSchema2),rows:external_exports.array(DatasetRowSchema),totalRows:external_exports.number().int().nonnegative().optional(),nextCursor:external_exports.string().nullable().optional(),producedBy:DatasetVersionProducerSchema.optional()});var TransformSpecSchema=external_exports.object({specId:TransformSpecIdSchema,name:external_exports.string().min(1),sourceDatasetId:DatasetIdSchema,sourceVersionId:DatasetVersionIdSchema.nullable(),steps:external_exports.array(TransformStepSchema)}),SaveTransformSpecInputSchema=external_exports.object({specId:TransformSpecIdSchema.optional(),name:external_exports.string().min(1),sourceDatasetId:DatasetIdSchema,sourceVersionId:DatasetVersionIdSchema,steps:external_exports.array(TransformStepSchema).max(MAX_TRANSFORM_STEPS),idempotencyKey:IdempotencyKeySchema}),LiveDatasetReadSchema=external_exports.object({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,columns:external_exports.array(DatasetColumnSchema2),rows:external_exports.array(DatasetRowSchema),totalRows:external_exports.number().int().nonnegative(),truncated:external_exports.boolean(),executedAt:external_exports.iso.datetime(),durationMs:external_exports.number().int().nonnegative()}),TransformInputSchema=external_exports.object({specId:TransformSpecIdSchema,specVersion:external_exports.number().int().positive().optional(),idempotencyKey:TransformRunKeyInputSchema}),GetTransformSpecInputSchema=external_exports.object({sourceDatasetId:DatasetIdSchema,specId:TransformSpecIdSchema.optional(),version:external_exports.number().int().positive().optional()}),MAX_SPEC_VERSION_HISTORY=50,TransformSpecVersionSchema=external_exports.object({version:external_exports.number().int().positive(),savedAt:external_exports.string().datetime(),stepCount:external_exports.number().int().nonnegative().nullable()}),SavedTransformSpecSchema=TransformSpecSchema.extend({version:external_exports.number().int().positive(),isLatest:external_exports.boolean(),savedAt:external_exports.string().datetime(),versions:external_exports.array(TransformSpecVersionSchema).max(MAX_SPEC_VERSION_HISTORY),versionCount:external_exports.number().int().nonnegative()}),RecipeSourceSchema=external_exports.object({slot:external_exports.string().min(1),datasetId:DatasetIdSchema,name:external_exports.string().min(1),kind:DatasetKindSchema,provenance:DatasetProvenanceSchema}),DatasetTransformationSchema=SavedTransformSpecSchema.omit({sourceDatasetId:!0}).extend({sources:external_exports.array(RecipeSourceSchema).min(1),result:RecipeResultSchema,sourcePin:RecipeSourcePinSchema.nullable(),currentLoad:external_exports.object({loadNumber:external_exports.number().int().positive(),specVersion:external_exports.number().int().positive().nullable(),madeByMaker:external_exports.boolean().optional()}).nullable()});var PreviewReturnRowsSchema=external_exports.enum(["none","all"]).describe("Whether to return the sampled ROW PAYLOADS. `none` (THE DEFAULT) returns the column diff and the counts only \u2014 which is what a caller iterating on a step list is reading, and it keeps the source data's own cell values out of a reply that does not need them. `all` returns `sourceRows` and `rows` as well, for a client that renders the sample. The counts (`sampledRows`, `sourceRowCount`, `resultRows`, `stepsEvaluated`) and the whole column diff ride on the wire in EVERY mode, so nothing about what the steps DO is hidden by the default."),PreviewSpecStepsInputSchema=external_exports.object({sourceDatasetId:DatasetIdSchema,sourceVersionId:DatasetVersionIdSchema.optional(),steps:external_exports.array(TransformStepSchema).max(MAX_TRANSFORM_STEPS),upToIndex:external_exports.number().int().nonnegative().optional(),returnRows:PreviewReturnRowsSchema.optional()}),PreviewRemovedColumnSchema=DatasetColumnSchema2.extend({renamedTo:external_exports.string().min(1).optional()}),PreviewRetypedColumnSchema=external_exports.object({name:external_exports.string().min(1),from:DatasetColumnTypeSchema,to:DatasetColumnTypeSchema}),PreviewColumnDiffSchema=external_exports.object({added:external_exports.array(DatasetColumnSchema2),removed:external_exports.array(PreviewRemovedColumnSchema),retyped:external_exports.array(PreviewRetypedColumnSchema)}),SpecStepsPreviewSchema=external_exports.object({columnsBefore:external_exports.array(DatasetColumnSchema2),columnsAfter:external_exports.array(DatasetColumnSchema2),diff:PreviewColumnDiffSchema,sourceRows:external_exports.array(DatasetRowSchema).optional(),rows:external_exports.array(DatasetRowSchema).optional(),resultRows:external_exports.number().int().nonnegative(),sampledRows:external_exports.number().int().nonnegative(),sourceRowCount:external_exports.number().int().nonnegative(),stepsEvaluated:external_exports.number().int().nonnegative()}),StartImportJobTransformRequestSchema=TransformInputSchema.omit({idempotencyKey:!0}).strict(),StartImportJobInputSchema=external_exports.discriminatedUnion("mode",[external_exports.strictObject({mode:external_exports.literal("land"),idempotencyKey:ImportJobLandIdempotencyKeySchema,request:RawLandWireInputSchema}),external_exports.strictObject({mode:external_exports.literal("transform"),idempotencyKey:ImportJobTransformIdempotencyKeySchema,request:StartImportJobTransformRequestSchema}),external_exports.strictObject({mode:external_exports.literal("declared"),idempotencyKey:ImportJobDeclaredIdempotencyKeySchema,request:StartImportJobDeclaredRequestSchema})]),ImportJobWorkSchema=external_exports.discriminatedUnion("mode",[external_exports.strictObject({mode:external_exports.literal("land"),request:LandInputSchema}),external_exports.strictObject({mode:external_exports.literal("transform"),request:TransformInputSchema}),external_exports.strictObject({mode:external_exports.literal("declared"),request:RunSourceTransformationInputSchema})]);var rejectedConfigSource={config:external_exports.never({error:REJECTED_CONFIG_SOURCE}).optional()},inspectColumnTypesFacet={columnTypes:columnTypesWireFacet.columnTypes.describe(INSPECT_COLUMN_TYPES_DESCRIPTION)},inspectParseFacets={...parseFacets,sheet:parseFacets.sheet.describe(INSPECT_SHEET_DESCRIPTION)},inspectInlineTextSource={content:inlineTextSource.content.describe(INSPECT_CONTENT_DESCRIPTION)},inspectInlineBase64Source={contentBase64:inlineBase64Source.contentBase64.describe(INSPECT_CONTENT_BASE64_DESCRIPTION)},inspectUploadRefSource={uploadRef:uploadRefSource.uploadRef.describe(INSPECT_UPLOAD_REF_DESCRIPTION)},INSPECT_OBJECT_REF_DESCRIPTION="An opaque handle to an object captured through the Integrations capture seam (`integrations.beginCapture` \u2192 a direct-to-bucket PUT \u2192 `integrations.completeCapture`) \u2014 how a CAPTURED file gets previewed before it is landed. The server never reads the bytes: it resolves the ref server-side and the query engine reads the object directly from object storage, so the preview is bounded work at ANY object size \u2014 the header plus a bounded row sample. csv only, exactly like the land this previews (`csvDialect` applies, gzip comes from the capture source's registration). ONE HONEST GAP: the response carries NO `rowCount` \u2014 counting is a full pass over the object, which is the read a preview must not cost; the landing job counts. Recipe: capture \u2192 `inspectUpload` with the ref \u2192 `datasets.startImportJob` (mode `land`) naming the same ref. Inspecting neither consumes nor extends the capture. Exactly one of `content` / `contentBase64` / `uploadRef` / `objectRef` may be supplied.",inspectObjectRefSource={objectRef:objectRefSource.objectRef.describe(INSPECT_OBJECT_REF_DESCRIPTION)},InspectUploadInputSchema=external_exports.intersection(external_exports.object(rejectedConfigSource),external_exports.union([external_exports.object({...inspectParseFacets,...inspectColumnTypesFacet,...inspectInlineTextSource}).strict(),external_exports.object({...inspectParseFacets,...inspectColumnTypesFacet,...inspectInlineBase64Source}).strict(),external_exports.object({...inspectParseFacets,...inspectColumnTypesFacet,...inspectUploadRefSource}).strict(),external_exports.object({...inspectParseFacets,...csvDialectFacet,...inspectObjectRefSource}).strict()])),UploadSheetSchema=external_exports.object({name:external_exports.string().min(1),empty:external_exports.boolean(),rowCount:external_exports.number().int().nonnegative().optional(),columnCount:external_exports.number().int().nonnegative().optional()}),CAST_REPORT_MAX_SAMPLES=5,CAST_SAMPLE_MAX_LENGTH=256,ColumnCastSampleSchema=external_exports.object({value:external_exports.string().max(CAST_SAMPLE_MAX_LENGTH),row:external_exports.number().int().positive()}),ColumnCastReportSchema=external_exports.object({column:external_exports.string().min(1),declared:DatasetColumnTypeSchema,failingCount:external_exports.number().int().nonnegative(),samples:external_exports.array(ColumnCastSampleSchema).max(CAST_REPORT_MAX_SAMPLES)}),UploadInspectionSchema=external_exports.object({format:DatasetFormatSchema,sheets:external_exports.array(UploadSheetSchema),sheet:external_exports.string().min(1).optional(),columns:external_exports.array(DatasetColumnSchema2),rows:external_exports.array(DatasetRowSchema),rowCount:external_exports.number().int().nonnegative().optional(),castReport:external_exports.array(ColumnCastReportSchema).optional()});var CountSchema=external_exports.number().int().nonnegative();var SkippedDatasetSchema=external_exports.object({datasetName:external_exports.string(),slug:external_exports.string(),fallbackSlug:external_exports.string().optional(),code:external_exports.string(),reason:external_exports.string()}),DirectoryLastRunSchema=external_exports.discriminatedUnion("outcome",[external_exports.object({outcome:external_exports.literal("published"),finishedAt:external_exports.iso.datetime(),asOf:external_exports.iso.datetime(),identifierCount:CountSchema,assetCount:CountSchema,assetsWithoutLocation:CountSchema.optional(),skippedDatasets:external_exports.array(SkippedDatasetSchema).optional()}),external_exports.object({outcome:external_exports.literal("refused"),finishedAt:external_exports.iso.datetime(),asOf:external_exports.iso.datetime(),skippedDatasets:external_exports.array(SkippedDatasetSchema).min(1)}),external_exports.object({outcome:external_exports.literal("empty"),finishedAt:external_exports.iso.datetime(),asOf:external_exports.iso.datetime()}),external_exports.object({outcome:external_exports.literal("failed"),finishedAt:external_exports.iso.datetime(),reason:external_exports.string().min(1)})]),DirectoryPublishedSchema=external_exports.object({finishedAt:external_exports.iso.datetime(),asOf:external_exports.iso.datetime(),identifierCount:CountSchema,assetCount:CountSchema,assetsWithoutLocation:CountSchema.optional(),previousAssetsWithoutLocation:CountSchema.optional(),skippedDatasets:external_exports.array(SkippedDatasetSchema).optional()}),PublishDirectoryInputSchema=external_exports.strictObject({idempotencyKey:IdempotencyKeySchema}),PublishDirectoryResultSchema=external_exports.discriminatedUnion("kind",[external_exports.object({kind:external_exports.literal("started")}),external_exports.object({kind:external_exports.literal("already-running")})]),DirectoryAutoRefreshSchema=external_exports.object({enabled:external_exports.boolean(),pending:external_exports.boolean(),pendingSince:external_exports.iso.datetime().nullable(),lastChangedAt:external_exports.iso.datetime().nullable(),lastRunFailed:external_exports.boolean().optional(),lastFailedAt:external_exports.iso.datetime().nullable().optional(),consecutiveFailures:external_exports.number().int().nonnegative().optional()}),DirectoryPublishStatusSchema=external_exports.object({everPublished:external_exports.boolean(),runInProgress:external_exports.boolean(),runStale:external_exports.boolean(),lastRun:DirectoryLastRunSchema.nullable(),lastPublished:DirectoryPublishedSchema.nullable(),autoRefresh:DirectoryAutoRefreshSchema});var ASSET_SELECTION_OMITTED={orderBy:!0,offset:!0,limit:!0,cursor:!0,asOf:!0,knownAt:!0,subtreeOf:!0,underAssetIds:!0,conditions:!0};var DELETE_IMPACT_MAX_IDS=100,DELETE_MANY_MAX_IDS=100,DeleteImpactVerdictSchema=external_exports.enum(["deletable","reparentable","reparentable-too-wide","blocked","not-found"]),HierarchyEdgeDirectionSchema=external_exports.enum(["child","parent"]),DeleteRefusalReasonSchema=external_exports.enum(["not-found","has-relationships","has-external-id-bindings"]);var SET_LOCATION_MANY_MAX_PLACEMENTS=1e4;var AssetPlacementSchema=external_exports.strictObject({get assetId(){return AssetIdSchema},get geometry(){return GeoJsonGeometryInputSchema}}),IDEMPOTENCY_KEY_MAX_LENGTH=200,SetLocationManyInputSchema=external_exports.strictObject({placements:external_exports.array(AssetPlacementSchema).min(1).max(SET_LOCATION_MANY_MAX_PLACEMENTS),idempotencyKey:IdempotencyKeySchema.max(IDEMPOTENCY_KEY_MAX_LENGTH),returnResults:ReturnResultsSchema.optional()}),SetLocationManyErrorCodeSchema=external_exports.enum(["asset-not-found","invalid-geometry","conflict"]),SetLocationManyItemResultSchema=external_exports.discriminatedUnion("status",[external_exports.object({get assetId(){return AssetIdSchema},status:external_exports.literal("placed")}),external_exports.object({get assetId(){return AssetIdSchema},status:external_exports.literal("failed"),error:external_exports.object({code:SetLocationManyErrorCodeSchema,message:external_exports.string().min(1)})})]),SetLocationManyOutputSchema=external_exports.object({summary:external_exports.object({requested:external_exports.number().int().nonnegative(),placed:external_exports.number().int().nonnegative(),failed:external_exports.number().int().nonnegative()}),results:external_exports.array(SetLocationManyItemResultSchema)});var DerivedPropertyCodeSchema=external_exports.string().min(1).max(64),DerivedPropertyDeclarationSchema=external_exports.strictObject({code:DerivedPropertyCodeSchema,displayName:external_exports.string().min(1)}),DerivedRoutingRuleSchema=external_exports.strictObject({propertyCode:DerivedPropertyCodeSchema,projectId:external_exports.string().min(1),element:external_exports.string().min(1)}),DerivedRoutingConfigSchema=external_exports.strictObject({rules:external_exports.array(DerivedRoutingRuleSchema).max(200)}),SaveDerivedRoutingInputSchema=external_exports.strictObject({config:DerivedRoutingConfigSchema,idempotencyKey:IdempotencyKeySchema.max(IDEMPOTENCY_KEY_MAX_LENGTH)}),DerivedValueProvenanceSchema=external_exports.strictObject({runId:external_exports.string().min(1),datasetVersionId:external_exports.string().min(1),periodId:external_exports.string().min(1)}),DerivedValueSchema=external_exports.strictObject({propertyCode:DerivedPropertyCodeSchema,displayName:external_exports.string().min(1),valueKind:external_exports.string().min(1),value:external_exports.string(),unit:external_exports.string().min(1).optional(),computedAt:external_exports.iso.datetime(),provenance:DerivedValueProvenanceSchema}),ListDerivedValuesInputSchema=external_exports.strictObject({get assetId(){return AssetIdSchema}}),ApplyDerivedValuesInputSchema=external_exports.strictObject({datasetVersionId:external_exports.string().min(1)}),ApplyDerivedValuesReportSchema=external_exports.strictObject({datasetVersionId:external_exports.string().min(1),slotsWritten:external_exports.number().int().nonnegative(),slotsRemoved:external_exports.number().int().nonnegative(),assetsTouched:external_exports.number().int().nonnegative(),skipped:external_exports.number().int().nonnegative().default(0)}),DueDerivedApplySchema=external_exports.strictObject({datasetVersionId:external_exports.string().min(1),datasetId:external_exports.string().min(1),triggeredAt:external_exports.iso.datetime()});var NumberingSchemeSchema=external_exports.strictObject({prefix:external_exports.string().min(1).max(32).optional(),categoryCode:external_exports.string().min(1).max(32).optional(),counterWidth:external_exports.number().int().min(1).max(12),suffix:external_exports.string().min(1).max(32).optional(),separator:external_exports.string().max(4),locked:external_exports.boolean()});var NumberingCategoryOverrideSchema=external_exports.strictObject({get categoryId(){return AssetCategoryIdSchema},scheme:NumberingSchemeSchema}),NumberingConfigSchema=external_exports.strictObject({defaultScheme:NumberingSchemeSchema.nullable(),categoryOverrides:external_exports.array(NumberingCategoryOverrideSchema)}),NUMBERING_CATEGORY_OVERRIDES_WIRE_MAX=1e3,NumberingConfigInputSchema=NumberingConfigSchema.extend({categoryOverrides:external_exports.array(NumberingCategoryOverrideSchema).max(NUMBERING_CATEGORY_OVERRIDES_WIRE_MAX)}),SaveNumberingConfigInputSchema=external_exports.strictObject({config:NumberingConfigInputSchema,idempotencyKey:IdempotencyKeySchema}),SuggestAssetCodeInputSchema=external_exports.strictObject({get categoryId(){return AssetCategoryIdSchema.optional()}}),SuggestAssetCodeResultSchema=external_exports.strictObject({code:external_exports.string().nullable(),scheme:NumberingSchemeSchema.nullable(),locked:external_exports.boolean().describe("ADVISORY: the active scheme declares the code field read-only in the UI. The backend does NOT enforce it \u2014 any string a caller binds is accepted; uniqueness alone is enforced (DB natural-key index).")});var EXTERNAL_ID_RESOLVE_MANY_MAX=500,ResolveManySystemSchema=external_exports.discriminatedUnion("kind",[external_exports.strictObject({kind:external_exports.literal("asset-id")}),external_exports.strictObject({kind:external_exports.literal("external-id"),key:ExternalIdSystemSchema})]),ResolveExternalIdManyInputSchema=external_exports.strictObject({system:ResolveManySystemSchema,values:external_exports.array(ExternalIdValueSchema).min(1).max(EXTERNAL_ID_RESOLVE_MANY_MAX)}),ResolvedExternalIdSchema=external_exports.object({value:external_exports.string().min(1),outcome:external_exports.enum(["matched","ambiguous","not-found"]),assetIds:external_exports.array(AssetIdSchema)}),ResolveExternalIdManyOutputSchema=external_exports.object({results:external_exports.array(ResolvedExternalIdSchema)}),EXTERNAL_ID_SYSTEM_NOT_CONFIGURED="EXTERNAL_ID_SYSTEM_NOT_CONFIGURED";var SetAssetTemplateInputSchema=external_exports.strictObject({idempotencyKey:UnreceiptedIdempotencyKeySchema,assetTypeId:AssetTypeIdSchema,get properties(){return external_exports.array(TemplatePropertyInputSchema).max(TEMPLATE_PROPERTIES_WIRE_MAX).describe("The type's authored properties \u2014 a FULL-STATE REPLACE, always: whatever you send becomes the new version's complete property set, so a property you omit is REMOVED and `[]` erases them all. Read the current template first and send it back with your edit applied; there is no partial-update form. Every existing asset of this type is validated against the new definition from here on, so adding a `required` property makes every asset that lacks it fail its next write, and dropping `required` from one is what makes previously-refused rows importable. Versioning is APPEND-ONLY \u2014 the previous version stays readable and the assets that pinned it keep pointing at it \u2014 so an edit is recoverable, not destructive.")},get derivedProperties(){return external_exports.array(DerivedPropertyDeclarationSchema).max(TEMPLATE_DERIVED_PROPERTIES_WIRE_MAX).optional().describe('Derived-property declarations. This field is GENUINELY OPTIONAL and OMITTING IT IS SAFE \u2014 the answer to "does leaving it out clear them?" is NO. ABSENT = the current version\'s declarations are carried FORWARD untouched, which is what lets a caller edit `properties` without knowing this field exists (and is why it carries no `[]` default: a default would make every such caller submit an empty full-state replace and destroy them). PRESENT = a FULL-STATE replace exactly like `properties` \u2014 an omitted declaration is a removal, and `[]` clears them all. So: omit to preserve, send the full list to change, send `[]` to clear.')}}),RawSetAssetTemplateInputSchema=SetAssetTemplateInputSchema.omit({idempotencyKey:!0});var MAX_NEARBY_RADIUS_METERS=20015087;var SPATIAL_QUERY_MAX_LIMIT=200,BoundingBoxSchema=external_exports.strictObject({southWest:GeoJsonPositionSchema,northEast:GeoJsonPositionSchema}),NearbyAssetsInputSchema=external_exports.strictObject({center:GeoJsonPositionSchema,radiusMeters:external_exports.number().positive().max(MAX_NEARBY_RADIUS_METERS),limit:external_exports.number().int().min(1).max(SPATIAL_QUERY_MAX_LIMIT).optional()}),NearbyAssetMatchSchema=external_exports.object({get asset(){return AssetSchema},distanceMeters:external_exports.number().min(0)}),NearbyAssetsOutputSchema=external_exports.object({items:external_exports.array(NearbyAssetMatchSchema),total:external_exports.number().int().min(0)}),AssetsWithinBoundsInputSchema=external_exports.strictObject({bounds:BoundingBoxSchema,limit:external_exports.number().int().min(1).max(SPATIAL_QUERY_MAX_LIMIT).optional()}),AssetsWithinBoundsOutputSchema=external_exports.object({get items(){return external_exports.array(AssetSchema)},total:external_exports.number().int().min(0)}),WITHIN_POLYGON_IDS_MAX=200,AssetsWithinPolygonInputSchema=external_exports.strictObject({polygon:GeoJsonPolygonSchema}),AssetsWithinPolygonOutputSchema=external_exports.object({get assetIds(){return external_exports.array(AssetIdSchema).max(WITHIN_POLYGON_IDS_MAX)},total:external_exports.number().int().min(0)}),MAP_AGGREGATE_MIN_ZOOM=0,MAP_AGGREGATE_MAX_ZOOM=22;var MapAggregateInputSchema=external_exports.strictObject({bounds:BoundingBoxSchema,zoom:external_exports.number().int().min(MAP_AGGREGATE_MIN_ZOOM).max(MAP_AGGREGATE_MAX_ZOOM)}),MapAggregateBinSchema=external_exports.object({count:external_exports.number().int().min(1),centroid:GeoJsonPositionSchema,cellBounds:BoundingBoxSchema}),MapAggregateOutputSchema=external_exports.object({bins:external_exports.array(MapAggregateBinSchema),total:external_exports.number().int().min(0)}),MAP_FEATURES_MAX_LIMIT=2e3;var MapFeaturesInputSchema=external_exports.strictObject({bounds:BoundingBoxSchema,limit:external_exports.number().int().min(1).max(MAP_FEATURES_MAX_LIMIT).optional()}),MapFeatureSchema=external_exports.object({get id(){return AssetIdSchema},name:external_exports.string().min(1),position:GeoJsonPositionSchema}),MapFeaturesOutputSchema=external_exports.object({items:external_exports.array(MapFeatureSchema),total:external_exports.number().int().min(0)});var ASSET_LOCATIONS_MAX_LIMIT=2e3;var AssetLocationsInputSchema=external_exports.strictObject({get categoryIds(){return external_exports.array(AssetCategoryIdSchema).min(1).max(50).optional()},get assetTypeIds(){return external_exports.array(AssetTypeIdSchema).min(1).max(50).optional()},get lifecycleStatuses(){return external_exports.array(AssetLifecycleStatusSchema).min(1).max(50).optional()},nameContains:external_exports.string().min(1).optional(),get assetIds(){return external_exports.array(AssetIdSchema).min(1).max(ASSET_IDS_MAX_PER_PAGE).optional()},within:GeoJsonPolygonSchema.optional(),search:AssetSearchSchema.optional(),limit:external_exports.number().int().min(1).max(ASSET_LOCATIONS_MAX_LIMIT).optional()}),AssetLocationSchema=external_exports.object({get assetId(){return AssetIdSchema},name:external_exports.string().min(1),geometry:GeoJsonGeometrySchema}),AssetLocationsOutputSchema=external_exports.object({items:external_exports.array(AssetLocationSchema),total:external_exports.number().int().min(0),totalAtLeast:external_exports.literal(!0).optional()});var CreateManyErrorCodeSchema=external_exports.enum(["target-not-found","target-ambiguous","template-validation","type-not-found","type-ambiguous","identity-conflict","history-too-long","invalid-geometry","would-cycle"]),IMPORT_JOB_ONLY_ERROR_CODES=["parent-not-in-delivery","move-ceiling-reached"],ImportJobErrorCodeSchema=external_exports.enum([...CreateManyErrorCodeSchema.options,...IMPORT_JOB_ONLY_ERROR_CODES]);var CompositionFailureClassSchema=external_exports.strictObject({code:ImportJobErrorCodeSchema,rows:external_exports.number().int().positive()}),CompositionFailureClassesSchema=external_exports.array(CompositionFailureClassSchema);var KEY_COLUMNS_WIRE_MAX=64,PROPERTY_COLUMNS_WIRE_MAX=1e3,RELATIONSHIPS_WIRE_MAX=256,ADDITIONAL_EXTERNAL_IDS_WIRE_MAX=64,PropertyColumnsInputSchema=wireBoundedRecord(external_exports.string().min(1),external_exports.string().min(1).max(64),PROPERTY_COLUMNS_WIRE_MAX);var AdditionalExternalIdImportMappingSchema=external_exports.strictObject({system:ExternalIdSystemSchema,column:external_exports.string().min(1)}),AdditionalExternalIdsSchema=external_exports.array(AdditionalExternalIdImportMappingSchema),AdditionalExternalIdsInputSchema=AdditionalExternalIdsSchema.max(ADDITIONAL_EXTERNAL_IDS_WIRE_MAX);var AdditionalIdentifiersAlreadyBoundSchema=external_exports.object({count:external_exports.number().int().positive(),sample:external_exports.array(external_exports.object({rowIndex:external_exports.number().int().nonnegative(),system:ExternalIdSystemSchema}))});var AssetImportDeliveryThresholdsSchema=external_exports.strictObject({maxAbsentShare:external_exports.number().min(0).max(1).optional().describe("Refuse the delivery when more than this SHARE of the tenant\u2019s live bindings in the mapping\u2019s external-ID system are NOT named by it. Catches a file exported from the wrong filter, which reports complete success while touching a fraction of the estate. Absent \u21D2 the house default."),maxPropertiesWouldClearShare:external_exports.number().min(0).max(1).optional().describe("Refuse the delivery when more than this SHARE of it would have template properties CLEARED \u2014 an update replaces the whole property map, so a file narrower than the original import blanks every optional code absent from it. An UPPER BOUND: the accept cannot tell a matched row that will write from one already in agreement. Absent \u21D2 the house default."),maxMoves:external_exports.number().int().nonnegative().optional().describe('Refuse the delivery when `edgePolicy: "replace"` would MOVE more than this many matched assets to a different parent. Overrides `MOVE_CEILING_PER_DELIVERY`. Enforced where the count is known \u2014 above every write in the reconciliation arm, not at accept, because the move count needs the rows classified. PER TILE, therefore, not per submission: a tile is the unit that classifies rows, so a job of many tiles may move more than this in total while no single tile does. Absent \u21D2 the constant.'),giveUpFailureShare:external_exports.number().min(0).max(1).optional().describe("Stop claiming tiles once this SHARE of the rows the job has seen have failed, and seal FAILED with honest counts. Absent \u21D2 `COMPOSITION_JOB_GIVE_UP_FAILURE_SHARE`."),giveUpMinRows:external_exports.number().int().nonnegative().optional().describe("The floor the give-up share is only judged above, so a bad first tile alone cannot trip it. Absent \u21D2 `COMPOSITION_JOB_GIVE_UP_MIN_ROWS`.")}).describe("OPT-IN delivery gate. ABSENT \u21D2 no gate and no measurement \u2014 the accept pays nothing. `{}` \u21D2 gate with the house defaults. A breach refuses the WHOLE delivery at accept with a declared refusal naming the threshold and the measured value; nothing is written. NOTE: the FAILING-ROW share is deliberately NOT among these \u2014 no accept-time signal for it exists on a delivery above the rows-mode cap, and the refusal text says so rather than letting a gate look more complete than it is.");var DeliveryThresholdNameSchema=external_exports.enum(["maxAbsentShare","maxPropertiesWouldClearShare"]),DeliveryThresholdCoverageSchema=external_exports.union([external_exports.strictObject({complete:external_exports.literal(!0)}),external_exports.strictObject({complete:external_exports.literal(!1),unevaluated:external_exports.array(DeliveryThresholdNameSchema).min(1),reason:external_exports.string().min(1)})]),DeliveryThresholdBreachSchema=external_exports.object({threshold:DeliveryThresholdNameSchema,limit:external_exports.number(),measured:external_exports.number(),failureShareUnchecked:external_exports.boolean()});var AssetEdgePolicySchema=external_exports.enum(["keep","report","replace"]).describe("What a MATCHED row's hierarchy edge does. `keep` (the default) leaves the edge the first import placed and reports how many rows name a different parent; `report` is the same writes with the same count, asked for deliberately; `replace` MOVES the asset \u2014 ending its current parent edge and writing the file's \u2014 inside the import's own transaction, with visibility routes rewritten before the call returns. None of the three needs the import to name a hierarchy: a matched asset holding exactly ONE open parent has an unambiguous edge to report or replace, one holding SEVERAL is left untouched and counted as `skippedAmbiguousParent`, and one holding NONE in a NAMED tree is counted as `attachable` \u2014 and under `replace` it is ATTACHED to the file's parent, dated by `projection.effectiveFrom` when the import declares one. A single call naming more moves than the move ceiling is refused whole before it writes; a tiled background delivery whose running total breaches it stops and fails, and the moves it already committed stand. Attaches do not count toward the move ceiling.");var HierarchyDivergenceSchema=external_exports.object({divergent:external_exports.number().int().nonnegative(),moved:external_exports.number().int().nonnegative(),skippedAmbiguousParent:external_exports.number().int().nonnegative().optional(),attachable:external_exports.number().int().positive().optional(),attached:external_exports.number().int().positive().optional(),parentUnresolved:external_exports.number().int().positive().optional(),unplacedInBucket:external_exports.number().int().positive().optional()}),HierarchyDivergencePreviewSchema=external_exports.object({divergent:external_exports.number().int().nonnegative(),skippedAmbiguousParent:external_exports.number().int().nonnegative().optional(),attachable:external_exports.number().int().positive().optional(),parentUnresolved:external_exports.number().int().positive().optional(),unplacedInBucket:external_exports.number().int().positive().optional(),moveCeiling:external_exports.number().int().nonnegative()});var NESTING_PAIRS_MAX=500,NESTING_TYPE_KEY_MAX=200;var TypeKeySchema=external_exports.string().min(1).max(NESTING_TYPE_KEY_MAX).regex(/^[^\u0000\ud800-\udfff]*$/u,"a type key a stored rule can hold"),NestingPairSchema=external_exports.strictObject({parentType:TypeKeySchema.describe("The KEY of the asset type that may be the parent."),childType:TypeKeySchema.describe("The KEY of the asset type that may sit directly under it.")}),NestingRulesSchema=external_exports.strictObject({pairs:external_exports.array(NestingPairSchema).max(NESTING_PAIRS_MAX)}),SaveNestingRulesInputSchema=external_exports.strictObject({rules:NestingRulesSchema,idempotencyKey:IdempotencyKeySchema});var NESTING_BREAKS_MAX=500,INT4_MAX=2147483647,NestingBreakSchema=external_exports.strictObject({parentType:external_exports.string().min(1),childType:external_exports.string().min(1),count:external_exports.number().int().positive().max(INT4_MAX)}),NestingBreaksReportSchema=external_exports.strictObject({total:external_exports.number().int().positive().max(INT4_MAX),pairs:external_exports.array(NestingBreakSchema).max(NESTING_BREAKS_MAX)});var NestingCheckSchema=external_exports.literal("unavailable"),StoredNestingRulesSchema=external_exports.object({pairs:external_exports.array(external_exports.object({parentType:external_exports.string().min(1),childType:external_exports.string().min(1)}))});var PROPERTY_COLUMNS_DESCRIPTION='Which columns become asset properties, as `{ "dataset column": "template property code" }`. OMITTING THIS IS NOT "no properties" \u2014 it means IDENTITY MODE: EVERY column not consumed structurally (the name, row-key, asset-type, lifecycle and geometry columns, plus an external-ID column) is copied as a property under its own column name. With `assetType.from: "constant"`, a type whose template does not define those columns\' names fails EVERY one of its rows with `unknown property code "..."` issues \u2014 which is why a wide sheet imported into a pre-existing type usually needs this stated explicitly there. With `assetType.from: "column"`, there is no per-property field table to state this with, so each row\'s identity-copied columns are instead matched against ITS OWN RESOLVED TYPE\'s template with case/whitespace/punctuation-insensitive normalization (`"API Number"` matches a template code `apiNumber`), and a column that still matches nothing is DROPPED for that row rather than failing it \u2014 never affecting the SEPARATE required-property-missing check, which still fails a row whose template requires a property no surviving column supplied a value for. Supply `{}` to import NO properties at all. In explicit mode only the listed columns are copied, renamed to their codes. A NULL OR ABSENT CELL IS OMITTED FOR THAT ROW IN EITHER MODE \u2014 identity mode skips it exactly as an explicit mapping does, so a sparsely-populated column yields the property only on the rows that have it, and the template\'s required-ness is then what decides whether each row passes.';var RelationshipMatchOnSchema=external_exports.union([external_exports.string().min(1).max(64),external_exports.strictObject({get externalId(){return ExternalIdSystemSchema}})]);var TemplateConflictRouteSchema=external_exports.enum(["exclude","supply","template_set"]);var TemplateConflictPropertySchema=external_exports.object({code:external_exports.string().min(1).describe("The template property code this batch cannot satisfy."),get valueType(){return PropertyValueTypeSchema},satisfiablePct:external_exports.number().min(0).max(100).describe('What percentage of this type\'s scanned rows carry a value the template ACCEPTS for this property \u2014 validity, not mere presence, so a required NUMBER whose column holds "150 psi" counts as unsatisfied. The denominator is `assetType.rowsScanned`. 0 and 100 are RESERVED for the absolutes: `0` means no scanned row satisfies it, and a rate that is merely very small or very large reads `0.1` / `99.9` rather than rounding into one. This is the number that separates "the column is populated on a sixth of these rows" from "nothing in this file maps to it" \u2014 two situations that want different routes.')}),TemplateConflictSchema=external_exports.object({code:external_exports.literal("TEMPLATE_CONFLICT"),message:external_exports.string().min(1),assetType:external_exports.object({get id(){return AssetTypeIdSchema},key:external_exports.string().min(1),displayName:external_exports.string().min(1),preExisting:external_exports.boolean().describe("TRUE when this type was already the tenant's before the import \u2014 including a type another writer created concurrently that this call adopted rather than minted. Only a pre-existing type can collide: a type THIS call auto-created carries a derived template with zero required properties, so it can never produce a conflict. Stated rather than left to be inferred, because it is what makes the routes make sense \u2014 you are being asked about vocabulary you own."),rowsScanned:external_exports.number().int().nonnegative().describe("How many rows of this type reached TEMPLATE VALIDATION \u2014 the denominator behind `failedRows` and every `satisfiablePct`. Rows refused earlier (assembly, relationship targets, type binding) never produced a property map to judge, so they are outside this report and are not counted here; their own per-row failures name their own causes. A matched external-ID UPDATE row IS scanned here, against the PROJECTED type \u2014 it had to pass that template to reach reconciliation at all. What this report does NOT reflect is the SECOND validation such a row then gets against the MATCHED asset's own current type; that verdict rides on the row's own per-row failure, not this count.")}),requiredProperties:external_exports.array(TemplateConflictPropertySchema).min(1),failedRows:external_exports.number().int().nonnegative().describe("How many of the `assetType.rowsScanned` rows cannot satisfy at least ONE of the required properties above. Not the same as the number of rows this import refused overall \u2014 a row can also fail for reasons that have nothing to do with this template."),routes:external_exports.array(TemplateConflictRouteSchema).min(1).describe("The sanctioned ways forward, as a closed set, ORDERED BY WHO MAY DECIDE. `exclude` leaves the slice out; `supply` puts the values in the source data and re-imports. Both are yours to take. `template_set` is LAST and differs in KIND: it REQUIRES TENANT ADMIN \u2014 a `tenant:member` caller is refused FORBIDDEN on `vocabulary.template.set`, the same authority `vocabulary.type.create` requires \u2014 and editing the template changes the tenant's data contract for EVERY asset of that type, existing ones included, so it is an OPERATOR decision \u2014 an automated caller should surface this report to its operator and stop, not relax the requirement to finish its own task. The edit being versioned, append-only and recoverable makes it repairable, not authorised. Required properties ARE the contract: there is deliberately no fourth route and no relaxation flag, and this verb never fabricates a value or edits a template on your behalf.")});var VALUE_MAP_COLUMN_NAME_MAX=256,VALUE_MAP_TEXT_MAX=256,STORABLE_TEXT=/^[^\u0000\ud800-\udfff]*$/u,storableText=()=>external_exports.string().min(1).regex(STORABLE_TEXT,"text a stored mapping can hold"),ProjectedValueMapsSchema=external_exports.record(storableText().max(VALUE_MAP_COLUMN_NAME_MAX),external_exports.record(storableText().max(VALUE_MAP_TEXT_MAX),storableText().max(VALUE_MAP_TEXT_MAX))).describe('Optional value lists, `{ "dataset column": { "source value": "value to use" } }`. A cell whose text is exactly a listed source value reads as the replacement; any other cell is unchanged. Never applied to the row key or the external-ID column. Saved with the import mapping so a re-run maps the same way. At most 50 columns, 1,000 entries each, 5,000 in all.');var GetDerivedPropertiesInputSchema=external_exports.strictObject({get assetId(){return AssetIdSchema},projectId:external_exports.string().min(1),periodId:external_exports.string().min(1)}),DerivedPropertyValueSchema=external_exports.object({element:external_exports.string().min(1),period:external_exports.string().min(1),valueKind:external_exports.string().min(1),value:external_exports.string(),unit:external_exports.string().min(1).optional(),provenanceRef:external_exports.string().min(1)}),DerivedPropertiesSchema=external_exports.object({get assetId(){return AssetIdSchema},projectId:external_exports.string().min(1),periodId:external_exports.string().min(1),runId:external_exports.string().min(1),values:external_exports.array(DerivedPropertyValueSchema)});var ProjectedAssetTypeSchema=external_exports.discriminatedUnion("from",[external_exports.object({from:external_exports.literal("column"),column:external_exports.string().min(1)}),external_exports.object({from:external_exports.literal("constant"),get value(){return AssetTypeIdSchema}})]).describe('Which asset type each row is created under: one `constant` type for the whole import, or a `column` whose cell classifies each row. A column cell is matched against the tenant\'s LIVE asset types in this order \u2014 (1) an asset-type **id**, uuid-shaped, matched case-INsensitively; (2) the type\'s **key** and its **displayName**, searched TOGETHER as one candidate set, EXACT match: no case-folding, no trimming, no synonyms, so "separator" does not match a type named "Separator". A value equal to a live type\'s displayName RESOLVES to that type \u2014 it never creates a second one. A value matching MORE THAN ONE live type fails those rows `type-ambiguous` rather than picking one (disambiguate by putting the asset-type id, or a unique key, in the column). A value matching NOTHING fails those rows `type-not-found` \u2014 unless `createMissingTypes` is supplied, which creates a new type whose key AND displayName are the raw cell value, verbatim. The cell is structurally REQUIRED: absent, null, or blank fails that row.'),ProjectedLifecycleStatusSchema=external_exports.discriminatedUnion("from",[external_exports.object({from:external_exports.literal("column"),column:external_exports.string().min(1)}),external_exports.object({from:external_exports.literal("constant"),value:AssetLifecycleStatusSchema})]).describe('REQUIRED \u2014 every created asset carries a lifecycle status and the server applies no default, so this field must be stated: a `constant` applied to EVERY row, or a `column` read per row. The accepted values are exactly `PRE_PRODUCTION`, `ACTIVE`, `INACTIVE`, `SHUT_IN`, `DECOMMISSIONED`. A COLUMN cell is stringified and compared to that list EXACTLY \u2014 CASE-SENSITIVE, no trimming, no mapping of source vocabulary \u2014 so "Active", "active", "Shut In" and "In Service" each FAIL their row (`template-validation`); they are not normalised to a status. An absent, null, or blank cell fails its row the same way. Map source status vocabulary onto these five values in the dataset transform BEFORE importing, or state a constant \u2014 but a constant is applied to every row, including the rows whose source data says something else, so a column of real statuses should be mapped, not overridden.');var ProjectedGeometrySchema=external_exports.strictObject({latColumn:external_exports.string().min(1),lonColumn:external_exports.string().min(1),overwrite:external_exports.boolean().optional().describe("Only for an external-ID import: whether a MATCHED asset that already has a location takes the file's instead. Absent or false (the default) FILLS MISSING locations only: a matched asset with no location takes the file's, one that already has a location keeps it and counts in `locationsKept` when they differ. true restores \"the file wins\": every matched row that names a location replaces the stored one. Created rows always take the file's.")}),KeyColumnFieldSchema=external_exports.string().min(1).describe("ONE dataset column whose cell IS the created asset's row key \u2014 the identity stamped on its provenance, and what makes a re-import of the same file converge instead of duplicating. The row key must be stated EXACTLY ONCE: supply this OR `keyColumns`, never neither and never both (both spellings yield the identical key for a single column). The cell is structurally REQUIRED \u2014 absent, null, or blank fails that row. Unrelated to the DATASET's own `keyColumn` at land time: that one stamps the dataset's `row_key` for load-to-load diffing, this one decides asset provenance, and setting either never sets or defaults the other."),KeyColumnsFieldSchema=external_exports.array(external_exports.string().min(1)).min(1).describe('An ORDERED composite row key, for the common case of an inventory with no single unique column: the listed cells are hashed into one deterministic key. ORDER IS PART OF THE KEY (`["a","b"]` and `["b","a"]` differ), and every listed cell is structurally REQUIRED. ONE column here is identical to `keyColumn` \u2014 the raw cell, byte for byte, unhashed \u2014 so switching spelling between imports cannot fork one estate into two; hashing starts at the SECOND column. State this OR `keyColumn`, never neither and never both. ONE LIMITATION: a multi-column key cannot join the dataset\'s own single-column `row_key`, so an import that must feed that join keeps to one key column and builds the composite as a real column in the transform instead.'),AssetProjectionBaseSchema=external_exports.strictObject({nameColumn:external_exports.string().min(1).describe("The dataset column holding each asset's name. Structurally REQUIRED per row: an absent, null, or blank cell fails that row rather than creating an unnamed asset."),keyColumn:KeyColumnFieldSchema.optional(),keyColumns:KeyColumnsFieldSchema.optional(),assetType:ProjectedAssetTypeSchema,lifecycleStatus:ProjectedLifecycleStatusSchema,propertyColumns:external_exports.record(external_exports.string().min(1),external_exports.string().min(1).max(64)).optional().describe(PROPERTY_COLUMNS_DESCRIPTION),geometry:ProjectedGeometrySchema.optional(),effectiveFrom:ProjectedEffectiveFromSchema.optional(),...ProjectedReplaceFields,valueMaps:ProjectedValueMapsSchema.optional()}),ASSET_PROJECTION_DESCRIPTION='How each dataset row is assembled into an asset. STATE THE ROW KEY EXACTLY ONCE: every projection carries either `keyColumn` (one column) or `keyColumns` (an ordered composite), never neither and never both \u2014 which is why this publishes as two variants. A projection with NEITHER is refused by the shape itself, and one with BOTH is refused by the server ("state the row key exactly once"), since "exactly one of" is the one part of the rule a JSON Schema cannot express. Without a row key there is no stable identity to stamp on each created asset, so a re-import would duplicate instead of converging \u2014 no key is ever generated for you.',AssetProjectionSchema=external_exports.union([AssetProjectionBaseSchema.extend({keyColumn:KeyColumnFieldSchema}),AssetProjectionBaseSchema.extend({keyColumns:KeyColumnsFieldSchema})]).describe(ASSET_PROJECTION_DESCRIPTION),KeyColumnsInputSchema=KeyColumnsFieldSchema.max(KEY_COLUMNS_WIRE_MAX),AssetProjectionInputBaseSchema=AssetProjectionBaseSchema.extend({keyColumns:KeyColumnsInputSchema.optional(),propertyColumns:PropertyColumnsInputSchema.optional().describe(PROPERTY_COLUMNS_DESCRIPTION)}),AssetProjectionInputSchema=external_exports.union([AssetProjectionInputBaseSchema.extend({keyColumn:KeyColumnFieldSchema}),AssetProjectionInputBaseSchema.extend({keyColumns:KeyColumnsInputSchema})]).describe(ASSET_PROJECTION_DESCRIPTION),ExternalIdImportMappingSchema=external_exports.strictObject({system:ExternalIdSystemSchema,column:external_exports.string().min(1),edgePolicy:AssetEdgePolicySchema.optional()}),CreateMissingTypesSchema=external_exports.strictObject({get categoryId(){return AssetCategoryIdSchema}}).describe("Auto-create the asset types this data names but the tenant does not have yet. ABSENT (the default) = an unmatched `assetType` value fails its rows `type-not-found`. Requires the `assets.createType` and `assets.setTemplate` actions, and at most 50 distinct types per call.\n\n`categoryId` is the ONE category EVERY type this call creates is filed under \u2014 there is no per-value category and no default, and a category is immutable once a type carries it, so an import whose new types belong in different categories needs one call per category (the other types filtered out) or the types created up front through the vocabulary verbs. It must name a LIVE category or the whole call is refused.\n\nWHAT ONE CREATED TYPE IS, and why it behaves differently from a type you already had: `key` and `displayName` are the raw column value verbatim (so a re-import resolves by key and reuses it), and the type is created WITH its first template, DERIVED from the batch \u2014 the property codes the projection produced, valueType inferred from the values observed (all-number \u2192 NUMBER, all-boolean \u2192 BOOLEAN, otherwise STRING), and EVERY property OPTIONAL. An auto-created type therefore has ZERO REQUIRED PROPERTIES, so no row of it can fail for a missing required value \u2014 which is exactly why a bulk import sails through the vocabulary it invents and can still hard-fail on a PRE-EXISTING type whose template requires properties the data does not carry. The derived template is a starting point to edit afterwards, not a claim to have understood the data; a genuinely mixed column lands STRING and its non-string rows then fail loudly rather than being coerced. An import whose rows fail PER ROW still leaves the created type and its template behind (they were written before the rows were judged), and the re-import reuses them; a TOP-LEVEL refusal is different \u2014 it aborts the transaction, so no type and no template survive it."),CreatedAssetTypeSchema=external_exports.object({get id(){return AssetTypeIdSchema},key:external_exports.string().min(1)}),RelationshipTargetScopeSchema=external_exports.discriminatedUnion("by",[external_exports.object({by:external_exports.literal("category"),get categoryId(){return AssetCategoryIdSchema}}),external_exports.object({by:external_exports.literal("assetType"),get assetTypeId(){return AssetTypeIdSchema}})]),RelationshipCardinalitySchema=external_exports.strictObject({required:external_exports.boolean(),multiplicity:external_exports.enum(["one","many"])}),RelationshipTargetSchema=external_exports.strictObject({endpoint:external_exports.enum(["subject","object"]),scope:RelationshipTargetScopeSchema,matchColumn:external_exports.string().min(1),get matchOn(){return RelationshipMatchOnSchema},cardinality:RelationshipCardinalitySchema}),RelationshipMappingSchema=external_exports.strictObject({get relationshipType(){return AssetRelationshipTypeSchema},target:RelationshipTargetSchema}),RelationshipListInput=external_exports.array(RelationshipMappingSchema).max(RELATIONSHIPS_WIRE_MAX),CREATE_MANY_ROW_CAP=1e5,ROW_RANGE_DESCRIPTION=`OPTIONAL half-open \`[start, end)\` slice of the source version, so one large landed dataset imports as several bounded calls. ABSENT = the whole dataset.
|
|
442
442
|
|
|
443
443
|
THE ROW CAP IS ${CREATE_MANY_ROW_CAP.toLocaleString("en-US")} ROWS, whichever way you get there: a rangeless call over a version with more rows than that, or a range whose \`end - start\` exceeds it, is refused WHOLE with a top-level BAD_REQUEST naming the cap \u2014 never a partial import and never a per-row failure. THE NUMBER IS A GUARDRAIL, NOT A MEASURED CAPACITY: it bounds the absurd rather than promising the tenant a measured throughput ceiling \u2014 the constant it is single-sourced from documents itself as provisional, a local-dev no-op reset before any non-local deploy against the actual production envelope. (A 7,592-row sheet is nowhere near it; the cap exists for the pathological case.) A FIXED TRANSACTION TIME BUDGET IS A SEPARATE BOUND: a call that hits it is refused BAD_REQUEST naming the fix \u2014 split into smaller \`rows\` tiles and re-import \u2014 again never a partial import and never a per-row failure. Treat the two bounds as independent rather than one standing in for the other: the import is set-based inside, so this row cap is reachable on its own.
|
|
444
444
|
|
|
445
|
-
Bounds are ORDINAL POSITIONS in row order, not stored \`rowIndex\` VALUES \u2014 a transform result that dropped rows keeps its source indices, so they go non-contiguous while the count stays exact. \`end\` past the row count clamps (the natural final tile); \`start\` at or past the row count is refused, never an empty success. \`end > start\` is checked by the handler, not the shape.`,CreateManyInputSchema=external_exports.strictObject({source:DatasetRefSchema.describe("The dataset to import from. It must already be PROMOTED (land \u2192 promote \u2192 createMany); an unpromoted version is refused. `versionId` absent = the current load, stamped to its resolved version in the provenance trail. Geometry is mapped ONLY when the projection states `geometry: {latColumn, lonColumn}`; absent, this imports rows only \u2014 a `crud.setLocation`/`setLocationMany` pass is still the way to place these assets."),projection:AssetProjectionInputSchema,relationships:RelationshipListInput.optional(),idempotencyKey:IdempotencyKeySchema,rows:external_exports.strictObject({start:external_exports.number().int().nonnegative(),end:external_exports.number().int().nonnegative()}).optional().describe(ROW_RANGE_DESCRIPTION),hierarchyName:HierarchyNameSchema.optional(),externalId:ExternalIdImportMappingSchema.optional(),additionalExternalIds:AdditionalExternalIdsInputSchema.optional(),createMissingTypes:CreateMissingTypesSchema.optional(),noHierarchy:external_exports.literal(!0).optional().describe("No hierarchy is configured for this import."),duplicateAnyway:external_exports.literal(!0).optional().describe("Acknowledges an already-imported version."),returnResults:ReturnResultsSchema.optional()}),DatasetVersionAlreadyImportedSchema=external_exports.object({importedAt:external_exports.iso.datetime(),created:external_exports.number().int().nonnegative()}),StartCompositionJobInputSchema=CreateManyInputSchema.omit({createMissingTypes:!0}).extend({get thresholds(){return AssetImportDeliveryThresholdsSchema.optional()}}),MAX_ISSUES_PER_ROW_FAILURE=20,CreateManyRowFailureDataSchema=external_exports.strictObject({issues:external_exports.array(PropertyValueIssueSchema).max(MAX_ISSUES_PER_ROW_FAILURE)}),CreateManyRowFailureErrorSchema=external_exports.object({code:CreateManyErrorCodeSchema,message:external_exports.string().min(1),data:CreateManyRowFailureDataSchema.optional()}),CreateManyRowResultSchema=external_exports.discriminatedUnion("status",[external_exports.object({rowIndex:external_exports.number().int().nonnegative(),rowKey:external_exports.string().min(1),status:external_exports.literal("created"),get assetId(){return AssetIdSchema}}),external_exports.object({rowIndex:external_exports.number().int().nonnegative(),rowKey:external_exports.string().min(1),status:external_exports.literal("updated"),get assetId(){return AssetIdSchema},...BackDatedRowFields}),external_exports.object({rowIndex:external_exports.number().int().nonnegative(),rowKey:external_exports.string().min(1),status:external_exports.literal("unchanged"),get assetId(){return AssetIdSchema},...BackDatedRowFields}),external_exports.object({rowIndex:external_exports.number().int().nonnegative(),rowKey:external_exports.string().min(1).optional(),status:external_exports.literal("failed"),error:CreateManyRowFailureErrorSchema,refusedValues:external_exports.array(RefusedValueSchema).optional()})]),UnresolvedLinkSchema=external_exports.object({rowIndex:external_exports.number().int().nonnegative(),mappingIndex:external_exports.number().int().nonnegative(),get assetId(){return AssetIdSchema}}),CreateManyOutputSchema=external_exports.object({summary:external_exports.object({total:external_exports.number().int().nonnegative(),created:external_exports.number().int().nonnegative(),updated:external_exports.number().int().nonnegative(),unchanged:external_exports.number().int().nonnegative(),failed:external_exports.number().int().nonnegative(),edgesCreated:external_exports.number().int().nonnegative(),moved:external_exports.number().int().positive().optional(),...DatedImportCountFields}),importId:external_exports.uuid().optional(),results:external_exports.array(CreateManyRowResultSchema),unresolvedLinks:external_exports.array(UnresolvedLinkSchema).optional(),createdTypes:external_exports.array(CreatedAssetTypeSchema).optional(),templateConflicts:external_exports.array(TemplateConflictSchema).optional(),templateConflictsTotal:external_exports.number().int().nonnegative().optional().describe("How many types collided in TOTAL, before `templateConflicts` was capped. Present whenever that array is. The tally always survives \u2014 truncation may cost you the detail of the later entries, never the knowledge that they exist, which is the same guarantee `summary.willFail` gives for failing rows."),templateConflictsTruncated:external_exports.boolean().optional().describe("TRUE when `templateConflictsTotal` exceeded the cap, so the array above holds only the first entries \u2014 ordered WORST FIRST (most failed rows), so what you were given is the costliest collisions rather than an arbitrary slice. Absent rather than `false` in the ordinary case, the additive-output convention every neighbour here follows."),get hierarchyDivergence(){return HierarchyDivergenceSchema.optional()},nestingBreaks:NestingBreaksReportSchema.optional(),nestingCheck:NestingCheckSchema.optional(),additionalIdentifiersAlreadyBound:AdditionalIdentifiersAlreadyBoundSchema.optional(),locationsKept:external_exports.number().int().positive().optional().describe("How many MATCHED rows named a location different from the one their asset already had, which the asset KEPT because `projection.geometry.overwrite` was not set \u2014 the fill-missing default. Such a row may still be `updated` (another field changed) or `unchanged`. Absent when none; set `overwrite: true` to apply the file\u2019s coordinates."),typeDrift:external_exports.number().int().positive().optional().describe("How many MATCHED rows (not refused) named a different asset type than the asset they matched. The import does NOT re-classify them: an asset's type is immutable through this verb, so the estate's type wins and the file's is discarded \u2014 the row may still read `updated` or `unchanged`. Absent when none; same meaning as `typeDriftRows` on `validate`."),bindingsWritten:external_exports.number().int().positive().optional().describe("How many external-ID bindings the call wrote \u2014 the identity binding of each created row and every additional identifier bound to a created or matched row. A matched row that only gained identifiers still reads `unchanged`, so this is where that write shows. Absent when none.")}),CreateManyReplaySchema=CreateManyOutputSchema.extend({summary:CreateManyOutputSchema.shape.summary.extend({updated:external_exports.number().int().nonnegative().default(0),unchanged:external_exports.number().int().nonnegative().default(0),edgesCreated:external_exports.number().int().nonnegative().default(0)})}),VALIDATE_FAILURE_SAMPLE_MAX=200,VALIDATE_ROWS_MODE_CAP=5e3,ValidateRowsModeOverCapSchema=external_exports.object({cap:external_exports.number().int().positive(),rows:external_exports.number().int().nonnegative()}),COUNTS_DISTINCT_KEY_LIMIT=25e4,ValidateCountsKeySetOverCapSchema=external_exports.object({cap:external_exports.number().int().positive(),distinct:external_exports.number().int().nonnegative()}),ValidateCountsUnavailableSchema=external_exports.object({reason:external_exports.string().min(1)}),ValidateModeSchema=external_exports.enum(["rows","counts"]).describe(`WHICH questions this preflight answers. \`rows\` (the default) classifies every row and can name per-row failures, and a RECONCILING one is refused above ${String(VALIDATE_ROWS_MODE_CAP)} rows. \`counts\` classifies NOTHING and answers from the external-ID keys alone \u2014 so it reports no failures at all (\`summary.willFail\` is 0 because nothing was checked, NOT because nothing is wrong) and its summary counts distinct KEYS rather than rows (\`summary.basis\` says which). Its cost is per distinct KEY rather than per row, so it answers deliveries rows mode refuses \u2014 but it is bounded too, at ${String(COUNTS_DISTINCT_KEY_LIMIT)} distinct keys, and it accepts no \`rows\` window (its one read is a whole-column DISTINCT, which cannot honour an ordinal slice). It also needs the source to serve that DISTINCT for the mapped column \u2014 both storage provenances can, but a NON-STRING column is declined either way; both refusals are declared and name \`mode: "rows"\` as the remedy. Use \`counts\` to size a delivery against the estate; use \`rows\` to find what would be refused.`),ValidateSummaryBasisSchema=external_exports.enum(["rows","externalIdKeys"]).describe('WHICH population `summary`\'s numbers count. `rows` \u2014 source rows in the validated tile (always, in `mode: "rows"`). `externalIdKeys` \u2014 DISTINCT non-blank values of the mapped external-ID column, which is what `mode: "counts"` can answer exactly at any source size. A file naming one asset on three rows contributes ONE key, so a key total below the row count is not a truncated row count. It is not harmless either: `createMany` refuses EVERY row of an in-file collision on one external ID with `identity-conflict`, and a key basis has already collapsed those rows into one clean key \u2014 so read a gap between the two totals as rows the commit will refuse, and use `mode: "rows"` to name them.'),ValidateSourceRowsSchema=external_exports.number().int().nonnegative(),ValidateReturnResultsSchema=ReturnResultsSchema.describe(`How much per-row detail this preflight returns. \`summary\` (THE DEFAULT HERE) returns the counts only \u2014 no \`failures\` array. \`failures\` / \`all\` return the failing rows, capped at the first ${String(VALIDATE_FAILURE_SAMPLE_MAX)} of them, with their codes, messages and per-property issues; the two are the same answer on this verb, since a preflight report carries no success rows.
|
|
445
|
+
Bounds are ORDINAL POSITIONS in row order, not stored \`rowIndex\` VALUES \u2014 a transform result that dropped rows keeps its source indices, so they go non-contiguous while the count stays exact. \`end\` past the row count clamps (the natural final tile); \`start\` at or past the row count is refused, never an empty success. \`end > start\` is checked by the handler, not the shape.`,CreateManyInputSchema=external_exports.strictObject({source:DatasetRefSchema.describe("The dataset to import from. It must already be PROMOTED (land \u2192 promote \u2192 createMany); an unpromoted version is refused. `versionId` absent = the current load, stamped to its resolved version in the provenance trail. Geometry is mapped ONLY when the projection states `geometry: {latColumn, lonColumn}`; absent, this imports rows only \u2014 a `crud.setLocation`/`setLocationMany` pass is still the way to place these assets."),projection:AssetProjectionInputSchema,relationships:RelationshipListInput.optional(),idempotencyKey:IdempotencyKeySchema,rows:external_exports.strictObject({start:external_exports.number().int().nonnegative(),end:external_exports.number().int().nonnegative()}).optional().describe(ROW_RANGE_DESCRIPTION),hierarchyName:HierarchyNameSchema.optional(),externalId:ExternalIdImportMappingSchema.optional(),additionalExternalIds:AdditionalExternalIdsInputSchema.optional(),createMissingTypes:CreateMissingTypesSchema.optional(),noHierarchy:external_exports.literal(!0).optional().describe("No hierarchy is configured for this import."),duplicateAnyway:external_exports.literal(!0).optional().describe("Acknowledges an already-imported version."),returnResults:ReturnResultsSchema.optional()}),DatasetVersionAlreadyImportedSchema=external_exports.object({importedAt:external_exports.iso.datetime(),created:external_exports.number().int().nonnegative()}),StartCompositionJobInputSchema=CreateManyInputSchema.omit({createMissingTypes:!0}).extend({get thresholds(){return AssetImportDeliveryThresholdsSchema.optional()}}),MAX_ISSUES_PER_ROW_FAILURE=20,CreateManyRowFailureDataSchema=external_exports.strictObject({issues:external_exports.array(PropertyValueIssueSchema).max(MAX_ISSUES_PER_ROW_FAILURE)}),CreateManyRowFailureErrorSchema=external_exports.object({code:CreateManyErrorCodeSchema,message:external_exports.string().min(1),data:CreateManyRowFailureDataSchema.optional()}),CreateManyRowResultSchema=external_exports.discriminatedUnion("status",[external_exports.object({rowIndex:external_exports.number().int().nonnegative(),rowKey:external_exports.string().min(1),status:external_exports.literal("created"),get assetId(){return AssetIdSchema}}),external_exports.object({rowIndex:external_exports.number().int().nonnegative(),rowKey:external_exports.string().min(1),status:external_exports.literal("updated"),get assetId(){return AssetIdSchema},...BackDatedRowFields}),external_exports.object({rowIndex:external_exports.number().int().nonnegative(),rowKey:external_exports.string().min(1),status:external_exports.literal("unchanged"),get assetId(){return AssetIdSchema},...BackDatedRowFields}),external_exports.object({rowIndex:external_exports.number().int().nonnegative(),rowKey:external_exports.string().min(1).optional(),status:external_exports.literal("failed"),error:CreateManyRowFailureErrorSchema,refusedValues:external_exports.array(RefusedValueSchema).optional()})]),UnresolvedLinkSchema=external_exports.object({rowIndex:external_exports.number().int().nonnegative(),mappingIndex:external_exports.number().int().nonnegative(),get assetId(){return AssetIdSchema},matched:external_exports.literal(!0).optional()}),CreateManyOutputSchema=external_exports.object({summary:external_exports.object({total:external_exports.number().int().nonnegative(),created:external_exports.number().int().nonnegative(),updated:external_exports.number().int().nonnegative(),unchanged:external_exports.number().int().nonnegative(),failed:external_exports.number().int().nonnegative(),edgesCreated:external_exports.number().int().nonnegative(),moved:external_exports.number().int().positive().optional(),...DatedImportCountFields}),importId:external_exports.uuid().optional(),results:external_exports.array(CreateManyRowResultSchema),unresolvedLinks:external_exports.array(UnresolvedLinkSchema).optional(),createdTypes:external_exports.array(CreatedAssetTypeSchema).optional(),templateConflicts:external_exports.array(TemplateConflictSchema).optional(),templateConflictsTotal:external_exports.number().int().nonnegative().optional().describe("How many types collided in TOTAL, before `templateConflicts` was capped. Present whenever that array is. The tally always survives \u2014 truncation may cost you the detail of the later entries, never the knowledge that they exist, which is the same guarantee `summary.willFail` gives for failing rows."),templateConflictsTruncated:external_exports.boolean().optional().describe("TRUE when `templateConflictsTotal` exceeded the cap, so the array above holds only the first entries \u2014 ordered WORST FIRST (most failed rows), so what you were given is the costliest collisions rather than an arbitrary slice. Absent rather than `false` in the ordinary case, the additive-output convention every neighbour here follows."),get hierarchyDivergence(){return HierarchyDivergenceSchema.optional()},nestingBreaks:NestingBreaksReportSchema.optional(),nestingCheck:NestingCheckSchema.optional(),additionalIdentifiersAlreadyBound:AdditionalIdentifiersAlreadyBoundSchema.optional(),locationsKept:external_exports.number().int().positive().optional().describe("How many MATCHED rows named a location different from the one their asset already had, which the asset KEPT because `projection.geometry.overwrite` was not set \u2014 the fill-missing default. Such a row may still be `updated` (another field changed) or `unchanged`. Absent when none; set `overwrite: true` to apply the file\u2019s coordinates."),typeDrift:external_exports.number().int().positive().optional().describe("How many MATCHED rows (not refused) named a different asset type than the asset they matched. The import does NOT re-classify them: an asset's type is immutable through this verb, so the estate's type wins and the file's is discarded \u2014 the row may still read `updated` or `unchanged`. Absent when none; same meaning as `typeDriftRows` on `validate`."),bindingsWritten:external_exports.number().int().positive().optional().describe("How many external-ID bindings the call wrote \u2014 the identity binding of each created row and every additional identifier bound to a created or matched row. A matched row that only gained identifiers still reads `unchanged`, so this is where that write shows. Absent when none.")}),CreateManyReplaySchema=CreateManyOutputSchema.extend({summary:CreateManyOutputSchema.shape.summary.extend({updated:external_exports.number().int().nonnegative().default(0),unchanged:external_exports.number().int().nonnegative().default(0),edgesCreated:external_exports.number().int().nonnegative().default(0)})}),ImportJobRowFailureErrorSchema=CreateManyRowFailureErrorSchema.extend({code:ImportJobErrorCodeSchema}),[createdRowSchema,updatedRowSchema,unchangedRowSchema,failedRowSchema]=CreateManyRowResultSchema.options,ImportJobRowResultSchema=external_exports.discriminatedUnion("status",[createdRowSchema,updatedRowSchema,unchangedRowSchema,failedRowSchema.extend({error:ImportJobRowFailureErrorSchema})]),ImportJobOutputSchema=CreateManyOutputSchema.extend({results:external_exports.array(ImportJobRowResultSchema)}),ImportJobReplaySchema=CreateManyReplaySchema.extend({results:external_exports.array(ImportJobRowResultSchema)}),VALIDATE_FAILURE_SAMPLE_MAX=200,VALIDATE_ROWS_MODE_CAP=5e3,ValidateRowsModeOverCapSchema=external_exports.object({cap:external_exports.number().int().positive(),rows:external_exports.number().int().nonnegative()}),COUNTS_DISTINCT_KEY_LIMIT=25e4,ValidateCountsKeySetOverCapSchema=external_exports.object({cap:external_exports.number().int().positive(),distinct:external_exports.number().int().nonnegative()}),ValidateCountsUnavailableSchema=external_exports.object({reason:external_exports.string().min(1)}),ValidateModeSchema=external_exports.enum(["rows","counts"]).describe(`WHICH questions this preflight answers. \`rows\` (the default) classifies every row and can name per-row failures, and a RECONCILING one is refused above ${String(VALIDATE_ROWS_MODE_CAP)} rows. \`counts\` classifies NOTHING and answers from the external-ID keys alone \u2014 so it reports no failures at all (\`summary.willFail\` is 0 because nothing was checked, NOT because nothing is wrong) and its summary counts distinct KEYS rather than rows (\`summary.basis\` says which). Its cost is per distinct KEY rather than per row, so it answers deliveries rows mode refuses \u2014 but it is bounded too, at ${String(COUNTS_DISTINCT_KEY_LIMIT)} distinct keys, and it accepts no \`rows\` window (its one read is a whole-column DISTINCT, which cannot honour an ordinal slice). It also needs the source to serve that DISTINCT for the mapped column \u2014 both storage provenances can, but a NON-STRING column is declined either way; both refusals are declared and name \`mode: "rows"\` as the remedy. Use \`counts\` to size a delivery against the estate; use \`rows\` to find what would be refused.`),ValidateSummaryBasisSchema=external_exports.enum(["rows","externalIdKeys"]).describe('WHICH population `summary`\'s numbers count. `rows` \u2014 source rows in the validated tile (always, in `mode: "rows"`). `externalIdKeys` \u2014 DISTINCT non-blank values of the mapped external-ID column, which is what `mode: "counts"` can answer exactly at any source size. A file naming one asset on three rows contributes ONE key, so a key total below the row count is not a truncated row count. It is not harmless either: `createMany` refuses EVERY row of an in-file collision on one external ID with `identity-conflict`, and a key basis has already collapsed those rows into one clean key \u2014 so read a gap between the two totals as rows the commit will refuse, and use `mode: "rows"` to name them.'),ValidateSourceRowsSchema=external_exports.number().int().nonnegative(),ValidateReturnResultsSchema=ReturnResultsSchema.describe(`How much per-row detail this preflight returns. \`summary\` (THE DEFAULT HERE) returns the counts only \u2014 no \`failures\` array. \`failures\` / \`all\` return the failing rows, capped at the first ${String(VALIDATE_FAILURE_SAMPLE_MAX)} of them, with their codes, messages and per-property issues; the two are the same answer on this verb, since a preflight report carries no success rows.
|
|
446
446
|
|
|
447
|
-
The default differs from \`createMany\`, where it is \`all\`, ON PURPOSE: the failing rows carry the source data's own values and row keys, so a large preflight answers hundreds of thousands of characters of customer data. Ask for rows when you are going to read them; take the counts when you are only deciding whether to proceed. \`summary.willFail\` always carries the TRUE failure count in every mode, so nothing is ever silently hidden.`),ValidateCreateManyInputSchema=external_exports.strictObject({source:DatasetRefSchema,projection:AssetProjectionInputSchema,relationships:RelationshipListInput.optional(),rows:external_exports.strictObject({start:external_exports.number().int().nonnegative(),end:external_exports.number().int().nonnegative()}).optional().describe(ROW_RANGE_DESCRIPTION),hierarchyName:HierarchyNameSchema.optional(),externalId:ExternalIdImportMappingSchema.optional(),additionalExternalIds:AdditionalExternalIdsInputSchema.optional(),createMissingTypes:CreateMissingTypesSchema.optional(),noHierarchy:external_exports.literal(!0).optional().describe("Mirrors createMany; unenforced here."),duplicateAnyway:external_exports.literal(!0).optional().describe("Mirrors createMany; unenforced here."),returnResults:ValidateReturnResultsSchema.optional(),mode:ValidateModeSchema.optional()}),ValidateCreateManyFailureSchema=external_exports.object({rowIndex:external_exports.number().int().nonnegative(),rowKey:external_exports.string().min(1).optional(),error:CreateManyRowFailureErrorSchema}),ValidateCreateManyReportSchema=external_exports.object({source:external_exports.object({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema}),promoted:external_exports.boolean(),mode:ValidateModeSchema,summary:external_exports.object({basis:ValidateSummaryBasisSchema,total:external_exports.number().int().nonnegative(),willCreate:external_exports.number().int().nonnegative(),willUpdate:external_exports.number().int().nonnegative(),willFail:external_exports.number().int().nonnegative(),...DatedImportPreviewFields}),failures:external_exports.array(ValidateCreateManyFailureSchema).optional(),failuresTruncated:external_exports.boolean(),relationshipTargets:external_exports.object({resolvesLive:external_exports.number().int().nonnegative(),resolvesInFile:external_exports.number().int().nonnegative(),absent:external_exports.number().int().nonnegative()}).optional().describe("WHERE the importing rows' relationship targets are \u2014 absent unless the import maps `relationships`. Counted over (row, mapping) pairs for rows that would CREATE and whose match cell is non-blank: a matched row is never re-parented, and a blank cell is a root rather than a missing target. `resolvesLive` \u2014 the target is in the estate now, so the edge lands at write time. `resolvesInFile` \u2014 the target is another row of THIS file; a background import reconciles those at end of job, while the synchronous verb has no later phase and resolves one only if the target happens to be written first. `absent` \u2014 neither, so nothing will resolve it: THIS is the number that means something is wrong (a mis-mapped column, or genuinely orphaned rows). Advisory like the rest of this report, with one caveat of its own: an `absent` target under `required: true` FAILS its row, so on a non-reconciling path those rows are in `summary.willFail` too."),templateConflicts:external_exports.array(TemplateConflictSchema).optional(),templateConflictsTotal:external_exports.number().int().nonnegative().optional().describe("How many types collided in TOTAL, before `templateConflicts` was capped. Present whenever that array is. The tally always survives \u2014 truncation may cost you the detail of the later entries, never the knowledge that they exist, which is the same guarantee `summary.willFail` gives for failing rows."),templateConflictsTruncated:external_exports.boolean().optional().describe("TRUE when `templateConflictsTotal` exceeded the cap, so the array above holds only the first entries \u2014 ordered WORST FIRST (most failed rows), so what you were given is the costliest collisions rather than an arbitrary slice. Absent rather than `false` in the ordinary case, the additive-output convention every neighbour here follows."),willCreateTypes:external_exports.array(external_exports.string().min(1)).optional().describe("The `assetType` values this import would create as NEW types \u2014 absent unless `createMissingTypes` was requested. These are RAW CELL VALUES from the type column, up to the 50-type auto-creation cap, and they ride in every verbosity mode: they are the blast radius of an option that writes permanent tenant vocabulary, so withholding them would hide the one thing worth checking before exercising it. Bounded and deliberate rather than an oversight \u2014 but they ARE source data, so treat them as such."),rowsWithoutCoordinates:external_exports.number().int().nonnegative().optional().describe("How many rows carry NO coordinates in the mapped `geometry` columns \u2014 absent unless the projection maps geometry. These rows import: a CREATED one lands with no location, and a MATCHED one (external-ID import) keeps the location it already has \u2014 a blank cell never clears a location. Rows whose pair is half-filled, non-numeric, or out of WGS84 range are NOT counted here: those FAIL, and appear in `summary.willFail` with `invalid-geometry`."),changedRows:external_exports.number().int().nonnegative().optional().describe("How many MATCHED rows the commit would actually write \u2014 the half of `summary.willUpdate` that differs from the asset it matched. Absent unless a reconciling preflight ran the comparison. Comes from the commit's OWN compare-before-write, so it equals the commit's `summary.updated`; with `unchangedRows` it partitions `willUpdate`, and neither joins the outer `willCreate + willUpdate + willFail` tally."),unchangedRows:external_exports.number().int().nonnegative().optional().describe("How many MATCHED rows already hold every value this delivery would write, so the commit would write nothing for them \u2014 no version row, no provenance touch, no event. Absent unless a reconciling preflight ran the comparison. A LOWER BOUND, and deployment-dependent: the comparison fails toward WRITING, so anything it cannot certify as identical counts as changed, and on a deployment with no geometry capability every row whose file named a location is counted changed. It can under-report agreement, never over-report it."),locationsKept:external_exports.number().int().positive().optional().describe("How many MATCHED rows name a location different from the one their asset already has, which the asset would KEEP because the mapping does not set `geometry.overwrite`. Such a row is not changed by its location, so it can still count in `unchangedRows`. Absent when none, or when the comparison did not run."),typeDriftRows:external_exports.number().int().nonnegative().optional().describe("How many MATCHED rows name a different asset type than the asset they matched. The import does NOT re-classify them: an asset's type is immutable through this verb, so the estate's type wins and the file's is discarded silently \u2014 this is the number that says so. Absent unless a reconciling preflight classified rows. Drifted rows are additionally re-validated against the MATCHED asset's template, so one that does not satisfy it is ALSO counted in `summary.willFail`."),absentRows:external_exports.number().int().nonnegative().optional().describe("How many live assets bound in this import's external-ID system are NOT named by this delivery. EXACT whenever present \u2014 a counts-mode call over a key set larger than it can read completely is REFUSED rather than answered partially, because a partial key set reports unread keys as absent. ADVISORY and it names no action: an absent asset may be retired, out of scope, or genuinely dropped upstream, and this verb neither knows which nor changes anything about it."),sourceRows:ValidateSourceRowsSchema.optional().describe("How many ROWS the validated source holds, reported next to a key-basis `summary` because it is a different denominator. A row count far above the key total means the delivery names some assets more than once. Absent when the source states no stable total (a live version, or a relation past the count probe)."),propertiesWouldClear:external_exports.object({codes:external_exports.array(external_exports.string().min(1))}).optional().describe('Property codes a MATCHED asset would LOSE, because this verb replaces an asset\'s property map wholesale rather than merging into it: a property the estate holds and this projection does not produce is CLEARED, not left alone. MAPPING-LEVEL and zero rows read \u2014 the template of the type the FILE names, minus the codes the projection maps \u2014 so it needs no row read. Present with an empty `codes` means "checked, nothing would clear"; absent means the check could not run (not reconciling, identity-mode projection, or a column-mode `assetType` whose target type needs rows to know). A LOWER bound, on TWO counts: a MAPPED column left blank on a given row also clears, and a matched asset whose type DRIFTED from the file\'s is judged by its OWN template rather than the one this answer is computed from. Size that second gap with `typeDriftRows` \u2014 but ONLY on a `mode: "rows"` report, where `0` means checked-and-none-drifted. `mode: "counts"` classifies no row and never computes `typeDriftRows` at all, so its absence THERE means the drift is UNKNOWN rather than absent, and these codes are a lower bound of unknown tightness.'),hierarchyDivergence:HierarchyDivergencePreviewSchema.optional().describe('What `externalId.edgePolicy` would do to the MATCHED rows\u2019 placements: `divergent` is how many name a parent they do not hold (the population `replace` would move), `skippedAmbiguousParent` how many hold SEVERAL open parents and are therefore left alone, `attachable` how many hold NONE in a NAMED tree (the rows `replace` would ATTACH, which the move ceiling does not count), `parentUnresolved` how many name a parent the estate does not hold yet (under `replace` a re-delivery places them once it does), `unplacedInBucket` how many a tree-less import leaves parentless in the unassigned bucket (never attached there; a `replace` import naming a tree places them), and `moveCeiling` the per-call bound a synchronous commit would judge `divergent` against. ABSENT unless the mapping declares an `edgePolicy` \u2014 absent means "not asked", not "nothing diverges". ADVISORY: nothing is locked between validating and committing. `moveCeiling` IS ALWAYS THE PLATFORM BOUND, never a mapping\'s own: this verb\'s input carries no `thresholds`, so a stored `thresholds.maxMoves` is invisible here and can only be TIGHTER. A background delivery of the same file may therefore refuse below the number reported \u2014 read `divergent` against the mapping when it names one. It cannot predict the DELIVERY-wide ceiling such an import is additionally judged against either.')}),DatasetProvenanceSchema2=external_exports.object({kind:external_exports.literal("dataset"),datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,rowKey:external_exports.string().min(1)}),AssetProvenanceSchema=external_exports.discriminatedUnion("kind",[external_exports.object({kind:external_exports.literal("native")}),DatasetProvenanceSchema2]),ProvenanceDirectoryInputSchema=external_exports.strictObject({datasetId:external_exports.string().min(1),cursor:external_exports.string().min(1).optional(),limit:external_exports.number().int().min(1).max(1e4).optional(),asOf:external_exports.iso.datetime().optional()}),ProvenanceDirectoryEntrySchema=external_exports.object({rowKey:external_exports.string().min(1),get assetId(){return AssetIdSchema}}),ProvenanceDirectoryOutputSchema=external_exports.object({items:external_exports.array(ProvenanceDirectoryEntrySchema),nextCursor:external_exports.string().nullable()});var UnresolvedTypeValueSchema=external_exports.discriminatedUnion("reason",[external_exports.strictObject({value:external_exports.string(),reason:external_exports.literal("not-found")}),external_exports.strictObject({value:external_exports.string(),reason:external_exports.literal("ambiguous")}),external_exports.strictObject({value:external_exports.string(),reason:external_exports.literal("no-template"),resolvedType:external_exports.strictObject({key:external_exports.string(),displayName:external_exports.string()})})]);var CompositionJobFailureCodeSchema=external_exports.enum(["COMPOSITION_TYPES_UNRESOLVED","COMPOSITION_DELIVERY_THRESHOLD_BREACHED","COMPOSITION_SOURCE_EMPTY","COMPOSITION_ROWS_RANGE_PAST_END","COMPOSITION_ESTIMATE_OVER_BUDGET","COMPOSITION_SOURCE_COLUMN_MISSING","COMPOSITION_TYPE_VALUES_OVER_CAP"]).describe("Why a FAILED job stopped at its gate, before writing anything. Absent on any other failure. TYPES_UNRESOLVED carries `unresolvedTypes`; DELIVERY_THRESHOLD_BREACHED carries `thresholdBreach`; SOURCE_EMPTY, ROWS_RANGE_PAST_END and ESTIMATE_OVER_BUDGET are the row-count refusals, named in `failureDetail`; SOURCE_COLUMN_MISSING (a mapped column the source lacks) and TYPE_VALUES_OVER_CAP (a type column with more distinct values than a vocabulary holds) are mapping defects, named in `failureDetail`."),COMPOSITION_JOB_UNRESOLVED_TYPES_MAX=100;var CompositionJobUnresolvedTypesSchema=external_exports.array(UnresolvedTypeValueSchema).min(1).max(COMPOSITION_JOB_UNRESOLVED_TYPES_MAX),CompositionJobThresholdBreachSchema=DeliveryThresholdBreachSchema;var CompositionJobIdSchema=external_exports.uuid().brand(),CompositionJobStateSchema=external_exports.enum(["PENDING","RUNNING","COMPLETED","FAILED"]);var NonTerminalCompositionJobStateSchema=CompositionJobStateSchema.extract(["PENDING","RUNNING"]);var COMPOSITION_JOB_MAX_ESTIMATED_SECONDS=480*60;var CompositionLinkReconcileOutcomeSchema=external_exports.strictObject({nestingBreaks:NestingBreaksReportSchema.optional(),nestingCheck:NestingCheckSchema.optional(),edgesCreated:external_exports.number().int().nonnegative(),linksUnresolved:external_exports.number().int().nonnegative(),rowsCompensated:external_exports.number().int().nonnegative(),rowsKeptDespiteRequired:external_exports.number().int().nonnegative().default(0)}),VocabularyCoverageSchema=external_exports.union([external_exports.strictObject({complete:external_exports.literal(!0)}),external_exports.strictObject({complete:external_exports.literal(!1),rowsScanned:external_exports.number().int().nonnegative(),totalRows:external_exports.number().int().nonnegative()})]),StartCompositionJobResultSchema=external_exports.strictObject({jobId:CompositionJobIdSchema,state:CompositionJobStateSchema,vocabularyCoverage:VocabularyCoverageSchema.optional(),thresholdCoverage:DeliveryThresholdCoverageSchema.optional()});var CompositionJobStatusInputSchema=external_exports.strictObject({jobId:CompositionJobIdSchema}),COMPOSITION_JOBS_PAGE_MAX=200,COMPOSITION_JOBS_PAGE_DEFAULT=25,ListCompositionJobsInputSchema=external_exports.strictObject({take:external_exports.number().int().min(1).max(COMPOSITION_JOBS_PAGE_MAX).optional().describe(`How many jobs to return, 1\u2013${String(COMPOSITION_JOBS_PAGE_MAX)}; defaults to ${String(COMPOSITION_JOBS_PAGE_DEFAULT)}. Newest first. An over-cap ask is REFUSED, never clamped \u2014 a clamp hands back a page the caller did not request and cannot tell apart from the one it did.`)}),CompositionJobSummarySchema=external_exports.strictObject({jobId:CompositionJobIdSchema,state:NonTerminalCompositionJobStateSchema,attempt:external_exports.number().int().positive(),rowsCreated:external_exports.number().int().nonnegative(),rowsUpdated:external_exports.number().int().nonnegative(),rowsUnchanged:external_exports.number().int().nonnegative(),rowsFailed:external_exports.number().int().nonnegative(),principal:external_exports.string().min(1),startedAt:external_exports.iso.datetime(),updatedAt:external_exports.iso.datetime()}),CompositionJobStatusSchema=external_exports.strictObject({jobId:CompositionJobIdSchema,state:CompositionJobStateSchema,attempt:external_exports.number().int().positive(),releasedAttempts:external_exports.number().int().positive().optional(),rowsCreated:external_exports.number().int().nonnegative(),rowsUpdated:external_exports.number().int().nonnegative(),rowsUnchanged:external_exports.number().int().nonnegative(),rowsFailed:external_exports.number().int().nonnegative(),rowsMoved:external_exports.number().int().positive().optional(),backDated:external_exports.number().int().positive().optional(),valuesDated:external_exports.number().int().positive().optional(),valuesKept:external_exports.number().int().positive().optional(),valuesRefused:external_exports.number().int().positive().optional(),statusesDated:external_exports.number().int().positive().optional(),statusesKept:external_exports.number().int().positive().optional(),statusesRefused:external_exports.number().int().positive().optional(),parentsDated:external_exports.number().int().positive().optional(),parentsKept:external_exports.number().int().positive().optional(),parentsRefused:external_exports.number().int().positive().optional(),appliedToday:external_exports.number().int().positive().optional(),edgesCreated:external_exports.number().int().nonnegative(),linksUnresolved:external_exports.number().int().nonnegative(),locationsKept:external_exports.number().int().positive().optional(),nestingBreaks:external_exports.number().int().positive().max(2147483647).optional(),nestingFindings:external_exports.array(NestingBreakSchema).max(NESTING_BREAKS_MAX).optional(),nestingCheck:NestingCheckSchema.optional(),failureDetail:external_exports.string().optional(),failureCode:CompositionJobFailureCodeSchema.optional(),unresolvedTypes:CompositionJobUnresolvedTypesSchema.optional(),unresolvedTypesTotal:external_exports.number().int().positive().optional(),thresholdBreach:CompositionJobThresholdBreachSchema.optional(),failureClasses:CompositionFailureClassesSchema.optional(),completionRecordId:external_exports.string().min(1).optional(),startedAt:external_exports.iso.datetime(),updatedAt:external_exports.iso.datetime()}),CompositionJobCompletionDetailSchema=external_exports.object({state:external_exports.enum(["COMPLETED","FAILED"]),jobId:CompositionJobIdSchema,attempt:external_exports.number().int().positive(),rowsCreated:external_exports.number().int().nonnegative().optional(),rowsUpdated:external_exports.number().int().nonnegative().optional(),rowsFailed:external_exports.number().int().nonnegative().optional(),edgesCreated:external_exports.number().int().nonnegative().optional(),rowsMoved:external_exports.number().int().nonnegative().optional(),rowsAttached:external_exports.number().int().nonnegative().optional(),rowsParentUnresolved:external_exports.number().int().positive().optional(),rowsUnplacedInBucket:external_exports.number().int().positive().optional(),rowsSkippedAmbiguousParent:external_exports.number().int().nonnegative().optional(),additionalIdentifiersAlreadyBound:external_exports.number().int().nonnegative().optional(),locationsKept:external_exports.number().int().nonnegative().optional(),nestingBreaks:external_exports.number().int().positive().optional(),nestingCheck:NestingCheckSchema.optional(),linksUnresolved:external_exports.number().int().nonnegative().optional(),failureDetail:external_exports.string().optional()});var AssetsImportJobFailedDetailSchema=external_exports.strictObject({jobId:CompositionJobIdSchema,failedAt:external_exports.iso.datetime(),originatingFlowRunId:external_exports.string().min(1).optional()});var TeardownSelectorSchema=external_exports.discriminatedUnion("kind",[external_exports.strictObject({kind:external_exports.literal("importRun"),jobId:CompositionJobIdSchema})]);var TeardownItemClassificationSchema=external_exports.enum(["deletable","changed-since","gained-children","blocked-edges","blocked-bindings","not-found"]);var TEARDOWN_PREVIEW_SAMPLE_CAP=10,TeardownPreviewSampleSchema=external_exports.strictObject({assetId:external_exports.uuid(),name:external_exports.string()}),TeardownPreviewSectionSchema=external_exports.strictObject({total:external_exports.number().int().nonnegative(),sample:external_exports.array(TeardownPreviewSampleSchema).max(TEARDOWN_PREVIEW_SAMPLE_CAP)}),TeardownPreviewInputSchema=external_exports.strictObject({selector:TeardownSelectorSchema}),TeardownPreviewDigestSchema=external_exports.string().min(1),TeardownPreviewResultSchema=external_exports.strictObject({selector:TeardownSelectorSchema,runInstant:external_exports.iso.datetime(),deletable:TeardownPreviewSectionSchema,changedSince:TeardownPreviewSectionSchema,gainedChildren:TeardownPreviewSectionSchema,blockedEdges:TeardownPreviewSectionSchema,blockedBindings:TeardownPreviewSectionSchema,notFound:TeardownPreviewSectionSchema,previewDigest:TeardownPreviewDigestSchema,summary:external_exports.string()});var TeardownJobIdSchema=external_exports.uuid().brand(),TeardownJobStateSchema=external_exports.enum(["PENDING","RUNNING","COMPLETED","FAILED"]);var NonTerminalTeardownJobStateSchema=TeardownJobStateSchema.extract(["PENDING","RUNNING"]);var StartTeardownJobInputSchema=external_exports.strictObject({selector:TeardownSelectorSchema,previewDigest:TeardownPreviewDigestSchema,idempotencyKey:IdempotencyKeySchema}),StartTeardownJobResultSchema=external_exports.strictObject({jobId:TeardownJobIdSchema,state:TeardownJobStateSchema});var TeardownJobStatusInputSchema=external_exports.strictObject({jobId:TeardownJobIdSchema});var TEARDOWN_JOBS_PAGE_MAX=100,ListTeardownJobsInputSchema=external_exports.strictObject({take:external_exports.number().int().min(1).max(TEARDOWN_JOBS_PAGE_MAX).optional()}),TeardownJobCountsSchema=external_exports.strictObject({deleted:external_exports.number().int().nonnegative(),keptChangedSince:external_exports.number().int().nonnegative(),keptGainedChildren:external_exports.number().int().nonnegative(),keptBlockedEdges:external_exports.number().int().nonnegative(),keptBlockedBindings:external_exports.number().int().nonnegative(),keptNotFound:external_exports.number().int().nonnegative()}),TeardownJobSummarySchema=external_exports.strictObject({jobId:TeardownJobIdSchema,state:NonTerminalTeardownJobStateSchema,attempt:external_exports.number().int().positive(),...TeardownJobCountsSchema.shape,principal:external_exports.string(),startedAt:external_exports.iso.datetime(),updatedAt:external_exports.iso.datetime()}),TeardownJobStatusSchema=external_exports.strictObject({jobId:TeardownJobIdSchema,state:TeardownJobStateSchema,attempt:external_exports.number().int().positive(),...TeardownJobCountsSchema.shape,failureDetail:external_exports.string().optional(),startedAt:external_exports.iso.datetime(),updatedAt:external_exports.iso.datetime()});var QualityJobIdSchema=external_exports.uuid().brand(),QualityJobStateSchema=external_exports.enum(["PENDING","RUNNING","COMPLETED","FAILED"]),NonTerminalQualityJobStateSchema=QualityJobStateSchema.extract(["PENDING","RUNNING"]);var QualityJobPhaseSchema=external_exports.enum(["walk","cycles"]);var QUALITY_JOB_ORPHAN_SAMPLE_CAP=50;var QUALITY_JOB_NOT_FOUND="QUALITY_JOB_NOT_FOUND",QUALITY_JOB_RUNNER_UNAVAILABLE="QUALITY_JOB_RUNNER_UNAVAILABLE",QualityJobRunnerUnavailableDataSchema=external_exports.object({code:external_exports.literal(QUALITY_JOB_RUNNER_UNAVAILABLE)}),QualityJobNotFoundDataSchema=external_exports.object({code:external_exports.literal(QUALITY_JOB_NOT_FOUND)}),QUALITY_JOB_REUSE_WINDOW_MS=15*6e4,StartQualityJobResultSchema=external_exports.strictObject({jobId:QualityJobIdSchema,state:QualityJobStateSchema,alreadyRunning:external_exports.boolean(),reused:external_exports.boolean()}),QualityJobStatusInputSchema=external_exports.strictObject({jobId:QualityJobIdSchema}),QualityJobStatusSchema=external_exports.strictObject({jobId:QualityJobIdSchema,state:QualityJobStateSchema,phase:QualityJobPhaseSchema,attempt:external_exports.number().int().positive(),unitsDone:external_exports.number().int().nonnegative(),checkedAt:external_exports.iso.datetime().optional(),failureDetail:external_exports.string().optional(),startedAt:external_exports.iso.datetime(),updatedAt:external_exports.iso.datetime()}),QualityReceiptOrphansSchema=external_exports.strictObject({count:RelationshipRootsCountSchema,sample:external_exports.array(SubtreeNodeSchema).max(QUALITY_JOB_ORPHAN_SAMPLE_CAP)}),QualityReceiptSchema=external_exports.strictObject({jobId:QualityJobIdSchema,checkedAt:external_exports.iso.datetime(),completedAt:external_exports.iso.datetime(),orphans:QualityReceiptOrphansSchema,get edgeSanity(){return EdgeSanityReportSchema}}),QualityLiveJobSchema=external_exports.strictObject({jobId:QualityJobIdSchema,state:NonTerminalQualityJobStateSchema}),QualityLastFailureSchema=external_exports.strictObject({jobId:QualityJobIdSchema,failureDetail:external_exports.string().nullable(),failedAt:external_exports.iso.datetime()}),LatestQualityReceiptSchema=external_exports.strictObject({receipt:QualityReceiptSchema.nullable(),liveJob:QualityLiveJobSchema.nullable(),lastFailure:QualityLastFailureSchema.nullable(),changedSinceCheck:external_exports.boolean()});var IMPORT_MAPPING_NAME_MAX=120,ImportMappingNameSchema=external_exports.string().trim().min(1,"an import mapping name cannot be blank").max(IMPORT_MAPPING_NAME_MAX).describe("The mapping's operator-facing name, UNIQUE PER TENANT. `composition.startImport` references a mapping by this name, so it is the durable ref an operator types \u2014 not an internal code.").meta({entity:{domain:"assets",type:"asset-import-mapping"}}),ImportMappingVersionSchema=external_exports.number().int().positive().describe("The saved version of this mapping, 1-based and append-only. Pin one to run exactly the config that was authored then; omit it to run the latest."),AssetImportMappingConfigSchema=external_exports.strictObject({get projection(){return AssetProjectionSchema},get relationships(){return external_exports.array(RelationshipMappingSchema).optional()},get externalId(){return ExternalIdImportMappingSchema.optional()},get hierarchyName(){return HierarchyNameSchema.optional()},get noHierarchy(){return external_exports.literal(!0).optional()},get thresholds(){return AssetImportDeliveryThresholdsSchema.optional()}}),AssetImportMappingConfigInputSchema=AssetImportMappingConfigSchema.extend({get projection(){return AssetProjectionInputSchema},get relationships(){return RelationshipListInput.optional()}}),AssetImportMappingSchema=external_exports.object({name:ImportMappingNameSchema,version:ImportMappingVersionSchema,get config(){return AssetImportMappingConfigSchema},createdAt:external_exports.iso.datetime()}),SaveAssetImportMappingInputSchema=external_exports.strictObject({name:ImportMappingNameSchema,get config(){return AssetImportMappingConfigInputSchema},expectedVersion:ImportMappingVersionSchema.optional().describe("The version this edit was based on. ABSENT \u21D2 create a NEW name (refused if the name is taken). PRESENT \u21D2 append the next version, refused if the mapping has moved on since."),get idempotencyKey(){return IdempotencyKeySchema.max(IDEMPOTENCY_KEY_MAX_LENGTH)}}),GetAssetImportMappingInputSchema=external_exports.strictObject({name:ImportMappingNameSchema,version:ImportMappingVersionSchema.optional().describe("Pin a version. Absent \u21D2 the latest saved version of this name.")}),ListAssetImportMappingsOutputSchema=external_exports.object({get mappings(){return external_exports.array(AssetImportMappingSchema)}}),StartImportInputSchema=external_exports.strictObject({mappingName:ImportMappingNameSchema.describe("The saved mapping to run. Resolved server-side; the import runs exactly the projection, relationships, external-ID mapping and hierarchy that mapping holds."),mappingVersion:ImportMappingVersionSchema.optional().describe("Pin the mapping version. Absent \u21D2 the latest saved version at the moment of the call."),get source(){return DatasetRefSchema.describe("The dataset to import from. It must already be PROMOTED, and \u2014 as for every background job \u2014 it must be a FROZEN version with a stored row count; a LIVE version is refused. `versionId` absent = the current load, stamped to its resolved version in the trail.")},get rows(){return external_exports.strictObject({start:external_exports.number().int().nonnegative(),end:external_exports.number().int().nonnegative()}).optional().describe(ROW_RANGE_DESCRIPTION)},get idempotencyKey(){return IdempotencyKeySchema.max(IDEMPOTENCY_KEY_MAX_LENGTH)},duplicateAnyway:external_exports.literal(!0).optional()});var TypePreflightInputSchema=external_exports.strictObject({source:DatasetRefSchema,projection:AssetProjectionInputSchema,rows:external_exports.strictObject({start:external_exports.number().int().nonnegative(),end:external_exports.number().int().nonnegative()}).optional().describe(ROW_RANGE_DESCRIPTION)}),TypePreflightResultSchema=external_exports.strictObject({unresolved:external_exports.array(UnresolvedTypeValueSchema),distinctValues:external_exports.number().int().nonnegative(),coverage:VocabularyCoverageSchema}),CreateTypeFromValueInputSchema=external_exports.strictObject({source:DatasetRefSchema,projection:AssetProjectionInputSchema,rows:external_exports.strictObject({start:external_exports.number().int().nonnegative(),end:external_exports.number().int().nonnegative()}).optional().describe(ROW_RANGE_DESCRIPTION),value:external_exports.string().min(1),get categoryId(){return AssetCategoryIdSchema},get externalId(){return ExternalIdImportMappingSchema.optional()},get additionalExternalIds(){return AdditionalExternalIdsInputSchema.optional()},key:external_exports.string().min(1).optional(),displayName:external_exports.string().min(1).optional()}),CreateTypeFromValueResultSchema=external_exports.strictObject({get type(){return AssetTypeSchema},get template(){return AssetTemplateVersionSchema}});var IMPORT_PREFLIGHT_LIST_MAX=COMPOSITION_JOB_UNRESOLVED_TYPES_MAX,IMPORT_PREFLIGHT_VALUE_MAX_CHARS=256,PreflightValueSchema=external_exports.string().min(1).max(IMPORT_PREFLIGHT_VALUE_MAX_CHARS),PreflightImportJobIdSchema=external_exports.uuid().brand(),buildRedescribed=()=>({mappingName:StartImportInputSchema.shape.mappingName.describe("The saved mapping to check. Resolved server-side at accept; the check reads exactly the projection, relationships and external-ID mapping that version holds."),source:StartImportInputSchema.shape.source.describe("The dataset to check. Unlike `startImport`, the accept refuses neither an unpromoted load nor a live version \u2014 a check is a question, not a consumption. A `rows` slice of a LIVE version cannot be read, though: a live version carries no stored row count to slice, so that check ends FAILED `IMPORT_PREFLIGHT_FAULT`. `versionId` absent = the current load, pinned to its resolved version at accept."),rows:StartImportInputSchema.shape.rows.describe('OPTIONAL half-open `[start, end)` slice of the source version \u2014 the rows the import will read. ABSENT = the whole load. A slice is checked by scanning its rows, and the scan reads a bounded number of them; a slice wider than that bound is refused at accept with `BAD_REQUEST` / `data.code = "IMPORT_PREFLIGHT_ROWS_TOO_WIDE"`, whose `data.maxRows` and message name the bound. Check a wider range as several slices, or the whole load.')}),redescribed,redescribedSchemas=()=>redescribed??=buildRedescribed(),PreflightImportInputSchema=external_exports.strictObject({get mappingName(){return redescribedSchemas().mappingName},get mappingVersion(){return StartImportInputSchema.shape.mappingVersion},get source(){return redescribedSchemas().source},get rows(){return redescribedSchemas().rows},get idempotencyKey(){return StartImportInputSchema.shape.idempotencyKey}}),PreflightImportJobStateSchema=external_exports.enum(["PENDING","RUNNING","COMPLETED","FAILED"]),PreflightImportAcceptResultSchema=external_exports.strictObject({jobId:PreflightImportJobIdSchema,state:PreflightImportJobStateSchema}),buildMappingRefSchema=()=>external_exports.strictObject({name:ImportMappingNameSchema,version:ImportMappingVersionSchema}),mappingRef,mappingRefSchema=()=>mappingRef??=buildMappingRefSchema(),PreflightImportJobRequestSchema=external_exports.strictObject({get mapping(){return mappingRefSchema()},source:PinnedDatasetRefSchema,rows:external_exports.strictObject({start:external_exports.number().int().nonnegative(),end:external_exports.number().int().nonnegative()}).optional()}),PreflightImportFailureCodeSchema=external_exports.enum(["IMPORT_PREFLIGHT_BLOCKED","IMPORT_PREFLIGHT_FAULT"]),PreflightImportBlockerKindSchema=external_exports.enum(["type-ambiguous","type-no-template","fixed-type-unresolved","match-system-not-registered","coverage-incomplete"]),PreflightImportBlockerSchema=external_exports.strictObject({kind:PreflightImportBlockerKindSchema,value:PreflightValueSchema}),PreflightImportBlockersSchema=external_exports.array(PreflightImportBlockerSchema).min(1).max(IMPORT_PREFLIGHT_LIST_MAX),PreflightImportFailureFactsSchema=external_exports.strictObject({blockers:PreflightImportBlockersSchema,blockersTotal:external_exports.number().int().positive()}),IMPORT_PREFLIGHT_JOB_NOT_FOUND="IMPORT_PREFLIGHT_JOB_NOT_FOUND",IMPORT_PREFLIGHT_RUNNER_UNAVAILABLE="IMPORT_PREFLIGHT_RUNNER_UNAVAILABLE",PreflightImportRunnerUnavailableDataSchema=external_exports.object({code:external_exports.literal(IMPORT_PREFLIGHT_RUNNER_UNAVAILABLE)}),IMPORT_PREFLIGHT_ROWS_TOO_WIDE="IMPORT_PREFLIGHT_ROWS_TOO_WIDE",PreflightImportRowsTooWideDataSchema=external_exports.object({code:external_exports.literal(IMPORT_PREFLIGHT_ROWS_TOO_WIDE),maxRows:external_exports.number().int().positive()}),PreflightImportJobNotFoundDataSchema=external_exports.object({code:external_exports.literal(IMPORT_PREFLIGHT_JOB_NOT_FOUND)}),PreflightImportStatusInputSchema=external_exports.strictObject({jobId:PreflightImportJobIdSchema}),PreflightImportStatusSchema=external_exports.strictObject({jobId:PreflightImportJobIdSchema,state:PreflightImportJobStateSchema,attempt:external_exports.number().int().positive(),failureCode:PreflightImportFailureCodeSchema.optional(),failureDetail:external_exports.string().optional(),blockers:PreflightImportBlockersSchema.optional(),blockersTotal:external_exports.number().int().positive().optional(),completionRecordId:external_exports.string().min(1).optional(),startedAt:external_exports.iso.datetime(),updatedAt:external_exports.iso.datetime()}),namedValues=external_exports.array(PreflightValueSchema).max(IMPORT_PREFLIGHT_LIST_MAX),PreflightImportCompletionDetailSchema=external_exports.object({get mapping(){return mappingRefSchema()},source:PinnedDatasetRefSchema,wouldCreate:external_exports.object({total:external_exports.number().int().nonnegative(),types:external_exports.number().int().nonnegative(),idSystems:external_exports.number().int().nonnegative()}),distinctTypeValues:external_exports.number().int().nonnegative(),types:namedValues,typesTotal:external_exports.number().int().nonnegative(),idSystems:namedValues,idSystemsTotal:external_exports.number().int().nonnegative()}),PreflightImportFindingSchema=external_exports.strictObject({family:external_exports.enum(["assets.type-not-found","assets.id-system-not-registered"]),severity:external_exports.literal("info"),count:external_exports.number().int().positive(),rowsRef:external_exports.null(),matchKey:PreflightValueSchema,handling:external_exports.literal("carry"),recommended:external_exports.strictObject({outcome:external_exports.literal("accept"),reason:external_exports.string().min(1)})}),PreflightImportSealedDetailSchema=PreflightImportCompletionDetailSchema.extend({jobId:PreflightImportJobIdSchema,attempt:external_exports.number().int().positive(),coverage:VocabularyCoverageSchema,findings:external_exports.array(PreflightImportFindingSchema).max(IMPORT_PREFLIGHT_LIST_MAX),originatingFlowRunId:external_exports.string().min(1).optional()}).strict(),PreflightImportFailedDetailSchema=external_exports.strictObject({jobId:PreflightImportJobIdSchema,attempt:external_exports.number().int().positive(),failureCode:PreflightImportFailureCodeSchema,failureDetail:external_exports.string(),originatingFlowRunId:external_exports.string().min(1).optional()});var ExternalIdBindJobIdSchema=external_exports.uuid().brand(),ExternalIdBindJobStateSchema=external_exports.enum(["PENDING","RUNNING","COMPLETED","FAILED"]);var ExternalIdBindStallCauseSchema=external_exports.enum(["tile-timeout","service-unavailable","unexpected"]),ExternalIdBindMappingSchema=external_exports.strictObject({assetIdColumn:external_exports.string().min(1),system:ExternalIdSystemSchema,valueColumn:external_exports.string().min(1)}),StartExternalIdBindJobInputSchema=external_exports.strictObject({source:DatasetRefSchema,mapping:ExternalIdBindMappingSchema,rows:external_exports.strictObject({start:external_exports.number().int().nonnegative(),end:external_exports.number().int().nonnegative()}).optional(),idempotencyKey:IdempotencyKeySchema}),StartExternalIdBindJobResultSchema=external_exports.strictObject({jobId:ExternalIdBindJobIdSchema,state:ExternalIdBindJobStateSchema}),ExternalIdBindRefusalCodeSchema=external_exports.enum(["asset-not-found","invalid-value","already-bound","in-batch-duplicate"]);var ExternalIdBindRefusalSchema=external_exports.object({rowIndex:external_exports.number().int().nonnegative(),get assetId(){return AssetIdSchema.optional()},system:ExternalIdSystemSchema,value:external_exports.string(),code:ExternalIdBindRefusalCodeSchema,detail:external_exports.string().max(200).optional(),get holdingAssetId(){return AssetIdSchema.optional()}}),ExternalIdBindTileRefusalSchema=external_exports.strictObject({rowIndex:external_exports.number().int().nonnegative(),code:ExternalIdBindRefusalCodeSchema,get holdingAssetId(){return AssetIdSchema.optional()}}),ExternalIdBindTileOutcomeSchema=external_exports.strictObject({bound:external_exports.number().int().nonnegative(),reasserted:external_exports.number().int().nonnegative().default(0),alreadyBound:external_exports.number().int().nonnegative(),unmatched:external_exports.number().int().nonnegative(),invalidValue:external_exports.number().int().nonnegative(),inBatchDuplicate:external_exports.number().int().nonnegative(),refusals:external_exports.array(ExternalIdBindTileRefusalSchema).default([])}),ExternalIdBindJobStatusInputSchema=external_exports.strictObject({jobId:ExternalIdBindJobIdSchema}),ExternalIdBindJobStatusSchema=external_exports.strictObject({jobId:ExternalIdBindJobIdSchema,state:ExternalIdBindJobStateSchema,attempt:external_exports.number().int().positive(),requested:external_exports.number().int().nonnegative(),bound:external_exports.number().int().nonnegative(),reasserted:external_exports.number().int().nonnegative(),alreadyBound:external_exports.number().int().nonnegative(),unmatched:external_exports.number().int().nonnegative(),invalidValue:external_exports.number().int().nonnegative(),inBatchDuplicate:external_exports.number().int().nonnegative(),refusalSample:external_exports.array(ExternalIdBindTileRefusalSchema),failureDetail:external_exports.string().optional(),stallCause:ExternalIdBindStallCauseSchema.optional(),completionRecordId:external_exports.string().min(1).optional(),startedAt:external_exports.iso.datetime(),updatedAt:external_exports.iso.datetime()}),ExternalIdBindJobCompletionDetailSchema=external_exports.object({state:external_exports.enum(["COMPLETED","FAILED"]),jobId:ExternalIdBindJobIdSchema,attempt:external_exports.number().int().positive(),requested:external_exports.number().int().nonnegative().optional(),bound:external_exports.number().int().nonnegative().optional(),reasserted:external_exports.number().int().nonnegative().optional(),alreadyBound:external_exports.number().int().nonnegative().optional(),unmatched:external_exports.number().int().nonnegative().optional(),invalidValue:external_exports.number().int().nonnegative().optional(),inBatchDuplicate:external_exports.number().int().nonnegative().optional(),failureDetail:external_exports.string().optional()});var DeriveTemplateTargetSchema=external_exports.strictObject({get assetTypeId(){return AssetTypeIdSchema}}),DERIVE_TEMPLATE_MANY_MAX_TARGETS=100,DeriveTemplateManyInputSchema=external_exports.strictObject({datasetRef:DatasetRefSchema,targets:external_exports.array(DeriveTemplateTargetSchema).min(1).max(DERIVE_TEMPLATE_MANY_MAX_TARGETS)}),DeriveTemplateErrorCodeSchema=external_exports.enum(["asset-type-not-found","would-lose-data","invalid-definition"]),DeriveTemplateFailureDataSchema=external_exports.strictObject({issues:external_exports.array(TemplateDefinitionIssueSchema).max(MAX_ISSUES_PER_ROW_FAILURE)}),DeriveTemplateItemResultSchema=external_exports.discriminatedUnion("status",[external_exports.object({get assetTypeId(){return AssetTypeIdSchema},status:external_exports.literal("derived"),get templateVersion(){return AssetTemplateVersionSchema}}),external_exports.object({get assetTypeId(){return AssetTypeIdSchema},status:external_exports.literal("failed"),error:external_exports.object({code:DeriveTemplateErrorCodeSchema,message:external_exports.string().min(1),data:DeriveTemplateFailureDataSchema.optional()})})]),DeriveTemplateManyOutputSchema=external_exports.object({results:external_exports.array(DeriveTemplateItemResultSchema)});var UNASSIGNED_NOTICE_DISMISSED_TREES_MAX=20,ASSETS_LIST_VIEW_SCOPE="assets-list",AssetsListViewFiltersSchema=external_exports.looseObject({get categoryIds(){return external_exports.array(AssetCategoryIdSchema).min(1).max(50).optional()},get assetTypeIds(){return external_exports.array(AssetTypeIdSchema).min(1).max(50).optional()},get lifecycleStatuses(){return external_exports.array(AssetLifecycleStatusSchema).min(1).max(50).optional()},get categoryId(){return AssetCategoryIdSchema.optional()},get assetTypeId(){return AssetTypeIdSchema.optional()},lifecycleStatus:AssetLifecycleStatusSchema.optional(),nameContains:external_exports.string().min(1).optional(),hasGeometry:external_exports.boolean().optional()}),AssetsListViewSchema=external_exports.looseObject({filters:AssetsListViewFiltersSchema.optional(),get orderBy(){return AssetOrderBySchema.optional()},columns:external_exports.array(external_exports.string().min(1)).max(VIEW_COLUMNS_MAX).optional()}),AssetsTablePreferencesSchema=external_exports.looseObject({columns:external_exports.array(external_exports.string().min(1)).max(VIEW_COLUMNS_MAX).optional(),get pageSize(){return external_exports.number().int().min(1).max(ASSET_IDS_MAX_PER_PAGE).optional()},density:external_exports.enum(["comfortable","compact"]).optional(),get forest(){return external_exports.object({tree:external_exports.string().min(1),relationshipType:HierarchyRelationshipTypeSchema}).optional()},get unassignedNoticeDismissedFor(){return external_exports.array(external_exports.string().refine(value2=>HierarchyIdSchema.safeParse(value2).success,"must be a hierarchy id")).max(UNASSIGNED_NOTICE_DISMISSED_TREES_MAX).optional()},unassignedNoticeDismissed:external_exports.literal(!0).optional()}),assetsViewShapes=createViewPreferenceShapes({scope:ASSETS_LIST_VIEW_SCOPE,view:AssetsListViewSchema,preferences:AssetsTablePreferencesSchema}),SavedViewSchema2=assetsViewShapes.SavedViewSchema,CreateSavedViewInputSchema2=assetsViewShapes.CreateSavedViewInputSchema,UpdateSavedViewInputSchema2=assetsViewShapes.UpdateSavedViewInputSchema,ListSavedViewsInputSchema2=assetsViewShapes.ListSavedViewsInputSchema,DeleteSavedViewInputSchema2=assetsViewShapes.DeleteSavedViewInputSchema,GetTablePreferencesInputSchema2=assetsViewShapes.GetTablePreferencesInputSchema,SetTablePreferencesInputSchema2=assetsViewShapes.SetTablePreferencesInputSchema,TablePreferencesSchema2=assetsViewShapes.TablePreferencesSchema;var LocationPlacementIdSchema=external_exports.uuid().brand(),LocationPlacementJobIdSchema=external_exports.uuid().brand(),LOCATION_PLACEMENT_NAME_MAX=120,LOCATION_PLACEMENT_SYSTEMS_MAX=8,LOCATION_PLACEMENT_COLUMN_MAX=256;var LOCATION_PLACEMENT_FAILURE_PAGE_MAX=500;var LocationPlacementNameSchema=external_exports.string().trim().min(1,"a placement name cannot be blank").max(LOCATION_PLACEMENT_NAME_MAX).describe("The placement's operator-facing name, unique per tenant."),ColumnNameSchema2=external_exports.string().min(1).max(LOCATION_PLACEMENT_COLUMN_MAX),LocationPlacementConfigSchema=external_exports.strictObject({source:external_exports.strictObject({datasetId:DatasetIdSchema}).describe("The dataset rows come from. A run reads its CURRENT version, which must be promoted."),idColumn:ColumnNameSchema2.describe("The column whose value identifies the asset, looked up as an external ID (trimmed, case-significant)."),systems:external_exports.array(ExternalIdSystemSchema).min(1).max(LOCATION_PLACEMENT_SYSTEMS_MAX).describe("The external-ID systems the identifier is looked up in, in order. A value bound to different assets in two of them fails the row as ambiguous."),geometryColumn:ColumnNameSchema2.describe("The column holding the geometry as WKT: Point, LineString, Polygon or their Multi forms, 2D longitude/latitude (SRID 4326).")}),LocationPlacementJobModeSchema=external_exports.enum(["preview","run"]),LocationPlacementJobStateSchema=external_exports.enum(["PENDING","RUNNING","COMPLETED","FAILED"]);var LocationPlacementStallCauseSchema=external_exports.enum(["geometry-unavailable","authority-unresolved","service-unavailable","tile-timeout","unexpected"]),LocationPlacementFailureCodeSchema=external_exports.enum(["unmatched","ambiguous","invalid-geometry","duplicate","conflict","not-permitted"]),LOCATION_PLACEMENT_IDENTIFIER_MAX=512,LocationPlacementFailureSchema=external_exports.strictObject({rowIndex:external_exports.number().int().nonnegative(),code:LocationPlacementFailureCodeSchema,detail:external_exports.string(),identifier:external_exports.string().max(LOCATION_PLACEMENT_IDENTIFIER_MAX).nullable(),get assetIds(){return external_exports.array(AssetIdSchema)}}),LocationPlacementCountsSchema=external_exports.strictObject({rows:external_exports.number().int().nonnegative(),new:external_exports.number().int().nonnegative(),moved:external_exports.number().int().nonnegative(),unchanged:external_exports.number().int().nonnegative(),unmatched:external_exports.number().int().nonnegative(),ambiguous:external_exports.number().int().nonnegative(),invalidGeometry:external_exports.number().int().nonnegative(),duplicate:external_exports.number().int().nonnegative(),conflict:external_exports.number().int().nonnegative(),notPermitted:external_exports.number().int().nonnegative()});var LOCATION_PLACEMENT_OVERLAP_PLACEMENTS_MAX=10,LOCATION_PLACEMENT_OVERLAP_SAMPLE=5,LocationPlacementOverlapSchema=external_exports.strictObject({total:external_exports.number().int().nonnegative(),placements:external_exports.array(external_exports.strictObject({get placementId(){return LocationPlacementIdSchema},name:external_exports.string().nullable(),count:external_exports.number().int().positive(),get sampleAssetIds(){return external_exports.array(AssetIdSchema).max(LOCATION_PLACEMENT_OVERLAP_SAMPLE)}})).max(LOCATION_PLACEMENT_OVERLAP_PLACEMENTS_MAX)});var LocationPlacementJobSummarySchema=external_exports.strictObject({jobId:LocationPlacementJobIdSchema,get placementId(){return LocationPlacementIdSchema},mode:LocationPlacementJobModeSchema,state:LocationPlacementJobStateSchema,source:external_exports.strictObject({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema}),get counts(){return LocationPlacementCountsSchema},requested:external_exports.number().int().nonnegative(),get overlap(){return LocationPlacementOverlapSchema},failureDetail:external_exports.string().optional(),get stallCause(){return LocationPlacementStallCauseSchema.optional()},startedAt:external_exports.iso.datetime(),updatedAt:external_exports.iso.datetime()}),LocationPlacementSchema=external_exports.strictObject({placementId:LocationPlacementIdSchema,name:LocationPlacementNameSchema,get config(){return LocationPlacementConfigSchema},version:external_exports.number().int().positive(),createdAt:external_exports.iso.datetime(),updatedAt:external_exports.iso.datetime(),get latestJob(){return LocationPlacementJobSummarySchema.nullable()}}),SaveLocationPlacementInputSchema=external_exports.strictObject({get placementId(){return LocationPlacementIdSchema.optional()},expectedVersion:external_exports.number().int().positive().optional().describe("Required with `placementId`: the version the edit was based on."),name:LocationPlacementNameSchema,get config(){return LocationPlacementConfigSchema},get idempotencyKey(){return IdempotencyKeySchema.max(IDEMPOTENCY_KEY_MAX_LENGTH)}}),DeleteLocationPlacementInputSchema=external_exports.strictObject({get placementId(){return LocationPlacementIdSchema},get idempotencyKey(){return IdempotencyKeySchema.max(IDEMPOTENCY_KEY_MAX_LENGTH)}}),DeleteLocationPlacementResultSchema=external_exports.strictObject({get placementId(){return LocationPlacementIdSchema},deleted:external_exports.literal(!0)}),GetLocationPlacementInputSchema=external_exports.strictObject({get placementId(){return LocationPlacementIdSchema}}),ListLocationPlacementsOutputSchema=external_exports.strictObject({get placements(){return external_exports.array(LocationPlacementSchema)}}),StartLocationPlacementJobInputSchema=external_exports.strictObject({get placementId(){return LocationPlacementIdSchema},mode:LocationPlacementJobModeSchema.describe("`preview` counts what a run would do and writes nothing; `run` writes the new and moved locations."),get idempotencyKey(){return IdempotencyKeySchema.max(IDEMPOTENCY_KEY_MAX_LENGTH)}}),StartLocationPlacementJobResultSchema=external_exports.strictObject({jobId:LocationPlacementJobIdSchema,state:LocationPlacementJobStateSchema,mode:LocationPlacementJobModeSchema,alreadyRunning:external_exports.boolean()}),LocationPlacementJobStatusInputSchema=external_exports.strictObject({get jobId(){return LocationPlacementJobIdSchema}}),LocationPlacementJobStatusSchema=external_exports.strictObject({get job(){return LocationPlacementJobSummarySchema},get sample(){return external_exports.array(LocationPlacementFailureSchema)},failuresTruncated:external_exports.boolean()}),ListLocationPlacementJobsInputSchema=external_exports.strictObject({get placementId(){return LocationPlacementIdSchema}}),ListLocationPlacementJobsOutputSchema=external_exports.strictObject({get jobs(){return external_exports.array(LocationPlacementJobSummarySchema)}}),LocationPlacementJobFailuresInputSchema=external_exports.strictObject({get jobId(){return LocationPlacementJobIdSchema},code:LocationPlacementFailureCodeSchema.optional(),afterRowIndex:external_exports.number().int().nonnegative().optional(),limit:external_exports.number().int().min(1).max(LOCATION_PLACEMENT_FAILURE_PAGE_MAX).optional()}),LocationPlacementJobFailuresOutputSchema=external_exports.strictObject({get failures(){return external_exports.array(LocationPlacementFailureSchema)},nextAfterRowIndex:external_exports.number().int().nonnegative().optional()}),LOCATION_PLACEMENT_NOT_FOUND="LOCATION_PLACEMENT_NOT_FOUND",LOCATION_PLACEMENT_NAME_TAKEN="LOCATION_PLACEMENT_NAME_TAKEN",LOCATION_PLACEMENT_CHANGED="LOCATION_PLACEMENT_CHANGED",LOCATION_PLACEMENT_INVALID="LOCATION_PLACEMENT_INVALID",LOCATION_PLACEMENT_JOB_LIVE="LOCATION_PLACEMENT_JOB_LIVE",LOCATION_PLACEMENT_SOURCE_REFUSED="LOCATION_PLACEMENT_SOURCE_REFUSED",LOCATION_PLACEMENT_JOB_NOT_FOUND="LOCATION_PLACEMENT_JOB_NOT_FOUND",LOCATION_PLACEMENT_RUNNER_UNAVAILABLE="LOCATION_PLACEMENT_RUNNER_UNAVAILABLE",LocationPlacementNotFoundDataSchema=external_exports.object({code:external_exports.literal(LOCATION_PLACEMENT_NOT_FOUND)}),LocationPlacementNameTakenDataSchema=external_exports.object({code:external_exports.literal(LOCATION_PLACEMENT_NAME_TAKEN)}),LocationPlacementChangedDataSchema=external_exports.object({code:external_exports.literal(LOCATION_PLACEMENT_CHANGED),currentVersion:external_exports.number().int().positive()}),LocationPlacementInvalidDataSchema=external_exports.object({code:external_exports.literal(LOCATION_PLACEMENT_INVALID)}),LocationPlacementJobLiveDataSchema=external_exports.object({code:external_exports.literal(LOCATION_PLACEMENT_JOB_LIVE)}),LocationPlacementSourceRefusedDataSchema=external_exports.object({code:external_exports.literal(LOCATION_PLACEMENT_SOURCE_REFUSED),reason:external_exports.enum(["not-promoted","live","empty","too-many-rows","missing-columns"])}),LocationPlacementJobNotFoundDataSchema=external_exports.object({code:external_exports.literal(LOCATION_PLACEMENT_JOB_NOT_FOUND)}),LocationPlacementRunnerUnavailableDataSchema=external_exports.object({code:external_exports.literal(LOCATION_PLACEMENT_RUNNER_UNAVAILABLE)});var AssetImportRunIdSchema=external_exports.string().min(1).brand(),AssetImportExceptionIdSchema=external_exports.string().min(1).brand(),AssetImportExceptionStatusSchema=external_exports.enum(["open","resolved","dismissed"]),AssetImportExceptionResolutionSchema=external_exports.enum(["resolved","dismissed"]);var IMPORT_EXCEPTION_ROW_DATA_MAX_KEY_CHARS=256,ImportExceptionRowDataSchema=external_exports.record(external_exports.string().max(IMPORT_EXCEPTION_ROW_DATA_MAX_KEY_CHARS),external_exports.union([external_exports.string(),external_exports.number(),external_exports.boolean(),external_exports.null()])),AssetImportExceptionSchema=external_exports.object({get id(){return AssetImportExceptionIdSchema},get runId(){return AssetImportRunIdSchema},rowIndex:external_exports.number().int().nonnegative(),rowKey:external_exports.string().min(1).optional(),get error(){return CreateManyRowFailureErrorSchema},get rowData(){return ImportExceptionRowDataSchema},get status(){return AssetImportExceptionStatusSchema},resolvedAt:external_exports.iso.datetime().optional(),resolvedBy:external_exports.string().min(1).optional(),get resolvedAssetId(){return AssetIdSchema.optional()},createdAt:external_exports.iso.datetime()}),AssetImportRunSchema=external_exports.object({get id(){return AssetImportRunIdSchema},principal:external_exports.string().min(1),get datasetId(){return DatasetIdSchema},get versionId(){return DatasetVersionIdSchema},summary:external_exports.object({total:external_exports.number().int().nonnegative(),created:external_exports.number().int().nonnegative(),updated:external_exports.number().int().nonnegative(),unchanged:external_exports.number().int().nonnegative(),failed:external_exports.number().int().nonnegative()}),openCount:external_exports.number().int().nonnegative(),storedCount:external_exports.number().int().nonnegative(),get jobId(){return CompositionJobIdSchema.optional()},createdAt:external_exports.iso.datetime()}),IMPORT_EXCEPTIONS_PAGE_MAX=200,IMPORT_EXCEPTIONS_PAGE_DEFAULT=50;var ListImportRunsInputSchema=external_exports.strictObject({openOnly:external_exports.boolean().optional().describe("Narrow to runs that still have open exceptions. Defaults to false (every run), so a worked-to-zero history stays reachable as the evidence the work happened."),limit:external_exports.number().int().min(1).max(IMPORT_EXCEPTIONS_PAGE_MAX).optional().describe(`Page size, 1\u2013${String(IMPORT_EXCEPTIONS_PAGE_MAX)}; defaults to ${String(IMPORT_EXCEPTIONS_PAGE_DEFAULT)}. Read \`total\` for the full count matching the filter.`),cursor:external_exports.string().min(1).optional().describe("Opaque keyset cursor \u2014 pass the previous page's `nextCursor` to get the next page. `null` `nextCursor` means the last page.")}),ListImportRunsOutputSchema=external_exports.object({runs:external_exports.array(AssetImportRunSchema),total:external_exports.number().int().nonnegative(),nextCursor:external_exports.string().min(1).nullish()}),ListImportExceptionsInputSchema=external_exports.strictObject({get runId(){return AssetImportRunIdSchema.optional()},get status(){return AssetImportExceptionStatusSchema.optional()},limit:external_exports.number().int().min(1).max(IMPORT_EXCEPTIONS_PAGE_MAX).optional().describe(`Page size, 1\u2013${String(IMPORT_EXCEPTIONS_PAGE_MAX)}; defaults to ${String(IMPORT_EXCEPTIONS_PAGE_DEFAULT)}. Read \`total\` for the full count matching the filter.`),cursor:external_exports.string().min(1).optional().describe("Opaque keyset cursor \u2014 pass the previous page's `nextCursor` to get the next page. `null` `nextCursor` means the last page.")}),ListImportExceptionsOutputSchema=external_exports.object({exceptions:external_exports.array(AssetImportExceptionSchema),total:external_exports.number().int().nonnegative(),nextCursor:external_exports.string().min(1).nullish()}),ResolveImportExceptionInputSchema=external_exports.strictObject({get exceptionId(){return AssetImportExceptionIdSchema},get status(){return AssetImportExceptionResolutionSchema},get resolvedAssetId(){return AssetIdSchema.optional()}}),ResolveImportExceptionOutputSchema=AssetImportExceptionSchema,IMPORT_EXCEPTIONS_RESOLVE_MANY_MAX=100,ResolveManyRefusalReasonSchema=external_exports.enum(["not-found","already-resolved"]),ResolveManyImportExceptionsInputSchema=external_exports.strictObject({get exceptionIds(){return external_exports.array(AssetImportExceptionIdSchema).min(1).max(IMPORT_EXCEPTIONS_RESOLVE_MANY_MAX).describe(`1\u2013${String(IMPORT_EXCEPTIONS_RESOLVE_MANY_MAX)} exception ids. Distinct \u2014 a repeated id would report a false already-resolved refusal against its own first item.`)},get status(){return AssetImportExceptionResolutionSchema}}),ResolveManyImportExceptionsItemResultSchema=external_exports.discriminatedUnion("outcome",[external_exports.object({get exceptionId(){return AssetImportExceptionIdSchema},outcome:external_exports.literal("moved")}),external_exports.object({get exceptionId(){return AssetImportExceptionIdSchema},outcome:external_exports.literal("refused"),get reason(){return ResolveManyRefusalReasonSchema},get atStatus(){return AssetImportExceptionStatusSchema.optional()}})]),ResolveManyImportExceptionsOutputSchema=external_exports.object({summary:external_exports.object({requested:external_exports.number().int().min(0),moved:external_exports.number().int().min(0),refused:external_exports.number().int().min(0)}),results:external_exports.array(ResolveManyImportExceptionsItemResultSchema)}),ImportRunRetryPlanSchema=external_exports.object({get runId(){return AssetImportRunIdSchema},get datasetId(){return DatasetIdSchema},get versionId(){return DatasetVersionIdSchema},request:external_exports.record(external_exports.string(),external_exports.unknown()),openRowIndexes:external_exports.array(external_exports.number().int().nonnegative()).max(IMPORT_EXCEPTIONS_PAGE_MAX),openRowIndexesTruncated:external_exports.boolean().optional()}),GetImportRunRetryPlanInputSchema=external_exports.strictObject({get runId(){return AssetImportRunIdSchema}});var assetCountConfigSchema=external_exports.object({label:external_exports.string().default("total assets").describe("Sublabel shown beneath the count, naming what is being counted.")}).meta({examples:[{label:"assets tracked"}]});var assetManagerConfigSchema=external_exports.object({view:external_exports.enum(["list","split","map"]).default("list").describe("Which /assets presentation this widget seeds on first render: list (the sortable table), split (master list + docked detail + map), or map (the pin view). Defaults to list.")}).meta({examples:[{view:"list"}]});var assetConfigurationComponentContract={name:"asset-configuration",binds:"none",configVersion:"1",configSchema:external_exports.object({}),description:"Asset vocabulary admin: the categories, types and property templates assets are classified with, plus the asset-code numbering schemes and derived-value routing. Tenant-admin territory, not an operator surface.",grain:"page"},assetViewConfigSchema=external_exports.object({});var ASSET_IMPORT_MAPPING_KIND={domain:"assets",type:"asset-import-mapping"},assetImportMappingEditorComponentContract={name:"asset-import-mapping-editor",binds:"entity",bindsToResource:"asset-import-mappings",entity:ASSET_IMPORT_MAPPING_KIND,configVersion:"1",configSchema:external_exports.object({}),description:"Edit one saved import mapping \u2014 how a dataset's rows become assets: pick a dataset to sample, review the mapping's name, unique ID, type, lifecycle, start date, parent and the column it is matched on, which columns become properties and the ID system, see which types and ID systems already exist or will be created, and save the mapping's next version.",grain:"page"},assetImportMappingCreateComponentContract={name:"asset-import-mapping-create",binds:"none",configVersion:"1",configSchema:external_exports.object({}),description:"Create a new import mapping \u2014 how a dataset's rows become assets: pick a dataset, review the mapping guessed from its columns (name, unique ID, type, lifecycle, start date, parent and the column it is matched on, which columns become properties, the ID system), see which types and ID systems already exist or will be created, and save it as a named, versioned import mapping that an import runs.",grain:"page"},assetTreePreviewComponentContract={name:"asset-tree-preview",binds:"entity",bindsToResource:"asset-import-mappings",entity:ASSET_IMPORT_MAPPING_KIND,configVersion:"1",configSchema:external_exports.object({}),description:"The asset tree one saved import mapping would build from a dataset, before anything is created: pick a dataset, then see its levels with each level's mix of asset types, the roots, the deepest level, the assets that won't roll up because their parent is not in the file (with the rows that cause it), and duplicate names and IDs. The totals are the server's dry run; nothing is created until the import runs.",grain:"page"};var UnlinkManyInputSchema=external_exports.strictObject({get relationshipType(){return HierarchyRelationshipTypeSchema},get selection(){return AssetSelectionSchema},hierarchy:HierarchyScopeSchema.optional(),idempotencyKey:IdempotencyKeySchema,returnResults:ReturnResultsSchema.optional()}),UnlinkRefusalReasonSchema=external_exports.enum(["asset-not-found","no-such-edge"]),UnlinkManyItemResultSchema=external_exports.discriminatedUnion("status",[external_exports.object({get assetId(){return AssetIdSchema},status:external_exports.literal("ended"),isolated:external_exports.boolean()}),external_exports.object({get assetId(){return AssetIdSchema},status:external_exports.literal("refused"),reason:UnlinkRefusalReasonSchema,isolated:external_exports.boolean()})]),UnlinkManyOutputSchema=external_exports.object({summary:external_exports.object({requested:external_exports.number().int().min(0),ended:external_exports.number().int().min(0),refused:external_exports.number().int().min(0),isolated:external_exports.number().int().min(0)}),results:external_exports.array(UnlinkManyItemResultSchema)}),UnlinkManyResponseSchema=UnlinkManyOutputSchema.extend({accessUpdate:AccessUpdateStateSchema}),RelateManyInputSchema=external_exports.strictObject({get relationshipType(){return AssetRelationshipTypeSchema},get targetAssetId(){return AssetIdSchema},get selection(){return AssetSelectionSchema},idempotencyKey:IdempotencyKeySchema,returnResults:ReturnResultsSchema.optional()}),RelateRefusalReasonSchema=external_exports.enum(["asset-not-found","self-edge","duplicate-edge","would-cycle"]),RelateManyItemResultSchema=external_exports.discriminatedUnion("status",[external_exports.object({get assetId(){return AssetIdSchema},status:external_exports.literal("created")}),external_exports.object({get assetId(){return AssetIdSchema},status:external_exports.literal("refused"),reason:RelateRefusalReasonSchema})]),RelateManyOutputSchema=external_exports.object({summary:external_exports.object({requested:external_exports.number().int().min(0),created:external_exports.number().int().min(0),refused:external_exports.number().int().min(0)}),results:external_exports.array(RelateManyItemResultSchema)}),RelateManyResponseSchema=RelateManyOutputSchema.extend({accessUpdate:AccessUpdateStateSchema});var AssetExportScalarFieldSchema=external_exports.enum(["assetId","name","category","type","lifecycleStatus","effectiveFrom","effectiveTo","location"]),AssetExportColumnSourceSchema=external_exports.discriminatedUnion("kind",[external_exports.object({kind:external_exports.literal("scalar"),field:AssetExportScalarFieldSchema}),external_exports.object({kind:external_exports.literal("property"),key:external_exports.string().min(1)}),external_exports.object({kind:external_exports.literal("derived"),code:external_exports.string().min(1),part:external_exports.enum(["value","unit"])}),external_exports.object({kind:external_exports.literal("parent"),get relationshipType(){return HierarchyRelationshipTypeSchema},part:external_exports.enum(["name","id"])})]),AssetExportColumnSchema=external_exports.object({id:external_exports.string().min(1),header:external_exports.string().min(1),source:AssetExportColumnSourceSchema}),SCALAR_COLUMNS=Object.freeze([{id:"assetId",header:"Asset ID",source:{kind:"scalar",field:"assetId"}},{id:"name",header:"Name",source:{kind:"scalar",field:"name"}},{id:"category",header:"Category",source:{kind:"scalar",field:"category"}},{id:"type",header:"Type",source:{kind:"scalar",field:"type"}},{id:"lifecycleStatus",header:"Lifecycle",source:{kind:"scalar",field:"lifecycleStatus"}},{id:"effectiveFrom",header:"Valid from",source:{kind:"scalar",field:"effectiveFrom"}},{id:"effectiveTo",header:"Valid to",source:{kind:"scalar",field:"effectiveTo"}}]),LOCATION_COLUMN=Object.freeze({id:"location",header:"Location (WKT)",source:{kind:"scalar",field:"location"}});var AssetExportFormatSchema=external_exports.enum(["csv","xlsx"]),AssetExportMediaTypeSchema=external_exports.enum(["text/csv","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"]);var AssetExportEstimateSchema=external_exports.object({rowCount:external_exports.number().int().nonnegative(),maxRows:external_exports.number().int().positive(),columnCount:external_exports.number().int().nonnegative(),maxColumns:external_exports.number().int().positive(),rowCountAtLeast:external_exports.literal(!0).optional(),capReached:SearchCapReachedSchema.optional()}),AssetExportGrantSchema=external_exports.object({url:external_exports.url(),headers:external_exports.record(external_exports.string(),external_exports.string()),expiresAt:external_exports.iso.datetime(),mediaType:AssetExportMediaTypeSchema,filename:external_exports.string().min(1),rowCount:external_exports.number().int().nonnegative()});var AssetExportJobStateSchema=external_exports.enum(["PENDING","RUNNING","READY","FAILED"]),AssetExportJobKindSchema=external_exports.enum(["assets","duplicate-assets"]);var AssetExportHandleSchema=external_exports.object({exportId:external_exports.string().min(1),state:AssetExportJobStateSchema,rowCount:external_exports.number().int().nonnegative(),columnCount:external_exports.number().int().nonnegative(),tilesTotal:external_exports.number().int().nonnegative()}),AssetExportStatusInputSchema=external_exports.strictObject({exportId:external_exports.string().min(1)}),AssetExportStatusSchema=external_exports.discriminatedUnion("state",[external_exports.object({state:external_exports.literal("pending"),rowCount:external_exports.number().int().nonnegative(),columnCount:external_exports.number().int().nonnegative(),tilesDone:external_exports.number().int().nonnegative(),tilesTotal:external_exports.number().int().nonnegative()}),external_exports.object({state:external_exports.literal("ready"),get grant(){return AssetExportGrantSchema},byteSize:external_exports.number().int().nonnegative()}),external_exports.object({state:external_exports.literal("failed"),reason:external_exports.string().min(1),retryable:external_exports.boolean()})]),ASSET_EXPORT_IDEMPOTENCY_KEY_DESCRIPTION="Client-minted replay key for this export authorization \u2014 unique per (tenant, caller, key). A retry with the same key and the same selection replays the ONE recorded authorization and returns a FRESH grant (a new URL with a future expiry) \u2014 never the first call's possibly-expired URL, and never a second Record. A reused key with a DIFFERENT selection or format is refused, as is another caller's key. Mint a new key per intended export.",AssetExportIdempotencyKeySchema=IdempotencyKeySchema.describe(ASSET_EXPORT_IDEMPOTENCY_KEY_DESCRIPTION),AssetExportEstimateInputSchema=external_exports.strictObject({get selection(){return AssetExportSelectionSchema}}),AssetExportInputSchema=external_exports.strictObject({get selection(){return AssetExportSelectionSchema},format:AssetExportFormatSchema,get idempotencyKey(){return AssetExportIdempotencyKeySchema}});var EXPORT_SEARCH_CAP_REASON="search-cap",AssetExportOverCapDataSchema=external_exports.object({reason:external_exports.literal(EXPORT_SEARCH_CAP_REASON)}).optional();var DuplicateAssetsExportFiltersSchema=DuplicateAssetsInputSchema.omit({page:!0,pageSize:!0}),DuplicateAssetsExportSelectionSchema=external_exports.strictObject({kind:external_exports.literal("duplicate-assets"),filters:DuplicateAssetsExportFiltersSchema}),DuplicateAssetsExportInputSchema=external_exports.strictObject({idempotencyKey:AssetExportIdempotencyKeySchema,filters:DuplicateAssetsExportFiltersSchema});var ASSET_COUNT_SAMPLE_MAX=50,AssetCountInputSchema=external_exports.strictObject({get selection(){return AssetCountSelectionSchema},get asOf(){return AsOfSchema.optional()},sampleLimit:external_exports.number().int().min(0).max(ASSET_COUNT_SAMPLE_MAX).optional()}),AssetCountOutputSchema=external_exports.object({total:external_exports.number().int().min(0),totalAtLeast:external_exports.literal(!0).optional(),capReached:SearchCapReachedSchema.optional(),get sampleAssetIds(){return external_exports.array(AssetIdSchema)}});var ASSET_SNAPSHOT_TYPES=["asset"],SnapshotAskSchema2=external_exports.strictObject({domain:external_exports.literal("assets"),type:external_exports.enum(ASSET_SNAPSHOT_TYPES),id:external_exports.string().min(1)});var AssetTemplateVersionIdSchema=external_exports.string().min(1).brand(),AssetVersionIdSchema=external_exports.string().min(1).brand().describe("Version-row id \u2014 OUTPUT ONLY, and deliberately unstable: an asset gains a new one on every edit. Never pass this where an `assetId` is asked for."),AssetRelationshipIdSchema=external_exports.string().min(1).brand(),AssetRelationshipVersionIdSchema=external_exports.string().min(1).brand(),AssetRelationshipCategorySchema=external_exports.enum(["PHYSICAL","LOGICAL"]),AssetRelationshipTypeSchema=external_exports.enum(["CONTAINS","FLOWS_TO","CONNECTED_TO","PART_OF","REPORTS_TO","BELONGS_TO"]).describe("Edge type, read subject\u2192object (`CONTAINS`: subject contains object). The four HIERARCHICAL types \u2014 CONTAINS, PART_OF, REPORTS_TO, BELONGS_TO \u2014 are the only ones the tree reads (parents/children/subtree/roots) and the cycle check operate on. FLOWS_TO and CONNECTED_TO are stored but non-hierarchical: passing one to a tree read is rejected.");var PropertyValueTypeSchema=external_exports.enum(["STRING","NUMBER","BOOLEAN","ENUM","MEASUREMENT"]),ObservedPropertyRefSchema=external_exports.object({observedProperty:external_exports.string().min(1),uom:external_exports.string().min(1)}),clientLibraryCatalog=Object.freeze({getObservedProperty:observedProperty=>OBSERVED_PROPERTY_CATALOG_ENTRIES.find(entry=>entry.observedProperty===observedProperty),listObservedProperties:()=>OBSERVED_PROPERTY_CATALOG_ENTRIES}),AssetRefSchema=external_exports.object({assetId:AssetIdSchema}),FeatureSchema=external_exports.object({assetId:AssetIdSchema,externalIds:external_exports.array(external_exports.string().min(1)).optional(),geometry:GeoJsonGeometrySchema.nullable().optional(),path:external_exports.array(AssetIdSchema).optional(),assetAsOf:external_exports.iso.datetime().optional()}),TemplatePropertyBaseSchema=external_exports.strictObject({code:external_exports.string().min(1).max(64),displayName:external_exports.string().min(1),required:external_exports.boolean()}),buildTemplatePropertySchema=allowedValues=>external_exports.discriminatedUnion("valueType",[TemplatePropertyBaseSchema.extend({valueType:external_exports.literal("STRING"),pattern:external_exports.string().min(1).max(200).optional()}),TemplatePropertyBaseSchema.extend({valueType:external_exports.literal("NUMBER"),min:external_exports.number().optional(),max:external_exports.number().optional()}),TemplatePropertyBaseSchema.extend({valueType:external_exports.literal("BOOLEAN")}),TemplatePropertyBaseSchema.extend({valueType:external_exports.literal("ENUM"),allowedValues}),TemplatePropertyBaseSchema.extend({valueType:external_exports.literal("MEASUREMENT"),observedProperty:ObservedPropertyRefSchema,min:external_exports.number().optional(),max:external_exports.number().optional()})]),TemplatePropertySchema=buildTemplatePropertySchema(external_exports.array(external_exports.string().min(1))),TEMPLATE_PROPERTIES_WIRE_MAX=1e3,TEMPLATE_DERIVED_PROPERTIES_WIRE_MAX=1e3,TEMPLATE_ENUM_VALUES_WIRE_MAX=1e3,TemplatePropertyInputSchema=buildTemplatePropertySchema(external_exports.array(external_exports.string().min(1)).max(TEMPLATE_ENUM_VALUES_WIRE_MAX)),AssetTemplateVersionSchema=external_exports.object({id:AssetTemplateVersionIdSchema,assetTypeId:AssetTypeIdSchema,properties:external_exports.array(TemplatePropertySchema),derivedProperties:external_exports.array(DerivedPropertyDeclarationSchema).default([]),effectiveFrom:external_exports.iso.datetime(),effectiveTo:external_exports.iso.datetime().nullable()}),GetAssetTemplateInputSchema=external_exports.strictObject({assetTypeId:AssetTypeIdSchema}),AssetSchema=external_exports.object({id:AssetVersionIdSchema,assetId:AssetIdSchema,name:external_exports.string().min(1),assetTypeId:AssetTypeIdSchema,lifecycleStatus:AssetLifecycleStatusSchema,properties:PropertyValuesSchema,templateVersionId:AssetTemplateVersionIdSchema,effectiveFrom:external_exports.iso.datetime(),effectiveTo:external_exports.iso.datetime().nullable(),geometry:GeoJsonGeometrySchema.nullable().optional()}),AssetReadSchema=AssetSchema.extend({appliedDatedValueIds:AppliedDatedValueIdsSchema.optional()}),CreateAssetInputSchema=external_exports.strictObject({name:external_exports.string().min(1),assetTypeId:AssetTypeIdSchema,lifecycleStatus:AssetLifecycleStatusSchema,properties:PropertyValuesInputSchema,effectiveFrom:InitialEffectiveFromSchema.optional()}),GetAssetInputSchema=external_exports.strictObject({assetId:AssetIdSchema,asOf:AsOfSchema.optional(),knownAt:KnownAtSchema.optional()}),UpdateAssetInputSchema=external_exports.strictObject({assetId:AssetIdSchema,name:external_exports.string().min(1),lifecycleStatus:AssetLifecycleStatusSchema,properties:PropertyValuesInputSchema,effectiveFrom:EffectiveFromSchema.optional()}),ChildReparentingSchema=external_exports.discriminatedUnion("mode",[external_exports.strictObject({mode:external_exports.literal("refuse")}),external_exports.strictObject({mode:external_exports.literal("reparent"),newParentAssetId:AssetIdSchema})]),DeleteAssetInputSchema=external_exports.strictObject({assetId:AssetIdSchema,childReparenting:ChildReparentingSchema.optional()}),GovernedCreateAssetInputSchema=CreateAssetInputSchema.extend({idempotencyKey:IdempotencyKeySchema}),GovernedUpdateAssetInputSchema=UpdateAssetInputSchema.extend({idempotencyKey:IdempotencyKeySchema}),GovernedDeleteAssetInputSchema=DeleteAssetInputSchema.extend({idempotencyKey:IdempotencyKeySchema}),DeleteImpactInputSchema=external_exports.strictObject({assetIds:external_exports.array(AssetIdSchema).min(1).max(DELETE_IMPACT_MAX_IDS)}),DeleteImpactEdgeSchema=external_exports.object({relationshipId:AssetRelationshipIdSchema,relationshipType:AssetRelationshipTypeSchema,otherAssetId:AssetIdSchema}),DeleteImpactHierarchyEdgeSchema=DeleteImpactEdgeSchema.extend({relationshipType:HierarchyRelationshipTypeSchema,direction:HierarchyEdgeDirectionSchema}),DeleteImpactBindingSchema=external_exports.object({bindingId:ExternalIdBindingIdSchema,system:ExternalIdSystemSchema,value:ExternalIdValueSchema}),DeleteImpactEdgeSectionSchema=external_exports.object({total:external_exports.number().int().min(0),sample:external_exports.array(DeleteImpactEdgeSchema)}),DeleteImpactBindingSectionSchema=external_exports.object({total:external_exports.number().int().min(0),sample:external_exports.array(DeleteImpactBindingSchema)}),DeleteImpactHierarchySectionSchema=external_exports.object({total:external_exports.number().int().min(0),childTotal:external_exports.number().int().min(0),sample:external_exports.array(DeleteImpactHierarchyEdgeSchema)}),DeleteImpactItemSchema=external_exports.object({assetId:AssetIdSchema,verdict:DeleteImpactVerdictSchema,hierarchyEdges:DeleteImpactHierarchySectionSchema,storageEdges:DeleteImpactEdgeSectionSchema,externalIdBindings:DeleteImpactBindingSectionSchema}),DeleteImpactOutputSchema=external_exports.object({items:external_exports.array(DeleteImpactItemSchema)}),DeleteManyInputSchema=external_exports.strictObject({assetIds:external_exports.array(AssetIdSchema).min(1).max(DELETE_MANY_MAX_IDS),idempotencyKey:IdempotencyKeySchema,returnResults:ReturnResultsSchema.optional()}),DeleteManyItemResultSchema=external_exports.discriminatedUnion("status",[external_exports.object({assetId:AssetIdSchema,status:external_exports.literal("deleted")}),external_exports.object({assetId:AssetIdSchema,status:external_exports.literal("refused"),reason:DeleteRefusalReasonSchema})]),DeleteManyOutputSchema=external_exports.object({summary:external_exports.object({requested:external_exports.number().int().min(0),deleted:external_exports.number().int().min(0),refused:external_exports.number().int().min(0)}),results:external_exports.array(DeleteManyItemResultSchema)}),SetAssetLocationInputSchema=external_exports.strictObject({assetId:AssetIdSchema,geometry:GeoJsonGeometryInputSchema.nullable()}),GovernedSetAssetLocationInputSchema=SetAssetLocationInputSchema.extend({idempotencyKey:IdempotencyKeySchema}),ASSET_IDS_MAX_PER_PAGE=200,ASSET_VERSION_IDS_MAX=200,EXCLUDE_ASSET_IDS_MAX=1e3,ListAssetsInputSchema=external_exports.strictObject({asOf:AsOfSchema.optional(),knownAt:KnownAtSchema.optional(),assetIds:external_exports.array(AssetIdSchema).min(1).max(ASSET_IDS_MAX_PER_PAGE).optional(),subtreeOf:AssetSubtreeScopeSchema.optional(),underAssetIds:AssetBranchScopeSchema.optional().describe(UNDER_ASSET_IDS_DESCRIPTION),excludeAssetIds:external_exports.array(AssetIdSchema).min(1).max(EXCLUDE_ASSET_IDS_MAX).optional().describe("Assets to SUBTRACT from whatever the other filters match \u2014 the opposite direction to `assetIds`, which ADDS. Applied last, so an id in both is excluded. Excluding an id nothing matched is a no-op, never an error."),categoryIds:external_exports.array(AssetCategoryIdSchema).min(1).max(50).optional(),assetTypeIds:external_exports.array(AssetTypeIdSchema).min(1).max(50).optional(),lifecycleStatuses:external_exports.array(AssetLifecycleStatusSchema).min(1).max(50).optional(),nameContains:external_exports.string().min(1).optional().describe("THE name filter \u2014 a case-insensitive substring match on the asset name. There is no `name` parameter; this is it for a name-only match. To also find an asset by the start of an external ID, send `search`."),search:AssetSearchSchema.optional(),propertyFilters:AssetPropertyFilterSchema.optional(),conditions:AssetConditionsSchema.optional(),hasGeometry:external_exports.boolean().optional(),within:GeoJsonPolygonSchema.optional(),orderBy:AssetOrderBySchema.optional(),offset:external_exports.number().int().min(0).optional().describe("Rows to skip; defaults to 0. Ignored when `cursor` is supplied."),limit:external_exports.number().int().min(1).max(200).optional().describe("Page size, 1\u2013200; defaults to 50. Read `total` for the full filtered count \u2014 present on a first-page/offset call, omitted on a cursor-paged call."),cursor:external_exports.string().min(1).optional().describe("Opaque keyset cursor \u2014 pass the previous page's `nextCursor` to get the next page. WINS over `offset` when both are present; `null` `nextCursor` means the last page.")}),ListAssetsOutputSchema=external_exports.object({items:external_exports.array(AssetReadSchema),total:external_exports.number().int().min(0).optional(),nextCursor:external_exports.string().nullable().optional(),matchedExternalIds:external_exports.array(AssetExternalIdSchema).optional(),totalAtLeast:external_exports.literal(!0).optional(),capReached:SearchCapReachedSchema.optional()}),AssetCountSelectionSchema=ListAssetsInputSchema.omit(ASSET_SELECTION_OMITTED),AssetSelectionSchema=AssetCountSelectionSchema.extend({propertyFilters:AssetPropertyEqualsFilterSchema.optional()}),AssetListFilterSchema=ListAssetsInputSchema.omit({orderBy:!0,offset:!0,limit:!0,cursor:!0}),AssetDescendantScopeSchema=external_exports.strictObject({rootAssetIds:external_exports.array(AssetIdSchema).min(1).max(ASSET_IDS_MAX_PER_PAGE),relationshipType:HierarchyRelationshipTypeSchema}),AssetExportSelectionSchema=ListAssetsInputSchema.omit({offset:!0,limit:!0,cursor:!0,asOf:!0,knownAt:!0,subtreeOf:!0,underAssetIds:!0,conditions:!0}).extend({descendantOf:AssetDescendantScopeSchema.optional()}),AssetFieldSchema=AssetSchema.keyof(),ASSET_FIELDS=Object.freeze([...AssetFieldSchema.options]),ListAssetIndexInputSchema=ListAssetsInputSchema.omit({asOf:!0,knownAt:!0}).extend({fields:external_exports.array(AssetFieldSchema).min(1).max(ASSET_FIELDS.length)}),AssetIndexItemSchema=AssetSchema.partial().required({assetId:!0}),ListAssetIndexOutputSchema=ListAssetsOutputSchema.extend({items:external_exports.array(AssetIndexItemSchema)}),ListAssetVersionsInputSchema=external_exports.strictObject({assetId:AssetIdSchema,versionIds:external_exports.array(external_exports.string().min(1)).min(1).max(ASSET_VERSION_IDS_MAX).optional()}),ListAssetActivityInputSchema=external_exports.strictObject({assetId:AssetIdSchema,cursor:external_exports.string().min(1).optional(),limit:external_exports.number().int().positive().max(200).optional()}),AssetCategoryCountSchema=external_exports.object({categoryId:AssetCategoryIdSchema,key:external_exports.string().min(1),displayName:external_exports.string().min(1),count:external_exports.number().int().min(0)}),AssetTypeCountSchema=external_exports.object({assetTypeId:AssetTypeIdSchema,categoryId:AssetCategoryIdSchema,key:external_exports.string().min(1),displayName:external_exports.string().min(1),count:external_exports.number().int().min(0)}),AssetCategorySummarySchema=external_exports.object({total:external_exports.number().int().min(0),byCategory:external_exports.array(AssetCategoryCountSchema),byType:external_exports.array(AssetTypeCountSchema)}),FlowDescriptorSchema=external_exports.object({observedProperty:ObservedPropertyRefSchema,unit:external_exports.string().min(1),fraction:external_exports.number().min(0).max(1)}),AssetRelationshipSchema=external_exports.object({id:AssetRelationshipVersionIdSchema,relationshipId:AssetRelationshipIdSchema,relationshipType:AssetRelationshipTypeSchema,subjectAssetId:AssetIdSchema,objectAssetId:AssetIdSchema,effectiveFrom:external_exports.iso.datetime(),effectiveTo:external_exports.iso.datetime().nullable(),flowDescriptor:FlowDescriptorSchema.optional(),hierarchyId:HierarchyIdSchema.nullable().default(null)}),AssetRelationshipWriteResultSchema=AssetRelationshipSchema.extend({accessUpdate:AccessUpdateStateSchema}),CreateAssetRelationshipInputSchema=external_exports.strictObject({idempotencyKey:UnreceiptedIdempotencyKeySchema,relationshipType:AssetRelationshipTypeSchema,subjectAssetId:AssetIdSchema,objectAssetId:AssetIdSchema,flowDescriptor:FlowDescriptorSchema.optional(),hierarchy:HierarchyScopeSchema.optional(),effectiveFrom:EffectiveFromSchema.optional(),effectiveTo:EffectiveToSchema.optional(),...DATED_CREATE_FIELDS}),RawCreateAssetRelationshipInputSchema=CreateAssetRelationshipInputSchema.omit({idempotencyKey:!0}),EndAssetRelationshipInputSchema=external_exports.strictObject({idempotencyKey:UnreceiptedIdempotencyKeySchema,relationshipId:AssetRelationshipIdSchema,effectiveTo:EffectiveToSchema.optional()}),RawEndAssetRelationshipInputSchema=EndAssetRelationshipInputSchema.omit({idempotencyKey:!0}),MoveRelationshipInputSchema=external_exports.strictObject({relationshipId:AssetRelationshipIdSchema,newParentAssetId:AssetIdSchema,effectiveFrom:EffectiveFromSchema.optional(),...DATED_CREATE_FIELDS}),GovernedMoveRelationshipInputSchema=MoveRelationshipInputSchema.extend({idempotencyKey:IdempotencyKeySchema}),ListAssetRelationshipsInputSchema=external_exports.strictObject({assetId:AssetIdSchema,relationshipType:AssetRelationshipTypeSchema.optional(),asOf:AsOfSchema.optional()}),QUALITY_PAGE_LIMIT_MAX=200;var OrphanedAssetsInputSchema=external_exports.strictObject({offset:external_exports.number().int().min(0).optional(),limit:external_exports.number().int().min(1).max(QUALITY_PAGE_LIMIT_MAX).optional(),nameContains:external_exports.string().min(1).optional()}),OrphanedAssetsOutputSchema=external_exports.object({items:external_exports.array(SubtreeNodeSchema),count:RelationshipRootsCountSchema}),UnparentedAssetsInputSchema=external_exports.strictObject({offset:external_exports.number().int().min(0).optional(),limit:external_exports.number().int().min(1).max(QUALITY_PAGE_LIMIT_MAX).optional(),nameContains:external_exports.string().min(1).optional(),get assetTypeId(){return AssetTypeIdSchema.optional()},hierarchy:UnparentedScopeSchema.optional()}),UnparentedAssetsOutputSchema=external_exports.object({items:external_exports.array(SubtreeNodeSchema),count:RelationshipRootsCountSchema}),DanglingEdgeSchema=external_exports.object({relationship:AssetRelationshipSchema,missingSubject:external_exports.boolean(),missingObject:external_exports.boolean()}),EdgeCycleSchema=external_exports.object({relationshipType:HierarchyRelationshipTypeSchema,path:external_exports.array(AssetIdSchema).min(2)}),MultiParentChildSchema=external_exports.object({assetId:AssetIdSchema,relationshipType:HierarchyRelationshipTypeSchema,parentCount:external_exports.number().int().min(2)}),EdgeSanityReportSchema=external_exports.object({selfEdges:external_exports.object({total:external_exports.number().int().min(0),sample:external_exports.array(AssetRelationshipSchema)}),danglingEdges:external_exports.object({total:external_exports.number().int().min(0),sample:external_exports.array(DanglingEdgeSchema)}),multiParentChildren:external_exports.object({total:external_exports.number().int().min(0),sample:external_exports.array(MultiParentChildSchema)}),nonCanonicalConnections:external_exports.object({total:external_exports.number().int().min(0),sample:external_exports.array(AssetRelationshipSchema)}),cycles:external_exports.object({sample:external_exports.array(EdgeCycleSchema),limitReached:external_exports.boolean()})}),RelationshipTypeCountSchema=external_exports.object({relationshipType:AssetRelationshipTypeSchema,count:external_exports.number().int().nonnegative()}),RelationshipEdgeSummarySchema=external_exports.object({total:external_exports.number().int().nonnegative(),byType:external_exports.array(RelationshipTypeCountSchema)});var RecordsPageOptionsShape={cursor:external_exports.string().min(1).optional().describe("Opaque keyset cursor copied verbatim from the previous page's `cursor` \u2014 pass it back to fetch the next page, and keep going until the response carries none. Never parse or construct one. Omit for the first page."),limit:external_exports.number().int().positive().optional().describe("Records per page. Omitted \u2192 50. Must be a positive integer.")},RecordsPageSchema=external_exports.object({items:external_exports.array(ActionRecordSchema),cursor:external_exports.string().min(1).optional()}),RecordsByEntityInputSchema=external_exports.object({ref:EntityRefInputSchema,...RecordsPageOptionsShape}),RecordsByActorInputSchema=external_exports.object({principal:external_exports.string().min(1),...RecordsPageOptionsShape}),RecordsByFlowRunInputSchema=external_exports.object({flowRunRecordId:RecordIdInputSchema,...RecordsPageOptionsShape}),RecordsByTimeInputSchema=external_exports.object({from:external_exports.iso.datetime(),to:external_exports.iso.datetime(),...RecordsPageOptionsShape}),recordsContract=oc.router({byEntity:oc.input(RecordsByEntityInputSchema).output(RecordsPageSchema),byActor:oc.input(RecordsByActorInputSchema).output(RecordsPageSchema),byFlowRun:oc.input(RecordsByFlowRunInputSchema).output(RecordsPageSchema),byTime:oc.input(RecordsByTimeInputSchema).output(RecordsPageSchema)});var assetsAccessContract=oc.router({status:oc.input(AccessStatusInputSchema).output(AccessStatusSchema),rerun:oc.output(RerunAccessUpdateResultSchema).errors({SERVICE_UNAVAILABLE:{message:"access updates are not re-run on this deployment",data:AccessUpdateRunnerUnavailableDataSchema}})});var CONDITION_ERRORS={INVALID_CONDITION:{status:400,message:"A condition does not fit its field: check the operator and value against the field, or remove the condition",data:InvalidConditionDataSchema}};var datedValueProcedures={setDatedValues:oc.input(SetDatedValuesInputSchema).output(SetDatedValuesOutputSchema),listDatedValues:oc.input(ListDatedValuesInputSchema).output(ListDatedValuesOutputSchema),listDatedValueChanges:oc.input(ListDatedValueChangesInputSchema).output(ListDatedValueChangesOutputSchema)},revertDatedValuesProcedures={revertDatedValues:oc.input(RevertDatedValuesInputSchema).output(RevertDatedValuesOutputSchema)};var READ_TX_BUDGET_ERRORS={TX_BUDGET_OVERRUN:{status:422,message:"This read ran out of its transaction time; narrow it \u2014 a lower root or a shallower maxDepth for a walk, an id or a narrower filter for a list \u2014 or try again if the system was busy",data:ReadTxBudgetOverrunDataSchema}},WALK_OVER_CAP_ERRORS={OVER_CAP:{status:422,message:"This hierarchy walk reaches more assets than one walk can return; narrow it with a shallower maxDepth or a lower root"}},DESCENDANTS_OVER_CAP_ERRORS={OVER_CAP:{status:422,message:"This hierarchy walk reaches more assets than one descendants read can return; narrow it with a shallower maxDepth or a lower root"}},LONG_READ_BUSY_ERRORS={SERVICE_UNAVAILABLE:{status:503,message:"This server is already running its long reads; the walk was not started. Try again shortly",data:LongReadBusyDataSchema}},WALK_CALLER_REFUSAL_ERRORS={FORBIDDEN:{status:403,message:"relationships.walkDescendants serves unattended runners only; read relationships.descendants instead",data:RunnerOnlyDataSchema},NOT_IMPLEMENTED:{status:501,message:"this host runs no long reads; read relationships.descendants instead",data:NoLongReadDataSchema}};var assetsDescendantsProcedures={descendants:oc.input(AssetDescendantsInputSchema).output(AssetDescendantsOutputSchema).errors({...DESCENDANTS_OVER_CAP_ERRORS,...READ_TX_BUDGET_ERRORS}).meta({agenticSurface:"excluded",agenticSurfaceReason:"semantic"}),walkDescendants:oc.input(AssetDescendantsInputSchema).output(AssetDescendantsOutputSchema).errors({...DESCENDANTS_OVER_CAP_ERRORS,...READ_TX_BUDGET_ERRORS,...LONG_READ_BUSY_ERRORS,...WALK_CALLER_REFUSAL_ERRORS}).meta({agenticSurface:"excluded",agenticSurfaceReason:"semantic"})};var assetsExternalIdContract=oc.router({create:oc.input(GovernedBindExternalIdInputSchema).output(ExternalIdBindingSchema),createMany:oc.input(BulkBindExternalIdInputSchema).output(BulkBindExternalIdOutputSchema),get:oc.input(ResolveExternalIdInputSchema).output(ExternalIdBindingSchema),resolveMany:oc.input(ResolveExternalIdManyInputSchema).output(ResolveExternalIdManyOutputSchema).errors({NOT_FOUND:{message:"the external-ID system is not configured",data:external_exports.object({code:external_exports.literal(EXTERNAL_ID_SYSTEM_NOT_CONFIGURED),system:external_exports.string()})}}),list:oc.input(ListAssetExternalIdsInputSchema).output(external_exports.array(ExternalIdBindingSchema)),delete:oc.input(GovernedUnbindExternalIdInputSchema).output(ExternalIdBindingSchema),startBindJob:oc.input(StartExternalIdBindJobInputSchema).output(StartExternalIdBindJobResultSchema),bindJobStatus:oc.input(ExternalIdBindJobStatusInputSchema).output(ExternalIdBindJobStatusSchema)}),SYSTEM_TERM_ERRORS={ASSET_SYSTEM_TERM_UNKNOWN:{status:422,message:"the term is not in this tenant\u2019s vocabulary \u2014 pick one from the vocabulary list"},ASSET_SYSTEM_TERM_UNCHECKABLE:{status:424,message:"the vocabulary could not be read to check the term; nothing was changed"}},assetsSystemContract=oc.router({create:oc.input(CreateAssetSystemInputSchema).output(AssetSystemSchema).errors(SYSTEM_TERM_ERRORS),get:oc.input(GetAssetSystemInputSchema).output(AssetSystemSchema),list:oc.input(ListAssetSystemsInputSchema).output(external_exports.array(AssetSystemSchema)),update:oc.input(UpdateAssetSystemInputSchema).output(AssetSystemSchema).errors(SYSTEM_TERM_ERRORS),delete:oc.input(DeleteAssetSystemInputSchema).output(AssetSystemSchema)});var assetsImportPreflightProcedures={preflightImport:oc.input(PreflightImportInputSchema).output(PreflightImportAcceptResultSchema).errors({BAD_REQUEST:{message:"the rows slice is wider than the import pre-flight can check",data:PreflightImportRowsTooWideDataSchema},SERVICE_UNAVAILABLE:{message:"background import pre-flights are not available on this deployment",data:PreflightImportRunnerUnavailableDataSchema}}),preflightImportStatus:oc.input(PreflightImportStatusInputSchema).output(PreflightImportStatusSchema).errors({NOT_FOUND:{message:"import pre-flight not found",data:PreflightImportJobNotFoundDataSchema}})};var placementNotFound={NOT_FOUND:{message:"location placement not found",data:LocationPlacementNotFoundDataSchema}},jobNotFound={NOT_FOUND:{message:"location placement job not found",data:LocationPlacementJobNotFoundDataSchema}},assetsPlacementsContract=oc.router({save:oc.input(SaveLocationPlacementInputSchema).output(LocationPlacementSchema).errors({BAD_REQUEST:{message:"the placement is not valid",data:LocationPlacementInvalidDataSchema},CONFLICT:{message:"the placement could not be saved as asked",data:LocationPlacementNameTakenDataSchema.or(LocationPlacementChangedDataSchema)},...placementNotFound}),delete:oc.input(DeleteLocationPlacementInputSchema).output(DeleteLocationPlacementResultSchema).errors({CONFLICT:{message:"the placement has a job in progress",data:LocationPlacementJobLiveDataSchema},...placementNotFound}),get:oc.input(GetLocationPlacementInputSchema).output(LocationPlacementSchema).errors(placementNotFound),list:oc.output(ListLocationPlacementsOutputSchema),startJob:oc.input(StartLocationPlacementJobInputSchema).output(StartLocationPlacementJobResultSchema).errors({BAD_REQUEST:{message:"the placement cannot run over this dataset",data:LocationPlacementSourceRefusedDataSchema},CONFLICT:{message:"the dataset version is not promoted",data:LocationPlacementSourceRefusedDataSchema},...placementNotFound,SERVICE_UNAVAILABLE:{message:"placing assets from a dataset is not available on this deployment",data:LocationPlacementRunnerUnavailableDataSchema}}),jobStatus:oc.input(LocationPlacementJobStatusInputSchema).output(LocationPlacementJobStatusSchema).errors(jobNotFound),jobFailures:oc.input(LocationPlacementJobFailuresInputSchema).output(LocationPlacementJobFailuresOutputSchema).errors(jobNotFound),listJobs:oc.input(ListLocationPlacementJobsInputSchema).output(ListLocationPlacementJobsOutputSchema).errors(placementNotFound)});var qualityScanRefusal={UNPROCESSABLE_CONTENT:{message:"this data-quality check ran out of time at this estate size",data:QualityScanRefusalDataSchema}},assetsQualityContract=oc.router({orphanedAssets:oc.input(OrphanedAssetsInputSchema).output(OrphanedAssetsOutputSchema).errors(qualityScanRefusal),unparentedAssets:oc.input(UnparentedAssetsInputSchema).output(UnparentedAssetsOutputSchema).errors({...qualityScanRefusal,NOT_FOUND:{message:"Hierarchy not found"}}),edgeSanity:oc.output(EdgeSanityReportSchema).errors(qualityScanRefusal),edgeSummary:oc.output(RelationshipEdgeSummarySchema).errors(qualityScanRefusal),duplicateAssets:oc.input(DuplicateAssetsInputSchema.optional()).output(DuplicateAssetsReportSchema).errors(qualityScanRefusal),exportDuplicates:oc.input(DuplicateAssetsExportInputSchema).output(AssetExportHandleSchema).errors({...qualityScanRefusal,OVER_CAP:{status:422,message:"These duplicate groups exceed this deployment\u2019s export row cap; narrow them with a search or a filter"},EMPTY_RESULT:{status:422,message:"No duplicate groups match these filters; nothing to export"},SERVICE_UNAVAILABLE:{message:"exports are not available on this deployment \u2014 the export object store is not configured for it",data:ExportStoreUnavailableDataSchema}}),startJob:oc.output(StartQualityJobResultSchema).errors({SERVICE_UNAVAILABLE:{message:"background data-quality checks are not available on this deployment",data:QualityJobRunnerUnavailableDataSchema}}),jobStatus:oc.input(QualityJobStatusInputSchema).output(QualityJobStatusSchema).errors({NOT_FOUND:{message:"quality job not found",data:QualityJobNotFoundDataSchema}}),latestReceipt:oc.output(LatestQualityReceiptSchema)});var CreateRelationshipWireInputSchema=CreateAssetRelationshipInputSchema.refine(previewsADatedLink,DATED_DRY_RUN_ISSUE),MoveRelationshipWireInputSchema=GovernedMoveRelationshipInputSchema.refine(previewsADatedLink,DATED_DRY_RUN_ISSUE),CreateAssetRelationshipOutputSchema=external_exports.union([AssetRelationshipWriteResultSchema.extend({dated:DatedLinkResultSchema.optional()}),DatedLinkDryRunSchema]),MoveRelationshipOutputSchema=external_exports.union([AssetRelationshipWriteResultSchema,DatedLinkDryRunSchema]),parentLinkProcedures={listParentLinks:oc.input(ListParentLinksInputSchema).output(ListParentLinksOutputSchema)};var locationsProcedure=oc.input(AssetLocationsInputSchema).output(AssetLocationsOutputSchema).errors(READ_TX_BUDGET_ERRORS),exportEstimateProcedure=oc.input(AssetExportEstimateInputSchema).output(AssetExportEstimateSchema).errors(READ_TX_BUDGET_ERRORS);var assetsSpatialContract=oc.router({nearby:oc.input(NearbyAssetsInputSchema).output(NearbyAssetsOutputSchema),withinBounds:oc.input(AssetsWithinBoundsInputSchema).output(AssetsWithinBoundsOutputSchema),withinPolygon:oc.input(AssetsWithinPolygonInputSchema).output(AssetsWithinPolygonOutputSchema),aggregate:oc.input(MapAggregateInputSchema).output(MapAggregateOutputSchema),mapFeatures:oc.input(MapFeaturesInputSchema).output(MapFeaturesOutputSchema)});for(let{schema,max:max2}of WIRE_BOUNDED_RECORDS2)JSON_SCHEMA_REGISTRY.add(schema,wireRecordPublished({max:max2}));var EDGE_WRITE_DEADLOCK_ERRORS={SERVICE_UNAVAILABLE:{message:"a concurrent change to the same assets deadlocked with this one and it was rolled back whole; nothing was written \u2014 retry it",data:EdgeWriteDeadlockDataSchema}},assetsContract=oc.router({list:oc.output(external_exports.array(AssetRefSchema)),snapshot:oc.input(SnapshotAskSchema2).output(EntitySnapshotRefSchema).errors({NOT_FOUND:{message:"The entity to snapshot does not exist"}}),crud:oc.router({create:oc.input(GovernedCreateAssetInputSchema).output(AssetSchema),get:oc.input(GetAssetInputSchema).output(AssetReadSchema),list:oc.input(ListAssetsInputSchema).output(ListAssetsOutputSchema).errors({...READ_TX_BUDGET_ERRORS,...CONDITION_ERRORS}),distinctValues:oc.input(AssetDistinctValuesInputSchema).output(AssetDistinctValuesOutputSchema).errors({...READ_TX_BUDGET_ERRORS,...CONDITION_ERRORS}),index:oc.input(ListAssetIndexInputSchema).output(ListAssetIndexOutputSchema).errors({...READ_TX_BUDGET_ERRORS,...CONDITION_ERRORS}),count:oc.input(AssetCountInputSchema).output(AssetCountOutputSchema).errors(READ_TX_BUDGET_ERRORS),exportEstimate:exportEstimateProcedure,exportStatus:oc.input(AssetExportStatusInputSchema).output(AssetExportStatusSchema),export:oc.input(AssetExportInputSchema).output(AssetExportHandleSchema).errors({OVER_CAP:{status:422,message:"The selection exceeds this deployment\u2019s export row cap; narrow it with filters or a subtree scope",data:AssetExportOverCapDataSchema},EMPTY_RESULT:{status:422,message:"The selection matches no assets; nothing to export"},FORMAT_UNAVAILABLE:{status:422,message:"This format is not available yet; export as CSV"},TOO_MANY_COLUMNS:{status:422,message:"The selection exceeds this deployment\u2019s export column cap; narrow it to assets with fewer distinct properties"},SERVICE_UNAVAILABLE:{message:"exports are not available on this deployment \u2014 the export object store is not configured for it",data:ExportStoreUnavailableDataSchema}}),locations:locationsProcedure,update:oc.input(GovernedUpdateAssetInputSchema).output(AssetSchema),delete:oc.input(GovernedDeleteAssetInputSchema).output(AssetSchema).errors(EDGE_WRITE_DEADLOCK_ERRORS),deleteImpact:oc.input(DeleteImpactInputSchema).output(DeleteImpactOutputSchema),deleteMany:oc.input(DeleteManyInputSchema).output(DeleteManyOutputSchema),setLocation:oc.input(GovernedSetAssetLocationInputSchema).output(AssetSchema),setLocationMany:oc.input(SetLocationManyInputSchema).output(SetLocationManyOutputSchema),...datedValueProcedures,versions:oc.input(ListAssetVersionsInputSchema).output(external_exports.array(AssetSchema)),activity:oc.input(ListAssetActivityInputSchema).output(RecordsPageSchema),provenanceDirectory:oc.input(ProvenanceDirectoryInputSchema).output(ProvenanceDirectoryOutputSchema),externalIdDirectory:oc.input(ExternalIdDirectoryInputSchema).output(ExternalIdDirectoryOutputSchema),summary:oc.output(AssetSummarySchema),summaryFiltered:oc.input(AssetListFilterSchema).output(AssetSummarySchema).errors({...READ_TX_BUDGET_ERRORS,...CONDITION_ERRORS}),summaryByCategory:oc.output(AssetCategorySummarySchema)}),spatial:assetsSpatialContract,vocabulary:oc.router({category:oc.router({create:oc.input(CreateAssetCategoryInputSchema).output(AssetCategorySchema),update:oc.input(UpdateAssetCategoryInputSchema).output(AssetCategorySchema),get:oc.input(GetAssetCategoryInputSchema).output(AssetCategorySchema),list:oc.input(ListAssetCategoriesInputSchema).output(external_exports.array(AssetCategorySchema)),delete:oc.input(DeleteAssetCategoryInputSchema).output(AssetCategorySchema)}),type:oc.router({create:oc.input(CreateAssetTypeInputSchema).output(AssetTypeSchema),update:oc.input(UpdateAssetTypeInputSchema).output(AssetTypeSchema),get:oc.input(GetAssetTypeInputSchema).output(AssetTypeSchema),list:oc.input(ListAssetTypesInputSchema).output(external_exports.array(AssetTypeSchema)),delete:oc.input(DeleteAssetTypeInputSchema).output(AssetTypeSchema)}),template:oc.router({get:oc.input(GetAssetTemplateInputSchema).output(AssetTemplateVersionSchema),set:oc.input(SetAssetTemplateInputSchema).output(AssetTemplateVersionSchema)}),deriveTemplateMany:oc.input(DeriveTemplateManyInputSchema).output(DeriveTemplateManyOutputSchema)}),relationships:oc.router({...parentLinkProcedures,create:oc.input(CreateRelationshipWireInputSchema).output(CreateAssetRelationshipOutputSchema).errors(EDGE_WRITE_DEADLOCK_ERRORS),end:oc.input(EndAssetRelationshipInputSchema).output(AssetRelationshipWriteResultSchema).errors(EDGE_WRITE_DEADLOCK_ERRORS),move:oc.input(MoveRelationshipWireInputSchema).output(MoveRelationshipOutputSchema).errors(EDGE_WRITE_DEADLOCK_ERRORS),moveMany:oc.input(MoveManyInputSchema).output(MoveManyResponseSchema).errors(EDGE_WRITE_DEADLOCK_ERRORS),createMany:oc.input(RelateManyInputSchema).output(RelateManyResponseSchema).errors(EDGE_WRITE_DEADLOCK_ERRORS),endMany:oc.input(UnlinkManyInputSchema).output(UnlinkManyResponseSchema).errors(EDGE_WRITE_DEADLOCK_ERRORS),listFor:oc.input(ListAssetRelationshipsInputSchema).output(external_exports.array(AssetRelationshipSchema)),parents:oc.input(RelationshipNeighborsInputSchema).output(external_exports.array(HierarchyBrowseNodeSchema)),children:oc.input(RelationshipNeighborsInputSchema).output(external_exports.array(HierarchyBrowseNodeSchema)).errors(READ_TX_BUDGET_ERRORS),subtree:oc.input(AssetSubtreeInputSchema).output(AssetSubtreeOutputSchema).errors({...WALK_OVER_CAP_ERRORS,...READ_TX_BUDGET_ERRORS}),...assetsDescendantsProcedures,ancestors:oc.input(AssetAncestorsInputSchema).output(AssetAncestorsOutputSchema).errors({...WALK_OVER_CAP_ERRORS,...READ_TX_BUDGET_ERRORS}),ancestorsMany:oc.input(RelationshipAncestorsManyInputSchema).output(RelationshipAncestorsManyOutputSchema).errors({...WALK_OVER_CAP_ERRORS,...READ_TX_BUDGET_ERRORS}),descendantCounts:oc.input(DescendantCountsInputSchema).output(DescendantCountsOutputSchema).errors(READ_TX_BUDGET_ERRORS),roots:oc.input(RelationshipRootsInputSchema).output(RelationshipRootsOutputSchema).errors(READ_TX_BUDGET_ERRORS),hasChildren:oc.input(RelationshipHasChildrenInputSchema).output(RelationshipHasChildrenOutputSchema),descendantGeometry:oc.input(DescendantGeometryInputSchema).output(DescendantGeometryOutputSchema)}),hierarchies:oc.router({create:oc.input(CreateHierarchyInputSchema).output(HierarchySchema),list:oc.input(ListHierarchiesInputSchema).output(ListHierarchiesOutputSchema)}),composition:oc.router({...assetsImportPreflightProcedures,createMany:oc.input(CreateManyInputSchema).output(CreateManyOutputSchema).errors({BAD_REQUEST:{message:"The import was refused whole; nothing was written"},CONFLICT:{message:"The estate changed under this import; nothing was written"},...EDGE_WRITE_DEADLOCK_ERRORS,PLACEMENT_NOT_DECLARED:{status:422,message:"this import declares no placement \u2014 configure a `relationships` mapping, or set `noHierarchy: true` if it is deliberately flat"},DATASET_VERSION_ALREADY_IMPORTED:{status:409,message:"this dataset version was already imported \u2014 pass `duplicateAnyway: true` to import it again",data:DatasetVersionAlreadyImportedSchema}}),validate:oc.input(ValidateCreateManyInputSchema).output(ValidateCreateManyReportSchema).errors({ROWS_MODE_OVER_CAP:{status:422,message:'this source has more rows than a row-by-row preflight can classify in one request \u2014 re-run with mode: "counts", which counts distinct external-ID keys rather than rows and so answers deliveries this mode refuses, or validate a rows tile',data:ValidateRowsModeOverCapSchema},COUNTS_MODE_UNAVAILABLE:{status:422,message:'this source cannot answer a DISTINCT over the external-ID column, which is the one read mode: "counts" is built on \u2014 re-run with mode: "rows", which reads rows and has no such dependency',data:ValidateCountsUnavailableSchema},COUNTS_KEY_SET_OVER_CAP:{status:422,message:"this delivery names more distinct external IDs than a counts preflight reads completely \u2014 refused rather than answered over part of the key set, which would report every unread key as both a create and an absent asset: validate a rows tile of the part you need",data:ValidateCountsKeySetOverCapSchema}}),preflight:oc.input(TypePreflightInputSchema).output(TypePreflightResultSchema),createUnresolvedType:oc.input(CreateTypeFromValueInputSchema).output(CreateTypeFromValueResultSchema),startJob:oc.input(StartCompositionJobInputSchema).output(StartCompositionJobResultSchema).errors({DELIVERY_THRESHOLD_BREACHED:{status:422,message:"A delivery threshold on this import mapping was breached; nothing was imported",data:DeliveryThresholdBreachSchema},PLACEMENT_NOT_DECLARED:{status:422,message:"this import declares no placement \u2014 configure a `relationships` mapping, or set `noHierarchy: true` if it is deliberately flat"},DATASET_VERSION_ALREADY_IMPORTED:{status:409,message:"this dataset version was already imported \u2014 pass `duplicateAnyway: true` to import it again",data:DatasetVersionAlreadyImportedSchema}}),...revertDatedValuesProcedures,startImport:oc.input(StartImportInputSchema).output(StartCompositionJobResultSchema).errors({DELIVERY_THRESHOLD_BREACHED:{status:422,message:"A delivery threshold on this import mapping was breached; nothing was imported",data:DeliveryThresholdBreachSchema},PLACEMENT_NOT_DECLARED:{status:422,message:"this import declares no placement \u2014 configure a `relationships` mapping, or set `noHierarchy: true` if it is deliberately flat"},DATASET_VERSION_ALREADY_IMPORTED:{status:409,message:"this dataset version was already imported \u2014 pass `duplicateAnyway: true` to import it again",data:DatasetVersionAlreadyImportedSchema}}),jobStatus:oc.input(CompositionJobStatusInputSchema).output(CompositionJobStatusSchema),listJobs:oc.input(ListCompositionJobsInputSchema).output(external_exports.array(CompositionJobSummarySchema))}),teardown:oc.router({preview:oc.input(TeardownPreviewInputSchema).output(TeardownPreviewResultSchema),startJob:oc.input(StartTeardownJobInputSchema).output(StartTeardownJobResultSchema),jobStatus:oc.input(TeardownJobStatusInputSchema).output(TeardownJobStatusSchema),listJobs:oc.input(ListTeardownJobsInputSchema).output(external_exports.array(TeardownJobSummarySchema))}),importExceptions:oc.router({listRuns:oc.input(ListImportRunsInputSchema).output(ListImportRunsOutputSchema),list:oc.input(ListImportExceptionsInputSchema).output(ListImportExceptionsOutputSchema),resolve:oc.input(ResolveImportExceptionInputSchema).output(ResolveImportExceptionOutputSchema),resolveMany:oc.input(ResolveManyImportExceptionsInputSchema).output(ResolveManyImportExceptionsOutputSchema),getRetryPlan:oc.input(GetImportRunRetryPlanInputSchema).output(ImportRunRetryPlanSchema)}),importMapping:oc.router({save:oc.input(SaveAssetImportMappingInputSchema).output(AssetImportMappingSchema),get:oc.input(GetAssetImportMappingInputSchema).output(AssetImportMappingSchema),list:oc.output(ListAssetImportMappingsOutputSchema)}),lifecycle:oc.router({saveRules:oc.input(SaveLifecycleRulesInputSchema).output(LifecycleRulesSchema),savePolicy:oc.input(SaveLifecyclePolicyInputSchema).output(LifecyclePolicyOverlaySchema),getPolicy:oc.output(LifecyclePolicyViewSchema)}),quality:assetsQualityContract,access:assetsAccessContract,placements:assetsPlacementsContract,numbering:oc.router({saveConfig:oc.input(SaveNumberingConfigInputSchema).output(NumberingConfigSchema),getConfig:oc.output(NumberingConfigSchema.nullable()),suggest:oc.input(SuggestAssetCodeInputSchema).output(SuggestAssetCodeResultSchema)}),nestingRules:oc.router({save:oc.input(SaveNestingRulesInputSchema).output(NestingRulesSchema),get:oc.output(NestingRulesSchema.nullable())}),system:assetsSystemContract,externalId:assetsExternalIdContract,derivedProperties:oc.router({get:oc.input(GetDerivedPropertiesInputSchema).output(DerivedPropertiesSchema)}),derivedValues:oc.router({list:oc.input(ListDerivedValuesInputSchema).output(external_exports.array(DerivedValueSchema)),apply:oc.input(ApplyDerivedValuesInputSchema).output(ApplyDerivedValuesReportSchema),getRouting:oc.output(DerivedRoutingConfigSchema),saveRouting:oc.input(SaveDerivedRoutingInputSchema).output(DerivedRoutingConfigSchema),due:oc.output(external_exports.array(DueDerivedApplySchema))}),views:oc.router({create:oc.input(CreateSavedViewInputSchema2).output(SavedViewSchema2),list:oc.input(ListSavedViewsInputSchema2).output(external_exports.array(SavedViewSchema2)),update:oc.input(UpdateSavedViewInputSchema2).output(SavedViewSchema2),delete:oc.input(DeleteSavedViewInputSchema2).output(SavedViewSchema2)}),preferences:oc.router({get:oc.input(GetTablePreferencesInputSchema2).output(TablePreferencesSchema2.nullable()),set:oc.input(SetTablePreferencesInputSchema2).output(TablePreferencesSchema2)}),directory:oc.router({status:oc.output(DirectoryPublishStatusSchema),publishNow:oc.input(PublishDirectoryInputSchema).output(PublishDirectoryResultSchema),getSchedule:oc.output(DirectoryScheduleReadSchema),setSchedule:oc.input(SetDirectoryScheduleInputSchema).output(DirectoryScheduleSchema)})});var PERIOD_TOKEN=/^\d{4}(-(0[1-9]|1[0-2]))?$/;function utcFromParts(year,monthIndex2,day,hour=0,minute=0,second=0){let at=new Date(0);return at.setUTCFullYear(year,monthIndex2,day),at.setUTCHours(hour,minute,second,0),at.getTime()}var SELECTABLE_ZONES=new Set(["UTC",...Intl.supportedValuesOf("timeZone")]),CANONICAL_ZONES=new Map,CANONICAL_ZONES_MAX=2e3;function resolveZone(timeZone){let memo2=CANONICAL_ZONES.get(timeZone);if(memo2!==void 0)return memo2;let resolved=new Intl.DateTimeFormat("en-US",{timeZone}).resolvedOptions().timeZone;return CANONICAL_ZONES.size<CANONICAL_ZONES_MAX&&CANONICAL_ZONES.set(timeZone,resolved),resolved}var WALL_CLOCK_FORMATTERS=new Map;function wallClockFormatter(canonical){let cached2=WALL_CLOCK_FORMATTERS.get(canonical);if(cached2!==void 0)return cached2;let built=new Intl.DateTimeFormat("en-US",{timeZone:canonical,hour12:!1,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"});return WALL_CLOCK_FORMATTERS.set(canonical,built),built}function zoneOffsetMs(timeZone,atMs){let parts=wallClockFormatter(timeZone).formatToParts(new Date(atMs)),read=type=>Number(parts.find(part2=>part2.type===type)?.value),hour=read("hour")%24;return utcFromParts(read("year"),read("month")-1,read("day"),hour,read("minute"),read("second"))-Math.floor(atMs/1e3)*1e3}function zonedDayStartMs(timeZone,year,monthIndex2,day){let zone=checkedZone(timeZone),wallClock=utcFromParts(year,monthIndex2,day);if(zone==="UTC")return wallClock;let memoKey=`${zone}|${wallClock}`,memo2=DAY_STARTS.get(memoKey);if(memo2!==void 0)return memo2;let resolved=localMidnight(zone,wallClock);return DAY_STARTS.size<DAY_STARTS_MAX&&DAY_STARTS.set(memoKey,resolved),resolved}var DAY_STARTS=new Map,DAY_STARTS_MAX=1e4,PROBE_MS=864e5;function localMidnight(zone,wallClock){let fromBefore=wallClock-zoneOffsetMs(zone,wallClock-PROBE_MS),fromAfter=wallClock-zoneOffsetMs(zone,wallClock+PROBE_MS),earlier=Math.min(fromBefore,fromAfter),later=Math.max(fromBefore,fromAfter),renders=at=>wallClock-at===zoneOffsetMs(zone,at);return renders(earlier)?earlier:(renders(later),later)}function checkedZone(timeZone){if(timeZone===void 0)return"UTC";let canonical;try{canonical=resolveZone(timeZone)}catch{canonical=void 0}if(canonical===void 0||!SELECTABLE_ZONES.has(canonical))throw new Error(`unknown time zone "${timeZone}" \u2014 expected an IANA id (e.g. America/Denver); an unknown zone is never read as UTC`);return canonical}var checkedTokenBrand=Symbol("calculations.periodInstant.checkedPeriodToken"),MIN_PERIOD_YEAR=100,MAX_PERIOD_YEAR=9998;function tokenSpan(checked,timeZone){let[yearPart,monthPart]=checked.token.split("-"),year=Number(yearPart);if(checked.token.includes("-")){let monthIndex2=Number(monthPart)-1;return{firstMs:zonedDayStartMs(timeZone,year,monthIndex2,1),lastMs:zonedDayStartMs(timeZone,year,monthIndex2+1,1)-1}}return{firstMs:zonedDayStartMs(timeZone,year,0,1),lastMs:zonedDayStartMs(timeZone,year+1,0,1)-1}}var PERIOD_BOUND=/^\d{4}(-(0[1-9]|1[0-2])(-(0[1-9]|[12]\d|3[01]))?)?$/;function checkPeriodBound(bound){if(!PERIOD_BOUND.test(bound))return;let[yearPart,monthPart,dayPart]=bound.split("-"),year=Number(yearPart);if(!(year<MIN_PERIOD_YEAR||year>MAX_PERIOD_YEAR)){if(dayPart!==void 0){let lastDay=new Date(Date.UTC(year,Number(monthPart),0)).getUTCDate();if(Number(dayPart)>lastDay)return}return{token:bound,[checkedTokenBrand]:!0}}}function boundSpan(checked,timeZone){let[yearPart,monthPart,dayPart]=checked.token.split("-");if(dayPart===void 0)return tokenSpan(checked,timeZone);let year=Number(yearPart),monthIndex2=Number(monthPart)-1,day=Number(dayPart);return{firstMs:zonedDayStartMs(timeZone,year,monthIndex2,day),lastMs:zonedDayStartMs(timeZone,year,monthIndex2,day+1)-1}}function periodBoundSpan(bound,timeZone){let zone=checkedZone(timeZone),checked=checkPeriodBound(bound);return checked===void 0?void 0:boundSpan(checked,zone)}var CadenceSchema=external_exports.enum(["monthly","quarterly","annual"]),CadenceUnitSchema=external_exports.enum(["month","week"]),ANCHOR_YEAR=String.raw`(?:0[1-9]\d{2}|[1-9]\d{3})`,ANCHOR_DATE=new RegExp(`^${ANCHOR_YEAR}-(0[1-9]|1[0-2])-(0[1-9]|[12]\\d|3[01])$`),MONTH_ANCHOR_DATE=new RegExp(`^${ANCHOR_YEAR}-(0[1-9]|1[0-2])-01$`),INTERVAL=external_exports.number().int().min(1).max(60),WEEK_ANCHOR_MESSAGE='A weekly cadence needs a start day: nothing in the calendar says which day a week begins, so "every N weeks" names no periods until one is chosen.',MONTH_ANCHOR_MESSAGE="A fiscal cadence's start must be the first of a month \u2014 a period running the 15th to the 14th is a rolling window, which is not built.",anchorDenotes=anchor2=>anchor2===void 0||periodBoundSpan(anchor2)!==void 0,REAL_DAY="the anchor is not a date this domain can denote: it must name a day that exists (2025-02-30 would otherwise roll over to 2 March and phase every period the project ever generates)",WeekCadenceRuleSchema=external_exports.object({unit:external_exports.literal("week"),interval:INTERVAL,anchor:external_exports.string().regex(ANCHOR_DATE,{message:WEEK_ANCHOR_MESSAGE})}),MonthCadenceRuleSchema=external_exports.object({unit:external_exports.literal("month"),interval:INTERVAL,anchor:external_exports.string().regex(MONTH_ANCHOR_DATE,{message:MONTH_ANCHOR_MESSAGE}).optional()}),CadenceRuleSchema=external_exports.discriminatedUnion("unit",[WeekCadenceRuleSchema,MonthCadenceRuleSchema]).refine(rule=>anchorDenotes(rule.anchor),{path:["anchor"],message:REAL_DAY}),UNPHASED_MONTHS_MESSAGE="A month cadence without a starting month must divide the year evenly (every 1, 2, 3, 4, 6 or 12 months). Choose the month its periods start from.";function calendarPhasesMonths(cadence){if(typeof cadence=="string"||cadence.unit!=="month"||cadence.anchor!==void 0)return!0;let{interval}=cadence;return!Number.isInteger(interval)||interval<1?!0:12%interval===0}var CADENCE_RULES=Object.freeze({monthly:CadenceRuleSchema.parse({unit:"month",interval:1}),quarterly:CadenceRuleSchema.parse({unit:"month",interval:3}),annual:CadenceRuleSchema.parse({unit:"month",interval:12})}),CadenceSpecSchema=external_exports.union([CadenceSchema,CadenceRuleSchema]),RULES_BY_NAME=new Map(Object.entries(CADENCE_RULES));function cadenceRule(cadence){return typeof cadence=="string"?RULES_BY_NAME.get(cadence):cadence}var EnteredPeriodSchema=external_exports.object({start:external_exports.iso.date(),end:external_exports.iso.date()});function enteredPeriodsIssue(periods){for(let[index,period]of periods.entries()){for(let field of["start","end"])if(periodBoundSpan(period[field])===void 0)return{index,field,message:`Period ${String(index+1)} has a ${field} date this system cannot record: ${period[field]}. Enter a real day from the year 0100 on.`};if(period.end<period.start)return{index,field:"end",message:`Period ${String(index+1)} ends on ${period.end}, before it starts on ${period.start}. A period's last day must be on or after its first.`}}let ordered=periods.map((period,index)=>({period,index})).toSorted((left,right)=>left.period.start.localeCompare(right.period.start));for(let at=1;at<ordered.length;at+=1){let earlier=ordered[at-1],later=ordered[at];if(!(earlier===void 0||later===void 0)&&later.period.start<=earlier.period.end)return{index:later.index,field:"start",message:`Periods ${String(earlier.index+1)} and ${String(later.index+1)} overlap: ${earlier.period.start} to ${earlier.period.end} and ${later.period.start} to ${later.period.end} share at least one day, which a roll-up would count twice. Change one so they do not share a day.`}}}var PROJECT_ENTITY_HINT={entity:{domain:"calculations",type:"project"},pickerResource:"calculations"},RUN_ENTITY_HINT={entity:{domain:"calculations",type:"run"},pickerResource:"calculation-run"},ProjectIdSchema=external_exports.string().min(1).brand().meta(PROJECT_ENTITY_HINT),RunIdSchema=external_exports.string().min(1).brand().meta(RUN_ENTITY_HINT),CallerMintedKeySchema2=IdempotencyKeySchema.max(200).describe("Client-minted replay key \u2014 REQUIRED by every governed write in this domain. Mint ONE per intent (a UUID is fine) and reuse it only to re-send that identical intent. Once a call has COMPLETED, reusing its key returns the original receipt without re-executing; a call that was REFUSED consumed nothing, so the same key is free to run again. `runs.trigger` adds a third state, because it opens and seals across two transactions: a key whose run is still IN FLIGHT resumes that run, re-executing over the inputs it pinned when it opened rather than resolving them afresh \u2014 and a key reused with a different project or period is refused with RUN_KEY_PARAM_MISMATCH rather than answering for the wrong run. The lifecycle verbs projects.activate, projects.archive and runs.cancel add two states of their own: a key reused against a DIFFERENT target is refused with KEY_PARAM_MISMATCH, and a NEW key naming a target that was already activated / archived / cancelled under some other key answers from that original action and records a no-op receipt under your key rather than acting twice."),DeclarationIdSchema=external_exports.string().min(1).brand(),DeclarationVersionIdSchema=external_exports.string().min(1).brand();var PERIOD_ENTITY_HINT={entity:{domain:"calculations",type:"period"},pickerResource:"calculation-period",scopedBy:{projectId:"projectId"}},PeriodIdSchema=external_exports.string().min(1).brand().meta(PERIOD_ENTITY_HINT),LISTED_PERIODS_MAX=500,PeriodStatusSchema=external_exports.enum(["open","closed","locked","reopened","superseded"]),FigureBasisSchema=external_exports.enum(["filed","current","none"]),basisHoldsFigures=basis=>basis==="filed"||basis==="current";function periodAnnotationsCohere(period,ctx){period.childCount===void 0!=(period.childrenSignedOff===void 0)&&ctx.addIssue({code:"custom",path:["childrenSignedOff"],message:"childCount and childrenSignedOff are read together: both present or both absent"}),period.childCount!==void 0&&period.childrenSignedOff!==void 0&&period.childrenSignedOff>period.childCount&&ctx.addIssue({code:"custom",path:["childrenSignedOff"],message:"more children signed off than the period has children"}),period.figureCount!==void 0!==basisHoldsFigures(period.figureBasis)&&ctx.addIssue({code:"custom",path:["figureCount"],message:"figureCount is present exactly when figureBasis is filed or current"}),figureAnnotationsCohere(period,ctx)}function figureAnnotationsCohere(period,ctx){period.figureRunId!==void 0!==basisHoldsFigures(period.figureBasis)&&ctx.addIssue({code:"custom",path:["figureRunId"],message:"figureRunId is present exactly when figureBasis is filed or current"}),period.figureVersion!==void 0!=(period.figureBasis==="filed")&&ctx.addIssue({code:"custom",path:["figureVersion"],message:"figureVersion is present exactly when figureBasis is filed"}),period.correctionRunId!==void 0&&(period.status!=="reopened"||period.figureBasis!=="filed"||period.correctionRunId===period.figureRunId)&&ctx.addIssue({code:"custom",path:["correctionRunId"],message:"correctionRunId is only on a reopened period with a filed basis, and is never the filed run"})}var PeriodSchema=external_exports.object({id:PeriodIdSchema,projectId:ProjectIdSchema,projectName:external_exports.string().min(1).optional(),periodKey:external_exports.string().min(1),start:external_exports.string().min(1),end:external_exports.string().min(1),status:PeriodStatusSchema,childrenUnsigned:external_exports.boolean().optional(),childCount:external_exports.number().int().nonnegative().optional(),childrenSignedOff:external_exports.number().int().nonnegative().optional(),figureBasis:FigureBasisSchema.optional(),figureCount:external_exports.number().int().nonnegative().optional(),figureRunId:external_exports.string().min(1).optional(),figureVersion:external_exports.number().int().positive().optional(),correctionRunId:external_exports.string().min(1).optional()}).superRefine(periodAnnotationsCohere);var TOKEN=/^(\d{4})(?:-(\d{2}))?$/;function parseToken(token,defaultMonth){let match=TOKEN.exec(token);if(!match)throw new Error(`invalid window token: ${token}`);let year=Number(match[1]),month=match[2]===void 0?defaultMonth:Number(match[2]);if(month<1||month>12)throw new Error(`invalid month in window token: ${token}`);return{year,month}}var dateToken=(year,month,day)=>`${String(year).padStart(4,"0")}-${String(month).padStart(2,"0")}-${String(day).padStart(2,"0")}`;function utcDayMs(year,month,day){let at=new Date(0);return at.setUTCFullYear(year,month-1,day),at.getTime()}var lastDayOfMonth=(year,month)=>new Date(utcDayMs(year,month+1,0)).getUTCDate();var MAX_PROJECT_PERIODS=LISTED_PERIODS_MAX;function generatedPeriodCount(schedule){if(schedule.kind==="entered")return schedule.periods.length;let walk=scheduleWalk(schedule);return walk===void 0||walk.first>walk.last?0:Math.floor((walk.last-walk.first)/walk.step)+1}function scheduleWalk(schedule){let start=parseToken(schedule.window.start,1),end=parseToken(schedule.window.end,12);if(monthIndex(end)<monthIndex(start))return;let rule=cadenceRule(schedule.cadence);if(rule!==void 0){if(!Number.isInteger(rule.interval)||rule.interval<1)throw new Error(`generatePeriods: a cadence interval must be a whole number of at least 1, got ${String(rule.interval)}`);return rule.unit==="month"?monthWalk(rule,start,end):rule.anchor===void 0?void 0:weekWalk(rule,start,end)}}function monthWalk(rule,start,end){return{unit:"month",rule,first:monthStartIndex(rule,monthIndex(start)),last:monthIndex(end),step:rule.interval}}function weekWalk(rule,start,end){let windowStart=dayNumber(dateToken(start.year,start.month,1)),anchor2=dayNumber(rule.anchor),step=rule.interval*DAYS_PER_WEEK;return{unit:"week",anchor:anchor2,first:anchor2+Math.ceil((windowStart-anchor2)/step)*step,last:dayNumber(dateToken(end.year,end.month,lastDayOfMonth(end.year,end.month))),step}}var DAYS_PER_WEEK=7,MS_PER_DAY=864e5;function dayNumber(date5){let[year,month,day]=date5.split("-").map(Number);return Math.floor(utcDayMs(year??0,month??1,day??1)/MS_PER_DAY)}function monthStartIndex(rule,startIdx){if(rule.anchor===void 0)return Math.floor(startIdx/rule.interval)*rule.interval;let anchorIdx=anchorMonthIndex(rule),steps=Math.floor((startIdx-anchorIdx)/rule.interval);return anchorIdx+steps*rule.interval}function anchorMonthIndex(rule){if(rule.anchor===void 0)return 0;let[year,month]=rule.anchor.split("-").map(Number);return(year??0)*12+((month??1)-1)}var monthIndex=at=>at.year*12+(at.month-1);var RunStatusSchema2=external_exports.enum(["PENDING","RUNNING","COMPLETED","FAILED","CANCELLED"]),ExecStatusSchema=RunStatusSchema2.extract(["COMPLETED","FAILED"]),ReceiptStateSchema=external_exports.enum(["pending","promoted","promotedEmpty","unreceipted"]),ResultsPublishingSchema=external_exports.enum(["publishing","not-published"]);var BasisAbsenceReasonSchema=external_exports.enum(["no-earlier-period","no-earlier-run","no-approved-basis","basis-unavailable","basis-loading"]);var CloseBasisAbsenceSchema=external_exports.enum(["no-earlier-period","no-signed-basis"]);var AS_OF_IN_FUTURE_MESSAGE="The instant to read at is later than now.",DecisionSubjectSchema=external_exports.enum(["period","run"]),DecisionBasisInputSchema=external_exports.strictObject({periodId:PeriodIdSchema,runId:RunIdSchema,subject:DecisionSubjectSchema.optional(),asOf:external_exports.iso.datetime().optional()}),requestedAt=external_exports.iso.datetime({offset:!0}).nullable(),DecisionBasisSchema=external_exports.discriminatedUnion("kind",[external_exports.strictObject({kind:external_exports.literal("own-close"),runId:external_exports.string().min(1),version:external_exports.number().int().positive(),closedAt:external_exports.string().min(1),requestedAt}),external_exports.strictObject({kind:external_exports.literal("signed-period"),periodKey:external_exports.string().min(1),runId:external_exports.string().min(1),version:external_exports.number().int().positive().nullable(),closedAt:external_exports.string().min(1).nullable(),approvedAt:external_exports.string().min(1).optional(),requestedAt}),external_exports.strictObject({kind:external_exports.literal("absent"),reason:CloseBasisAbsenceSchema,requestedAt})]);var READ_ELEMENT_ID_PATTERN=/^(?:[^\u0000\uD800-\uDFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF])+$/,ReadElementIdSchema=external_exports.string().min(1).regex(READ_ELEMENT_ID_PATTERN,"An element id may not hold a NUL or an unpaired surrogate").brand();var ResultBehaviourSchema=external_exports.discriminatedUnion("kind",[external_exports.strictObject({kind:external_exports.literal("adds-up")}),external_exports.strictObject({kind:external_exports.literal("ratio-from-totals"),numerator:external_exports.string().min(1).describe("The result whose total is divided. It must add up."),denominator:external_exports.string().min(1).describe("The result whose total divides. It must add up."),scale:external_exports.number().positive().describe("Multiplies the quotient of the two totals into `unit`: 1000 for t \xF7 BOE as kg/BOE."),unit:external_exports.string().min(1).describe("The unit the ratio files in: the result\u2019s own unit.")}),external_exports.strictObject({kind:external_exports.literal("per-asset-only")})]);function canonicalDecimal2(decimal){let trimmed=decimal.trim(),match=/^([+-]?)(\d*)(?:\.(\d*))?(?:[eE]([+-]?\d{1,6}))?$/.exec(trimmed);if(match===null||!/\d/.test(trimmed.split(/[eE]/)[0]??""))throw new Error(`not a decimal: '${decimal}'`);let[,sign="",whole="",fraction="",exponent="0"]=match,digits=`${whole}${fraction}`,point=whole.length+Number(exponent),padded=point<=0?`0.${"0".repeat(-point)}${digits}`:point>=digits.length?`${digits}${"0".repeat(point-digits.length)}`:`${digits.slice(0,point)}.${digits.slice(point)}`,[intPart="",fracPart=""]=padded.split("."),int2=intPart.replace(/^0+(?=\d)/,"")||"0",frac=fracPart.replace(/0+$/,""),body=frac===""?int2:`${int2}.${frac}`;return body==="0"||sign!=="-"?body:`-${body}`}function exactOf(decimal){let canonical=canonicalDecimal2(decimal),negative=canonical.startsWith("-"),[whole="0",fraction=""]=(negative?canonical.slice(1):canonical).split("."),units=BigInt(`${whole}${fraction}`);return{units:negative?-units:units,scale:fraction.length}}var MAX_FINITE_DECIMAL="1.7976931348623157e308",MAX_FINITE=exactOf(MAX_FINITE_DECIMAL);var ADDS_UP={kind:"adds-up"},INTENSITY={kind:"ratio-from-totals",numerator:"CO2e_t",denominator:"Production_BOE",scale:1e3,unit:"kg CO2e/BOE"},BEHAVIOURS={CO2e_t:ADDS_UP,Production_BOE:ADDS_UP,Intensity:INTENSITY,Factor:{kind:"per-asset-only"}},t=value2=>({value:value2,unit:"t CO2e"}),boe=value2=>({value:value2,unit:"BOE"}),qt=value2=>({kind:"quantity",value:value2,unit:"t CO2e"}),qBoe=value2=>({kind:"quantity",value:value2,unit:"BOE"}),qKg=value2=>({kind:"quantity",value:value2,unit:"kg CO2e/BOE"}),none=reason=>({kind:"empty",reason}),NESTED={kind:"ratio-from-totals",numerator:"Intensity",denominator:"Production_BOE",scale:1,unit:"kg CO2e/BOE per BOE"},NESTED_CELLS={a:{CO2e_t:t("10"),Production_BOE:boe("100")},b:{CO2e_t:t("30"),Production_BOE:boe("900")}},NESTED_EXPECTED={N:{CO2e_t:qt("40"),Production_BOE:qBoe("1000"),Intensity:qKg("40"),Nested:none("numeratorMissing")}},ROLLUP_CONFORMANCE_CASES=[{name:"a sum is exact and does not depend on row order",behaviours:{CO2e_t:ADDS_UP},members:{N:["a","b","c"]},cells:{a:{CO2e_t:t("10000000000000000")},b:{CO2e_t:t("1")},c:{CO2e_t:t("-10000000000000000")}},expected:{N:{CO2e_t:qt("1")}}},{name:"a sum keeps decimals binary floating point cannot hold",behaviours:{CO2e_t:ADDS_UP},members:{N:["a","b"]},cells:{a:{CO2e_t:t("0.1")},b:{CO2e_t:t("0.2")}},expected:{N:{CO2e_t:qt("0.3")}}},{name:"a ratio divides the totals, never the mean of the members\u2019 ratios",behaviours:BEHAVIOURS,members:{N:["a","b"]},cells:{a:{CO2e_t:t("10"),Production_BOE:boe("100"),Factor:t("0.5")},b:{CO2e_t:t("30"),Production_BOE:boe("900"),Factor:t("0.7")}},expected:{N:{CO2e_t:qt("40"),Production_BOE:qBoe("1000"),Intensity:qKg("40")}}},{name:"a zero denominator is empty, never 0, and the level above still answers",behaviours:BEHAVIOURS,members:{SOUTH:["c"],USA:["a","c"]},cells:{a:{CO2e_t:t("30"),Production_BOE:boe("400")},c:{CO2e_t:t("12"),Production_BOE:boe("0")}},expected:{SOUTH:{CO2e_t:qt("12"),Production_BOE:qBoe("0"),Intensity:none("denominatorZero")},USA:{CO2e_t:qt("42"),Production_BOE:qBoe("400"),Intensity:qKg("105")}}},{name:"a ratio over another ratio has no numerator: the other ratio listed first",behaviours:{...BEHAVIOURS,Nested:NESTED},members:{N:["a","b"]},cells:NESTED_CELLS,expected:NESTED_EXPECTED},{name:"a ratio over another ratio has no numerator: the other ratio listed after",behaviours:{Nested:NESTED,...BEHAVIOURS},members:{N:["a","b"]},cells:NESTED_CELLS,expected:NESTED_EXPECTED},{name:"a part no member filed leaves the ratio empty with its reason",behaviours:BEHAVIOURS,members:{N:["a"]},cells:{a:{CO2e_t:t("5")}},expected:{N:{CO2e_t:qt("5"),Intensity:none("denominatorMissing")}}},{name:"blank members are skipped; a node whose members are all blank is empty, not nothing",behaviours:BEHAVIOURS,members:{SOME:["a","b"],ALL:["b","c"]},cells:{a:{CO2e_t:t("5"),Production_BOE:boe("50")},b:{CO2e_t:{blank:"blankOnError"},Production_BOE:{blank:"blankOnError"}},c:{CO2e_t:{blank:"blankByCondition"},Production_BOE:{blank:"blankOnError"}}},expected:{SOME:{CO2e_t:qt("5"),Production_BOE:qBoe("50"),Intensity:qKg("100")},ALL:{CO2e_t:none("allMembersBlank"),Production_BOE:none("allMembersBlank"),Intensity:none("allMembersBlank")}}},{name:"a sum never adds across units",behaviours:{CO2e_t:ADDS_UP},members:{N:["a","b"]},cells:{a:{CO2e_t:t("1")},b:{CO2e_t:{value:"1000",unit:"kg CO2e"}}},expected:{N:{CO2e_t:none("mixedUnits")}}},{name:"a ratio that does not terminate keeps QUOTIENT_PLACES digits, rounded half away from zero",behaviours:BEHAVIOURS,members:{THIRDS:["a"],SEVENTHS:["b"]},cells:{a:{CO2e_t:t("2"),Production_BOE:boe("3")},b:{CO2e_t:t("100000000000000000"),Production_BOE:boe("7000")}},expected:{THIRDS:{CO2e_t:qt("2"),Production_BOE:qBoe("3"),Intensity:qKg("666.666666666666666666666666666667")},SEVENTHS:{CO2e_t:qt("100000000000000000"),Production_BOE:qBoe("7000"),Intensity:qKg("14285714285714285.714285714285714285714285714286")}}},{name:"a negative ratio rounds half away from zero too, never toward zero or down",behaviours:BEHAVIOURS,members:{BELOW_HALF:["a"],ABOVE_HALF:["b"],HALF:["c"],BOTH:["d"]},cells:{a:{CO2e_t:t("-1"),Production_BOE:boe("3")},b:{CO2e_t:t("2"),Production_BOE:boe("-3")},c:{CO2e_t:t("-1e-33"),Production_BOE:boe("2")},d:{CO2e_t:t("-2"),Production_BOE:boe("-3")}},expected:{BELOW_HALF:{CO2e_t:qt("-1"),Production_BOE:qBoe("3"),Intensity:qKg("-333.333333333333333333333333333333")},ABOVE_HALF:{CO2e_t:qt("2"),Production_BOE:qBoe("-3"),Intensity:qKg("-666.666666666666666666666666666667")},HALF:{CO2e_t:qt("-1e-33"),Production_BOE:qBoe("2"),Intensity:qKg("-0.000000000000000000000000000001")},BOTH:{CO2e_t:qt("-2"),Production_BOE:qBoe("-3"),Intensity:qKg("666.666666666666666666666666666667")}}},{name:"a total past what a JSON number holds is notFinite, a sum or a ratio",behaviours:BEHAVIOURS,members:{SUM:["a","b"],RATIO:["c"]},cells:{a:{CO2e_t:t("1e308"),Production_BOE:boe("1")},b:{CO2e_t:t("1e308"),Production_BOE:boe("1")},c:{CO2e_t:t("1e308"),Production_BOE:boe("0.001")}},expected:{SUM:{CO2e_t:none("notFinite"),Production_BOE:qBoe("2"),Intensity:none("notFinite")},RATIO:{CO2e_t:qt("1e308"),Production_BOE:qBoe("0.001"),Intensity:none("notFinite")}}},{name:"units are trimmed by one rule, and a quantity whose unit trims blank is not filed",behaviours:{CO2e_t:ADDS_UP},members:{PADDED:["a","b"],BLANK:["c","d"],NONE:["e"]},cells:{a:{CO2e_t:{value:"1",unit:" t CO2e\xA0"}},b:{CO2e_t:t("2")},c:{CO2e_t:{value:"5",unit:"\xA0"}},d:{CO2e_t:t("1")},e:{CO2e_t:{value:"7",unit:" "}}},expected:{PADDED:{CO2e_t:qt("3")},BLANK:{CO2e_t:qt("1")}}}];var UNIT_TRIM_CHARACTERS=`
|
|
447
|
+
The default differs from \`createMany\`, where it is \`all\`, ON PURPOSE: the failing rows carry the source data's own values and row keys, so a large preflight answers hundreds of thousands of characters of customer data. Ask for rows when you are going to read them; take the counts when you are only deciding whether to proceed. \`summary.willFail\` always carries the TRUE failure count in every mode, so nothing is ever silently hidden.`),ValidateCreateManyInputSchema=external_exports.strictObject({source:DatasetRefSchema,projection:AssetProjectionInputSchema,relationships:RelationshipListInput.optional(),rows:external_exports.strictObject({start:external_exports.number().int().nonnegative(),end:external_exports.number().int().nonnegative()}).optional().describe(ROW_RANGE_DESCRIPTION),hierarchyName:HierarchyNameSchema.optional(),externalId:ExternalIdImportMappingSchema.optional(),additionalExternalIds:AdditionalExternalIdsInputSchema.optional(),createMissingTypes:CreateMissingTypesSchema.optional(),noHierarchy:external_exports.literal(!0).optional().describe("Mirrors createMany; enforced here."),duplicateAnyway:external_exports.literal(!0).optional().describe("Mirrors createMany; enforced here."),returnResults:ValidateReturnResultsSchema.optional(),mode:ValidateModeSchema.optional()}),ValidateCreateManyFailureSchema=external_exports.object({rowIndex:external_exports.number().int().nonnegative(),rowKey:external_exports.string().min(1).optional(),error:CreateManyRowFailureErrorSchema}),ValidateCreateManyReportSchema=external_exports.object({source:external_exports.object({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema}),promoted:external_exports.boolean(),mode:ValidateModeSchema,summary:external_exports.object({basis:ValidateSummaryBasisSchema,total:external_exports.number().int().nonnegative(),willCreate:external_exports.number().int().nonnegative(),willUpdate:external_exports.number().int().nonnegative(),willFail:external_exports.number().int().nonnegative(),...DatedImportPreviewFields}),failures:external_exports.array(ValidateCreateManyFailureSchema).optional(),failuresTruncated:external_exports.boolean(),relationshipTargets:external_exports.object({resolvesLive:external_exports.number().int().nonnegative(),resolvesInFile:external_exports.number().int().nonnegative(),absent:external_exports.number().int().nonnegative()}).optional().describe("WHERE the importing rows' relationship targets are \u2014 absent unless the import maps `relationships`. Counted over (row, mapping) pairs for rows that would CREATE and whose match cell is non-blank: a matched row is never re-parented, and a blank cell is a root rather than a missing target. `resolvesLive` \u2014 the target is in the estate now, so the edge lands at write time. `resolvesInFile` \u2014 the target is another row of THIS file; a background import reconciles those at end of job, while the synchronous verb has no later phase and resolves one only if the target happens to be written first. `absent` \u2014 neither, so nothing will resolve it: THIS is the number that means something is wrong (a mis-mapped column, or genuinely orphaned rows). Advisory like the rest of this report, with one caveat of its own: an `absent` target under `required: true` FAILS its row, so on a non-reconciling path those rows are in `summary.willFail` too."),templateConflicts:external_exports.array(TemplateConflictSchema).optional(),templateConflictsTotal:external_exports.number().int().nonnegative().optional().describe("How many types collided in TOTAL, before `templateConflicts` was capped. Present whenever that array is. The tally always survives \u2014 truncation may cost you the detail of the later entries, never the knowledge that they exist, which is the same guarantee `summary.willFail` gives for failing rows."),templateConflictsTruncated:external_exports.boolean().optional().describe("TRUE when `templateConflictsTotal` exceeded the cap, so the array above holds only the first entries \u2014 ordered WORST FIRST (most failed rows), so what you were given is the costliest collisions rather than an arbitrary slice. Absent rather than `false` in the ordinary case, the additive-output convention every neighbour here follows."),willCreateTypes:external_exports.array(external_exports.string().min(1)).optional().describe("The `assetType` values this import would create as NEW types \u2014 absent unless `createMissingTypes` was requested. These are RAW CELL VALUES from the type column, up to the 50-type auto-creation cap, and they ride in every verbosity mode: they are the blast radius of an option that writes permanent tenant vocabulary, so withholding them would hide the one thing worth checking before exercising it. Bounded and deliberate rather than an oversight \u2014 but they ARE source data, so treat them as such."),rowsWithoutCoordinates:external_exports.number().int().nonnegative().optional().describe("How many rows carry NO coordinates in the mapped `geometry` columns \u2014 absent unless the projection maps geometry. These rows import: a CREATED one lands with no location, and a MATCHED one (external-ID import) keeps the location it already has \u2014 a blank cell never clears a location. Rows whose pair is half-filled, non-numeric, or out of WGS84 range are NOT counted here: those FAIL, and appear in `summary.willFail` with `invalid-geometry`."),changedRows:external_exports.number().int().nonnegative().optional().describe("How many MATCHED rows the commit would actually write \u2014 the half of `summary.willUpdate` that differs from the asset it matched. Absent unless a reconciling preflight ran the comparison. Comes from the commit's OWN compare-before-write, so it equals the commit's `summary.updated`; with `unchangedRows` it partitions `willUpdate`, and neither joins the outer `willCreate + willUpdate + willFail` tally."),unchangedRows:external_exports.number().int().nonnegative().optional().describe("How many MATCHED rows already hold every value this delivery would write, so the commit would write nothing for them \u2014 no version row, no provenance touch, no event. Absent unless a reconciling preflight ran the comparison. A LOWER BOUND, and deployment-dependent: the comparison fails toward WRITING, so anything it cannot certify as identical counts as changed, and on a deployment with no geometry capability every row whose file named a location is counted changed. It can under-report agreement, never over-report it."),locationsKept:external_exports.number().int().positive().optional().describe("How many MATCHED rows name a location different from the one their asset already has, which the asset would KEEP because the mapping does not set `geometry.overwrite`. Such a row is not changed by its location, so it can still count in `unchangedRows`. Absent when none, or when the comparison did not run."),typeDriftRows:external_exports.number().int().nonnegative().optional().describe("How many MATCHED rows name a different asset type than the asset they matched. The import does NOT re-classify them: an asset's type is immutable through this verb, so the estate's type wins and the file's is discarded silently \u2014 this is the number that says so. Absent unless a reconciling preflight classified rows. Drifted rows are additionally re-validated against the MATCHED asset's template, so one that does not satisfy it is ALSO counted in `summary.willFail`."),absentRows:external_exports.number().int().nonnegative().optional().describe("How many live assets bound in this import's external-ID system are NOT named by this delivery. EXACT whenever present \u2014 a counts-mode call over a key set larger than it can read completely is REFUSED rather than answered partially, because a partial key set reports unread keys as absent. ADVISORY and it names no action: an absent asset may be retired, out of scope, or genuinely dropped upstream, and this verb neither knows which nor changes anything about it."),sourceRows:ValidateSourceRowsSchema.optional().describe("How many ROWS the validated source holds, reported next to a key-basis `summary` because it is a different denominator. A row count far above the key total means the delivery names some assets more than once. Absent when the source states no stable total (a live version, or a relation past the count probe)."),propertiesWouldClear:external_exports.object({codes:external_exports.array(external_exports.string().min(1))}).optional().describe('Property codes a MATCHED asset would LOSE, because this verb replaces an asset\'s property map wholesale rather than merging into it: a property the estate holds and this projection does not produce is CLEARED, not left alone. MAPPING-LEVEL and zero rows read \u2014 the template of the type the FILE names, minus the codes the projection maps \u2014 so it needs no row read. Present with an empty `codes` means "checked, nothing would clear"; absent means the check could not run (not reconciling, identity-mode projection, or a column-mode `assetType` whose target type needs rows to know). A LOWER bound, on TWO counts: a MAPPED column left blank on a given row also clears, and a matched asset whose type DRIFTED from the file\'s is judged by its OWN template rather than the one this answer is computed from. Size that second gap with `typeDriftRows` \u2014 but ONLY on a `mode: "rows"` report, where `0` means checked-and-none-drifted. `mode: "counts"` classifies no row and never computes `typeDriftRows` at all, so its absence THERE means the drift is UNKNOWN rather than absent, and these codes are a lower bound of unknown tightness.'),hierarchyDivergence:HierarchyDivergencePreviewSchema.optional().describe('What `externalId.edgePolicy` would do to the MATCHED rows\u2019 placements: `divergent` is how many name a parent they do not hold (the population `replace` would move), `skippedAmbiguousParent` how many hold SEVERAL open parents and are therefore left alone, `attachable` how many hold NONE in a NAMED tree (the rows `replace` would ATTACH, which the move ceiling does not count), `parentUnresolved` how many name a parent the estate does not hold yet (under `replace` a re-delivery places them once it does), `unplacedInBucket` how many a tree-less import leaves parentless in the unassigned bucket (never attached there; a `replace` import naming a tree places them), and `moveCeiling` the per-call bound a synchronous commit would judge `divergent` against. ABSENT unless the mapping declares an `edgePolicy` \u2014 absent means "not asked", not "nothing diverges". ADVISORY: nothing is locked between validating and committing. `moveCeiling` IS ALWAYS THE PLATFORM BOUND, never a mapping\'s own: this verb\'s input carries no `thresholds`, so a stored `thresholds.maxMoves` is invisible here and can only be TIGHTER. A background delivery of the same file may therefore refuse below the number reported \u2014 read `divergent` against the mapping when it names one. It cannot predict the DELIVERY-wide ceiling such an import is additionally judged against either.')}),DatasetProvenanceSchema2=external_exports.object({kind:external_exports.literal("dataset"),datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema,rowKey:external_exports.string().min(1)}),AssetProvenanceSchema=external_exports.discriminatedUnion("kind",[external_exports.object({kind:external_exports.literal("native")}),DatasetProvenanceSchema2]),ProvenanceDirectoryInputSchema=external_exports.strictObject({datasetId:external_exports.string().min(1),cursor:external_exports.string().min(1).optional(),limit:external_exports.number().int().min(1).max(1e4).optional(),asOf:external_exports.iso.datetime().optional()}),ProvenanceDirectoryEntrySchema=external_exports.object({rowKey:external_exports.string().min(1),get assetId(){return AssetIdSchema}}),ProvenanceDirectoryOutputSchema=external_exports.object({items:external_exports.array(ProvenanceDirectoryEntrySchema),nextCursor:external_exports.string().nullable()});var UnresolvedTypeValueSchema=external_exports.discriminatedUnion("reason",[external_exports.strictObject({value:external_exports.string(),reason:external_exports.literal("not-found")}),external_exports.strictObject({value:external_exports.string(),reason:external_exports.literal("ambiguous")}),external_exports.strictObject({value:external_exports.string(),reason:external_exports.literal("no-template"),resolvedType:external_exports.strictObject({key:external_exports.string(),displayName:external_exports.string()})})]);var CompositionJobFailureCodeSchema=external_exports.enum(["COMPOSITION_TYPES_UNRESOLVED","COMPOSITION_DELIVERY_THRESHOLD_BREACHED","COMPOSITION_SOURCE_EMPTY","COMPOSITION_ROWS_RANGE_PAST_END","COMPOSITION_ESTIMATE_OVER_BUDGET","COMPOSITION_SOURCE_COLUMN_MISSING","COMPOSITION_TYPE_VALUES_OVER_CAP"]).describe("Why a FAILED job stopped at its gate, before writing anything. Absent on any other failure. TYPES_UNRESOLVED carries `unresolvedTypes`; DELIVERY_THRESHOLD_BREACHED carries `thresholdBreach`; SOURCE_EMPTY, ROWS_RANGE_PAST_END and ESTIMATE_OVER_BUDGET are the row-count refusals, named in `failureDetail`; SOURCE_COLUMN_MISSING (a mapped column the source lacks) and TYPE_VALUES_OVER_CAP (a type column with more distinct values than a vocabulary holds) are mapping defects, named in `failureDetail`."),COMPOSITION_JOB_UNRESOLVED_TYPES_MAX=100;var CompositionJobUnresolvedTypesSchema=external_exports.array(UnresolvedTypeValueSchema).min(1).max(COMPOSITION_JOB_UNRESOLVED_TYPES_MAX),CompositionJobThresholdBreachSchema=DeliveryThresholdBreachSchema;var CompositionJobIdSchema=external_exports.uuid().brand(),CompositionJobStateSchema=external_exports.enum(["PENDING","RUNNING","COMPLETED","FAILED"]);var NonTerminalCompositionJobStateSchema=CompositionJobStateSchema.extract(["PENDING","RUNNING"]);var COMPOSITION_JOB_MAX_ESTIMATED_SECONDS=480*60;var CompositionLinkReconcileOutcomeSchema=external_exports.strictObject({nestingBreaks:NestingBreaksReportSchema.optional(),nestingCheck:NestingCheckSchema.optional(),edgesCreated:external_exports.number().int().nonnegative(),linksUnresolved:external_exports.number().int().nonnegative(),rowsCompensated:external_exports.number().int().nonnegative(),rowsKeptDespiteRequired:external_exports.number().int().nonnegative().default(0),heldBack:external_exports.strictObject({replayed:external_exports.number().int().nonnegative(),updated:external_exports.number().int().nonnegative(),unchanged:external_exports.number().int().nonnegative(),failed:external_exports.number().int().nonnegative(),moved:external_exports.number().int().nonnegative(),attached:external_exports.number().int().nonnegative(),failureClasses:CompositionFailureClassesSchema}).optional(),lateParents:external_exports.strictObject({resolved:external_exports.number().int().nonnegative(),divergent:external_exports.number().int().nonnegative()}).optional()}),VocabularyCoverageSchema=external_exports.union([external_exports.strictObject({complete:external_exports.literal(!0)}),external_exports.strictObject({complete:external_exports.literal(!1),rowsScanned:external_exports.number().int().nonnegative(),totalRows:external_exports.number().int().nonnegative()})]),StartCompositionJobResultSchema=external_exports.strictObject({jobId:CompositionJobIdSchema,state:CompositionJobStateSchema,vocabularyCoverage:VocabularyCoverageSchema.optional(),thresholdCoverage:DeliveryThresholdCoverageSchema.optional()});var CompositionJobStatusInputSchema=external_exports.strictObject({jobId:CompositionJobIdSchema}),COMPOSITION_JOBS_PAGE_MAX=200,COMPOSITION_JOBS_PAGE_DEFAULT=25,ListCompositionJobsInputSchema=external_exports.strictObject({take:external_exports.number().int().min(1).max(COMPOSITION_JOBS_PAGE_MAX).optional().describe(`How many jobs to return, 1\u2013${String(COMPOSITION_JOBS_PAGE_MAX)}; defaults to ${String(COMPOSITION_JOBS_PAGE_DEFAULT)}. Newest first. An over-cap ask is REFUSED, never clamped \u2014 a clamp hands back a page the caller did not request and cannot tell apart from the one it did.`)}),CompositionJobSummarySchema=external_exports.strictObject({jobId:CompositionJobIdSchema,state:NonTerminalCompositionJobStateSchema,attempt:external_exports.number().int().positive(),rowsCreated:external_exports.number().int().nonnegative(),rowsUpdated:external_exports.number().int().nonnegative(),rowsUnchanged:external_exports.number().int().nonnegative(),rowsFailed:external_exports.number().int().nonnegative(),principal:external_exports.string().min(1),startedAt:external_exports.iso.datetime(),updatedAt:external_exports.iso.datetime()}),CompositionJobStatusSchema=external_exports.strictObject({jobId:CompositionJobIdSchema,state:CompositionJobStateSchema,attempt:external_exports.number().int().positive(),releasedAttempts:external_exports.number().int().positive().optional(),rowsCreated:external_exports.number().int().nonnegative(),rowsUpdated:external_exports.number().int().nonnegative(),rowsUnchanged:external_exports.number().int().nonnegative(),rowsFailed:external_exports.number().int().nonnegative(),rowsMoved:external_exports.number().int().positive().optional(),backDated:external_exports.number().int().positive().optional(),valuesDated:external_exports.number().int().positive().optional(),valuesKept:external_exports.number().int().positive().optional(),valuesRefused:external_exports.number().int().positive().optional(),statusesDated:external_exports.number().int().positive().optional(),statusesKept:external_exports.number().int().positive().optional(),statusesRefused:external_exports.number().int().positive().optional(),parentsDated:external_exports.number().int().positive().optional(),parentsKept:external_exports.number().int().positive().optional(),parentsRefused:external_exports.number().int().positive().optional(),appliedToday:external_exports.number().int().positive().optional(),edgesCreated:external_exports.number().int().nonnegative(),linksUnresolved:external_exports.number().int().nonnegative(),locationsKept:external_exports.number().int().positive().optional(),nestingBreaks:external_exports.number().int().positive().max(2147483647).optional(),nestingFindings:external_exports.array(NestingBreakSchema).max(NESTING_BREAKS_MAX).optional(),nestingCheck:NestingCheckSchema.optional(),failureDetail:external_exports.string().optional(),failureCode:CompositionJobFailureCodeSchema.optional(),unresolvedTypes:CompositionJobUnresolvedTypesSchema.optional(),unresolvedTypesTotal:external_exports.number().int().positive().optional(),thresholdBreach:CompositionJobThresholdBreachSchema.optional(),failureClasses:CompositionFailureClassesSchema.optional(),completionRecordId:external_exports.string().min(1).optional(),startedAt:external_exports.iso.datetime(),updatedAt:external_exports.iso.datetime()}),CompositionJobCompletionDetailSchema=external_exports.object({state:external_exports.enum(["COMPLETED","FAILED"]),jobId:CompositionJobIdSchema,attempt:external_exports.number().int().positive(),rowsCreated:external_exports.number().int().nonnegative().optional(),rowsUpdated:external_exports.number().int().nonnegative().optional(),rowsFailed:external_exports.number().int().nonnegative().optional(),edgesCreated:external_exports.number().int().nonnegative().optional(),rowsMoved:external_exports.number().int().nonnegative().optional(),rowsAttached:external_exports.number().int().nonnegative().optional(),rowsParentUnresolved:external_exports.number().int().positive().optional(),rowsUnplacedInBucket:external_exports.number().int().positive().optional(),rowsSkippedAmbiguousParent:external_exports.number().int().nonnegative().optional(),additionalIdentifiersAlreadyBound:external_exports.number().int().nonnegative().optional(),locationsKept:external_exports.number().int().nonnegative().optional(),nestingBreaks:external_exports.number().int().positive().optional(),nestingCheck:NestingCheckSchema.optional(),linksUnresolved:external_exports.number().int().nonnegative().optional(),failureDetail:external_exports.string().optional()});var AssetsImportJobFailedDetailSchema=external_exports.strictObject({jobId:CompositionJobIdSchema,failedAt:external_exports.iso.datetime(),originatingFlowRunId:external_exports.string().min(1).optional()});var TeardownSelectorSchema=external_exports.discriminatedUnion("kind",[external_exports.strictObject({kind:external_exports.literal("importRun"),jobId:CompositionJobIdSchema})]);var TeardownItemClassificationSchema=external_exports.enum(["deletable","changed-since","gained-children","blocked-edges","blocked-bindings","not-found"]);var TEARDOWN_PREVIEW_SAMPLE_CAP=10,TeardownPreviewSampleSchema=external_exports.strictObject({assetId:external_exports.uuid(),name:external_exports.string()}),TeardownPreviewSectionSchema=external_exports.strictObject({total:external_exports.number().int().nonnegative(),sample:external_exports.array(TeardownPreviewSampleSchema).max(TEARDOWN_PREVIEW_SAMPLE_CAP)}),TeardownPreviewInputSchema=external_exports.strictObject({selector:TeardownSelectorSchema}),TeardownPreviewDigestSchema=external_exports.string().min(1),TeardownPreviewResultSchema=external_exports.strictObject({selector:TeardownSelectorSchema,runInstant:external_exports.iso.datetime(),deletable:TeardownPreviewSectionSchema,changedSince:TeardownPreviewSectionSchema,gainedChildren:TeardownPreviewSectionSchema,blockedEdges:TeardownPreviewSectionSchema,blockedBindings:TeardownPreviewSectionSchema,notFound:TeardownPreviewSectionSchema,previewDigest:TeardownPreviewDigestSchema,summary:external_exports.string()});var TeardownJobIdSchema=external_exports.uuid().brand(),TeardownJobStateSchema=external_exports.enum(["PENDING","RUNNING","COMPLETED","FAILED"]);var NonTerminalTeardownJobStateSchema=TeardownJobStateSchema.extract(["PENDING","RUNNING"]);var StartTeardownJobInputSchema=external_exports.strictObject({selector:TeardownSelectorSchema,previewDigest:TeardownPreviewDigestSchema,idempotencyKey:IdempotencyKeySchema}),StartTeardownJobResultSchema=external_exports.strictObject({jobId:TeardownJobIdSchema,state:TeardownJobStateSchema});var TeardownJobStatusInputSchema=external_exports.strictObject({jobId:TeardownJobIdSchema});var TEARDOWN_JOBS_PAGE_MAX=100,ListTeardownJobsInputSchema=external_exports.strictObject({take:external_exports.number().int().min(1).max(TEARDOWN_JOBS_PAGE_MAX).optional()}),TeardownJobCountsSchema=external_exports.strictObject({deleted:external_exports.number().int().nonnegative(),keptChangedSince:external_exports.number().int().nonnegative(),keptGainedChildren:external_exports.number().int().nonnegative(),keptBlockedEdges:external_exports.number().int().nonnegative(),keptBlockedBindings:external_exports.number().int().nonnegative(),keptNotFound:external_exports.number().int().nonnegative()}),TeardownJobSummarySchema=external_exports.strictObject({jobId:TeardownJobIdSchema,state:NonTerminalTeardownJobStateSchema,attempt:external_exports.number().int().positive(),...TeardownJobCountsSchema.shape,principal:external_exports.string(),startedAt:external_exports.iso.datetime(),updatedAt:external_exports.iso.datetime()}),TeardownJobStatusSchema=external_exports.strictObject({jobId:TeardownJobIdSchema,state:TeardownJobStateSchema,attempt:external_exports.number().int().positive(),...TeardownJobCountsSchema.shape,failureDetail:external_exports.string().optional(),startedAt:external_exports.iso.datetime(),updatedAt:external_exports.iso.datetime()});var QualityJobIdSchema=external_exports.uuid().brand(),QualityJobStateSchema=external_exports.enum(["PENDING","RUNNING","COMPLETED","FAILED"]),NonTerminalQualityJobStateSchema=QualityJobStateSchema.extract(["PENDING","RUNNING"]);var QualityJobPhaseSchema=external_exports.enum(["walk","cycles"]);var QUALITY_JOB_ORPHAN_SAMPLE_CAP=50;var QUALITY_JOB_NOT_FOUND="QUALITY_JOB_NOT_FOUND",QUALITY_JOB_RUNNER_UNAVAILABLE="QUALITY_JOB_RUNNER_UNAVAILABLE",QualityJobRunnerUnavailableDataSchema=external_exports.object({code:external_exports.literal(QUALITY_JOB_RUNNER_UNAVAILABLE)}),QualityJobNotFoundDataSchema=external_exports.object({code:external_exports.literal(QUALITY_JOB_NOT_FOUND)}),QUALITY_JOB_REUSE_WINDOW_MS=15*6e4,StartQualityJobResultSchema=external_exports.strictObject({jobId:QualityJobIdSchema,state:QualityJobStateSchema,alreadyRunning:external_exports.boolean(),reused:external_exports.boolean()}),QualityJobStatusInputSchema=external_exports.strictObject({jobId:QualityJobIdSchema}),QualityJobStatusSchema=external_exports.strictObject({jobId:QualityJobIdSchema,state:QualityJobStateSchema,phase:QualityJobPhaseSchema,attempt:external_exports.number().int().positive(),unitsDone:external_exports.number().int().nonnegative(),checkedAt:external_exports.iso.datetime().optional(),failureDetail:external_exports.string().optional(),startedAt:external_exports.iso.datetime(),updatedAt:external_exports.iso.datetime()}),QualityReceiptOrphansSchema=external_exports.strictObject({count:RelationshipRootsCountSchema,sample:external_exports.array(SubtreeNodeSchema).max(QUALITY_JOB_ORPHAN_SAMPLE_CAP)}),QualityReceiptSchema=external_exports.strictObject({jobId:QualityJobIdSchema,checkedAt:external_exports.iso.datetime(),completedAt:external_exports.iso.datetime(),orphans:QualityReceiptOrphansSchema,get edgeSanity(){return EdgeSanityReportSchema}}),QualityLiveJobSchema=external_exports.strictObject({jobId:QualityJobIdSchema,state:NonTerminalQualityJobStateSchema}),QualityLastFailureSchema=external_exports.strictObject({jobId:QualityJobIdSchema,failureDetail:external_exports.string().nullable(),failedAt:external_exports.iso.datetime()}),LatestQualityReceiptSchema=external_exports.strictObject({receipt:QualityReceiptSchema.nullable(),liveJob:QualityLiveJobSchema.nullable(),lastFailure:QualityLastFailureSchema.nullable(),changedSinceCheck:external_exports.boolean()});var IMPORT_MAPPING_NAME_MAX=120,ImportMappingNameSchema=external_exports.string().trim().min(1,"an import mapping name cannot be blank").max(IMPORT_MAPPING_NAME_MAX).describe("The mapping's operator-facing name, UNIQUE PER TENANT. `composition.startImport` references a mapping by this name, so it is the durable ref an operator types \u2014 not an internal code.").meta({entity:{domain:"assets",type:"asset-import-mapping"}}),ImportMappingVersionSchema=external_exports.number().int().positive().describe("The saved version of this mapping, 1-based and append-only. Pin one to run exactly the config that was authored then; omit it to run the latest."),AssetImportMappingConfigSchema=external_exports.strictObject({get projection(){return AssetProjectionSchema},get relationships(){return external_exports.array(RelationshipMappingSchema).optional()},get externalId(){return ExternalIdImportMappingSchema.optional()},get hierarchyName(){return HierarchyNameSchema.optional()},get noHierarchy(){return external_exports.literal(!0).optional()},get thresholds(){return AssetImportDeliveryThresholdsSchema.optional()}}),AssetImportMappingConfigInputSchema=AssetImportMappingConfigSchema.extend({get projection(){return AssetProjectionInputSchema},get relationships(){return RelationshipListInput.optional()}}),AssetImportMappingSchema=external_exports.object({name:ImportMappingNameSchema,version:ImportMappingVersionSchema,get config(){return AssetImportMappingConfigSchema},createdAt:external_exports.iso.datetime()}),SaveAssetImportMappingInputSchema=external_exports.strictObject({name:ImportMappingNameSchema,get config(){return AssetImportMappingConfigInputSchema},expectedVersion:ImportMappingVersionSchema.optional().describe("The version this edit was based on. ABSENT \u21D2 create a NEW name (refused if the name is taken). PRESENT \u21D2 append the next version, refused if the mapping has moved on since."),get idempotencyKey(){return IdempotencyKeySchema.max(IDEMPOTENCY_KEY_MAX_LENGTH)}}),GetAssetImportMappingInputSchema=external_exports.strictObject({name:ImportMappingNameSchema,version:ImportMappingVersionSchema.optional().describe("Pin a version. Absent \u21D2 the latest saved version of this name.")}),ListAssetImportMappingsOutputSchema=external_exports.object({get mappings(){return external_exports.array(AssetImportMappingSchema)}}),StartImportInputSchema=external_exports.strictObject({mappingName:ImportMappingNameSchema.describe("The saved mapping to run. Resolved server-side; the import runs exactly the projection, relationships, external-ID mapping and hierarchy that mapping holds."),mappingVersion:ImportMappingVersionSchema.optional().describe("Pin the mapping version. Absent \u21D2 the latest saved version at the moment of the call."),get source(){return DatasetRefSchema.describe("The dataset to import from. It must already be PROMOTED, and \u2014 as for every background job \u2014 it must be a FROZEN version with a stored row count; a LIVE version is refused. `versionId` absent = the current load, stamped to its resolved version in the trail.")},get rows(){return external_exports.strictObject({start:external_exports.number().int().nonnegative(),end:external_exports.number().int().nonnegative()}).optional().describe(ROW_RANGE_DESCRIPTION)},get idempotencyKey(){return IdempotencyKeySchema.max(IDEMPOTENCY_KEY_MAX_LENGTH)},duplicateAnyway:external_exports.literal(!0).optional()});var TypePreflightInputSchema=external_exports.strictObject({source:DatasetRefSchema,projection:AssetProjectionInputSchema,rows:external_exports.strictObject({start:external_exports.number().int().nonnegative(),end:external_exports.number().int().nonnegative()}).optional().describe(ROW_RANGE_DESCRIPTION)}),TypePreflightResultSchema=external_exports.strictObject({unresolved:external_exports.array(UnresolvedTypeValueSchema),distinctValues:external_exports.number().int().nonnegative(),coverage:VocabularyCoverageSchema}),CreateTypeFromValueInputSchema=external_exports.strictObject({source:DatasetRefSchema,projection:AssetProjectionInputSchema,rows:external_exports.strictObject({start:external_exports.number().int().nonnegative(),end:external_exports.number().int().nonnegative()}).optional().describe(ROW_RANGE_DESCRIPTION),value:external_exports.string().min(1),get categoryId(){return AssetCategoryIdSchema},get externalId(){return ExternalIdImportMappingSchema.optional()},get additionalExternalIds(){return AdditionalExternalIdsInputSchema.optional()},key:external_exports.string().min(1).optional(),displayName:external_exports.string().min(1).optional()}),CreateTypeFromValueResultSchema=external_exports.strictObject({get type(){return AssetTypeSchema},get template(){return AssetTemplateVersionSchema}});var IMPORT_PREFLIGHT_LIST_MAX=COMPOSITION_JOB_UNRESOLVED_TYPES_MAX,IMPORT_PREFLIGHT_VALUE_MAX_CHARS=256,PreflightValueSchema=external_exports.string().min(1).max(IMPORT_PREFLIGHT_VALUE_MAX_CHARS),PreflightImportJobIdSchema=external_exports.uuid().brand(),buildRedescribed=()=>({mappingName:StartImportInputSchema.shape.mappingName.describe("The saved mapping to check. Resolved server-side at accept; the check reads exactly the projection, relationships and external-ID mapping that version holds."),source:StartImportInputSchema.shape.source.describe("The dataset to check. Unlike `startImport`, the accept refuses neither an unpromoted load nor a live version \u2014 a check is a question, not a consumption. A `rows` slice of a LIVE version cannot be read, though: a live version carries no stored row count to slice, so that check ends FAILED `IMPORT_PREFLIGHT_FAULT`. `versionId` absent = the current load, pinned to its resolved version at accept."),rows:StartImportInputSchema.shape.rows.describe('OPTIONAL half-open `[start, end)` slice of the source version \u2014 the rows the import will read. ABSENT = the whole load. A slice is checked by scanning its rows, and the scan reads a bounded number of them; a slice wider than that bound is refused at accept with `BAD_REQUEST` / `data.code = "IMPORT_PREFLIGHT_ROWS_TOO_WIDE"`, whose `data.maxRows` and message name the bound. Check a wider range as several slices, or the whole load.')}),redescribed,redescribedSchemas=()=>redescribed??=buildRedescribed(),PreflightImportInputSchema=external_exports.strictObject({get mappingName(){return redescribedSchemas().mappingName},get mappingVersion(){return StartImportInputSchema.shape.mappingVersion},get source(){return redescribedSchemas().source},get rows(){return redescribedSchemas().rows},get idempotencyKey(){return StartImportInputSchema.shape.idempotencyKey}}),PreflightImportJobStateSchema=external_exports.enum(["PENDING","RUNNING","COMPLETED","FAILED"]),PreflightImportAcceptResultSchema=external_exports.strictObject({jobId:PreflightImportJobIdSchema,state:PreflightImportJobStateSchema}),buildMappingRefSchema=()=>external_exports.strictObject({name:ImportMappingNameSchema,version:ImportMappingVersionSchema}),mappingRef,mappingRefSchema=()=>mappingRef??=buildMappingRefSchema(),PreflightImportJobRequestSchema=external_exports.strictObject({get mapping(){return mappingRefSchema()},source:PinnedDatasetRefSchema,rows:external_exports.strictObject({start:external_exports.number().int().nonnegative(),end:external_exports.number().int().nonnegative()}).optional()}),PreflightImportFailureCodeSchema=external_exports.enum(["IMPORT_PREFLIGHT_BLOCKED","IMPORT_PREFLIGHT_FAULT"]),PreflightImportBlockerKindSchema=external_exports.enum(["type-ambiguous","type-no-template","fixed-type-unresolved","match-system-not-registered","coverage-incomplete"]),PreflightImportBlockerSchema=external_exports.strictObject({kind:PreflightImportBlockerKindSchema,value:PreflightValueSchema}),PreflightImportBlockersSchema=external_exports.array(PreflightImportBlockerSchema).min(1).max(IMPORT_PREFLIGHT_LIST_MAX),PreflightImportFailureFactsSchema=external_exports.strictObject({blockers:PreflightImportBlockersSchema,blockersTotal:external_exports.number().int().positive()}),IMPORT_PREFLIGHT_JOB_NOT_FOUND="IMPORT_PREFLIGHT_JOB_NOT_FOUND",IMPORT_PREFLIGHT_RUNNER_UNAVAILABLE="IMPORT_PREFLIGHT_RUNNER_UNAVAILABLE",PreflightImportRunnerUnavailableDataSchema=external_exports.object({code:external_exports.literal(IMPORT_PREFLIGHT_RUNNER_UNAVAILABLE)}),IMPORT_PREFLIGHT_ROWS_TOO_WIDE="IMPORT_PREFLIGHT_ROWS_TOO_WIDE",PreflightImportRowsTooWideDataSchema=external_exports.object({code:external_exports.literal(IMPORT_PREFLIGHT_ROWS_TOO_WIDE),maxRows:external_exports.number().int().positive()}),PreflightImportJobNotFoundDataSchema=external_exports.object({code:external_exports.literal(IMPORT_PREFLIGHT_JOB_NOT_FOUND)}),PreflightImportStatusInputSchema=external_exports.strictObject({jobId:PreflightImportJobIdSchema}),PreflightImportStatusSchema=external_exports.strictObject({jobId:PreflightImportJobIdSchema,state:PreflightImportJobStateSchema,attempt:external_exports.number().int().positive(),failureCode:PreflightImportFailureCodeSchema.optional(),failureDetail:external_exports.string().optional(),blockers:PreflightImportBlockersSchema.optional(),blockersTotal:external_exports.number().int().positive().optional(),completionRecordId:external_exports.string().min(1).optional(),startedAt:external_exports.iso.datetime(),updatedAt:external_exports.iso.datetime()}),namedValues=external_exports.array(PreflightValueSchema).max(IMPORT_PREFLIGHT_LIST_MAX),PreflightImportCompletionDetailSchema=external_exports.object({get mapping(){return mappingRefSchema()},source:PinnedDatasetRefSchema,wouldCreate:external_exports.object({total:external_exports.number().int().nonnegative(),types:external_exports.number().int().nonnegative(),idSystems:external_exports.number().int().nonnegative()}),distinctTypeValues:external_exports.number().int().nonnegative(),types:namedValues,typesTotal:external_exports.number().int().nonnegative(),idSystems:namedValues,idSystemsTotal:external_exports.number().int().nonnegative()}),PreflightImportFindingSchema=external_exports.strictObject({family:external_exports.enum(["assets.type-not-found","assets.id-system-not-registered"]),severity:external_exports.literal("info"),count:external_exports.number().int().positive(),rowsRef:external_exports.null(),matchKey:PreflightValueSchema,handling:external_exports.literal("carry"),recommended:external_exports.strictObject({outcome:external_exports.literal("accept"),reason:external_exports.string().min(1)})}),PreflightImportSealedDetailSchema=PreflightImportCompletionDetailSchema.extend({jobId:PreflightImportJobIdSchema,attempt:external_exports.number().int().positive(),coverage:VocabularyCoverageSchema,findings:external_exports.array(PreflightImportFindingSchema).max(IMPORT_PREFLIGHT_LIST_MAX),originatingFlowRunId:external_exports.string().min(1).optional()}).strict(),PreflightImportFailedDetailSchema=external_exports.strictObject({jobId:PreflightImportJobIdSchema,attempt:external_exports.number().int().positive(),failureCode:PreflightImportFailureCodeSchema,failureDetail:external_exports.string(),originatingFlowRunId:external_exports.string().min(1).optional()});var ExternalIdBindJobIdSchema=external_exports.uuid().brand(),ExternalIdBindJobStateSchema=external_exports.enum(["PENDING","RUNNING","COMPLETED","FAILED"]);var ExternalIdBindStallCauseSchema=external_exports.enum(["tile-timeout","service-unavailable","unexpected"]),ExternalIdBindMappingSchema=external_exports.strictObject({assetIdColumn:external_exports.string().min(1),system:ExternalIdSystemSchema,valueColumn:external_exports.string().min(1)}),StartExternalIdBindJobInputSchema=external_exports.strictObject({source:DatasetRefSchema,mapping:ExternalIdBindMappingSchema,rows:external_exports.strictObject({start:external_exports.number().int().nonnegative(),end:external_exports.number().int().nonnegative()}).optional(),idempotencyKey:IdempotencyKeySchema}),StartExternalIdBindJobResultSchema=external_exports.strictObject({jobId:ExternalIdBindJobIdSchema,state:ExternalIdBindJobStateSchema}),ExternalIdBindRefusalCodeSchema=external_exports.enum(["asset-not-found","invalid-value","already-bound","in-batch-duplicate"]);var ExternalIdBindRefusalSchema=external_exports.object({rowIndex:external_exports.number().int().nonnegative(),get assetId(){return AssetIdSchema.optional()},system:ExternalIdSystemSchema,value:external_exports.string(),code:ExternalIdBindRefusalCodeSchema,detail:external_exports.string().max(200).optional(),get holdingAssetId(){return AssetIdSchema.optional()}}),ExternalIdBindTileRefusalSchema=external_exports.strictObject({rowIndex:external_exports.number().int().nonnegative(),code:ExternalIdBindRefusalCodeSchema,get holdingAssetId(){return AssetIdSchema.optional()}}),ExternalIdBindTileOutcomeSchema=external_exports.strictObject({bound:external_exports.number().int().nonnegative(),reasserted:external_exports.number().int().nonnegative().default(0),alreadyBound:external_exports.number().int().nonnegative(),unmatched:external_exports.number().int().nonnegative(),invalidValue:external_exports.number().int().nonnegative(),inBatchDuplicate:external_exports.number().int().nonnegative(),refusals:external_exports.array(ExternalIdBindTileRefusalSchema).default([])}),ExternalIdBindJobStatusInputSchema=external_exports.strictObject({jobId:ExternalIdBindJobIdSchema}),ExternalIdBindJobStatusSchema=external_exports.strictObject({jobId:ExternalIdBindJobIdSchema,state:ExternalIdBindJobStateSchema,attempt:external_exports.number().int().positive(),requested:external_exports.number().int().nonnegative(),bound:external_exports.number().int().nonnegative(),reasserted:external_exports.number().int().nonnegative(),alreadyBound:external_exports.number().int().nonnegative(),unmatched:external_exports.number().int().nonnegative(),invalidValue:external_exports.number().int().nonnegative(),inBatchDuplicate:external_exports.number().int().nonnegative(),refusalSample:external_exports.array(ExternalIdBindTileRefusalSchema),failureDetail:external_exports.string().optional(),stallCause:ExternalIdBindStallCauseSchema.optional(),completionRecordId:external_exports.string().min(1).optional(),startedAt:external_exports.iso.datetime(),updatedAt:external_exports.iso.datetime()}),ExternalIdBindJobCompletionDetailSchema=external_exports.object({state:external_exports.enum(["COMPLETED","FAILED"]),jobId:ExternalIdBindJobIdSchema,attempt:external_exports.number().int().positive(),requested:external_exports.number().int().nonnegative().optional(),bound:external_exports.number().int().nonnegative().optional(),reasserted:external_exports.number().int().nonnegative().optional(),alreadyBound:external_exports.number().int().nonnegative().optional(),unmatched:external_exports.number().int().nonnegative().optional(),invalidValue:external_exports.number().int().nonnegative().optional(),inBatchDuplicate:external_exports.number().int().nonnegative().optional(),failureDetail:external_exports.string().optional()});var DeriveTemplateTargetSchema=external_exports.strictObject({get assetTypeId(){return AssetTypeIdSchema}}),DERIVE_TEMPLATE_MANY_MAX_TARGETS=100,DeriveTemplateManyInputSchema=external_exports.strictObject({datasetRef:DatasetRefSchema,targets:external_exports.array(DeriveTemplateTargetSchema).min(1).max(DERIVE_TEMPLATE_MANY_MAX_TARGETS)}),DeriveTemplateErrorCodeSchema=external_exports.enum(["asset-type-not-found","would-lose-data","invalid-definition"]),DeriveTemplateFailureDataSchema=external_exports.strictObject({issues:external_exports.array(TemplateDefinitionIssueSchema).max(MAX_ISSUES_PER_ROW_FAILURE)}),DeriveTemplateItemResultSchema=external_exports.discriminatedUnion("status",[external_exports.object({get assetTypeId(){return AssetTypeIdSchema},status:external_exports.literal("derived"),get templateVersion(){return AssetTemplateVersionSchema}}),external_exports.object({get assetTypeId(){return AssetTypeIdSchema},status:external_exports.literal("failed"),error:external_exports.object({code:DeriveTemplateErrorCodeSchema,message:external_exports.string().min(1),data:DeriveTemplateFailureDataSchema.optional()})})]),DeriveTemplateManyOutputSchema=external_exports.object({results:external_exports.array(DeriveTemplateItemResultSchema)});var UNASSIGNED_NOTICE_DISMISSED_TREES_MAX=20,ASSETS_LIST_VIEW_SCOPE="assets-list",AssetsListViewFiltersSchema=external_exports.looseObject({get categoryIds(){return external_exports.array(AssetCategoryIdSchema).min(1).max(50).optional()},get assetTypeIds(){return external_exports.array(AssetTypeIdSchema).min(1).max(50).optional()},get lifecycleStatuses(){return external_exports.array(AssetLifecycleStatusSchema).min(1).max(50).optional()},get categoryId(){return AssetCategoryIdSchema.optional()},get assetTypeId(){return AssetTypeIdSchema.optional()},lifecycleStatus:AssetLifecycleStatusSchema.optional(),nameContains:external_exports.string().min(1).optional(),hasGeometry:external_exports.boolean().optional()}),AssetsListViewSchema=external_exports.looseObject({filters:AssetsListViewFiltersSchema.optional(),get orderBy(){return AssetOrderBySchema.optional()},columns:external_exports.array(external_exports.string().min(1)).max(VIEW_COLUMNS_MAX).optional()}),AssetsTablePreferencesSchema=external_exports.looseObject({columns:external_exports.array(external_exports.string().min(1)).max(VIEW_COLUMNS_MAX).optional(),get pageSize(){return external_exports.number().int().min(1).max(ASSET_IDS_MAX_PER_PAGE).optional()},density:external_exports.enum(["comfortable","compact"]).optional(),get forest(){return external_exports.object({tree:external_exports.string().min(1),relationshipType:HierarchyRelationshipTypeSchema}).optional()},get unassignedNoticeDismissedFor(){return external_exports.array(external_exports.string().refine(value2=>HierarchyIdSchema.safeParse(value2).success,"must be a hierarchy id")).max(UNASSIGNED_NOTICE_DISMISSED_TREES_MAX).optional()},unassignedNoticeDismissed:external_exports.literal(!0).optional()}),assetsViewShapes=createViewPreferenceShapes({scope:ASSETS_LIST_VIEW_SCOPE,view:AssetsListViewSchema,preferences:AssetsTablePreferencesSchema}),SavedViewSchema2=assetsViewShapes.SavedViewSchema,CreateSavedViewInputSchema2=assetsViewShapes.CreateSavedViewInputSchema,UpdateSavedViewInputSchema2=assetsViewShapes.UpdateSavedViewInputSchema,ListSavedViewsInputSchema2=assetsViewShapes.ListSavedViewsInputSchema,DeleteSavedViewInputSchema2=assetsViewShapes.DeleteSavedViewInputSchema,GetTablePreferencesInputSchema2=assetsViewShapes.GetTablePreferencesInputSchema,SetTablePreferencesInputSchema2=assetsViewShapes.SetTablePreferencesInputSchema,TablePreferencesSchema2=assetsViewShapes.TablePreferencesSchema;var LocationPlacementIdSchema=external_exports.uuid().brand(),LocationPlacementJobIdSchema=external_exports.uuid().brand(),LOCATION_PLACEMENT_NAME_MAX=120,LOCATION_PLACEMENT_SYSTEMS_MAX=8,LOCATION_PLACEMENT_COLUMN_MAX=256;var LOCATION_PLACEMENT_FAILURE_PAGE_MAX=500;var LocationPlacementNameSchema=external_exports.string().trim().min(1,"a placement name cannot be blank").max(LOCATION_PLACEMENT_NAME_MAX).describe("The placement's operator-facing name, unique per tenant."),ColumnNameSchema2=external_exports.string().min(1).max(LOCATION_PLACEMENT_COLUMN_MAX),LocationPlacementConfigSchema=external_exports.strictObject({source:external_exports.strictObject({datasetId:DatasetIdSchema}).describe("The dataset rows come from. A run reads its CURRENT version, which must be promoted."),idColumn:ColumnNameSchema2.describe("The column whose value identifies the asset, looked up as an external ID (trimmed, case-significant)."),systems:external_exports.array(ExternalIdSystemSchema).min(1).max(LOCATION_PLACEMENT_SYSTEMS_MAX).describe("The external-ID systems the identifier is looked up in, in order. A value bound to different assets in two of them fails the row as ambiguous."),geometryColumn:ColumnNameSchema2.describe("The column holding the geometry as WKT: Point, LineString, Polygon or their Multi forms, 2D longitude/latitude (SRID 4326).")}),LocationPlacementJobModeSchema=external_exports.enum(["preview","run"]),LocationPlacementJobStateSchema=external_exports.enum(["PENDING","RUNNING","COMPLETED","FAILED"]);var LocationPlacementStallCauseSchema=external_exports.enum(["geometry-unavailable","authority-unresolved","service-unavailable","tile-timeout","unexpected"]),LocationPlacementFailureCodeSchema=external_exports.enum(["unmatched","ambiguous","invalid-geometry","duplicate","conflict","not-permitted"]),LOCATION_PLACEMENT_IDENTIFIER_MAX=512,LocationPlacementFailureSchema=external_exports.strictObject({rowIndex:external_exports.number().int().nonnegative(),code:LocationPlacementFailureCodeSchema,detail:external_exports.string(),identifier:external_exports.string().max(LOCATION_PLACEMENT_IDENTIFIER_MAX).nullable(),get assetIds(){return external_exports.array(AssetIdSchema)}}),LocationPlacementCountsSchema=external_exports.strictObject({rows:external_exports.number().int().nonnegative(),new:external_exports.number().int().nonnegative(),moved:external_exports.number().int().nonnegative(),unchanged:external_exports.number().int().nonnegative(),unmatched:external_exports.number().int().nonnegative(),ambiguous:external_exports.number().int().nonnegative(),invalidGeometry:external_exports.number().int().nonnegative(),duplicate:external_exports.number().int().nonnegative(),conflict:external_exports.number().int().nonnegative(),notPermitted:external_exports.number().int().nonnegative()});var LOCATION_PLACEMENT_OVERLAP_PLACEMENTS_MAX=10,LOCATION_PLACEMENT_OVERLAP_SAMPLE=5,LocationPlacementOverlapSchema=external_exports.strictObject({total:external_exports.number().int().nonnegative(),placements:external_exports.array(external_exports.strictObject({get placementId(){return LocationPlacementIdSchema},name:external_exports.string().nullable(),count:external_exports.number().int().positive(),get sampleAssetIds(){return external_exports.array(AssetIdSchema).max(LOCATION_PLACEMENT_OVERLAP_SAMPLE)}})).max(LOCATION_PLACEMENT_OVERLAP_PLACEMENTS_MAX)});var LocationPlacementJobSummarySchema=external_exports.strictObject({jobId:LocationPlacementJobIdSchema,get placementId(){return LocationPlacementIdSchema},mode:LocationPlacementJobModeSchema,state:LocationPlacementJobStateSchema,source:external_exports.strictObject({datasetId:DatasetIdSchema,versionId:DatasetVersionIdSchema}),get counts(){return LocationPlacementCountsSchema},requested:external_exports.number().int().nonnegative(),get overlap(){return LocationPlacementOverlapSchema},failureDetail:external_exports.string().optional(),get stallCause(){return LocationPlacementStallCauseSchema.optional()},startedAt:external_exports.iso.datetime(),updatedAt:external_exports.iso.datetime()}),LocationPlacementSchema=external_exports.strictObject({placementId:LocationPlacementIdSchema,name:LocationPlacementNameSchema,get config(){return LocationPlacementConfigSchema},version:external_exports.number().int().positive(),createdAt:external_exports.iso.datetime(),updatedAt:external_exports.iso.datetime(),get latestJob(){return LocationPlacementJobSummarySchema.nullable()}}),SaveLocationPlacementInputSchema=external_exports.strictObject({get placementId(){return LocationPlacementIdSchema.optional()},expectedVersion:external_exports.number().int().positive().optional().describe("Required with `placementId`: the version the edit was based on."),name:LocationPlacementNameSchema,get config(){return LocationPlacementConfigSchema},get idempotencyKey(){return IdempotencyKeySchema.max(IDEMPOTENCY_KEY_MAX_LENGTH)}}),DeleteLocationPlacementInputSchema=external_exports.strictObject({get placementId(){return LocationPlacementIdSchema},get idempotencyKey(){return IdempotencyKeySchema.max(IDEMPOTENCY_KEY_MAX_LENGTH)}}),DeleteLocationPlacementResultSchema=external_exports.strictObject({get placementId(){return LocationPlacementIdSchema},deleted:external_exports.literal(!0)}),GetLocationPlacementInputSchema=external_exports.strictObject({get placementId(){return LocationPlacementIdSchema}}),ListLocationPlacementsOutputSchema=external_exports.strictObject({get placements(){return external_exports.array(LocationPlacementSchema)}}),StartLocationPlacementJobInputSchema=external_exports.strictObject({get placementId(){return LocationPlacementIdSchema},mode:LocationPlacementJobModeSchema.describe("`preview` counts what a run would do and writes nothing; `run` writes the new and moved locations."),get idempotencyKey(){return IdempotencyKeySchema.max(IDEMPOTENCY_KEY_MAX_LENGTH)}}),StartLocationPlacementJobResultSchema=external_exports.strictObject({jobId:LocationPlacementJobIdSchema,state:LocationPlacementJobStateSchema,mode:LocationPlacementJobModeSchema,alreadyRunning:external_exports.boolean()}),LocationPlacementJobStatusInputSchema=external_exports.strictObject({get jobId(){return LocationPlacementJobIdSchema}}),LocationPlacementJobStatusSchema=external_exports.strictObject({get job(){return LocationPlacementJobSummarySchema},get sample(){return external_exports.array(LocationPlacementFailureSchema)},failuresTruncated:external_exports.boolean()}),ListLocationPlacementJobsInputSchema=external_exports.strictObject({get placementId(){return LocationPlacementIdSchema}}),ListLocationPlacementJobsOutputSchema=external_exports.strictObject({get jobs(){return external_exports.array(LocationPlacementJobSummarySchema)}}),LocationPlacementJobFailuresInputSchema=external_exports.strictObject({get jobId(){return LocationPlacementJobIdSchema},code:LocationPlacementFailureCodeSchema.optional(),afterRowIndex:external_exports.number().int().nonnegative().optional(),limit:external_exports.number().int().min(1).max(LOCATION_PLACEMENT_FAILURE_PAGE_MAX).optional()}),LocationPlacementJobFailuresOutputSchema=external_exports.strictObject({get failures(){return external_exports.array(LocationPlacementFailureSchema)},nextAfterRowIndex:external_exports.number().int().nonnegative().optional()}),LOCATION_PLACEMENT_NOT_FOUND="LOCATION_PLACEMENT_NOT_FOUND",LOCATION_PLACEMENT_NAME_TAKEN="LOCATION_PLACEMENT_NAME_TAKEN",LOCATION_PLACEMENT_CHANGED="LOCATION_PLACEMENT_CHANGED",LOCATION_PLACEMENT_INVALID="LOCATION_PLACEMENT_INVALID",LOCATION_PLACEMENT_JOB_LIVE="LOCATION_PLACEMENT_JOB_LIVE",LOCATION_PLACEMENT_SOURCE_REFUSED="LOCATION_PLACEMENT_SOURCE_REFUSED",LOCATION_PLACEMENT_JOB_NOT_FOUND="LOCATION_PLACEMENT_JOB_NOT_FOUND",LOCATION_PLACEMENT_RUNNER_UNAVAILABLE="LOCATION_PLACEMENT_RUNNER_UNAVAILABLE",LocationPlacementNotFoundDataSchema=external_exports.object({code:external_exports.literal(LOCATION_PLACEMENT_NOT_FOUND)}),LocationPlacementNameTakenDataSchema=external_exports.object({code:external_exports.literal(LOCATION_PLACEMENT_NAME_TAKEN)}),LocationPlacementChangedDataSchema=external_exports.object({code:external_exports.literal(LOCATION_PLACEMENT_CHANGED),currentVersion:external_exports.number().int().positive()}),LocationPlacementInvalidDataSchema=external_exports.object({code:external_exports.literal(LOCATION_PLACEMENT_INVALID)}),LocationPlacementJobLiveDataSchema=external_exports.object({code:external_exports.literal(LOCATION_PLACEMENT_JOB_LIVE)}),LocationPlacementSourceRefusedDataSchema=external_exports.object({code:external_exports.literal(LOCATION_PLACEMENT_SOURCE_REFUSED),reason:external_exports.enum(["not-promoted","live","empty","too-many-rows","missing-columns"])}),LocationPlacementJobNotFoundDataSchema=external_exports.object({code:external_exports.literal(LOCATION_PLACEMENT_JOB_NOT_FOUND)}),LocationPlacementRunnerUnavailableDataSchema=external_exports.object({code:external_exports.literal(LOCATION_PLACEMENT_RUNNER_UNAVAILABLE)});var AssetImportRunIdSchema=external_exports.string().min(1).brand(),AssetImportExceptionIdSchema=external_exports.string().min(1).brand(),AssetImportExceptionStatusSchema=external_exports.enum(["open","resolved","dismissed"]),AssetImportExceptionResolutionSchema=external_exports.enum(["resolved","dismissed"]);var IMPORT_EXCEPTION_ROW_DATA_MAX_KEY_CHARS=256,ImportExceptionRowDataSchema=external_exports.record(external_exports.string().max(IMPORT_EXCEPTION_ROW_DATA_MAX_KEY_CHARS),external_exports.union([external_exports.string(),external_exports.number(),external_exports.boolean(),external_exports.null()])),AssetImportExceptionSchema=external_exports.object({get id(){return AssetImportExceptionIdSchema},get runId(){return AssetImportRunIdSchema},rowIndex:external_exports.number().int().nonnegative(),rowKey:external_exports.string().min(1).optional(),get error(){return ImportJobRowFailureErrorSchema},get rowData(){return ImportExceptionRowDataSchema},get status(){return AssetImportExceptionStatusSchema},resolvedAt:external_exports.iso.datetime().optional(),resolvedBy:external_exports.string().min(1).optional(),get resolvedAssetId(){return AssetIdSchema.optional()},createdAt:external_exports.iso.datetime()}),AssetImportRunSchema=external_exports.object({get id(){return AssetImportRunIdSchema},principal:external_exports.string().min(1),get datasetId(){return DatasetIdSchema},get versionId(){return DatasetVersionIdSchema},summary:external_exports.object({total:external_exports.number().int().nonnegative(),created:external_exports.number().int().nonnegative(),updated:external_exports.number().int().nonnegative(),unchanged:external_exports.number().int().nonnegative(),failed:external_exports.number().int().nonnegative()}),openCount:external_exports.number().int().nonnegative(),storedCount:external_exports.number().int().nonnegative(),get jobId(){return CompositionJobIdSchema.optional()},createdAt:external_exports.iso.datetime()}),IMPORT_EXCEPTIONS_PAGE_MAX=200,IMPORT_EXCEPTIONS_PAGE_DEFAULT=50;var ListImportRunsInputSchema=external_exports.strictObject({openOnly:external_exports.boolean().optional().describe("Narrow to runs that still have open exceptions. Defaults to false (every run), so a worked-to-zero history stays reachable as the evidence the work happened."),limit:external_exports.number().int().min(1).max(IMPORT_EXCEPTIONS_PAGE_MAX).optional().describe(`Page size, 1\u2013${String(IMPORT_EXCEPTIONS_PAGE_MAX)}; defaults to ${String(IMPORT_EXCEPTIONS_PAGE_DEFAULT)}. Read \`total\` for the full count matching the filter.`),cursor:external_exports.string().min(1).optional().describe("Opaque keyset cursor \u2014 pass the previous page's `nextCursor` to get the next page. `null` `nextCursor` means the last page.")}),ListImportRunsOutputSchema=external_exports.object({runs:external_exports.array(AssetImportRunSchema),total:external_exports.number().int().nonnegative(),nextCursor:external_exports.string().min(1).nullish()}),ListImportExceptionsInputSchema=external_exports.strictObject({get runId(){return AssetImportRunIdSchema.optional()},get status(){return AssetImportExceptionStatusSchema.optional()},limit:external_exports.number().int().min(1).max(IMPORT_EXCEPTIONS_PAGE_MAX).optional().describe(`Page size, 1\u2013${String(IMPORT_EXCEPTIONS_PAGE_MAX)}; defaults to ${String(IMPORT_EXCEPTIONS_PAGE_DEFAULT)}. Read \`total\` for the full count matching the filter.`),cursor:external_exports.string().min(1).optional().describe("Opaque keyset cursor \u2014 pass the previous page's `nextCursor` to get the next page. `null` `nextCursor` means the last page.")}),ListImportExceptionsOutputSchema=external_exports.object({exceptions:external_exports.array(AssetImportExceptionSchema),total:external_exports.number().int().nonnegative(),nextCursor:external_exports.string().min(1).nullish()}),ResolveImportExceptionInputSchema=external_exports.strictObject({get exceptionId(){return AssetImportExceptionIdSchema},get status(){return AssetImportExceptionResolutionSchema},get resolvedAssetId(){return AssetIdSchema.optional()}}),ResolveImportExceptionOutputSchema=AssetImportExceptionSchema,IMPORT_EXCEPTIONS_RESOLVE_MANY_MAX=100,ResolveManyRefusalReasonSchema=external_exports.enum(["not-found","already-resolved"]),ResolveManyImportExceptionsInputSchema=external_exports.strictObject({get exceptionIds(){return external_exports.array(AssetImportExceptionIdSchema).min(1).max(IMPORT_EXCEPTIONS_RESOLVE_MANY_MAX).describe(`1\u2013${String(IMPORT_EXCEPTIONS_RESOLVE_MANY_MAX)} exception ids. Distinct \u2014 a repeated id would report a false already-resolved refusal against its own first item.`)},get status(){return AssetImportExceptionResolutionSchema}}),ResolveManyImportExceptionsItemResultSchema=external_exports.discriminatedUnion("outcome",[external_exports.object({get exceptionId(){return AssetImportExceptionIdSchema},outcome:external_exports.literal("moved")}),external_exports.object({get exceptionId(){return AssetImportExceptionIdSchema},outcome:external_exports.literal("refused"),get reason(){return ResolveManyRefusalReasonSchema},get atStatus(){return AssetImportExceptionStatusSchema.optional()}})]),ResolveManyImportExceptionsOutputSchema=external_exports.object({summary:external_exports.object({requested:external_exports.number().int().min(0),moved:external_exports.number().int().min(0),refused:external_exports.number().int().min(0)}),results:external_exports.array(ResolveManyImportExceptionsItemResultSchema)}),ImportRunRetryPlanSchema=external_exports.object({get runId(){return AssetImportRunIdSchema},get datasetId(){return DatasetIdSchema},get versionId(){return DatasetVersionIdSchema},request:external_exports.record(external_exports.string(),external_exports.unknown()),openRowIndexes:external_exports.array(external_exports.number().int().nonnegative()).max(IMPORT_EXCEPTIONS_PAGE_MAX),openRowIndexesTruncated:external_exports.boolean().optional()}),GetImportRunRetryPlanInputSchema=external_exports.strictObject({get runId(){return AssetImportRunIdSchema}});var assetCountConfigSchema=external_exports.object({label:external_exports.string().default("total assets").describe("Sublabel shown beneath the count, naming what is being counted.")}).meta({examples:[{label:"assets tracked"}]});var assetManagerConfigSchema=external_exports.object({view:external_exports.enum(["list","split","map"]).default("list").describe("Which /assets presentation this widget seeds on first render: list (the sortable table), split (master list + docked detail + map), or map (the pin view). Defaults to list.")}).meta({examples:[{view:"list"}]});var assetConfigurationComponentContract={name:"asset-configuration",binds:"none",configVersion:"1",configSchema:external_exports.object({}),description:"Asset vocabulary admin: the categories, types and property templates assets are classified with, plus the asset-code numbering schemes and derived-value routing. Tenant-admin territory, not an operator surface.",grain:"page"},assetViewConfigSchema=external_exports.object({});var ASSET_IMPORT_MAPPING_KIND={domain:"assets",type:"asset-import-mapping"},assetImportMappingEditorComponentContract={name:"asset-import-mapping-editor",binds:"entity",bindsToResource:"asset-import-mappings",entity:ASSET_IMPORT_MAPPING_KIND,configVersion:"1",configSchema:external_exports.object({}),description:"Edit one saved import mapping \u2014 how a dataset's rows become assets: pick a dataset to sample, review the mapping's name, unique ID, type, lifecycle, start date, parent and the column it is matched on, which columns become properties and the ID system, see which types and ID systems already exist or will be created, and save the mapping's next version.",grain:"page"},assetImportMappingCreateComponentContract={name:"asset-import-mapping-create",binds:"none",configVersion:"1",configSchema:external_exports.object({}),description:"Create a new import mapping \u2014 how a dataset's rows become assets: pick a dataset, review the mapping guessed from its columns (name, unique ID, type, lifecycle, start date, parent and the column it is matched on, which columns become properties, the ID system), see which types and ID systems already exist or will be created, and save it as a named, versioned import mapping that an import runs.",grain:"page"},assetTreePreviewComponentContract={name:"asset-tree-preview",binds:"entity",bindsToResource:"asset-import-mappings",entity:ASSET_IMPORT_MAPPING_KIND,configVersion:"1",configSchema:external_exports.object({}),description:"The asset tree one saved import mapping would build from a dataset, before anything is created: pick a dataset, then see its levels with each level's mix of asset types, the roots, the deepest level, the assets that won't roll up because their parent is not in the file (with the rows that cause it), and duplicate names and IDs. The totals are the server's dry run; nothing is created until the import runs.",grain:"page"};var UnlinkManyInputSchema=external_exports.strictObject({get relationshipType(){return HierarchyRelationshipTypeSchema},get selection(){return AssetSelectionSchema},hierarchy:HierarchyScopeSchema.optional(),idempotencyKey:IdempotencyKeySchema,returnResults:ReturnResultsSchema.optional()}),UnlinkRefusalReasonSchema=external_exports.enum(["asset-not-found","no-such-edge"]),UnlinkManyItemResultSchema=external_exports.discriminatedUnion("status",[external_exports.object({get assetId(){return AssetIdSchema},status:external_exports.literal("ended"),isolated:external_exports.boolean()}),external_exports.object({get assetId(){return AssetIdSchema},status:external_exports.literal("refused"),reason:UnlinkRefusalReasonSchema,isolated:external_exports.boolean()})]),UnlinkManyOutputSchema=external_exports.object({summary:external_exports.object({requested:external_exports.number().int().min(0),ended:external_exports.number().int().min(0),refused:external_exports.number().int().min(0),isolated:external_exports.number().int().min(0)}),results:external_exports.array(UnlinkManyItemResultSchema)}),UnlinkManyResponseSchema=UnlinkManyOutputSchema.extend({accessUpdate:AccessUpdateStateSchema}),RelateManyInputSchema=external_exports.strictObject({get relationshipType(){return AssetRelationshipTypeSchema},get targetAssetId(){return AssetIdSchema},get selection(){return AssetSelectionSchema},idempotencyKey:IdempotencyKeySchema,returnResults:ReturnResultsSchema.optional()}),RelateRefusalReasonSchema=external_exports.enum(["asset-not-found","self-edge","duplicate-edge","would-cycle"]),RelateManyItemResultSchema=external_exports.discriminatedUnion("status",[external_exports.object({get assetId(){return AssetIdSchema},status:external_exports.literal("created")}),external_exports.object({get assetId(){return AssetIdSchema},status:external_exports.literal("refused"),reason:RelateRefusalReasonSchema})]),RelateManyOutputSchema=external_exports.object({summary:external_exports.object({requested:external_exports.number().int().min(0),created:external_exports.number().int().min(0),refused:external_exports.number().int().min(0)}),results:external_exports.array(RelateManyItemResultSchema)}),RelateManyResponseSchema=RelateManyOutputSchema.extend({accessUpdate:AccessUpdateStateSchema});var AssetExportScalarFieldSchema=external_exports.enum(["assetId","name","category","type","lifecycleStatus","effectiveFrom","effectiveTo","location"]),AssetExportColumnSourceSchema=external_exports.discriminatedUnion("kind",[external_exports.object({kind:external_exports.literal("scalar"),field:AssetExportScalarFieldSchema}),external_exports.object({kind:external_exports.literal("property"),key:external_exports.string().min(1)}),external_exports.object({kind:external_exports.literal("derived"),code:external_exports.string().min(1),part:external_exports.enum(["value","unit"])}),external_exports.object({kind:external_exports.literal("parent"),get relationshipType(){return HierarchyRelationshipTypeSchema},part:external_exports.enum(["name","id"])})]),AssetExportColumnSchema=external_exports.object({id:external_exports.string().min(1),header:external_exports.string().min(1),source:AssetExportColumnSourceSchema}),SCALAR_COLUMNS=Object.freeze([{id:"assetId",header:"Asset ID",source:{kind:"scalar",field:"assetId"}},{id:"name",header:"Name",source:{kind:"scalar",field:"name"}},{id:"category",header:"Category",source:{kind:"scalar",field:"category"}},{id:"type",header:"Type",source:{kind:"scalar",field:"type"}},{id:"lifecycleStatus",header:"Lifecycle",source:{kind:"scalar",field:"lifecycleStatus"}},{id:"effectiveFrom",header:"Valid from",source:{kind:"scalar",field:"effectiveFrom"}},{id:"effectiveTo",header:"Valid to",source:{kind:"scalar",field:"effectiveTo"}}]),LOCATION_COLUMN=Object.freeze({id:"location",header:"Location (WKT)",source:{kind:"scalar",field:"location"}});var AssetExportFormatSchema=external_exports.enum(["csv","xlsx"]),AssetExportMediaTypeSchema=external_exports.enum(["text/csv","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"]);var AssetExportEstimateSchema=external_exports.object({rowCount:external_exports.number().int().nonnegative(),maxRows:external_exports.number().int().positive(),columnCount:external_exports.number().int().nonnegative(),maxColumns:external_exports.number().int().positive(),rowCountAtLeast:external_exports.literal(!0).optional(),capReached:SearchCapReachedSchema.optional()}),AssetExportGrantSchema=external_exports.object({url:external_exports.url(),headers:external_exports.record(external_exports.string(),external_exports.string()),expiresAt:external_exports.iso.datetime(),mediaType:AssetExportMediaTypeSchema,filename:external_exports.string().min(1),rowCount:external_exports.number().int().nonnegative()});var AssetExportJobStateSchema=external_exports.enum(["PENDING","RUNNING","READY","FAILED"]),AssetExportJobKindSchema=external_exports.enum(["assets","duplicate-assets"]);var AssetExportHandleSchema=external_exports.object({exportId:external_exports.string().min(1),state:AssetExportJobStateSchema,rowCount:external_exports.number().int().nonnegative(),columnCount:external_exports.number().int().nonnegative(),tilesTotal:external_exports.number().int().nonnegative()}),AssetExportStatusInputSchema=external_exports.strictObject({exportId:external_exports.string().min(1)}),AssetExportStatusSchema=external_exports.discriminatedUnion("state",[external_exports.object({state:external_exports.literal("pending"),rowCount:external_exports.number().int().nonnegative(),columnCount:external_exports.number().int().nonnegative(),tilesDone:external_exports.number().int().nonnegative(),tilesTotal:external_exports.number().int().nonnegative()}),external_exports.object({state:external_exports.literal("ready"),get grant(){return AssetExportGrantSchema},byteSize:external_exports.number().int().nonnegative()}),external_exports.object({state:external_exports.literal("failed"),reason:external_exports.string().min(1),retryable:external_exports.boolean()})]),ASSET_EXPORT_IDEMPOTENCY_KEY_DESCRIPTION="Client-minted replay key for this export authorization \u2014 unique per (tenant, caller, key). A retry with the same key and the same selection replays the ONE recorded authorization and returns a FRESH grant (a new URL with a future expiry) \u2014 never the first call's possibly-expired URL, and never a second Record. A reused key with a DIFFERENT selection or format is refused, as is another caller's key. Mint a new key per intended export.",AssetExportIdempotencyKeySchema=IdempotencyKeySchema.describe(ASSET_EXPORT_IDEMPOTENCY_KEY_DESCRIPTION),AssetExportEstimateInputSchema=external_exports.strictObject({get selection(){return AssetExportSelectionSchema}}),AssetExportInputSchema=external_exports.strictObject({get selection(){return AssetExportSelectionSchema},format:AssetExportFormatSchema,get idempotencyKey(){return AssetExportIdempotencyKeySchema}});var EXPORT_SEARCH_CAP_REASON="search-cap",AssetExportOverCapDataSchema=external_exports.object({reason:external_exports.literal(EXPORT_SEARCH_CAP_REASON)}).optional();var DuplicateAssetsExportFiltersSchema=DuplicateAssetsInputSchema.omit({page:!0,pageSize:!0}),DuplicateAssetsExportSelectionSchema=external_exports.strictObject({kind:external_exports.literal("duplicate-assets"),filters:DuplicateAssetsExportFiltersSchema}),DuplicateAssetsExportInputSchema=external_exports.strictObject({idempotencyKey:AssetExportIdempotencyKeySchema,filters:DuplicateAssetsExportFiltersSchema});var ASSET_COUNT_SAMPLE_MAX=50,AssetCountInputSchema=external_exports.strictObject({get selection(){return AssetCountSelectionSchema},get asOf(){return AsOfSchema.optional()},sampleLimit:external_exports.number().int().min(0).max(ASSET_COUNT_SAMPLE_MAX).optional()}),AssetCountOutputSchema=external_exports.object({total:external_exports.number().int().min(0),totalAtLeast:external_exports.literal(!0).optional(),capReached:SearchCapReachedSchema.optional(),get sampleAssetIds(){return external_exports.array(AssetIdSchema)}});var ASSET_SNAPSHOT_TYPES=["asset"],SnapshotAskSchema2=external_exports.strictObject({domain:external_exports.literal("assets"),type:external_exports.enum(ASSET_SNAPSHOT_TYPES),id:external_exports.string().min(1)});var AssetTemplateVersionIdSchema=external_exports.string().min(1).brand(),AssetVersionIdSchema=external_exports.string().min(1).brand().describe("Version-row id \u2014 OUTPUT ONLY, and deliberately unstable: an asset gains a new one on every edit. Never pass this where an `assetId` is asked for."),AssetRelationshipIdSchema=external_exports.string().min(1).brand(),AssetRelationshipVersionIdSchema=external_exports.string().min(1).brand(),AssetRelationshipCategorySchema=external_exports.enum(["PHYSICAL","LOGICAL"]),AssetRelationshipTypeSchema=external_exports.enum(["CONTAINS","FLOWS_TO","CONNECTED_TO","PART_OF","REPORTS_TO","BELONGS_TO"]).describe("Edge type, read subject\u2192object (`CONTAINS`: subject contains object). The four HIERARCHICAL types \u2014 CONTAINS, PART_OF, REPORTS_TO, BELONGS_TO \u2014 are the only ones the tree reads (parents/children/subtree/roots) and the cycle check operate on. FLOWS_TO and CONNECTED_TO are stored but non-hierarchical: passing one to a tree read is rejected.");var PropertyValueTypeSchema=external_exports.enum(["STRING","NUMBER","BOOLEAN","ENUM","MEASUREMENT"]),ObservedPropertyRefSchema=external_exports.object({observedProperty:external_exports.string().min(1),uom:external_exports.string().min(1)}),clientLibraryCatalog=Object.freeze({getObservedProperty:observedProperty=>OBSERVED_PROPERTY_CATALOG_ENTRIES.find(entry=>entry.observedProperty===observedProperty),listObservedProperties:()=>OBSERVED_PROPERTY_CATALOG_ENTRIES}),AssetRefSchema=external_exports.object({assetId:AssetIdSchema}),FeatureSchema=external_exports.object({assetId:AssetIdSchema,externalIds:external_exports.array(external_exports.string().min(1)).optional(),geometry:GeoJsonGeometrySchema.nullable().optional(),path:external_exports.array(AssetIdSchema).optional(),assetAsOf:external_exports.iso.datetime().optional()}),TemplatePropertyBaseSchema=external_exports.strictObject({code:external_exports.string().min(1).max(64),displayName:external_exports.string().min(1),required:external_exports.boolean()}),buildTemplatePropertySchema=allowedValues=>external_exports.discriminatedUnion("valueType",[TemplatePropertyBaseSchema.extend({valueType:external_exports.literal("STRING"),pattern:external_exports.string().min(1).max(200).optional()}),TemplatePropertyBaseSchema.extend({valueType:external_exports.literal("NUMBER"),min:external_exports.number().optional(),max:external_exports.number().optional()}),TemplatePropertyBaseSchema.extend({valueType:external_exports.literal("BOOLEAN")}),TemplatePropertyBaseSchema.extend({valueType:external_exports.literal("ENUM"),allowedValues}),TemplatePropertyBaseSchema.extend({valueType:external_exports.literal("MEASUREMENT"),observedProperty:ObservedPropertyRefSchema,min:external_exports.number().optional(),max:external_exports.number().optional()})]),TemplatePropertySchema=buildTemplatePropertySchema(external_exports.array(external_exports.string().min(1))),TEMPLATE_PROPERTIES_WIRE_MAX=1e3,TEMPLATE_DERIVED_PROPERTIES_WIRE_MAX=1e3,TEMPLATE_ENUM_VALUES_WIRE_MAX=1e3,TemplatePropertyInputSchema=buildTemplatePropertySchema(external_exports.array(external_exports.string().min(1)).max(TEMPLATE_ENUM_VALUES_WIRE_MAX)),AssetTemplateVersionSchema=external_exports.object({id:AssetTemplateVersionIdSchema,assetTypeId:AssetTypeIdSchema,properties:external_exports.array(TemplatePropertySchema),derivedProperties:external_exports.array(DerivedPropertyDeclarationSchema).default([]),effectiveFrom:external_exports.iso.datetime(),effectiveTo:external_exports.iso.datetime().nullable()}),GetAssetTemplateInputSchema=external_exports.strictObject({assetTypeId:AssetTypeIdSchema}),AssetSchema=external_exports.object({id:AssetVersionIdSchema,assetId:AssetIdSchema,name:external_exports.string().min(1),assetTypeId:AssetTypeIdSchema,lifecycleStatus:AssetLifecycleStatusSchema,properties:PropertyValuesSchema,templateVersionId:AssetTemplateVersionIdSchema,effectiveFrom:external_exports.iso.datetime(),effectiveTo:external_exports.iso.datetime().nullable(),geometry:GeoJsonGeometrySchema.nullable().optional()}),AssetReadSchema=AssetSchema.extend({appliedDatedValueIds:AppliedDatedValueIdsSchema.optional()}),CreateAssetInputSchema=external_exports.strictObject({name:external_exports.string().min(1),assetTypeId:AssetTypeIdSchema,lifecycleStatus:AssetLifecycleStatusSchema,properties:PropertyValuesInputSchema,effectiveFrom:InitialEffectiveFromSchema.optional()}),GetAssetInputSchema=external_exports.strictObject({assetId:AssetIdSchema,asOf:AsOfSchema.optional(),knownAt:KnownAtSchema.optional()}),UpdateAssetInputSchema=external_exports.strictObject({assetId:AssetIdSchema,name:external_exports.string().min(1),lifecycleStatus:AssetLifecycleStatusSchema,properties:PropertyValuesInputSchema,effectiveFrom:EffectiveFromSchema.optional()}),ChildReparentingSchema=external_exports.discriminatedUnion("mode",[external_exports.strictObject({mode:external_exports.literal("refuse")}),external_exports.strictObject({mode:external_exports.literal("reparent"),newParentAssetId:AssetIdSchema})]),DeleteAssetInputSchema=external_exports.strictObject({assetId:AssetIdSchema,childReparenting:ChildReparentingSchema.optional()}),GovernedCreateAssetInputSchema=CreateAssetInputSchema.extend({idempotencyKey:IdempotencyKeySchema}),GovernedUpdateAssetInputSchema=UpdateAssetInputSchema.extend({idempotencyKey:IdempotencyKeySchema}),GovernedDeleteAssetInputSchema=DeleteAssetInputSchema.extend({idempotencyKey:IdempotencyKeySchema}),DeleteImpactInputSchema=external_exports.strictObject({assetIds:external_exports.array(AssetIdSchema).min(1).max(DELETE_IMPACT_MAX_IDS)}),DeleteImpactEdgeSchema=external_exports.object({relationshipId:AssetRelationshipIdSchema,relationshipType:AssetRelationshipTypeSchema,otherAssetId:AssetIdSchema}),DeleteImpactHierarchyEdgeSchema=DeleteImpactEdgeSchema.extend({relationshipType:HierarchyRelationshipTypeSchema,direction:HierarchyEdgeDirectionSchema}),DeleteImpactBindingSchema=external_exports.object({bindingId:ExternalIdBindingIdSchema,system:ExternalIdSystemSchema,value:ExternalIdValueSchema}),DeleteImpactEdgeSectionSchema=external_exports.object({total:external_exports.number().int().min(0),sample:external_exports.array(DeleteImpactEdgeSchema)}),DeleteImpactBindingSectionSchema=external_exports.object({total:external_exports.number().int().min(0),sample:external_exports.array(DeleteImpactBindingSchema)}),DeleteImpactHierarchySectionSchema=external_exports.object({total:external_exports.number().int().min(0),childTotal:external_exports.number().int().min(0),sample:external_exports.array(DeleteImpactHierarchyEdgeSchema)}),DeleteImpactItemSchema=external_exports.object({assetId:AssetIdSchema,verdict:DeleteImpactVerdictSchema,hierarchyEdges:DeleteImpactHierarchySectionSchema,storageEdges:DeleteImpactEdgeSectionSchema,externalIdBindings:DeleteImpactBindingSectionSchema}),DeleteImpactOutputSchema=external_exports.object({items:external_exports.array(DeleteImpactItemSchema)}),DeleteManyInputSchema=external_exports.strictObject({assetIds:external_exports.array(AssetIdSchema).min(1).max(DELETE_MANY_MAX_IDS),idempotencyKey:IdempotencyKeySchema,returnResults:ReturnResultsSchema.optional()}),DeleteManyItemResultSchema=external_exports.discriminatedUnion("status",[external_exports.object({assetId:AssetIdSchema,status:external_exports.literal("deleted")}),external_exports.object({assetId:AssetIdSchema,status:external_exports.literal("refused"),reason:DeleteRefusalReasonSchema})]),DeleteManyOutputSchema=external_exports.object({summary:external_exports.object({requested:external_exports.number().int().min(0),deleted:external_exports.number().int().min(0),refused:external_exports.number().int().min(0)}),results:external_exports.array(DeleteManyItemResultSchema)}),SetAssetLocationInputSchema=external_exports.strictObject({assetId:AssetIdSchema,geometry:GeoJsonGeometryInputSchema.nullable()}),GovernedSetAssetLocationInputSchema=SetAssetLocationInputSchema.extend({idempotencyKey:IdempotencyKeySchema}),ASSET_IDS_MAX_PER_PAGE=200,ASSET_VERSION_IDS_MAX=200,EXCLUDE_ASSET_IDS_MAX=1e3,ListAssetsInputSchema=external_exports.strictObject({asOf:AsOfSchema.optional(),knownAt:KnownAtSchema.optional(),assetIds:external_exports.array(AssetIdSchema).min(1).max(ASSET_IDS_MAX_PER_PAGE).optional(),subtreeOf:AssetSubtreeScopeSchema.optional(),underAssetIds:AssetBranchScopeSchema.optional().describe(UNDER_ASSET_IDS_DESCRIPTION),excludeAssetIds:external_exports.array(AssetIdSchema).min(1).max(EXCLUDE_ASSET_IDS_MAX).optional().describe("Assets to SUBTRACT from whatever the other filters match \u2014 the opposite direction to `assetIds`, which ADDS. Applied last, so an id in both is excluded. Excluding an id nothing matched is a no-op, never an error."),categoryIds:external_exports.array(AssetCategoryIdSchema).min(1).max(50).optional(),assetTypeIds:external_exports.array(AssetTypeIdSchema).min(1).max(50).optional(),lifecycleStatuses:external_exports.array(AssetLifecycleStatusSchema).min(1).max(50).optional(),nameContains:external_exports.string().min(1).optional().describe("THE name filter \u2014 a case-insensitive substring match on the asset name. There is no `name` parameter; this is it for a name-only match. To also find an asset by the start of an external ID, send `search`."),search:AssetSearchSchema.optional(),propertyFilters:AssetPropertyFilterSchema.optional(),conditions:AssetConditionsSchema.optional(),hasGeometry:external_exports.boolean().optional(),within:GeoJsonPolygonSchema.optional(),orderBy:AssetOrderBySchema.optional(),offset:external_exports.number().int().min(0).optional().describe("Rows to skip; defaults to 0. Ignored when `cursor` is supplied."),limit:external_exports.number().int().min(1).max(200).optional().describe("Page size, 1\u2013200; defaults to 50. Read `total` for the full filtered count \u2014 present on a first-page/offset call, omitted on a cursor-paged call."),cursor:external_exports.string().min(1).optional().describe("Opaque keyset cursor \u2014 pass the previous page's `nextCursor` to get the next page. WINS over `offset` when both are present; `null` `nextCursor` means the last page.")}),ListAssetsOutputSchema=external_exports.object({items:external_exports.array(AssetReadSchema),total:external_exports.number().int().min(0).optional(),nextCursor:external_exports.string().nullable().optional(),matchedExternalIds:external_exports.array(AssetExternalIdSchema).optional(),totalAtLeast:external_exports.literal(!0).optional(),capReached:SearchCapReachedSchema.optional()}),AssetCountSelectionSchema=ListAssetsInputSchema.omit(ASSET_SELECTION_OMITTED),AssetSelectionSchema=AssetCountSelectionSchema.extend({propertyFilters:AssetPropertyEqualsFilterSchema.optional()}),AssetListFilterSchema=ListAssetsInputSchema.omit({orderBy:!0,offset:!0,limit:!0,cursor:!0}),AssetDescendantScopeSchema=external_exports.strictObject({rootAssetIds:external_exports.array(AssetIdSchema).min(1).max(ASSET_IDS_MAX_PER_PAGE),relationshipType:HierarchyRelationshipTypeSchema}),AssetExportSelectionSchema=ListAssetsInputSchema.omit({offset:!0,limit:!0,cursor:!0,asOf:!0,knownAt:!0,subtreeOf:!0,underAssetIds:!0,conditions:!0}).extend({descendantOf:AssetDescendantScopeSchema.optional()}),AssetFieldSchema=AssetSchema.keyof(),ASSET_FIELDS=Object.freeze([...AssetFieldSchema.options]),ListAssetIndexInputSchema=ListAssetsInputSchema.omit({asOf:!0,knownAt:!0}).extend({fields:external_exports.array(AssetFieldSchema).min(1).max(ASSET_FIELDS.length)}),AssetIndexItemSchema=AssetSchema.partial().required({assetId:!0}),ListAssetIndexOutputSchema=ListAssetsOutputSchema.extend({items:external_exports.array(AssetIndexItemSchema)}),ListAssetVersionsInputSchema=external_exports.strictObject({assetId:AssetIdSchema,versionIds:external_exports.array(external_exports.string().min(1)).min(1).max(ASSET_VERSION_IDS_MAX).optional()}),ListAssetActivityInputSchema=external_exports.strictObject({assetId:AssetIdSchema,cursor:external_exports.string().min(1).optional(),limit:external_exports.number().int().positive().max(200).optional()}),AssetCategoryCountSchema=external_exports.object({categoryId:AssetCategoryIdSchema,key:external_exports.string().min(1),displayName:external_exports.string().min(1),count:external_exports.number().int().min(0)}),AssetTypeCountSchema=external_exports.object({assetTypeId:AssetTypeIdSchema,categoryId:AssetCategoryIdSchema,key:external_exports.string().min(1),displayName:external_exports.string().min(1),count:external_exports.number().int().min(0)}),AssetCategorySummarySchema=external_exports.object({total:external_exports.number().int().min(0),byCategory:external_exports.array(AssetCategoryCountSchema),byType:external_exports.array(AssetTypeCountSchema)}),FlowDescriptorSchema=external_exports.object({observedProperty:ObservedPropertyRefSchema,unit:external_exports.string().min(1),fraction:external_exports.number().min(0).max(1)}),AssetRelationshipSchema=external_exports.object({id:AssetRelationshipVersionIdSchema,relationshipId:AssetRelationshipIdSchema,relationshipType:AssetRelationshipTypeSchema,subjectAssetId:AssetIdSchema,objectAssetId:AssetIdSchema,effectiveFrom:external_exports.iso.datetime(),effectiveTo:external_exports.iso.datetime().nullable(),flowDescriptor:FlowDescriptorSchema.optional(),hierarchyId:HierarchyIdSchema.nullable().default(null)}),AssetRelationshipWriteResultSchema=AssetRelationshipSchema.extend({accessUpdate:AccessUpdateStateSchema}),CreateAssetRelationshipInputSchema=external_exports.strictObject({idempotencyKey:UnreceiptedIdempotencyKeySchema,relationshipType:AssetRelationshipTypeSchema,subjectAssetId:AssetIdSchema,objectAssetId:AssetIdSchema,flowDescriptor:FlowDescriptorSchema.optional(),hierarchy:HierarchyScopeSchema.optional(),effectiveFrom:EffectiveFromSchema.optional(),effectiveTo:EffectiveToSchema.optional(),...DATED_CREATE_FIELDS}),RawCreateAssetRelationshipInputSchema=CreateAssetRelationshipInputSchema.omit({idempotencyKey:!0}),EndAssetRelationshipInputSchema=external_exports.strictObject({idempotencyKey:UnreceiptedIdempotencyKeySchema,relationshipId:AssetRelationshipIdSchema,effectiveTo:EffectiveToSchema.optional()}),RawEndAssetRelationshipInputSchema=EndAssetRelationshipInputSchema.omit({idempotencyKey:!0}),MoveRelationshipInputSchema=external_exports.strictObject({relationshipId:AssetRelationshipIdSchema,newParentAssetId:AssetIdSchema,effectiveFrom:EffectiveFromSchema.optional(),...DATED_CREATE_FIELDS}),GovernedMoveRelationshipInputSchema=MoveRelationshipInputSchema.extend({idempotencyKey:IdempotencyKeySchema}),ListAssetRelationshipsInputSchema=external_exports.strictObject({assetId:AssetIdSchema,relationshipType:AssetRelationshipTypeSchema.optional(),asOf:AsOfSchema.optional()}),QUALITY_PAGE_LIMIT_MAX=200;var OrphanedAssetsInputSchema=external_exports.strictObject({offset:external_exports.number().int().min(0).optional(),limit:external_exports.number().int().min(1).max(QUALITY_PAGE_LIMIT_MAX).optional(),nameContains:external_exports.string().min(1).optional()}),OrphanedAssetsOutputSchema=external_exports.object({items:external_exports.array(SubtreeNodeSchema),count:RelationshipRootsCountSchema}),UnparentedAssetsInputSchema=external_exports.strictObject({offset:external_exports.number().int().min(0).optional(),limit:external_exports.number().int().min(1).max(QUALITY_PAGE_LIMIT_MAX).optional(),nameContains:external_exports.string().min(1).optional(),get assetTypeId(){return AssetTypeIdSchema.optional()},hierarchy:UnparentedScopeSchema.optional()}),UnparentedAssetsOutputSchema=external_exports.object({items:external_exports.array(SubtreeNodeSchema),count:RelationshipRootsCountSchema}),DanglingEdgeSchema=external_exports.object({relationship:AssetRelationshipSchema,missingSubject:external_exports.boolean(),missingObject:external_exports.boolean()}),EdgeCycleSchema=external_exports.object({relationshipType:HierarchyRelationshipTypeSchema,path:external_exports.array(AssetIdSchema).min(2)}),MultiParentChildSchema=external_exports.object({assetId:AssetIdSchema,relationshipType:HierarchyRelationshipTypeSchema,parentCount:external_exports.number().int().min(2)}),EdgeSanityReportSchema=external_exports.object({selfEdges:external_exports.object({total:external_exports.number().int().min(0),sample:external_exports.array(AssetRelationshipSchema)}),danglingEdges:external_exports.object({total:external_exports.number().int().min(0),sample:external_exports.array(DanglingEdgeSchema)}),multiParentChildren:external_exports.object({total:external_exports.number().int().min(0),sample:external_exports.array(MultiParentChildSchema)}),nonCanonicalConnections:external_exports.object({total:external_exports.number().int().min(0),sample:external_exports.array(AssetRelationshipSchema)}),cycles:external_exports.object({sample:external_exports.array(EdgeCycleSchema),limitReached:external_exports.boolean()})}),RelationshipTypeCountSchema=external_exports.object({relationshipType:AssetRelationshipTypeSchema,count:external_exports.number().int().nonnegative()}),RelationshipEdgeSummarySchema=external_exports.object({total:external_exports.number().int().nonnegative(),byType:external_exports.array(RelationshipTypeCountSchema)});var RecordsPageOptionsShape={cursor:external_exports.string().min(1).optional().describe("Opaque keyset cursor copied verbatim from the previous page's `cursor` \u2014 pass it back to fetch the next page, and keep going until the response carries none. Never parse or construct one. Omit for the first page."),limit:external_exports.number().int().positive().optional().describe("Records per page. Omitted \u2192 50. Must be a positive integer.")},RecordsPageSchema=external_exports.object({items:external_exports.array(ActionRecordSchema),cursor:external_exports.string().min(1).optional()}),RecordsByEntityInputSchema=external_exports.object({ref:EntityRefInputSchema,...RecordsPageOptionsShape}),RecordsByActorInputSchema=external_exports.object({principal:external_exports.string().min(1),...RecordsPageOptionsShape}),RecordsByFlowRunInputSchema=external_exports.object({flowRunRecordId:RecordIdInputSchema,...RecordsPageOptionsShape}),RecordsByTimeInputSchema=external_exports.object({from:external_exports.iso.datetime(),to:external_exports.iso.datetime(),...RecordsPageOptionsShape}),recordsContract=oc.router({byEntity:oc.input(RecordsByEntityInputSchema).output(RecordsPageSchema),byActor:oc.input(RecordsByActorInputSchema).output(RecordsPageSchema),byFlowRun:oc.input(RecordsByFlowRunInputSchema).output(RecordsPageSchema),byTime:oc.input(RecordsByTimeInputSchema).output(RecordsPageSchema)});var assetsAccessContract=oc.router({status:oc.input(AccessStatusInputSchema).output(AccessStatusSchema),rerun:oc.output(RerunAccessUpdateResultSchema).errors({SERVICE_UNAVAILABLE:{message:"access updates are not re-run on this deployment",data:AccessUpdateRunnerUnavailableDataSchema}})});var CONDITION_ERRORS={INVALID_CONDITION:{status:400,message:"A condition does not fit its field: check the operator and value against the field, or remove the condition",data:InvalidConditionDataSchema}};var datedValueProcedures={setDatedValues:oc.input(SetDatedValuesInputSchema).output(SetDatedValuesOutputSchema),listDatedValues:oc.input(ListDatedValuesInputSchema).output(ListDatedValuesOutputSchema),listDatedValueChanges:oc.input(ListDatedValueChangesInputSchema).output(ListDatedValueChangesOutputSchema)},revertDatedValuesProcedures={revertDatedValues:oc.input(RevertDatedValuesInputSchema).output(RevertDatedValuesOutputSchema)};var READ_TX_BUDGET_ERRORS={TX_BUDGET_OVERRUN:{status:422,message:"This read ran out of its transaction time; narrow it \u2014 a lower root or a shallower maxDepth for a walk, an id or a narrower filter for a list \u2014 or try again if the system was busy",data:ReadTxBudgetOverrunDataSchema}},WALK_OVER_CAP_ERRORS={OVER_CAP:{status:422,message:"This hierarchy walk reaches more assets than one walk can return; narrow it with a shallower maxDepth or a lower root"}},DESCENDANTS_OVER_CAP_ERRORS={OVER_CAP:{status:422,message:"This hierarchy walk reaches more assets than one descendants read can return; narrow it with a shallower maxDepth or a lower root"}},LONG_READ_BUSY_ERRORS={SERVICE_UNAVAILABLE:{status:503,message:"This server is already running its long reads; the walk was not started. Try again shortly",data:LongReadBusyDataSchema}},WALK_CALLER_REFUSAL_ERRORS={FORBIDDEN:{status:403,message:"relationships.walkDescendants serves unattended runners only; read relationships.descendants instead",data:RunnerOnlyDataSchema},NOT_IMPLEMENTED:{status:501,message:"this host runs no long reads; read relationships.descendants instead",data:NoLongReadDataSchema}};var assetsDescendantsProcedures={descendants:oc.input(AssetDescendantsInputSchema).output(AssetDescendantsOutputSchema).errors({...DESCENDANTS_OVER_CAP_ERRORS,...READ_TX_BUDGET_ERRORS}).meta({agenticSurface:"excluded",agenticSurfaceReason:"semantic"}),walkDescendants:oc.input(AssetDescendantsInputSchema).output(AssetDescendantsOutputSchema).errors({...DESCENDANTS_OVER_CAP_ERRORS,...READ_TX_BUDGET_ERRORS,...LONG_READ_BUSY_ERRORS,...WALK_CALLER_REFUSAL_ERRORS}).meta({agenticSurface:"excluded",agenticSurfaceReason:"semantic"})};var assetsExternalIdContract=oc.router({create:oc.input(GovernedBindExternalIdInputSchema).output(ExternalIdBindingSchema),createMany:oc.input(BulkBindExternalIdInputSchema).output(BulkBindExternalIdOutputSchema),get:oc.input(ResolveExternalIdInputSchema).output(ExternalIdBindingSchema),resolveMany:oc.input(ResolveExternalIdManyInputSchema).output(ResolveExternalIdManyOutputSchema).errors({NOT_FOUND:{message:"the external-ID system is not configured",data:external_exports.object({code:external_exports.literal(EXTERNAL_ID_SYSTEM_NOT_CONFIGURED),system:external_exports.string()})}}),list:oc.input(ListAssetExternalIdsInputSchema).output(external_exports.array(ExternalIdBindingSchema)),delete:oc.input(GovernedUnbindExternalIdInputSchema).output(ExternalIdBindingSchema),startBindJob:oc.input(StartExternalIdBindJobInputSchema).output(StartExternalIdBindJobResultSchema),bindJobStatus:oc.input(ExternalIdBindJobStatusInputSchema).output(ExternalIdBindJobStatusSchema)}),SYSTEM_TERM_ERRORS={ASSET_SYSTEM_TERM_UNKNOWN:{status:422,message:"the term is not in this tenant\u2019s vocabulary \u2014 pick one from the vocabulary list"},ASSET_SYSTEM_TERM_UNCHECKABLE:{status:424,message:"the vocabulary could not be read to check the term; nothing was changed"}},assetsSystemContract=oc.router({create:oc.input(CreateAssetSystemInputSchema).output(AssetSystemSchema).errors(SYSTEM_TERM_ERRORS),get:oc.input(GetAssetSystemInputSchema).output(AssetSystemSchema),list:oc.input(ListAssetSystemsInputSchema).output(external_exports.array(AssetSystemSchema)),update:oc.input(UpdateAssetSystemInputSchema).output(AssetSystemSchema).errors(SYSTEM_TERM_ERRORS),delete:oc.input(DeleteAssetSystemInputSchema).output(AssetSystemSchema)});var assetsImportPreflightProcedures={preflightImport:oc.input(PreflightImportInputSchema).output(PreflightImportAcceptResultSchema).errors({BAD_REQUEST:{message:"the rows slice is wider than the import pre-flight can check",data:PreflightImportRowsTooWideDataSchema},SERVICE_UNAVAILABLE:{message:"background import pre-flights are not available on this deployment",data:PreflightImportRunnerUnavailableDataSchema}}),preflightImportStatus:oc.input(PreflightImportStatusInputSchema).output(PreflightImportStatusSchema).errors({NOT_FOUND:{message:"import pre-flight not found",data:PreflightImportJobNotFoundDataSchema}})};var placementNotFound={NOT_FOUND:{message:"location placement not found",data:LocationPlacementNotFoundDataSchema}},jobNotFound={NOT_FOUND:{message:"location placement job not found",data:LocationPlacementJobNotFoundDataSchema}},assetsPlacementsContract=oc.router({save:oc.input(SaveLocationPlacementInputSchema).output(LocationPlacementSchema).errors({BAD_REQUEST:{message:"the placement is not valid",data:LocationPlacementInvalidDataSchema},CONFLICT:{message:"the placement could not be saved as asked",data:LocationPlacementNameTakenDataSchema.or(LocationPlacementChangedDataSchema)},...placementNotFound}),delete:oc.input(DeleteLocationPlacementInputSchema).output(DeleteLocationPlacementResultSchema).errors({CONFLICT:{message:"the placement has a job in progress",data:LocationPlacementJobLiveDataSchema},...placementNotFound}),get:oc.input(GetLocationPlacementInputSchema).output(LocationPlacementSchema).errors(placementNotFound),list:oc.output(ListLocationPlacementsOutputSchema),startJob:oc.input(StartLocationPlacementJobInputSchema).output(StartLocationPlacementJobResultSchema).errors({BAD_REQUEST:{message:"the placement cannot run over this dataset",data:LocationPlacementSourceRefusedDataSchema},CONFLICT:{message:"the dataset version is not promoted",data:LocationPlacementSourceRefusedDataSchema},...placementNotFound,SERVICE_UNAVAILABLE:{message:"placing assets from a dataset is not available on this deployment",data:LocationPlacementRunnerUnavailableDataSchema}}),jobStatus:oc.input(LocationPlacementJobStatusInputSchema).output(LocationPlacementJobStatusSchema).errors(jobNotFound),jobFailures:oc.input(LocationPlacementJobFailuresInputSchema).output(LocationPlacementJobFailuresOutputSchema).errors(jobNotFound),listJobs:oc.input(ListLocationPlacementJobsInputSchema).output(ListLocationPlacementJobsOutputSchema).errors(placementNotFound)});var qualityScanRefusal={UNPROCESSABLE_CONTENT:{message:"this data-quality check ran out of time at this estate size",data:QualityScanRefusalDataSchema}},assetsQualityContract=oc.router({orphanedAssets:oc.input(OrphanedAssetsInputSchema).output(OrphanedAssetsOutputSchema).errors(qualityScanRefusal),unparentedAssets:oc.input(UnparentedAssetsInputSchema).output(UnparentedAssetsOutputSchema).errors({...qualityScanRefusal,NOT_FOUND:{message:"Hierarchy not found"}}),edgeSanity:oc.output(EdgeSanityReportSchema).errors(qualityScanRefusal),edgeSummary:oc.output(RelationshipEdgeSummarySchema).errors(qualityScanRefusal),duplicateAssets:oc.input(DuplicateAssetsInputSchema.optional()).output(DuplicateAssetsReportSchema).errors(qualityScanRefusal),exportDuplicates:oc.input(DuplicateAssetsExportInputSchema).output(AssetExportHandleSchema).errors({...qualityScanRefusal,OVER_CAP:{status:422,message:"These duplicate groups exceed this deployment\u2019s export row cap; narrow them with a search or a filter"},EMPTY_RESULT:{status:422,message:"No duplicate groups match these filters; nothing to export"},SERVICE_UNAVAILABLE:{message:"exports are not available on this deployment \u2014 the export object store is not configured for it",data:ExportStoreUnavailableDataSchema}}),startJob:oc.output(StartQualityJobResultSchema).errors({SERVICE_UNAVAILABLE:{message:"background data-quality checks are not available on this deployment",data:QualityJobRunnerUnavailableDataSchema}}),jobStatus:oc.input(QualityJobStatusInputSchema).output(QualityJobStatusSchema).errors({NOT_FOUND:{message:"quality job not found",data:QualityJobNotFoundDataSchema}}),latestReceipt:oc.output(LatestQualityReceiptSchema)});var CreateRelationshipWireInputSchema=CreateAssetRelationshipInputSchema.refine(previewsADatedLink,DATED_DRY_RUN_ISSUE),MoveRelationshipWireInputSchema=GovernedMoveRelationshipInputSchema.refine(previewsADatedLink,DATED_DRY_RUN_ISSUE),CreateAssetRelationshipOutputSchema=external_exports.union([AssetRelationshipWriteResultSchema.extend({dated:DatedLinkResultSchema.optional()}),DatedLinkDryRunSchema]),MoveRelationshipOutputSchema=external_exports.union([AssetRelationshipWriteResultSchema,DatedLinkDryRunSchema]),parentLinkProcedures={listParentLinks:oc.input(ListParentLinksInputSchema).output(ListParentLinksOutputSchema)};var locationsProcedure=oc.input(AssetLocationsInputSchema).output(AssetLocationsOutputSchema).errors(READ_TX_BUDGET_ERRORS),exportEstimateProcedure=oc.input(AssetExportEstimateInputSchema).output(AssetExportEstimateSchema).errors(READ_TX_BUDGET_ERRORS);var assetsSpatialContract=oc.router({nearby:oc.input(NearbyAssetsInputSchema).output(NearbyAssetsOutputSchema),withinBounds:oc.input(AssetsWithinBoundsInputSchema).output(AssetsWithinBoundsOutputSchema),withinPolygon:oc.input(AssetsWithinPolygonInputSchema).output(AssetsWithinPolygonOutputSchema),aggregate:oc.input(MapAggregateInputSchema).output(MapAggregateOutputSchema),mapFeatures:oc.input(MapFeaturesInputSchema).output(MapFeaturesOutputSchema)});for(let{schema,max:max2}of WIRE_BOUNDED_RECORDS2)JSON_SCHEMA_REGISTRY.add(schema,wireRecordPublished({max:max2}));var EDGE_WRITE_DEADLOCK_ERRORS={SERVICE_UNAVAILABLE:{message:"a concurrent change to the same assets deadlocked with this one and it was rolled back whole; nothing was written \u2014 retry it",data:EdgeWriteDeadlockDataSchema}},assetsContract=oc.router({list:oc.output(external_exports.array(AssetRefSchema)),snapshot:oc.input(SnapshotAskSchema2).output(EntitySnapshotRefSchema).errors({NOT_FOUND:{message:"The entity to snapshot does not exist"}}),crud:oc.router({create:oc.input(GovernedCreateAssetInputSchema).output(AssetSchema),get:oc.input(GetAssetInputSchema).output(AssetReadSchema),list:oc.input(ListAssetsInputSchema).output(ListAssetsOutputSchema).errors({...READ_TX_BUDGET_ERRORS,...CONDITION_ERRORS}),distinctValues:oc.input(AssetDistinctValuesInputSchema).output(AssetDistinctValuesOutputSchema).errors({...READ_TX_BUDGET_ERRORS,...CONDITION_ERRORS}),index:oc.input(ListAssetIndexInputSchema).output(ListAssetIndexOutputSchema).errors({...READ_TX_BUDGET_ERRORS,...CONDITION_ERRORS}),count:oc.input(AssetCountInputSchema).output(AssetCountOutputSchema).errors(READ_TX_BUDGET_ERRORS),exportEstimate:exportEstimateProcedure,exportStatus:oc.input(AssetExportStatusInputSchema).output(AssetExportStatusSchema),export:oc.input(AssetExportInputSchema).output(AssetExportHandleSchema).errors({OVER_CAP:{status:422,message:"The selection exceeds this deployment\u2019s export row cap; narrow it with filters or a subtree scope",data:AssetExportOverCapDataSchema},EMPTY_RESULT:{status:422,message:"The selection matches no assets; nothing to export"},FORMAT_UNAVAILABLE:{status:422,message:"This format is not available yet; export as CSV"},TOO_MANY_COLUMNS:{status:422,message:"The selection exceeds this deployment\u2019s export column cap; narrow it to assets with fewer distinct properties"},SERVICE_UNAVAILABLE:{message:"exports are not available on this deployment \u2014 the export object store is not configured for it",data:ExportStoreUnavailableDataSchema}}),locations:locationsProcedure,update:oc.input(GovernedUpdateAssetInputSchema).output(AssetSchema),delete:oc.input(GovernedDeleteAssetInputSchema).output(AssetSchema).errors(EDGE_WRITE_DEADLOCK_ERRORS),deleteImpact:oc.input(DeleteImpactInputSchema).output(DeleteImpactOutputSchema),deleteMany:oc.input(DeleteManyInputSchema).output(DeleteManyOutputSchema),setLocation:oc.input(GovernedSetAssetLocationInputSchema).output(AssetSchema),setLocationMany:oc.input(SetLocationManyInputSchema).output(SetLocationManyOutputSchema),...datedValueProcedures,versions:oc.input(ListAssetVersionsInputSchema).output(external_exports.array(AssetSchema)),activity:oc.input(ListAssetActivityInputSchema).output(RecordsPageSchema),provenanceDirectory:oc.input(ProvenanceDirectoryInputSchema).output(ProvenanceDirectoryOutputSchema),externalIdDirectory:oc.input(ExternalIdDirectoryInputSchema).output(ExternalIdDirectoryOutputSchema),summary:oc.output(AssetSummarySchema),summaryFiltered:oc.input(AssetListFilterSchema).output(AssetSummarySchema).errors({...READ_TX_BUDGET_ERRORS,...CONDITION_ERRORS}),summaryByCategory:oc.output(AssetCategorySummarySchema)}),spatial:assetsSpatialContract,vocabulary:oc.router({category:oc.router({create:oc.input(CreateAssetCategoryInputSchema).output(AssetCategorySchema),update:oc.input(UpdateAssetCategoryInputSchema).output(AssetCategorySchema),get:oc.input(GetAssetCategoryInputSchema).output(AssetCategorySchema),list:oc.input(ListAssetCategoriesInputSchema).output(external_exports.array(AssetCategorySchema)),delete:oc.input(DeleteAssetCategoryInputSchema).output(AssetCategorySchema)}),type:oc.router({create:oc.input(CreateAssetTypeInputSchema).output(AssetTypeSchema),update:oc.input(UpdateAssetTypeInputSchema).output(AssetTypeSchema),get:oc.input(GetAssetTypeInputSchema).output(AssetTypeSchema),list:oc.input(ListAssetTypesInputSchema).output(external_exports.array(AssetTypeSchema)),delete:oc.input(DeleteAssetTypeInputSchema).output(AssetTypeSchema)}),template:oc.router({get:oc.input(GetAssetTemplateInputSchema).output(AssetTemplateVersionSchema),set:oc.input(SetAssetTemplateInputSchema).output(AssetTemplateVersionSchema)}),deriveTemplateMany:oc.input(DeriveTemplateManyInputSchema).output(DeriveTemplateManyOutputSchema)}),relationships:oc.router({...parentLinkProcedures,create:oc.input(CreateRelationshipWireInputSchema).output(CreateAssetRelationshipOutputSchema).errors(EDGE_WRITE_DEADLOCK_ERRORS),end:oc.input(EndAssetRelationshipInputSchema).output(AssetRelationshipWriteResultSchema).errors(EDGE_WRITE_DEADLOCK_ERRORS),move:oc.input(MoveRelationshipWireInputSchema).output(MoveRelationshipOutputSchema).errors(EDGE_WRITE_DEADLOCK_ERRORS),moveMany:oc.input(MoveManyInputSchema).output(MoveManyResponseSchema).errors(EDGE_WRITE_DEADLOCK_ERRORS),createMany:oc.input(RelateManyInputSchema).output(RelateManyResponseSchema).errors(EDGE_WRITE_DEADLOCK_ERRORS),endMany:oc.input(UnlinkManyInputSchema).output(UnlinkManyResponseSchema).errors(EDGE_WRITE_DEADLOCK_ERRORS),listFor:oc.input(ListAssetRelationshipsInputSchema).output(external_exports.array(AssetRelationshipSchema)),parents:oc.input(RelationshipNeighborsInputSchema).output(external_exports.array(HierarchyBrowseNodeSchema)),children:oc.input(RelationshipNeighborsInputSchema).output(external_exports.array(HierarchyBrowseNodeSchema)).errors(READ_TX_BUDGET_ERRORS),subtree:oc.input(AssetSubtreeInputSchema).output(AssetSubtreeOutputSchema).errors({...WALK_OVER_CAP_ERRORS,...READ_TX_BUDGET_ERRORS}),...assetsDescendantsProcedures,ancestors:oc.input(AssetAncestorsInputSchema).output(AssetAncestorsOutputSchema).errors({...WALK_OVER_CAP_ERRORS,...READ_TX_BUDGET_ERRORS}),ancestorsMany:oc.input(RelationshipAncestorsManyInputSchema).output(RelationshipAncestorsManyOutputSchema).errors({...WALK_OVER_CAP_ERRORS,...READ_TX_BUDGET_ERRORS}),descendantCounts:oc.input(DescendantCountsInputSchema).output(DescendantCountsOutputSchema).errors(READ_TX_BUDGET_ERRORS),roots:oc.input(RelationshipRootsInputSchema).output(RelationshipRootsOutputSchema).errors(READ_TX_BUDGET_ERRORS),hasChildren:oc.input(RelationshipHasChildrenInputSchema).output(RelationshipHasChildrenOutputSchema),descendantGeometry:oc.input(DescendantGeometryInputSchema).output(DescendantGeometryOutputSchema)}),hierarchies:oc.router({create:oc.input(CreateHierarchyInputSchema).output(HierarchySchema),list:oc.input(ListHierarchiesInputSchema).output(ListHierarchiesOutputSchema)}),composition:oc.router({...assetsImportPreflightProcedures,createMany:oc.input(CreateManyInputSchema).output(CreateManyOutputSchema).errors({BAD_REQUEST:{message:"The import was refused whole; nothing was written"},CONFLICT:{message:"The estate changed under this import; nothing was written"},...EDGE_WRITE_DEADLOCK_ERRORS,PLACEMENT_NOT_DECLARED:{status:422,message:"this import declares no placement \u2014 configure a `relationships` mapping, or set `noHierarchy: true` if it is deliberately flat"},DATASET_VERSION_ALREADY_IMPORTED:{status:409,message:"this dataset version was already imported \u2014 pass `duplicateAnyway: true` to import it again",data:DatasetVersionAlreadyImportedSchema}}),validate:oc.input(ValidateCreateManyInputSchema).output(ValidateCreateManyReportSchema).errors({ROWS_MODE_OVER_CAP:{status:422,message:'this source has more rows than a row-by-row preflight can classify in one request \u2014 re-run with mode: "counts", which counts distinct external-ID keys rather than rows and so answers deliveries this mode refuses, or validate a rows tile',data:ValidateRowsModeOverCapSchema},COUNTS_MODE_UNAVAILABLE:{status:422,message:'this source cannot answer a DISTINCT over the external-ID column, which is the one read mode: "counts" is built on \u2014 re-run with mode: "rows", which reads rows and has no such dependency',data:ValidateCountsUnavailableSchema},COUNTS_KEY_SET_OVER_CAP:{status:422,message:"this delivery names more distinct external IDs than a counts preflight reads completely \u2014 refused rather than answered over part of the key set, which would report every unread key as both a create and an absent asset: validate a rows tile of the part you need",data:ValidateCountsKeySetOverCapSchema}}),preflight:oc.input(TypePreflightInputSchema).output(TypePreflightResultSchema),createUnresolvedType:oc.input(CreateTypeFromValueInputSchema).output(CreateTypeFromValueResultSchema),startJob:oc.input(StartCompositionJobInputSchema).output(StartCompositionJobResultSchema).errors({DELIVERY_THRESHOLD_BREACHED:{status:422,message:"A delivery threshold on this import mapping was breached; nothing was imported",data:DeliveryThresholdBreachSchema},PLACEMENT_NOT_DECLARED:{status:422,message:"this import declares no placement \u2014 configure a `relationships` mapping, or set `noHierarchy: true` if it is deliberately flat"},DATASET_VERSION_ALREADY_IMPORTED:{status:409,message:"this dataset version was already imported \u2014 pass `duplicateAnyway: true` to import it again",data:DatasetVersionAlreadyImportedSchema}}),...revertDatedValuesProcedures,startImport:oc.input(StartImportInputSchema).output(StartCompositionJobResultSchema).errors({DELIVERY_THRESHOLD_BREACHED:{status:422,message:"A delivery threshold on this import mapping was breached; nothing was imported",data:DeliveryThresholdBreachSchema},PLACEMENT_NOT_DECLARED:{status:422,message:"this import declares no placement \u2014 configure a `relationships` mapping, or set `noHierarchy: true` if it is deliberately flat"},DATASET_VERSION_ALREADY_IMPORTED:{status:409,message:"this dataset version was already imported \u2014 pass `duplicateAnyway: true` to import it again",data:DatasetVersionAlreadyImportedSchema}}),jobStatus:oc.input(CompositionJobStatusInputSchema).output(CompositionJobStatusSchema),listJobs:oc.input(ListCompositionJobsInputSchema).output(external_exports.array(CompositionJobSummarySchema))}),teardown:oc.router({preview:oc.input(TeardownPreviewInputSchema).output(TeardownPreviewResultSchema),startJob:oc.input(StartTeardownJobInputSchema).output(StartTeardownJobResultSchema),jobStatus:oc.input(TeardownJobStatusInputSchema).output(TeardownJobStatusSchema),listJobs:oc.input(ListTeardownJobsInputSchema).output(external_exports.array(TeardownJobSummarySchema))}),importExceptions:oc.router({listRuns:oc.input(ListImportRunsInputSchema).output(ListImportRunsOutputSchema),list:oc.input(ListImportExceptionsInputSchema).output(ListImportExceptionsOutputSchema),resolve:oc.input(ResolveImportExceptionInputSchema).output(ResolveImportExceptionOutputSchema),resolveMany:oc.input(ResolveManyImportExceptionsInputSchema).output(ResolveManyImportExceptionsOutputSchema),getRetryPlan:oc.input(GetImportRunRetryPlanInputSchema).output(ImportRunRetryPlanSchema)}),importMapping:oc.router({save:oc.input(SaveAssetImportMappingInputSchema).output(AssetImportMappingSchema),get:oc.input(GetAssetImportMappingInputSchema).output(AssetImportMappingSchema),list:oc.output(ListAssetImportMappingsOutputSchema)}),lifecycle:oc.router({saveRules:oc.input(SaveLifecycleRulesInputSchema).output(LifecycleRulesSchema),savePolicy:oc.input(SaveLifecyclePolicyInputSchema).output(LifecyclePolicyOverlaySchema),getPolicy:oc.output(LifecyclePolicyViewSchema)}),quality:assetsQualityContract,access:assetsAccessContract,placements:assetsPlacementsContract,numbering:oc.router({saveConfig:oc.input(SaveNumberingConfigInputSchema).output(NumberingConfigSchema),getConfig:oc.output(NumberingConfigSchema.nullable()),suggest:oc.input(SuggestAssetCodeInputSchema).output(SuggestAssetCodeResultSchema)}),nestingRules:oc.router({save:oc.input(SaveNestingRulesInputSchema).output(NestingRulesSchema),get:oc.output(NestingRulesSchema.nullable())}),system:assetsSystemContract,externalId:assetsExternalIdContract,derivedProperties:oc.router({get:oc.input(GetDerivedPropertiesInputSchema).output(DerivedPropertiesSchema)}),derivedValues:oc.router({list:oc.input(ListDerivedValuesInputSchema).output(external_exports.array(DerivedValueSchema)),apply:oc.input(ApplyDerivedValuesInputSchema).output(ApplyDerivedValuesReportSchema),getRouting:oc.output(DerivedRoutingConfigSchema),saveRouting:oc.input(SaveDerivedRoutingInputSchema).output(DerivedRoutingConfigSchema),due:oc.output(external_exports.array(DueDerivedApplySchema))}),views:oc.router({create:oc.input(CreateSavedViewInputSchema2).output(SavedViewSchema2),list:oc.input(ListSavedViewsInputSchema2).output(external_exports.array(SavedViewSchema2)),update:oc.input(UpdateSavedViewInputSchema2).output(SavedViewSchema2),delete:oc.input(DeleteSavedViewInputSchema2).output(SavedViewSchema2)}),preferences:oc.router({get:oc.input(GetTablePreferencesInputSchema2).output(TablePreferencesSchema2.nullable()),set:oc.input(SetTablePreferencesInputSchema2).output(TablePreferencesSchema2)}),directory:oc.router({status:oc.output(DirectoryPublishStatusSchema),publishNow:oc.input(PublishDirectoryInputSchema).output(PublishDirectoryResultSchema),getSchedule:oc.output(DirectoryScheduleReadSchema),setSchedule:oc.input(SetDirectoryScheduleInputSchema).output(DirectoryScheduleSchema)})});var PERIOD_TOKEN=/^\d{4}(-(0[1-9]|1[0-2]))?$/;function utcFromParts(year,monthIndex2,day,hour=0,minute=0,second=0){let at=new Date(0);return at.setUTCFullYear(year,monthIndex2,day),at.setUTCHours(hour,minute,second,0),at.getTime()}var SELECTABLE_ZONES=new Set(["UTC",...Intl.supportedValuesOf("timeZone")]),CANONICAL_ZONES=new Map,CANONICAL_ZONES_MAX=2e3;function resolveZone(timeZone){let memo2=CANONICAL_ZONES.get(timeZone);if(memo2!==void 0)return memo2;let resolved=new Intl.DateTimeFormat("en-US",{timeZone}).resolvedOptions().timeZone;return CANONICAL_ZONES.size<CANONICAL_ZONES_MAX&&CANONICAL_ZONES.set(timeZone,resolved),resolved}var WALL_CLOCK_FORMATTERS=new Map;function wallClockFormatter(canonical){let cached2=WALL_CLOCK_FORMATTERS.get(canonical);if(cached2!==void 0)return cached2;let built=new Intl.DateTimeFormat("en-US",{timeZone:canonical,hour12:!1,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"});return WALL_CLOCK_FORMATTERS.set(canonical,built),built}function zoneOffsetMs(timeZone,atMs){let parts=wallClockFormatter(timeZone).formatToParts(new Date(atMs)),read=type=>Number(parts.find(part2=>part2.type===type)?.value),hour=read("hour")%24;return utcFromParts(read("year"),read("month")-1,read("day"),hour,read("minute"),read("second"))-Math.floor(atMs/1e3)*1e3}function zonedDayStartMs(timeZone,year,monthIndex2,day){let zone=checkedZone(timeZone),wallClock=utcFromParts(year,monthIndex2,day);if(zone==="UTC")return wallClock;let memoKey=`${zone}|${wallClock}`,memo2=DAY_STARTS.get(memoKey);if(memo2!==void 0)return memo2;let resolved=localMidnight(zone,wallClock);return DAY_STARTS.size<DAY_STARTS_MAX&&DAY_STARTS.set(memoKey,resolved),resolved}var DAY_STARTS=new Map,DAY_STARTS_MAX=1e4,PROBE_MS=864e5;function localMidnight(zone,wallClock){let fromBefore=wallClock-zoneOffsetMs(zone,wallClock-PROBE_MS),fromAfter=wallClock-zoneOffsetMs(zone,wallClock+PROBE_MS),earlier=Math.min(fromBefore,fromAfter),later=Math.max(fromBefore,fromAfter),renders=at=>wallClock-at===zoneOffsetMs(zone,at);return renders(earlier)?earlier:(renders(later),later)}function checkedZone(timeZone){if(timeZone===void 0)return"UTC";let canonical;try{canonical=resolveZone(timeZone)}catch{canonical=void 0}if(canonical===void 0||!SELECTABLE_ZONES.has(canonical))throw new Error(`unknown time zone "${timeZone}" \u2014 expected an IANA id (e.g. America/Denver); an unknown zone is never read as UTC`);return canonical}var checkedTokenBrand=Symbol("calculations.periodInstant.checkedPeriodToken"),MIN_PERIOD_YEAR=100,MAX_PERIOD_YEAR=9998;function tokenSpan(checked,timeZone){let[yearPart,monthPart]=checked.token.split("-"),year=Number(yearPart);if(checked.token.includes("-")){let monthIndex2=Number(monthPart)-1;return{firstMs:zonedDayStartMs(timeZone,year,monthIndex2,1),lastMs:zonedDayStartMs(timeZone,year,monthIndex2+1,1)-1}}return{firstMs:zonedDayStartMs(timeZone,year,0,1),lastMs:zonedDayStartMs(timeZone,year+1,0,1)-1}}var PERIOD_BOUND=/^\d{4}(-(0[1-9]|1[0-2])(-(0[1-9]|[12]\d|3[01]))?)?$/;function checkPeriodBound(bound){if(!PERIOD_BOUND.test(bound))return;let[yearPart,monthPart,dayPart]=bound.split("-"),year=Number(yearPart);if(!(year<MIN_PERIOD_YEAR||year>MAX_PERIOD_YEAR)){if(dayPart!==void 0){let lastDay=new Date(Date.UTC(year,Number(monthPart),0)).getUTCDate();if(Number(dayPart)>lastDay)return}return{token:bound,[checkedTokenBrand]:!0}}}function boundSpan(checked,timeZone){let[yearPart,monthPart,dayPart]=checked.token.split("-");if(dayPart===void 0)return tokenSpan(checked,timeZone);let year=Number(yearPart),monthIndex2=Number(monthPart)-1,day=Number(dayPart);return{firstMs:zonedDayStartMs(timeZone,year,monthIndex2,day),lastMs:zonedDayStartMs(timeZone,year,monthIndex2,day+1)-1}}function periodBoundSpan(bound,timeZone){let zone=checkedZone(timeZone),checked=checkPeriodBound(bound);return checked===void 0?void 0:boundSpan(checked,zone)}var CadenceSchema=external_exports.enum(["monthly","quarterly","annual"]),CadenceUnitSchema=external_exports.enum(["month","week"]),ANCHOR_YEAR=String.raw`(?:0[1-9]\d{2}|[1-9]\d{3})`,ANCHOR_DATE=new RegExp(`^${ANCHOR_YEAR}-(0[1-9]|1[0-2])-(0[1-9]|[12]\\d|3[01])$`),MONTH_ANCHOR_DATE=new RegExp(`^${ANCHOR_YEAR}-(0[1-9]|1[0-2])-01$`),INTERVAL=external_exports.number().int().min(1).max(60),WEEK_ANCHOR_MESSAGE='A weekly cadence needs a start day: nothing in the calendar says which day a week begins, so "every N weeks" names no periods until one is chosen.',MONTH_ANCHOR_MESSAGE="A fiscal cadence's start must be the first of a month \u2014 a period running the 15th to the 14th is a rolling window, which is not built.",anchorDenotes=anchor2=>anchor2===void 0||periodBoundSpan(anchor2)!==void 0,REAL_DAY="the anchor is not a date this domain can denote: it must name a day that exists (2025-02-30 would otherwise roll over to 2 March and phase every period the project ever generates)",WeekCadenceRuleSchema=external_exports.object({unit:external_exports.literal("week"),interval:INTERVAL,anchor:external_exports.string().regex(ANCHOR_DATE,{message:WEEK_ANCHOR_MESSAGE})}),MonthCadenceRuleSchema=external_exports.object({unit:external_exports.literal("month"),interval:INTERVAL,anchor:external_exports.string().regex(MONTH_ANCHOR_DATE,{message:MONTH_ANCHOR_MESSAGE}).optional()}),CadenceRuleSchema=external_exports.discriminatedUnion("unit",[WeekCadenceRuleSchema,MonthCadenceRuleSchema]).refine(rule=>anchorDenotes(rule.anchor),{path:["anchor"],message:REAL_DAY}),UNPHASED_MONTHS_MESSAGE="A month cadence without a starting month must divide the year evenly (every 1, 2, 3, 4, 6 or 12 months). Choose the month its periods start from.";function calendarPhasesMonths(cadence){if(typeof cadence=="string"||cadence.unit!=="month"||cadence.anchor!==void 0)return!0;let{interval}=cadence;return!Number.isInteger(interval)||interval<1?!0:12%interval===0}var CADENCE_RULES=Object.freeze({monthly:CadenceRuleSchema.parse({unit:"month",interval:1}),quarterly:CadenceRuleSchema.parse({unit:"month",interval:3}),annual:CadenceRuleSchema.parse({unit:"month",interval:12})}),CadenceSpecSchema=external_exports.union([CadenceSchema,CadenceRuleSchema]),RULES_BY_NAME=new Map(Object.entries(CADENCE_RULES));function cadenceRule(cadence){return typeof cadence=="string"?RULES_BY_NAME.get(cadence):cadence}var EnteredPeriodSchema=external_exports.object({start:external_exports.iso.date(),end:external_exports.iso.date()});function enteredPeriodsIssue(periods){for(let[index,period]of periods.entries()){for(let field of["start","end"])if(periodBoundSpan(period[field])===void 0)return{index,field,message:`Period ${String(index+1)} has a ${field} date this system cannot record: ${period[field]}. Enter a real day from the year 0100 on.`};if(period.end<period.start)return{index,field:"end",message:`Period ${String(index+1)} ends on ${period.end}, before it starts on ${period.start}. A period's last day must be on or after its first.`}}let ordered=periods.map((period,index)=>({period,index})).toSorted((left,right)=>left.period.start.localeCompare(right.period.start));for(let at=1;at<ordered.length;at+=1){let earlier=ordered[at-1],later=ordered[at];if(!(earlier===void 0||later===void 0)&&later.period.start<=earlier.period.end)return{index:later.index,field:"start",message:`Periods ${String(earlier.index+1)} and ${String(later.index+1)} overlap: ${earlier.period.start} to ${earlier.period.end} and ${later.period.start} to ${later.period.end} share at least one day, which a roll-up would count twice. Change one so they do not share a day.`}}}var PROJECT_ENTITY_HINT={entity:{domain:"calculations",type:"project"},pickerResource:"calculations"},RUN_ENTITY_HINT={entity:{domain:"calculations",type:"run"},pickerResource:"calculation-run"},ProjectIdSchema=external_exports.string().min(1).brand().meta(PROJECT_ENTITY_HINT),RunIdSchema=external_exports.string().min(1).brand().meta(RUN_ENTITY_HINT),CallerMintedKeySchema2=IdempotencyKeySchema.max(200).describe("Client-minted replay key \u2014 REQUIRED by every governed write in this domain. Mint ONE per intent (a UUID is fine) and reuse it only to re-send that identical intent. Once a call has COMPLETED, reusing its key returns the original receipt without re-executing; a call that was REFUSED consumed nothing, so the same key is free to run again. `runs.trigger` adds a third state, because it opens and seals across two transactions: a key whose run is still IN FLIGHT resumes that run, re-executing over the inputs it pinned when it opened rather than resolving them afresh \u2014 and a key reused with a different project or period is refused with RUN_KEY_PARAM_MISMATCH rather than answering for the wrong run. The lifecycle verbs projects.activate, projects.archive and runs.cancel add two states of their own: a key reused against a DIFFERENT target is refused with KEY_PARAM_MISMATCH, and a NEW key naming a target that was already activated / archived / cancelled under some other key answers from that original action and records a no-op receipt under your key rather than acting twice."),DeclarationIdSchema=external_exports.string().min(1).brand(),DeclarationVersionIdSchema=external_exports.string().min(1).brand();var PERIOD_ENTITY_HINT={entity:{domain:"calculations",type:"period"},pickerResource:"calculation-period",scopedBy:{projectId:"projectId"}},PeriodIdSchema=external_exports.string().min(1).brand().meta(PERIOD_ENTITY_HINT),LISTED_PERIODS_MAX=500,PeriodStatusSchema=external_exports.enum(["open","closed","locked","reopened","superseded"]),FigureBasisSchema=external_exports.enum(["filed","current","none"]),basisHoldsFigures=basis=>basis==="filed"||basis==="current";function periodAnnotationsCohere(period,ctx){period.childCount===void 0!=(period.childrenSignedOff===void 0)&&ctx.addIssue({code:"custom",path:["childrenSignedOff"],message:"childCount and childrenSignedOff are read together: both present or both absent"}),period.childCount!==void 0&&period.childrenSignedOff!==void 0&&period.childrenSignedOff>period.childCount&&ctx.addIssue({code:"custom",path:["childrenSignedOff"],message:"more children signed off than the period has children"}),period.figureCount!==void 0!==basisHoldsFigures(period.figureBasis)&&ctx.addIssue({code:"custom",path:["figureCount"],message:"figureCount is present exactly when figureBasis is filed or current"}),figureAnnotationsCohere(period,ctx)}function figureAnnotationsCohere(period,ctx){period.figureRunId!==void 0!==basisHoldsFigures(period.figureBasis)&&ctx.addIssue({code:"custom",path:["figureRunId"],message:"figureRunId is present exactly when figureBasis is filed or current"}),period.figureVersion!==void 0!=(period.figureBasis==="filed")&&ctx.addIssue({code:"custom",path:["figureVersion"],message:"figureVersion is present exactly when figureBasis is filed"}),period.correctionRunId!==void 0&&(period.status!=="reopened"||period.figureBasis!=="filed"||period.correctionRunId===period.figureRunId)&&ctx.addIssue({code:"custom",path:["correctionRunId"],message:"correctionRunId is only on a reopened period with a filed basis, and is never the filed run"})}var PeriodSchema=external_exports.object({id:PeriodIdSchema,projectId:ProjectIdSchema,projectName:external_exports.string().min(1).optional(),periodKey:external_exports.string().min(1),start:external_exports.string().min(1),end:external_exports.string().min(1),status:PeriodStatusSchema,childrenUnsigned:external_exports.boolean().optional(),childCount:external_exports.number().int().nonnegative().optional(),childrenSignedOff:external_exports.number().int().nonnegative().optional(),figureBasis:FigureBasisSchema.optional(),figureCount:external_exports.number().int().nonnegative().optional(),figureRunId:external_exports.string().min(1).optional(),figureVersion:external_exports.number().int().positive().optional(),correctionRunId:external_exports.string().min(1).optional()}).superRefine(periodAnnotationsCohere);var TOKEN=/^(\d{4})(?:-(\d{2}))?$/;function parseToken(token,defaultMonth){let match=TOKEN.exec(token);if(!match)throw new Error(`invalid window token: ${token}`);let year=Number(match[1]),month=match[2]===void 0?defaultMonth:Number(match[2]);if(month<1||month>12)throw new Error(`invalid month in window token: ${token}`);return{year,month}}var dateToken=(year,month,day)=>`${String(year).padStart(4,"0")}-${String(month).padStart(2,"0")}-${String(day).padStart(2,"0")}`;function utcDayMs(year,month,day){let at=new Date(0);return at.setUTCFullYear(year,month-1,day),at.getTime()}var lastDayOfMonth=(year,month)=>new Date(utcDayMs(year,month+1,0)).getUTCDate();var MAX_PROJECT_PERIODS=LISTED_PERIODS_MAX;function generatedPeriodCount(schedule){if(schedule.kind==="entered")return schedule.periods.length;let walk=scheduleWalk(schedule);return walk===void 0||walk.first>walk.last?0:Math.floor((walk.last-walk.first)/walk.step)+1}function scheduleWalk(schedule){let start=parseToken(schedule.window.start,1),end=parseToken(schedule.window.end,12);if(monthIndex(end)<monthIndex(start))return;let rule=cadenceRule(schedule.cadence);if(rule!==void 0){if(!Number.isInteger(rule.interval)||rule.interval<1)throw new Error(`generatePeriods: a cadence interval must be a whole number of at least 1, got ${String(rule.interval)}`);return rule.unit==="month"?monthWalk(rule,start,end):rule.anchor===void 0?void 0:weekWalk(rule,start,end)}}function monthWalk(rule,start,end){return{unit:"month",rule,first:monthStartIndex(rule,monthIndex(start)),last:monthIndex(end),step:rule.interval}}function weekWalk(rule,start,end){let windowStart=dayNumber(dateToken(start.year,start.month,1)),anchor2=dayNumber(rule.anchor),step=rule.interval*DAYS_PER_WEEK;return{unit:"week",anchor:anchor2,first:anchor2+Math.ceil((windowStart-anchor2)/step)*step,last:dayNumber(dateToken(end.year,end.month,lastDayOfMonth(end.year,end.month))),step}}var DAYS_PER_WEEK=7,MS_PER_DAY=864e5;function dayNumber(date5){let[year,month,day]=date5.split("-").map(Number);return Math.floor(utcDayMs(year??0,month??1,day??1)/MS_PER_DAY)}function monthStartIndex(rule,startIdx){if(rule.anchor===void 0)return Math.floor(startIdx/rule.interval)*rule.interval;let anchorIdx=anchorMonthIndex(rule),steps=Math.floor((startIdx-anchorIdx)/rule.interval);return anchorIdx+steps*rule.interval}function anchorMonthIndex(rule){if(rule.anchor===void 0)return 0;let[year,month]=rule.anchor.split("-").map(Number);return(year??0)*12+((month??1)-1)}var monthIndex=at=>at.year*12+(at.month-1);var RunStatusSchema2=external_exports.enum(["PENDING","RUNNING","COMPLETED","FAILED","CANCELLED"]),ExecStatusSchema=RunStatusSchema2.extract(["COMPLETED","FAILED"]),ReceiptStateSchema=external_exports.enum(["pending","promoted","promotedEmpty","unreceipted"]),ResultsPublishingSchema=external_exports.enum(["publishing","not-published"]);var BasisAbsenceReasonSchema=external_exports.enum(["no-earlier-period","no-earlier-run","no-approved-basis","basis-unavailable","basis-loading"]);var CloseBasisAbsenceSchema=external_exports.enum(["no-earlier-period","no-signed-basis"]);var AS_OF_IN_FUTURE_MESSAGE="The instant to read at is later than now.",DecisionSubjectSchema=external_exports.enum(["period","run"]),DecisionBasisInputSchema=external_exports.strictObject({periodId:PeriodIdSchema,runId:RunIdSchema,subject:DecisionSubjectSchema.optional(),asOf:external_exports.iso.datetime().optional()}),requestedAt=external_exports.iso.datetime({offset:!0}).nullable(),DecisionBasisSchema=external_exports.discriminatedUnion("kind",[external_exports.strictObject({kind:external_exports.literal("own-close"),runId:external_exports.string().min(1),version:external_exports.number().int().positive(),closedAt:external_exports.string().min(1),requestedAt}),external_exports.strictObject({kind:external_exports.literal("signed-period"),periodKey:external_exports.string().min(1),runId:external_exports.string().min(1),version:external_exports.number().int().positive().nullable(),closedAt:external_exports.string().min(1).nullable(),approvedAt:external_exports.string().min(1).optional(),requestedAt}),external_exports.strictObject({kind:external_exports.literal("absent"),reason:CloseBasisAbsenceSchema,requestedAt})]);var READ_ELEMENT_ID_PATTERN=/^(?:[^\u0000\uD800-\uDFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF])+$/,ReadElementIdSchema=external_exports.string().min(1).regex(READ_ELEMENT_ID_PATTERN,"An element id may not hold a NUL or an unpaired surrogate").brand();var ResultBehaviourSchema=external_exports.discriminatedUnion("kind",[external_exports.strictObject({kind:external_exports.literal("adds-up")}),external_exports.strictObject({kind:external_exports.literal("ratio-from-totals"),numerator:external_exports.string().min(1).describe("The result whose total is divided. It must add up."),denominator:external_exports.string().min(1).describe("The result whose total divides. It must add up."),scale:external_exports.number().positive().describe("Multiplies the quotient of the two totals into `unit`: 1000 for t \xF7 BOE as kg/BOE."),unit:external_exports.string().min(1).describe("The unit the ratio files in: the result\u2019s own unit.")}),external_exports.strictObject({kind:external_exports.literal("per-asset-only")})]);function canonicalDecimal2(decimal){let trimmed=decimal.trim(),match=/^([+-]?)(\d*)(?:\.(\d*))?(?:[eE]([+-]?\d{1,6}))?$/.exec(trimmed);if(match===null||!/\d/.test(trimmed.split(/[eE]/)[0]??""))throw new Error(`not a decimal: '${decimal}'`);let[,sign="",whole="",fraction="",exponent="0"]=match,digits=`${whole}${fraction}`,point=whole.length+Number(exponent),padded=point<=0?`0.${"0".repeat(-point)}${digits}`:point>=digits.length?`${digits}${"0".repeat(point-digits.length)}`:`${digits.slice(0,point)}.${digits.slice(point)}`,[intPart="",fracPart=""]=padded.split("."),int2=intPart.replace(/^0+(?=\d)/,"")||"0",frac=fracPart.replace(/0+$/,""),body=frac===""?int2:`${int2}.${frac}`;return body==="0"||sign!=="-"?body:`-${body}`}function exactOf(decimal){let canonical=canonicalDecimal2(decimal),negative=canonical.startsWith("-"),[whole="0",fraction=""]=(negative?canonical.slice(1):canonical).split("."),units=BigInt(`${whole}${fraction}`);return{units:negative?-units:units,scale:fraction.length}}var MAX_FINITE_DECIMAL="1.7976931348623157e308",MAX_FINITE=exactOf(MAX_FINITE_DECIMAL);var ADDS_UP={kind:"adds-up"},INTENSITY={kind:"ratio-from-totals",numerator:"CO2e_t",denominator:"Production_BOE",scale:1e3,unit:"kg CO2e/BOE"},BEHAVIOURS={CO2e_t:ADDS_UP,Production_BOE:ADDS_UP,Intensity:INTENSITY,Factor:{kind:"per-asset-only"}},t=value2=>({value:value2,unit:"t CO2e"}),boe=value2=>({value:value2,unit:"BOE"}),qt=value2=>({kind:"quantity",value:value2,unit:"t CO2e"}),qBoe=value2=>({kind:"quantity",value:value2,unit:"BOE"}),qKg=value2=>({kind:"quantity",value:value2,unit:"kg CO2e/BOE"}),none=reason=>({kind:"empty",reason}),NESTED={kind:"ratio-from-totals",numerator:"Intensity",denominator:"Production_BOE",scale:1,unit:"kg CO2e/BOE per BOE"},NESTED_CELLS={a:{CO2e_t:t("10"),Production_BOE:boe("100")},b:{CO2e_t:t("30"),Production_BOE:boe("900")}},NESTED_EXPECTED={N:{CO2e_t:qt("40"),Production_BOE:qBoe("1000"),Intensity:qKg("40"),Nested:none("numeratorMissing")}},ROLLUP_CONFORMANCE_CASES=[{name:"a sum is exact and does not depend on row order",behaviours:{CO2e_t:ADDS_UP},members:{N:["a","b","c"]},cells:{a:{CO2e_t:t("10000000000000000")},b:{CO2e_t:t("1")},c:{CO2e_t:t("-10000000000000000")}},expected:{N:{CO2e_t:qt("1")}}},{name:"a sum keeps decimals binary floating point cannot hold",behaviours:{CO2e_t:ADDS_UP},members:{N:["a","b"]},cells:{a:{CO2e_t:t("0.1")},b:{CO2e_t:t("0.2")}},expected:{N:{CO2e_t:qt("0.3")}}},{name:"a ratio divides the totals, never the mean of the members\u2019 ratios",behaviours:BEHAVIOURS,members:{N:["a","b"]},cells:{a:{CO2e_t:t("10"),Production_BOE:boe("100"),Factor:t("0.5")},b:{CO2e_t:t("30"),Production_BOE:boe("900"),Factor:t("0.7")}},expected:{N:{CO2e_t:qt("40"),Production_BOE:qBoe("1000"),Intensity:qKg("40")}}},{name:"a zero denominator is empty, never 0, and the level above still answers",behaviours:BEHAVIOURS,members:{SOUTH:["c"],USA:["a","c"]},cells:{a:{CO2e_t:t("30"),Production_BOE:boe("400")},c:{CO2e_t:t("12"),Production_BOE:boe("0")}},expected:{SOUTH:{CO2e_t:qt("12"),Production_BOE:qBoe("0"),Intensity:none("denominatorZero")},USA:{CO2e_t:qt("42"),Production_BOE:qBoe("400"),Intensity:qKg("105")}}},{name:"a ratio over another ratio has no numerator: the other ratio listed first",behaviours:{...BEHAVIOURS,Nested:NESTED},members:{N:["a","b"]},cells:NESTED_CELLS,expected:NESTED_EXPECTED},{name:"a ratio over another ratio has no numerator: the other ratio listed after",behaviours:{Nested:NESTED,...BEHAVIOURS},members:{N:["a","b"]},cells:NESTED_CELLS,expected:NESTED_EXPECTED},{name:"a part no member filed leaves the ratio empty with its reason",behaviours:BEHAVIOURS,members:{N:["a"]},cells:{a:{CO2e_t:t("5")}},expected:{N:{CO2e_t:qt("5"),Intensity:none("denominatorMissing")}}},{name:"blank members are skipped; a node whose members are all blank is empty, not nothing",behaviours:BEHAVIOURS,members:{SOME:["a","b"],ALL:["b","c"]},cells:{a:{CO2e_t:t("5"),Production_BOE:boe("50")},b:{CO2e_t:{blank:"blankOnError"},Production_BOE:{blank:"blankOnError"}},c:{CO2e_t:{blank:"blankByCondition"},Production_BOE:{blank:"blankOnError"}}},expected:{SOME:{CO2e_t:qt("5"),Production_BOE:qBoe("50"),Intensity:qKg("100")},ALL:{CO2e_t:none("allMembersBlank"),Production_BOE:none("allMembersBlank"),Intensity:none("allMembersBlank")}}},{name:"a sum never adds across units",behaviours:{CO2e_t:ADDS_UP},members:{N:["a","b"]},cells:{a:{CO2e_t:t("1")},b:{CO2e_t:{value:"1000",unit:"kg CO2e"}}},expected:{N:{CO2e_t:none("mixedUnits")}}},{name:"a ratio that does not terminate keeps QUOTIENT_PLACES digits, rounded half away from zero",behaviours:BEHAVIOURS,members:{THIRDS:["a"],SEVENTHS:["b"]},cells:{a:{CO2e_t:t("2"),Production_BOE:boe("3")},b:{CO2e_t:t("100000000000000000"),Production_BOE:boe("7000")}},expected:{THIRDS:{CO2e_t:qt("2"),Production_BOE:qBoe("3"),Intensity:qKg("666.666666666666666666666666666667")},SEVENTHS:{CO2e_t:qt("100000000000000000"),Production_BOE:qBoe("7000"),Intensity:qKg("14285714285714285.714285714285714285714285714286")}}},{name:"a negative ratio rounds half away from zero too, never toward zero or down",behaviours:BEHAVIOURS,members:{BELOW_HALF:["a"],ABOVE_HALF:["b"],HALF:["c"],BOTH:["d"]},cells:{a:{CO2e_t:t("-1"),Production_BOE:boe("3")},b:{CO2e_t:t("2"),Production_BOE:boe("-3")},c:{CO2e_t:t("-1e-33"),Production_BOE:boe("2")},d:{CO2e_t:t("-2"),Production_BOE:boe("-3")}},expected:{BELOW_HALF:{CO2e_t:qt("-1"),Production_BOE:qBoe("3"),Intensity:qKg("-333.333333333333333333333333333333")},ABOVE_HALF:{CO2e_t:qt("2"),Production_BOE:qBoe("-3"),Intensity:qKg("-666.666666666666666666666666666667")},HALF:{CO2e_t:qt("-1e-33"),Production_BOE:qBoe("2"),Intensity:qKg("-0.000000000000000000000000000001")},BOTH:{CO2e_t:qt("-2"),Production_BOE:qBoe("-3"),Intensity:qKg("666.666666666666666666666666666667")}}},{name:"a total past what a JSON number holds is notFinite, a sum or a ratio",behaviours:BEHAVIOURS,members:{SUM:["a","b"],RATIO:["c"]},cells:{a:{CO2e_t:t("1e308"),Production_BOE:boe("1")},b:{CO2e_t:t("1e308"),Production_BOE:boe("1")},c:{CO2e_t:t("1e308"),Production_BOE:boe("0.001")}},expected:{SUM:{CO2e_t:none("notFinite"),Production_BOE:qBoe("2"),Intensity:none("notFinite")},RATIO:{CO2e_t:qt("1e308"),Production_BOE:qBoe("0.001"),Intensity:none("notFinite")}}},{name:"units are trimmed by one rule, and a quantity whose unit trims blank is not filed",behaviours:{CO2e_t:ADDS_UP},members:{PADDED:["a","b"],BLANK:["c","d"],NONE:["e"]},cells:{a:{CO2e_t:{value:"1",unit:" t CO2e\xA0"}},b:{CO2e_t:t("2")},c:{CO2e_t:{value:"5",unit:"\xA0"}},d:{CO2e_t:t("1")},e:{CO2e_t:{value:"7",unit:" "}}},expected:{PADDED:{CO2e_t:qt("3")},BLANK:{CO2e_t:qt("1")}}}];var UNIT_TRIM_CHARACTERS=`
|
|
448
448
|
\v\f\r \xA0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u2028\u2029\u202F\u205F\u3000\uFEFF`,TRIMMED=new Set(UNIT_TRIM_CHARACTERS);var NODE_EMPTY_REASONS=["numeratorMissing","denominatorMissing","denominatorZero","mixedUnits","notFinite","allMembersBlank"],NodeEmptyReasonSchema=external_exports.enum(NODE_EMPTY_REASONS),NodeResultValueSchema=external_exports.discriminatedUnion("kind",[external_exports.object({kind:external_exports.literal("quantity"),value:external_exports.number(),unit:external_exports.string().min(1)}),external_exports.object({kind:external_exports.literal("empty"),reason:NodeEmptyReasonSchema})]);var RESULT_BEHAVIOURS_MAX=200,ResultBehaviourInputSchema=external_exports.strictObject({element:external_exports.string().min(1),behaviour:ResultBehaviourSchema}),ResultBehaviourInputsSchema=external_exports.array(ResultBehaviourInputSchema).max(RESULT_BEHAVIOURS_MAX),ResultBehaviourEntrySchema=external_exports.object({element:external_exports.string().min(1),behaviour:ResultBehaviourSchema,source:external_exports.enum(["author","detected"])}),RollupLevelSchema=external_exports.discriminatedUnion("by",[external_exports.strictObject({by:external_exports.literal("assetType"),assetTypeId:external_exports.string().min(1)}),external_exports.strictObject({by:external_exports.literal("property"),propertyKey:external_exports.string().min(1)})]);var NodeRefSchema=external_exports.discriminatedUnion("kind",[external_exports.object({kind:external_exports.literal("asset"),assetId:external_exports.string().min(1)}),external_exports.object({kind:external_exports.literal("propertyValue"),value:external_exports.string()})]),NodeResultRowSchema=external_exports.object({node:NodeRefSchema,nodeName:external_exports.string().min(1).nullable(),level:external_exports.object({index:external_exports.number().int().min(0),level:RollupLevelSchema}),parent:NodeRefSchema.nullable(),period:external_exports.string().min(1),assetCount:external_exports.number().int().min(0),values:external_exports.record(external_exports.string().min(1),NodeResultValueSchema)}),NODE_RESULTS_SAVE_REFUSAL_CODES=["CALC_ROLLUP_SCOPE_NOT_A_TREE","CALC_ROLLUP_LEVEL_REPEATED","CALC_ROLLUP_LEVEL_UNKNOWN_TYPE","CALC_RESULT_BEHAVIOUR_INVALID"],NodeResultsRefusalDataSchema=external_exports.object({code:external_exports.enum(NODE_RESULTS_SAVE_REFUSAL_CODES),level:external_exports.string().optional(),element:external_exports.string().optional()}),NODE_RESULTS_RUN_WARNING_CODES=["CALC_ROLLUP_LEVEL_PARTIAL","CALC_ROLLUP_LEVEL_OVERLAP","CALC_ROLLUP_LEVEL_UNASSIGNED"];var RUN_NOT_ACCEPTED_RETRY="RUN_NOT_ACCEPTED_RETRY",RUN_NOT_ACCEPTED_REASONS=["tx-expired","pool-timeout","statement-timeout","lock-timeout","source-unavailable","input-read-over-budget","scope-read-over-budget","execution-interrupted","in-flight"],RunNotAcceptedReasonSchema=external_exports.enum(RUN_NOT_ACCEPTED_REASONS),RunNotAcceptedDataSchema=external_exports.discriminatedUnion("saved",[external_exports.object({code:external_exports.literal(RUN_NOT_ACCEPTED_RETRY),saved:external_exports.literal(!1),retryWithSameKey:external_exports.literal(!0),reason:RunNotAcceptedReasonSchema}),external_exports.object({code:external_exports.literal(RUN_NOT_ACCEPTED_RETRY),saved:external_exports.literal(!0),retryWithSameKey:external_exports.literal(!0),reason:RunNotAcceptedReasonSchema,runId:RunIdSchema})]);var RunNodeTotalsInputSchema=external_exports.strictObject({runId:RunIdSchema}),NodeLevelWarningCodeSchema=external_exports.enum(NODE_RESULTS_RUN_WARNING_CODES),NodeLevelWarningSchema=external_exports.object({code:NodeLevelWarningCodeSchema,message:external_exports.string().min(1),count:external_exports.number().int().min(0).optional()}),NodeTotalsBucketSchema=external_exports.object({assetCount:external_exports.number().int().min(0),values:external_exports.record(external_exports.string().min(1),NodeResultValueSchema)}),NodeTotalsLevelSchema=external_exports.object({index:external_exports.number().int().min(0),level:RollupLevelSchema,warnings:external_exports.array(NodeLevelWarningSchema),refused:external_exports.boolean(),unassigned:NodeTotalsBucketSchema.nullable()}),NodeTotalsColumnSchema=external_exports.discriminatedUnion("kind",[external_exports.object({element:external_exports.string().min(1),kind:external_exports.literal("adds-up"),unit:external_exports.string().min(1).nullable()}),external_exports.object({element:external_exports.string().min(1),kind:external_exports.literal("ratio-from-totals"),unit:external_exports.string().min(1),numerator:external_exports.string().min(1),denominator:external_exports.string().min(1),scale:external_exports.number().positive()})]),RunNodeTotalsSchema=external_exports.object({runId:RunIdSchema,period:external_exports.string().min(1),levels:external_exports.array(NodeTotalsLevelSchema),columns:external_exports.array(NodeTotalsColumnSchema),rows:external_exports.array(NodeResultRowSchema),total:NodeTotalsBucketSchema});var LevelDiagnosticSchema=external_exports.object({code:NodeLevelWarningCodeSchema,message:external_exports.string().min(1),level:external_exports.number().int().min(0).optional(),count:external_exports.number().int().min(0).optional()});var NODE_TOTALS_OUT_OF_TIME="NODE_TOTALS_OUT_OF_TIME",NODE_TOTALS_OUT_OF_TIME_MESSAGE="Reading the totals by level ran out of time on the server. Try again.",NodeTotalsOutOfTimeReasonSchema=RunNotAcceptedReasonSchema.extract(["tx-expired","pool-timeout","statement-timeout","lock-timeout"]),NodeTotalsOutOfTimeDataSchema=external_exports.object({code:external_exports.literal(NODE_TOTALS_OUT_OF_TIME),reason:NodeTotalsOutOfTimeReasonSchema}),PeriodNodeTotalsInputSchema=external_exports.strictObject({periodId:PeriodIdSchema,version:external_exports.number().int().positive().optional()}),YearDefinitionPartSchema=external_exports.enum(["behaviour","numerator","denominator","scale"]),YearLevelSchema=NodeTotalsLevelSchema.extend({untotalledIn:external_exports.array(external_exports.string().min(1))}).refine(level=>level.refused===level.untotalledIn.length>0,{message:"a year level is refused exactly where some month did not total it"}),YearNodeRowSchema=NodeResultRowSchema.extend({months:external_exports.array(external_exports.string().min(1)).min(1)}),YearRefusedResultSchema=external_exports.object({element:external_exports.string().min(1),differs:external_exports.array(YearDefinitionPartSchema).min(1)}),YearCountedUnitSchema=external_exports.enum(["month","period"]),PeriodNodeTotalsSchema=external_exports.discriminatedUnion("kind",[external_exports.object({kind:external_exports.literal("pending"),signed:external_exports.number().int().min(0),of:external_exports.number().int().min(0),unit:YearCountedUnitSchema,level:RollupLevelSchema.nullable()}),external_exports.object({kind:external_exports.literal("doublyReached"),months:external_exports.array(external_exports.string().min(1)).min(1)}),external_exports.object({kind:external_exports.literal("noNodeTotals"),months:external_exports.array(external_exports.string().min(1)).min(1)}),external_exports.object({kind:external_exports.literal("overlapped"),periods:external_exports.array(external_exports.string().min(1)).min(1)}),external_exports.object({kind:external_exports.literal("totals"),period:external_exports.string().min(1),months:external_exports.array(external_exports.string().min(1)).min(1),levels:external_exports.array(YearLevelSchema),columns:external_exports.array(NodeTotalsColumnSchema),rows:external_exports.array(YearNodeRowSchema),total:NodeTotalsBucketSchema,refused:external_exports.array(YearRefusedResultSchema),yearSigned:external_exports.boolean(),countsWithheldIn:external_exports.array(external_exports.string().min(1))})]);var outOfTimeDataSchema=code2=>external_exports.object({code:external_exports.literal(code2),reason:NodeTotalsOutOfTimeReasonSchema});var DECISION_HISTORY_PERIODS_MAX=24;var DECISION_HISTORY_ELEMENTS_MAX=12,DecisionHistoryInputSchema=external_exports.strictObject({periodId:PeriodIdSchema,runId:RunIdSchema,subject:DecisionSubjectSchema.optional(),asOf:external_exports.iso.datetime().optional(),periods:external_exports.number().int().min(1).max(DECISION_HISTORY_PERIODS_MAX).optional(),elements:external_exports.array(ReadElementIdSchema).min(1).max(DECISION_HISTORY_ELEMENTS_MAX).optional()});var HistoryFigureSchema=external_exports.union([external_exports.strictObject({value:external_exports.number(),unit:external_exports.string().nullable()}),external_exports.strictObject({refused:external_exports.string().min(1)})]),FiguresSchema=external_exports.record(external_exports.string().min(1),HistoryFigureSchema),periodFields={periodId:PeriodIdSchema,periodKey:external_exports.string().min(1),start:external_exports.string().min(1),end:external_exports.string().min(1)},HistoryPointSchema=external_exports.discriminatedUnion("counted",[external_exports.strictObject({counted:external_exports.literal("signed"),...periodFields,runId:RunIdSchema,version:external_exports.number().int().positive().nullable(),closedAt:external_exports.iso.datetime({offset:!0}).nullable(),approvedAt:external_exports.iso.datetime({offset:!0}).optional(),figures:FiguresSchema}),external_exports.strictObject({counted:external_exports.literal("unsigned"),...periodFields,runId:RunIdSchema,figures:FiguresSchema}),external_exports.strictObject({counted:external_exports.literal("none"),...periodFields})]),DecisionHistorySchema=external_exports.object({requestedAt:external_exports.iso.datetime({offset:!0}).nullable(),elements:external_exports.array(external_exports.object({element:external_exports.string().min(1),unit:external_exports.string().min(1).nullable()})).max(DECISION_HISTORY_ELEMENTS_MAX),omittedElements:external_exports.number().int().min(0),current:external_exports.strictObject({...periodFields,runId:RunIdSchema,figures:FiguresSchema}),points:external_exports.array(HistoryPointSchema).max(DECISION_HISTORY_PERIODS_MAX)}),DECISION_HISTORY_OUT_OF_TIME="DECISION_HISTORY_OUT_OF_TIME",DECISION_HISTORY_OUT_OF_TIME_MESSAGE="Reading the earlier periods ran out of time on the server. Try again.",DecisionHistoryOutOfTimeDataSchema=outOfTimeDataSchema(DECISION_HISTORY_OUT_OF_TIME);var COMPARE_NODE_ROWS_DEFAULT=10,COMPARE_NODE_ROWS_MAX=100,CompareRankBySchema=external_exports.enum(["value","change"]),CompareNodeTotalsInputSchema=external_exports.strictObject({runId:RunIdSchema,basisRunId:RunIdSchema,rows:external_exports.number().int().min(1).max(COMPARE_NODE_ROWS_MAX).default(COMPARE_NODE_ROWS_DEFAULT),rankBy:CompareRankBySchema.default("value"),rankElement:ReadElementIdSchema.optional(),reporting:ReadElementIdSchema.optional()}),OutOfRangeFieldSchema=external_exports.enum(["value","basis","change","movePercent"]),ComparedCellSchema=external_exports.object({value:NodeResultValueSchema.nullable(),basis:NodeResultValueSchema.nullable(),change:external_exports.number().nullable(),movePercent:external_exports.number().nullable(),outOfRange:external_exports.array(OutOfRangeFieldSchema).min(1).optional()}),NodePresenceSchema=external_exports.enum(["both","new","removed"]),ComparedNodeRowSchema=external_exports.object({node:NodeRefSchema,nodeName:external_exports.string().min(1).nullable(),presence:NodePresenceSchema,assetCount:external_exports.number().int().min(0).nullable(),basisAssetCount:external_exports.number().int().min(0).nullable(),cells:external_exports.record(external_exports.string().min(1),ComparedCellSchema),reporting:external_exports.object({assets:external_exports.number().int().min(0).nullable(),basisAssets:external_exports.number().int().min(0).nullable()}).optional()}),ComparedLevelSchema=external_exports.object({index:external_exports.number().int().min(0),level:RollupLevelSchema,basisIndex:external_exports.number().int().min(0).nullable(),nodeCount:external_exports.number().int().min(0),basisNodeCount:external_exports.number().int().min(0),rows:external_exports.array(ComparedNodeRowSchema).max(COMPARE_NODE_ROWS_MAX)}),CompareNodeTotalsSchema=external_exports.object({runId:RunIdSchema,basisRunId:RunIdSchema,columns:external_exports.array(external_exports.object({element:external_exports.string().min(1),unit:external_exports.string().min(1).nullable()})),rankElement:external_exports.string().min(1).nullable(),levels:external_exports.array(ComparedLevelSchema)});var LARGEST_ASSETS_DEFAULT=5,LARGEST_ASSETS_MAX=20,LargestAssetsInputSchema=external_exports.strictObject({runId:RunIdSchema,element:ReadElementIdSchema,basisRunId:RunIdSchema.optional(),limit:external_exports.number().int().min(1).max(LARGEST_ASSETS_MAX).default(LARGEST_ASSETS_DEFAULT)}),LargestAssetRowSchema=external_exports.object({assetId:external_exports.string().min(1),name:external_exports.string().nullable(),value:external_exports.number().nullable(),unit:external_exports.string().nullable(),basis:external_exports.number().nullable(),change:external_exports.number().nullable(),movePercent:external_exports.number().nullable(),outOfRange:external_exports.array(OutOfRangeFieldSchema).min(1).optional()}),LargestAssetsSchema=external_exports.object({runId:RunIdSchema,element:external_exports.string().min(1),basisRunId:RunIdSchema.nullable(),rows:external_exports.array(LargestAssetRowSchema).max(LARGEST_ASSETS_MAX)});var LARGEST_ASSETS_OUT_OF_TIME="LARGEST_ASSETS_OUT_OF_TIME",LARGEST_ASSETS_OUT_OF_TIME_MESSAGE="Reading the largest assets ran out of time on the server. Try again.",LargestAssetsOutOfTimeDataSchema=outOfTimeDataSchema(LARGEST_ASSETS_OUT_OF_TIME);var RESULT_NOT_ADDED_UP_MESSAGE="This result does not add up across assets, so it has no largest assets.";var ScopeLifecycleStatusSchema=external_exports.enum(["PRE_PRODUCTION","ACTIVE","INACTIVE","SHUT_IN","DECOMMISSIONED"]);var ScopePropertyCodeSchema=external_exports.string().min(1).max(64),ScopePropertyValueSchema=external_exports.union([external_exports.string(),external_exports.number(),external_exports.boolean()]),SCOPE_PROPERTY_FILTER_MAX=10,ScopePropertyPredicateSchema=external_exports.strictObject({code:ScopePropertyCodeSchema,equals:ScopePropertyValueSchema}),ScopePropertyFilterSchema=external_exports.array(ScopePropertyPredicateSchema).max(SCOPE_PROPERTY_FILTER_MAX);var SCOPE_PROPERTY_VALUES_MAX=20,SCOPE_PROPERTY_VALUE_TEXT_MAX=512,ScopePropertyListValueSchema=external_exports.union([external_exports.string().max(SCOPE_PROPERTY_VALUE_TEXT_MAX).regex(/^[^\u0000\ud800-\udfff]*$/u,"a value cannot hold a NUL character or an unpaired surrogate"),external_exports.number(),external_exports.boolean()]),ScopePropertyListEntrySchema=external_exports.strictObject({code:ScopePropertyCodeSchema,values:external_exports.array(ScopePropertyListValueSchema).min(1).max(SCOPE_PROPERTY_VALUES_MAX)}),ScopePropertyListSchema=external_exports.array(ScopePropertyListEntrySchema).max(SCOPE_PROPERTY_FILTER_MAX);var SCOPE_UNMATCHED_VALUES_MAX=20,ScopeUnmatchedValueSchema=external_exports.strictObject({code:ScopePropertyCodeSchema,comparison:external_exports.enum(["oneOf","noneOf"]),value:ScopePropertyValueSchema});var ScopeRelationshipTypeSchema=external_exports.enum(["CONTAINS","PART_OF","REPORTS_TO","BELONGS_TO"]);var DECLARATION_SHEETS_MAX=256,DECLARATION_COLUMNS_MAX=2e3,DECLARATION_ROWS_MAX=1e5,PROJECT_BINDINGS_MAX=DECLARATION_COLUMNS_MAX,PINNED_SAMPLE_FEATURES_MAX=1e4,CATEGORY_SPLIT_ELEMENTS_MAX=DECLARATION_COLUMNS_MAX,SCOPE_ASSET_TYPE_IDS_MAX=1e3,SCOPE_LIFECYCLE_STATUSES_MAX=64,ORACLE_UNITS_MAX=1e5,IMPORT_SHEET_ROLES_MAX=DECLARATION_SHEETS_MAX,RESULT_TIMESERIES_POINTS_MAX=1e5,EXEC_DIAGNOSTICS_MAX=1e4,DIAGNOSTIC_SAMPLES_WIRE_MAX=100,WIRE_RECORD_BOUNDS=[],boundedRecord3=(key,value2,max2)=>{let schema=external_exports.record(key,value2).superRefine((record2,context)=>{Object.keys(record2).length>max2&&context.addIssue({code:"custom",message:`give at most ${String(max2)} entries`})});return WIRE_RECORD_BOUNDS.push([schema,max2]),schema},described=(replacement,original)=>original.description===void 0?replacement:replacement.describe(original.description),looseList=(element,max2)=>external_exports.union([external_exports.array(element).max(max2),external_exports.unknown().superRefine((value2,context)=>{Array.isArray(value2)&&value2.length>max2&&context.addIssue({code:"too_big",origin:"array",maximum:max2,inclusive:!0,input:value2})})]);var ScopeHierarchySchema=external_exports.discriminatedUnion("by",[external_exports.object({by:external_exports.literal("hierarchy"),hierarchyId:external_exports.string().min(1)}),external_exports.object({by:external_exports.literal("unassigned")})]);var SCOPE_ROLLUP_LEVELS_MAX=8,ScopeFilterPredicateSchema=external_exports.strictObject({categoryId:external_exports.string().min(1).optional(),assetTypeId:external_exports.string().min(1).optional(),assetTypeIds:external_exports.array(external_exports.string().min(1)).optional(),pathContains:external_exports.string().min(1).optional().describe("Asset NAME substring (case-insensitive): selects every asset under any asset whose name contains this text, root included. Not an asset id \u2014 use rootAssetId for that. Cannot be combined with rootAssetId."),rootAssetId:external_exports.string().min(1).optional().describe("Asset id (a uuid, not a name \u2014 use pathContains for a name): selects every asset under exactly this asset, root included, in the chosen hierarchy and following relationshipType links. Cannot be combined with pathContains. An id that names no asset at the period end resolves to zero assets, with a warning."),relationshipType:ScopeRelationshipTypeSchema.optional().describe("Which link type the tree walk follows from the root: CONTAINS (the default when omitted), PART_OF, REPORTS_TO or BELONGS_TO. Set it to the type the chosen hierarchy's links use \u2014 a walk over the wrong type finds no children."),hierarchy:ScopeHierarchySchema.optional(),lifecycleStatuses:external_exports.array(ScopeLifecycleStatusSchema).optional(),propertyFilters:ScopePropertyFilterSchema.optional(),propertyOneOf:ScopePropertyListSchema.optional().describe(`Keep only assets whose property equals ANY listed value at the period end: \`[{ code, values: [..] }]\`. Values are exact and JSON-typed (the number 42 is not "42"). 1 to ${String(SCOPE_PROPERTY_VALUES_MAX)} values per entry; an empty list is refused. \`propertyFilters\`, \`propertyOneOf\` and \`propertyNoneOf\` entries are ANDed and count together, at most ${String(SCOPE_PROPERTY_FILTER_MAX)}.`),propertyNoneOf:ScopePropertyListSchema.optional().describe(`Drop assets whose property equals ANY listed value at the period end: \`[{ code, values: [..] }]\`. An asset with NO value for the property is KEPT. Values are exact and JSON-typed (the number 42 is not "42"). 1 to ${String(SCOPE_PROPERTY_VALUES_MAX)} values per entry; an empty list is refused. \`propertyFilters\`, \`propertyOneOf\` and \`propertyNoneOf\` entries are ANDed and count together, at most ${String(SCOPE_PROPERTY_FILTER_MAX)}.`),rollupLevels:external_exports.array(RollupLevelSchema).min(1).max(SCOPE_ROLLUP_LEVELS_MAX).optional().describe('Levels to total results by, top level first: a tree level ({by: "assetType"}) or a property field ({by: "property"}). A tree level needs a root (rootAssetId or pathContains) in a named hierarchy. Never changes which assets are selected.')}),ScopeFilterPredicateInputSchema=ScopeFilterPredicateSchema.extend({assetTypeIds:external_exports.array(external_exports.string().min(1)).max(SCOPE_ASSET_TYPE_IDS_MAX).optional(),lifecycleStatuses:external_exports.array(ScopeLifecycleStatusSchema).max(SCOPE_LIFECYCLE_STATUSES_MAX).optional()});var TOTAL_BY_FIELDS_SCOPE_MAX=2e4,ASSET_LIST_WIRE_MAX=TOTAL_BY_FIELDS_SCOPE_MAX*2,TotalByInputSchema=external_exports.strictObject({filter:ScopeFilterPredicateInputSchema}),TotalByFieldsInputSchema=external_exports.union([TotalByInputSchema,external_exports.strictObject({assetIds:external_exports.array(external_exports.string().min(1)).min(1).max(ASSET_LIST_WIRE_MAX)})]),TotalByPlaceInputSchema=external_exports.strictObject({rootAssetId:external_exports.string().min(1),hierarchy:ScopeHierarchySchema,relationshipType:ScopeRelationshipTypeSchema.optional()}),TotalByTwoParentsSchema=external_exports.object({assetId:external_exports.string().min(1),assetName:external_exports.string().min(1),nodeNames:external_exports.array(external_exports.string().min(1)).min(2)}),TotalByTreeLevelSchema=external_exports.object({assetTypeId:external_exports.string().min(1),depth:external_exports.number().int().min(0),nodeCount:external_exports.number().int().min(1),nested:external_exports.boolean().nullable(),twoParents:TotalByTwoParentsSchema.nullable()}),TotalByLevelsSchema=external_exports.discriminatedUnion("status",[external_exports.object({status:external_exports.literal("ready"),root:external_exports.object({assetId:external_exports.string().min(1),name:external_exports.string().min(1)}),subtreeCount:external_exports.number().int().min(0),checked:external_exports.boolean(),levels:external_exports.array(TotalByTreeLevelSchema)}),external_exports.object({status:external_exports.literal("notATree")})]),TotalByPartialSchema=external_exports.discriminatedUnion("status",[external_exports.object({status:external_exports.literal("ready"),leftOut:external_exports.number().int().min(0),partialTypes:external_exports.array(external_exports.string().min(1))}),external_exports.object({status:external_exports.literal("unchecked")}),external_exports.object({status:external_exports.literal("notATree")})]),TotalByFieldSchema=external_exports.object({propertyKey:external_exports.string().min(1),valueCount:external_exports.number().int().min(0),missingCount:external_exports.number().int().min(0),groupable:external_exports.boolean()}),TotalByFieldsSchema=external_exports.discriminatedUnion("status",[external_exports.object({status:external_exports.literal("ready"),inScopeCount:external_exports.number().int().min(0),fields:external_exports.array(TotalByFieldSchema)}),external_exports.object({status:external_exports.literal("tooLarge"),inScopeCount:external_exports.number().int().min(0)})]);var APPROVAL_REVIEW_BLOCKS_MAX=6;var ApprovalReviewBlockSchema=external_exports.discriminatedUnion("kind",[external_exports.strictObject({kind:external_exports.literal("trend"),periods:external_exports.number().int().min(2).max(DECISION_HISTORY_PERIODS_MAX).optional().describe("Earlier periods drawn. Unset: 5 for a year, 12 otherwise.")}),external_exports.strictObject({kind:external_exports.literal("largest"),rows:external_exports.number().int().min(1).max(LARGEST_ASSETS_MAX).optional().describe("Assets listed. Unset: 5.")}),external_exports.strictObject({kind:external_exports.literal("reporting"),level:external_exports.number().int().min(0).max(SCOPE_ROLLUP_LEVELS_MAX-1).optional().describe("Which level of the totals, 0 the top. Unset: the top.")})]),ApprovalReviewConfigSchema=external_exports.object({blocks:external_exports.array(ApprovalReviewBlockSchema).min(1).max(APPROVAL_REVIEW_BLOCKS_MAX).optional().meta({title:"Blocks",description:"What the tab shows, in order. Unset: all three."})}).strict();var ObservationAggregationSchema=external_exports.enum(["sum","average","latest"]),CoarserDataSchema=external_exports.enum(["skip","spread","inEffect"]),ValueChangeSchema=external_exports.enum(["stop","periodEnd","split"]);var ElementIdSchema=external_exports.string().min(1).brand(),ReferenceDatasetRefSchema=external_exports.object({code:external_exports.string().min(1),version:external_exports.string().min(1)}),ReferenceVersionPinSchema=external_exports.object({datasetId:external_exports.string().min(1),versionId:external_exports.string().min(1)}),PIN_DESCRIPTION="The approved (API: promoted) dataset version every run reads for `source.code`. Its `datasetId` must be the dataset `source.code` names, and no other binding may pin that code to another version. A save that adds this binding with neither `pin` nor `follow` sets it. Replacing a stored input on the same table and sheet: to the mode the same save sets on `source.code` (the one pin its bindings hold there, else unset beside a `follow` or a stored pin re-sent without it), or, when the save sets none, to the pin the replaced input held (unset when it followed). Otherwise: to the pin another binding holds on `source.code`, or to the latest approved version when no other binding reads it, else unset. Re-sending a stored binding without its `pin` drops the pin, and the binding follows; where the save sends no pin on `source.code`, that sets the code to follow, so no binding left or swapped in on it takes a removed pin. A save that removes every binding pinning `source.code`, setting no mode on it, sets the removed pin on the stored constants and Table lookups left on it with neither field, so their read does not move; when only copies of a calculation default (`origin`) are left there, it sets the pin on them and drops their `origin`, since a pinned copy no longer equals its default. With no constant or Table lookup left on the code, an observation, Data table or Category map still reading it reads its current version from then on, and the save answers no warning for it. A pin set this way that is not approved refuses `CALC_LOOKUP_PIN_NOT_PROMOTED`, naming the input it joined (`data.heldBy`) or was carried from (`data.carriedFrom`). Absent: the binding follows (see `follow`).",FOLLOW_DESCRIPTION="Follow approved versions: every run reads the newest approved (API: promoted) version of `source.code`, when every input reading it is an unpinned `constant` or `tableLookup`; else the current version, refused when it is not promoted. Only `true`. Refused beside `pin`, or on a code another binding pins (`CALC_SOURCE_PIN_AND_FOLLOW`). A stored binding with neither field reads as following.",VERSION_CHOICE={pin:ReferenceVersionPinSchema.optional().describe(PIN_DESCRIPTION),follow:external_exports.literal(!0).optional().describe(FOLLOW_DESCRIPTION)},ROW_FILTER_COLUMN_MAX_LENGTH=200,ROW_FILTER_VALUE_MAX_LENGTH=500,ROW_FILTERS_MAX=16,isTrimmed=text=>text.trim()===text&&text!=="",ObservationRowFilterSchema=external_exports.object({column:external_exports.string().min(1).max(ROW_FILTER_COLUMN_MAX_LENGTH).refine(isTrimmed,{message:"Only rows where (API: rowFilters[].column): the column must not be blank or start or end with a space"}),equals:external_exports.string().min(1).max(ROW_FILTER_VALUE_MAX_LENGTH).refine(isTrimmed,{message:"Only rows where (API: rowFilters[].equals): the value must not be blank or start or end with a space"})}),AggregationModeSchema=external_exports.enum(["sum"]);var BindingKindSchema=external_exports.enum(["constant","observation","assetProperty","node","tableLookup","assetAggregate","assetCount","observationGroup","event","eventQuantity","dataTable"]),BindingOriginSchema=external_exports.enum(["calculation"]),BINDING_ORIGIN={origin:BindingOriginSchema.optional().describe('Where this connection comes from: `calculation` = a copy of the pinned calculation version\'s default connection for this input ("From the calculation"). Absent = set on this project. A project save keeps the marker only on a connection equal to that default.')},BindingSchema=external_exports.discriminatedUnion("kind",[external_exports.object({kind:external_exports.literal("constant"),...BINDING_ORIGIN,targetElement:ElementIdSchema,name:external_exports.string().min(1),source:ReferenceDatasetRefSchema,targetSheet:external_exports.string().min(1).optional().describe("The lookup table (a `lookup`-role sheet of the pinned declaration) this constant's dataset fills. Absent: the sheet named like the dataset (`source.code`)."),...VERSION_CHOICE,whenValueChanges:ValueChangeSchema.optional().describe("What a run does when this value changes part-way through a period (API: whenValueChanges): `stop` refuses the run, `periodEnd` uses the value at the period end with a warning, `split` calculates the period in parts at each change. Absent: `stop`.")}),external_exports.object({kind:external_exports.literal("tableLookup"),...BINDING_ORIGIN,targetElement:ElementIdSchema,source:ReferenceDatasetRefSchema,targetSheet:external_exports.string().min(1).optional().describe("The lookup table (a `lookup`-role sheet of the pinned declaration) this binding fills. When set, `targetElement` must equal it. Absent: the sheet named like the dataset (`source.code`)."),...VERSION_CHOICE,whenValueChanges:ValueChangeSchema.optional().describe("What a run does when this value changes part-way through a period (API: whenValueChanges): `stop` refuses the run, `periodEnd` uses the value at the period end with a warning, `split` calculates the period in parts at each change. Absent: `stop`.")}),external_exports.object({kind:external_exports.literal("node"),...BINDING_ORIGIN,targetElement:ElementIdSchema,sourceElement:ElementIdSchema}),external_exports.object({kind:external_exports.literal("observation"),...BINDING_ORIGIN,targetElement:ElementIdSchema,observedProperty:external_exports.string().min(1),aggregation:ObservationAggregationSchema,coarserData:CoarserDataSchema.optional().describe("What a run does with a row longer than the period, or crossing its boundary (API: coarserData): `skip` leaves it out with a warning, `spread` shares it by days (Added up only), `inEffect` uses its whole value when no row fits inside the period. Absent: `skip`."),source:ReferenceDatasetRefSchema,assetColumn:external_exports.string().min(1).optional(),periodColumn:external_exports.string().min(1).optional(),valueColumn:external_exports.string().min(1).optional(),propertyColumn:external_exports.string().min(1).optional(),rowFilters:external_exports.array(ObservationRowFilterSchema).max(ROW_FILTERS_MAX).optional().describe("Only rows where (API: rowFilters): conditions every row this input reads must meet, each a column and the value its cell must equal; all must hold. Absent or empty: every row whose property (or value column) matches, as before.")}),external_exports.object({kind:external_exports.literal("assetProperty"),...BINDING_ORIGIN,targetElement:ElementIdSchema,propertyKey:external_exports.string().min(1),whenValueChanges:ValueChangeSchema.optional().describe("What a run does when this value changes part-way through a period (API: whenValueChanges): `stop` refuses the run, `periodEnd` uses the value at the period end with a warning, `split` calculates the period in parts at each change. Absent: `periodEnd`.")}),external_exports.object({kind:external_exports.literal("assetAggregate"),...BINDING_ORIGIN,targetElement:ElementIdSchema,propertyKey:external_exports.string().min(1),aggregation:AggregationModeSchema}),external_exports.object({kind:external_exports.literal("assetCount"),...BINDING_ORIGIN,targetElement:ElementIdSchema}),external_exports.object({kind:external_exports.literal("observationGroup"),...BINDING_ORIGIN,targetElement:ElementIdSchema,observedProperty:external_exports.string().min(1),source:ReferenceDatasetRefSchema}),external_exports.object({kind:external_exports.literal("event"),...BINDING_ORIGIN,targetElement:ElementIdSchema,eventType:external_exports.string().min(1)}),external_exports.object({kind:external_exports.literal("eventQuantity"),...BINDING_ORIGIN,targetElement:ElementIdSchema,eventType:external_exports.string().min(1),quantityField:external_exports.string().min(1)}),external_exports.object({kind:external_exports.literal("dataTable"),...BINDING_ORIGIN,targetSheet:external_exports.string().min(1),source:ReferenceDatasetRefSchema,assetColumn:external_exports.string().min(1).optional(),identityColumn:external_exports.string().min(1).optional(),timeColumn:external_exports.string().min(1).optional(),coarserData:CoarserDataSchema.optional().describe("What a run does with a row whose time value is longer than the period or crosses its boundary (API: coarserData): `skip` leaves it out, as a row outside the period is; `inEffect` delivers it whole to every period it overlaps. Needs `timeColumn`. Absent: `skip`.")})]);var ProjectBindingsSchema=external_exports.array(BindingSchema),DefaultBindingsSchema=external_exports.array(BindingSchema).describe("The calculation version's default connection per input: the connection every new project starts with, marked as following the calculation. Same shapes as a project's bindings, with no `origin`.");var ProjectBindingsInputSchema=external_exports.array(BindingSchema).max(PROJECT_BINDINGS_MAX);var DAY=1,SPAN_DAYS={year:365*DAY,month:30*DAY,day:DAY,instant:0};var DeclarationSheetRoleSchema=external_exports.enum(["calculator","data","lookup","other"]).describe("The sheet's job in the workbook. `calculator` carries the formulas that produce reportable elements (at least one is required, enforced by the engine); `data` and `lookup` carry input rows a calculator reads (each MUST supply `rows` or `source`); `other` is inert at execution \u2014 carried for round-trip fidelity with the workbook."),DECLARATION_TYPE_HINTS=["INTEGER","BIGINT","DOUBLE","FLOAT","DECIMAL","STRING","VARCHAR","BOOLEAN","JSON","DATE","TIMESTAMP","TIMESTAMPTZ","TIMESTAMP_TZ","TIME","INTERVAL"];var DeclarationCanonicalTypeHintSchema=external_exports.enum(DECLARATION_TYPE_HINTS).describe("A DuckDB column type, canonical UPPERCASE. `INTEGER` `BIGINT` `DOUBLE` `FLOAT` `BOOLEAN` `STRING` `VARCHAR` `JSON` `DATE` `TIMESTAMP` `TIMESTAMPTZ` are CAST at execution. `DECIMAL` is CAST as `DOUBLE`. `TIME` `INTERVAL` `TIMESTAMP_TZ` are accepted and stored but the engine has no mapping for them, so the column passes through UNCAST \u2014 they are not a type pin."),DeclarationTypeHintSchema=external_exports.union([DeclarationCanonicalTypeHintSchema,external_exports.string().describe("Any other hint spelling the engine tolerates: ANY CASE (it upper-cases before comparing), the timezone-suffixed `TIMESTAMPTZ:<IANA zone>` / `TIMESTAMP:<IANA zone>` form, or a hint it does not recognise at all (it WARNS and reads the column as text).")]).describe("A DuckDB column type. Prefer a canonical UPPERCASE spelling; `TIMESTAMPTZ:<IANA zone>` and `TIMESTAMP:<IANA zone>` pin the timezone the source values are parsed in."),DeclarationStaticCellValueTypeSchema=external_exports.enum(["string","number","boolean","date"]).describe("How a static cell above the header row is typed when the workbook is built."),SummaryAggregationTypeSchema=external_exports.enum(["sum","average","avg","count","max","min"]),PivotSubtotalSchema=external_exports.enum(["sum","count","average","avg","min","max"]),DeclarationColumnTypeHintSchema=external_exports.union([DeclarationTypeHintSchema,external_exports.looseObject({type:DeclarationTypeHintSchema,format:external_exports.string().nullable().optional().describe("A DuckDB `STRFTIME` format. When present the column is emitted as a formatted VARCHAR instead of a native temporal type.")})]).describe("The DuckDB type a column is read as \u2014 a bare hint, or `{ type, format? }`."),DeclarationStaticCellSchema=external_exports.union([external_exports.string(),external_exports.number(),external_exports.boolean(),external_exports.null(),external_exports.strictObject({valueType:DeclarationStaticCellValueTypeSchema.nullable().optional(),value:external_exports.unknown().optional().describe("The cell value, typed by `valueType`.")})]).describe('A value pinned to a cell ABOVE the header row (keyed `"B1"`, `"C2"`, \u2026 \u2014 the engine enforces the cell-reference format). Calculator sheets only; elsewhere the engine warns that it is meaningless.'),DeclarationSummaryAggregationSchema=external_exports.union([SummaryAggregationTypeSchema,external_exports.string().regex(/^=/,"A formula aggregation must start with `=`.").describe("An Excel formula aggregation, e.g. `=COUNTA(Calculator[Well ID])`."),external_exports.null(),external_exports.strictObject({type:external_exports.literal("value"),value:external_exports.unknown().optional().describe("The static value written into the summary row.")})]).describe('What this column shows in the summary row: a named aggregation (`sum`, `average`/`avg`, `count`, `max`, `min`), an Excel formula starting with `=`, a static `{ type: "value", value }`, or `null` to skip the column.'),DeclarationSummaryRowSchema=external_exports.strictObject({label:external_exports.string().nullable().optional().describe('Row label, e.g. `"TOTALS"`.'),aggregations:external_exports.record(external_exports.string(),DeclarationSummaryAggregationSchema).describe("Column name \u2192 what that column shows in this summary row.")}).describe("One aggregation row rendered BELOW the data rows. Calculator sheets only; elsewhere the engine warns that it is meaningless."),DeclarationLiteralOverrideSchema=external_exports.looseObject({rowId:external_exports.union([external_exports.string(),external_exports.number(),external_exports.boolean()]).describe("The `RowID` cell value identifying the row to override."),value:external_exports.unknown().optional().describe("The literal written instead of the column formula.")}).describe('Replaces ONE row\'s computed cell with a literal, lowered to a `CASE WHEN "RowID" = \u2026 THEN <literal> ELSE <formula> END`. Calculator sheets only, and the sheet must declare a `RowID` column.'),DeclarationSheetSourceSchema=external_exports.union([external_exports.string().describe("An external file path \u2014 CSV, Parquet, JSON or JSONL."),external_exports.looseObject({union:external_exports.union([external_exports.array(external_exports.unknown()),external_exports.record(external_exports.string(),external_exports.unknown())]).describe("Members to UNION into one virtual table.")}),external_exports.looseObject({groupBy:external_exports.record(external_exports.string(),external_exports.unknown()).describe("A grouping + aggregation that generates the seed rows.")}),external_exports.looseObject({crossJoin:external_exports.record(external_exports.string(),external_exports.unknown()).describe("A Cartesian product of two registered tables.")})]).describe("Where this sheet's rows come from: a file path string, or ONE of the virtual-table definitions `{ union }`, `{ groupBy }`, `{ crossJoin }`. Mutually exclusive with `rows` \u2014 except a `union`, which requires `rows: []` beside it. The engine validates the chosen definition's interior."),DeclarationSheetSchema=external_exports.strictObject({name:external_exports.string().min(1).describe("Sheet name \u2014 unique across the declaration."),role:DeclarationSheetRoleSchema,columns:external_exports.array(external_exports.string().min(1)).min(1).describe("Ordered column names. Non-empty, no duplicates \u2014 these ARE the elements."),rowGenerators:external_exports.array(external_exports.string().min(1)).nullable().optional().describe("Columns whose formula GENERATES the row set (`UNIQUE`/`FILTER`) rather than computing a value per existing row. Each must name a declared column."),rows:external_exports.array(external_exports.record(external_exports.string(),external_exports.unknown())).nullable().optional().describe("Inline data rows, one record per row keyed by column name. Cell values are carried verbatim \u2014 the engine types them via `columnTypeHints`."),source:DeclarationSheetSourceSchema.nullable().optional(),columnFormulas:external_exports.record(external_exports.string(),external_exports.string()).nullable().optional().describe('Column name \u2192 Excel formula, e.g. `"=[@Count] * [@Factor]"`. The formula text is carried OPAQUELY: the ENGINE parses, binds and lowers it \u2014 nothing here reads it.'),formulaSourceRow:external_exports.union([external_exports.number().int(),external_exports.unknown()]).optional().describe("A whole Excel row number: the row A1-style cell references in this sheet were written against \u2014 the anchor that turns `$A3` into a cross-row offset for LAG/LEAD. Defaults to `headerRowNumber + 1`, so a formula written against row 3 resolves same-row only when this field says 3; every extracted and seeded declaration says 3. LOAD-BEARING for the DuckDB recalc, and omitting it is only soft-warned at validate. The engine READS this field but omits it from its own strict key set, so it is accepted here rather than stripped."),columnTypeHints:external_exports.record(external_exports.string(),DeclarationColumnTypeHintSchema).nullable().optional().describe("Column name \u2192 the DuckDB type it is read as."),columnTimezones:external_exports.record(external_exports.string(),external_exports.string()).nullable().optional().describe("Column name \u2192 IANA timezone used to parse that column's timestamps."),staticCells:external_exports.record(external_exports.string(),DeclarationStaticCellSchema).nullable().optional().describe('Cell reference (`"B1"`) \u2192 the value pinned there. Calculator sheets only.'),summaryRows:external_exports.array(DeclarationSummaryRowSchema).nullable().optional().describe("Aggregation rows below the data. Calculator sheets only."),literalOverrides:external_exports.record(external_exports.string(),external_exports.array(DeclarationLiteralOverrideSchema)).nullable().optional().describe("Column name \u2192 per-row literal overrides. Calculator sheets only."),tableNames:external_exports.union([external_exports.array(external_exports.string().min(1)),external_exports.unknown()]).optional().describe("An array of Excel ListObject (Table) names hosted on this sheet. Structured references `TableName[Col]` resolve through these.")}).describe("One sheet: its role, its ordered columns, and where its rows come from (`rows`, `source`, or a `rowGenerators` formula). A declaration needs at least one `calculator` sheet \u2014 the engine enforces that, not this shape."),DeclarationPivotSourceSchema=external_exports.strictObject({sheetName:external_exports.string().min(1).nullable().optional().describe("The source SHEET this pivot reads."),tableName:external_exports.string().min(1).nullable().optional().describe("The source TABLE this pivot reads."),ref:external_exports.string().min(1).nullable().optional().describe("The source range reference, workbook-style."),headerRow:external_exports.union([external_exports.number().int(),external_exports.unknown()]).optional().describe("Which row of the range holds the headers, as a whole number."),name:external_exports.string().nullable().optional().describe("An extractor-emitted source label, carried for round-trip fidelity and read by nothing at execution. The engine emits this field but omits it from its own strict key set, so it is accepted here rather than refused.")}).describe("What the pivot aggregates. Exactly one of `sheetName` / `tableName` must be PRESENT and non-null \u2014 the ENGINE enforces that (a cross-field rule has no place on a JSON-Schema seam). The unused half is customarily carried as an explicit `null`."),DeclarationPivotDataFieldSchema=external_exports.strictObject({sourceField:external_exports.string().min(1).describe("The source column aggregated into this field."),subtotal:PivotSubtotalSchema.nullable().optional().describe("How it aggregates. Defaults to `sum`."),name:external_exports.string().nullable().optional().describe('Display name. Defaults to `"<subtotal> of <sourceField>"`.')}).describe("One aggregated value column of the pivot."),DeclarationPivotRowColFieldSchema=external_exports.strictObject({name:external_exports.string().min(1).describe("The column grouped on."),items:external_exports.union([external_exports.array(external_exports.unknown()),external_exports.unknown()]).optional().describe("An array of the field's pre-computed distinct values, preserved from the workbook manifest's `sharedItems` for round-trip fidelity. Values are carried verbatim.")}).describe("One row or column grouping field."),DeclarationPivotPageFieldSchema=external_exports.strictObject({name:external_exports.string().min(1).describe("The column filtered on."),selectedItem:external_exports.unknown().optional().describe("The selected filter value, carried verbatim.")}).describe("One page (filter) field."),DeclarationPivotCalculatedFieldSchema=external_exports.strictObject({name:external_exports.string().min(1).describe("The calculated field name."),formula:external_exports.string().min(1).describe("The pivot formula expression \u2014 carried OPAQUELY; the engine parses it.")}).describe("One field computed from the pivot's other fields."),DeclarationPivotSheetSchema=external_exports.strictObject({name:external_exports.string().min(1).describe("Pivot sheet name."),source:DeclarationPivotSourceSchema,dataFields:external_exports.array(DeclarationPivotDataFieldSchema).min(1).describe("The aggregated value columns \u2014 at least one."),rowFields:external_exports.array(DeclarationPivotRowColFieldSchema).nullable().optional().describe("Row groupings."),colFields:external_exports.array(DeclarationPivotRowColFieldSchema).nullable().optional().describe("Column groupings."),pageFields:external_exports.array(DeclarationPivotPageFieldSchema).nullable().optional().describe("Filter fields."),calculatedFields:external_exports.array(DeclarationPivotCalculatedFieldSchema).nullable().optional().describe("Fields computed from the other pivot fields."),dataOnRows:external_exports.union([external_exports.boolean(),external_exports.unknown()]).optional().describe("Transpose the summary layout. Default `false`."),rowGrandTotals:external_exports.union([external_exports.boolean(),external_exports.unknown()]).optional().describe("Include row grand totals. Default `true`."),colGrandTotals:external_exports.union([external_exports.boolean(),external_exports.unknown()]).optional().describe("Include column grand totals. Default `true`.")}).describe("A pivot table over a source sheet or table. In this domain the canonical use is the DECLARED FACILITY TOTAL \u2014 one `sum` data field per reportable element."),DeclarationExecutionSchema=external_exports.strictObject({defaultTimestampType:external_exports.string().nullable().optional().describe("Default temporal type for date/time columns. Engine default `TIMESTAMP`."),defaultSourceTimezone:external_exports.string().nullable().optional().describe("Default IANA timezone timestamps are parsed in when a column names none."),preserveRowOrder:external_exports.union([external_exports.boolean(),external_exports.unknown()]).optional().describe("Keep input row order in the output. Engine default `true`."),orderBy:external_exports.union([external_exports.string(),external_exports.array(external_exports.string()).min(1)]).nullable().optional().describe("Column(s) to sort output by. Overrides `preserveRowOrder` when set."),pipeline:external_exports.union([external_exports.array(external_exports.string().min(1)),external_exports.unknown()]).optional().describe("Calculator sheet names run in sequence \u2014 each stage materialised as a DuckDB table the next stage can read."),criteriaMatching:external_exports.enum(["excel","exact"]).nullable().optional().describe("How `*IFS` criteria, `XLOOKUP` and `ECE.LOOKUPWHERE` match cells. `excel` (the default) follows Excel's rules: wildcards, case-insensitive text, blank criteria, no number/text coercion. `exact` is plain SQL equality.")}).describe("Execution defaults. Runtime parameters passed to the engine take precedence."),DeclarationSchema=external_exports.strictObject({version:external_exports.string().min(1).describe('Declaration format version, currently `"1.0"`. NOT pinned to a literal here: a stored artifact declaring another version must still READ \u2014 the ENGINE decides whether it runs (strict mode errors on a mismatch, lax mode warns).'),sheets:external_exports.array(DeclarationSheetSchema).min(1).describe("The sheets, in order. At least one must be a `calculator`."),pivotSheets:external_exports.array(DeclarationPivotSheetSchema).nullable().optional().describe("Pivot tables over the sheets above \u2014 the declared-total surface."),execution:DeclarationExecutionSchema.nullable().optional()}).describe("The ECE declaration \u2014 a methodology as a self-contained JSON workbook: sheets \u2192 columns \u2192 Excel formulas, plus the data the formulas read. STRUCTURAL shape only: formulas are opaque strings and the ENGINE remains the arithmetic and cross-reference authority (it compiles, cross-checks and executes). Accepts the engine's own field sets PLUS exactly two extractor fields \u2014 `sheets[].formulaSourceRow` and `pivotSheets[].source.name` \u2014 which the engine reads but omits from its strict key sets. Every other unknown key is REFUSED.");var CategoryBreakdownSchema=external_exports.object({sourceTypeColumn:external_exports.string().min(1).describe("The column holding each input row\u2019s source type. Every source that feeds a result in `splitElements` must carry it."),map:ReferenceDatasetRefSchema.describe("The Category map: a reference dataset with columns `sourceType` (unique) and `family`, and optional `program`, `validFrom` / `validTo`. Any other column is ignored, except one that reads as `program` misnamed (`Program`, `program `) on a map with no `program` column, which is refused. A run pins the version it reads."),splitElements:external_exports.array(ElementIdSchema).min(1).describe("The results broken down by Emission category. Each must be a mass or CO2e result of the pinned calculation; a ratio is refused.")}),CategoryBreakdownInputSchema=CategoryBreakdownSchema.extend({splitElements:CategoryBreakdownSchema.shape.splitElements.max(CATEGORY_SPLIT_ELEMENTS_MAX)});var MASS_UNITS=["t","tonnes?","tons?","metrictonnes?","metrictons?","shorttons?","longtons?","kilotonnes?","megatonnes?","mt","mmt","kt","kg","kgs","kilograms?","g","gg","tg","grams?","mg","lbs?","pounds?"].join("|"),SUBSTANCES=["co2equivalents?","co2eq","co2e","co2","ch4","n2o","vocs?","nox","sox","so2","co","h2s","haps?","sf6","hfcs?","pfcs?","nf3","pm2\\.5","pm10","pm","ghgs?"].join("|"),TIME_UNITS="years?|yrs?|y|annum|a|quarters?|qtrs?|months?|mo|weeks?|wks?|days?|d|hours?|hrs?|h|minutes?|mins?|seconds?|secs?|s",MASS_UNIT_RE=new RegExp(`^(?:(?:${MASS_UNITS})(?:(?:of)?(?:${SUBSTANCES}))?(?:(?:/|per)(?:${TIME_UNITS}))?|tp[yda])$`);var PER_TIME_EXPONENT=new RegExp(`^(.*[^\\s/])(?:\\s+|\\s*/\\s*)(${TIME_UNITS})\\s*-1$`);var CATEGORY_SAVE_REFUSAL_CODES=["CALC_CATEGORY_GRAIN_UNSUPPORTED","CALC_CATEGORY_ELEMENT_NOT_SPLITTABLE","CALC_CATEGORY_READS_OTHER_ROWS","CALC_CATEGORY_MAP_UNRESOLVED","CALC_CATEGORY_MAP_SHAPE","CALC_CATEGORY_COLUMN_MISSING"],CategoryRefusalDataSchema=external_exports.object({code:external_exports.enum(CATEGORY_SAVE_REFUSAL_CODES),element:external_exports.string().optional(),feeds:external_exports.string().optional(),sheet:external_exports.string().optional(),input:external_exports.string().optional(),dataset:external_exports.string().optional()});var BREAKDOWN_UNMATCHED_SHOWN_MAX=50,BREAKDOWN_GROUPS_SHOWN_MAX=500,BREAKDOWN_GROUP_VALUES_SHOWN_MAX=50,BreakdownGroupsStatusInputSchema=external_exports.strictObject({projectId:ProjectIdSchema,breakdown:CategoryBreakdownInputSchema}),BreakdownGroupSchema=external_exports.object({name:external_exports.string().min(1),values:external_exports.array(external_exports.string().min(1)).max(BREAKDOWN_GROUP_VALUES_SHOWN_MAX),valueCount:external_exports.number().int().nonnegative()}),UnmatchedValueSchema=external_exports.object({value:external_exports.string().min(1),records:external_exports.number().int().positive()}),BreakdownGroupsStatusSchema=external_exports.object({groups:external_exports.array(BreakdownGroupSchema).max(BREAKDOWN_GROUPS_SHOWN_MAX),groupCount:external_exports.number().int().nonnegative(),unmatched:external_exports.object({values:external_exports.array(UnmatchedValueSchema).max(BREAKDOWN_UNMATCHED_SHOWN_MAX),valueCount:external_exports.number().int().nonnegative(),records:external_exports.number().int().nonnegative()}),blankRecords:external_exports.number().int().nonnegative(),assetCount:external_exports.number().int().nonnegative(),across:external_exports.literal("all periods")});var BREAKDOWN_COLUMNS_CHECKED_MAX=20,BREAKDOWN_COLUMNS_CONFIRMED_MAX=2,BREAKDOWN_TEMPLATE_VALUES_MAX=5e3,AcrossSchema=external_exports.literal("all periods"),SplitElementsSchema=external_exports.array(ElementIdSchema).min(1).max(CATEGORY_SPLIT_ELEMENTS_MAX).optional().describe("The results to split. Absent: every result of the calculation that can be split."),BreakdownColumnMatchInputSchema=external_exports.strictObject({projectId:ProjectIdSchema,map:ReferenceDatasetRefSchema,splitElements:SplitElementsSchema}),BreakdownColumnCandidateSchema=external_exports.object({column:external_exports.string().min(1),matchedValues:external_exports.number().int().nonnegative(),matchedRecords:external_exports.number().int().nonnegative(),unmatchedValues:external_exports.number().int().nonnegative(),unmatchedRecords:external_exports.number().int().nonnegative(),tooManyValues:external_exports.boolean()}),BreakdownColumnConfirmationSchema=external_exports.object({column:external_exports.string().min(1),matchedValues:external_exports.number().int().nonnegative(),matchedRecords:external_exports.number().int().nonnegative()}),BreakdownColumnMatchSchema=external_exports.object({splitElements:external_exports.array(ElementIdSchema),columns:external_exports.array(BreakdownColumnCandidateSchema).max(BREAKDOWN_COLUMNS_CHECKED_MAX),columnsNotChecked:external_exports.number().int().nonnegative(),confirmed:external_exports.array(BreakdownColumnConfirmationSchema).max(BREAKDOWN_COLUMNS_CONFIRMED_MAX),detected:external_exports.string().min(1).nullable(),overBudget:external_exports.boolean(),assetCount:external_exports.number().int().nonnegative(),across:AcrossSchema}),BreakdownTemplateValuesInputSchema=external_exports.strictObject({projectId:ProjectIdSchema,column:external_exports.string().min(1).optional(),map:ReferenceDatasetRefSchema.optional(),splitElements:SplitElementsSchema}),BreakdownTemplateValuesSchema=external_exports.object({column:external_exports.string().min(1),splitElements:external_exports.array(ElementIdSchema),values:external_exports.array(external_exports.object({value:external_exports.string().min(1),records:external_exports.number().int().positive()})).max(BREAKDOWN_TEMPLATE_VALUES_MAX),valueCount:external_exports.number().int().nonnegative(),assetCount:external_exports.number().int().nonnegative(),across:AcrossSchema}),BreakdownColumnCheckInputSchema=external_exports.strictObject({projectId:ProjectIdSchema}),BreakdownColumnCheckSchema=external_exports.object({column:external_exports.string().min(1),present:external_exports.boolean(),missingFrom:external_exports.array(external_exports.object({dataset:external_exports.string().min(1),input:external_exports.string().min(1),reason:external_exports.enum(["column-missing","dataset-unknown"])}))}).nullable().describe("Null when the project stores no breakdown.");var CONSTANTS_USED_ROWS_MAX=20;var ConstantsUsedInputSchema=external_exports.strictObject({runId:RunIdSchema}),FrozenCellSchema=external_exports.union([external_exports.string(),external_exports.number(),external_exports.boolean(),external_exports.null()]),FrozenRowCitationSchema=external_exports.object({title:external_exports.string().min(1),url:external_exports.string().min(1).optional()}),FrozenRowSchema=external_exports.object({cells:external_exports.record(external_exports.string(),FrozenCellSchema),validFrom:external_exports.string().nullable(),validTo:external_exports.string().nullable(),ownCitation:FrozenRowCitationSchema.nullable(),unit:external_exports.string().min(1).nullable()}),ConstantTableSchema=external_exports.object({code:external_exports.string().min(1),datasetId:external_exports.string().min(1).nullable(),versionId:external_exports.string().min(1).nullable()}),ReferenceConstantUsedSchema=external_exports.object({name:external_exports.string().min(1),targetElement:external_exports.string().min(1),table:ConstantTableSchema,sheet:external_exports.string().min(1),sheetRows:external_exports.number().int().nonnegative().nullable(),rowsNamingIt:external_exports.number().int().nonnegative().nullable(),rows:external_exports.array(FrozenRowSchema).max(CONSTANTS_USED_ROWS_MAX)}),TypedConstantUsedSchema=external_exports.object({name:external_exports.string().min(1),elementId:external_exports.string().min(1),value:FrozenCellSchema,unit:external_exports.string().nullable(),description:external_exports.string().nullable(),reference:external_exports.string().nullable()}),ConstantsUsedFrozenSchema=external_exports.discriminatedUnion("kind",[external_exports.object({kind:external_exports.literal("whole-period")}),external_exports.object({kind:external_exports.literal("end-values"),parts:external_exports.number().int().min(2)}),external_exports.object({kind:external_exports.literal("none"),reason:external_exports.enum(["posted","not-frozen","not-delivered"])})]),ConstantsUsedSchema=external_exports.object({runId:RunIdSchema,frozen:ConstantsUsedFrozenSchema,note:external_exports.string().min(1).nullable(),projectVersion:external_exports.number().int().positive().nullable(),declarationVersionId:external_exports.string().min(1),constants:external_exports.array(ReferenceConstantUsedSchema),typed:external_exports.array(TypedConstantUsedSchema)});var ResultSubjectSchema=external_exports.discriminatedUnion("kind",[external_exports.strictObject({kind:external_exports.literal("asset"),assetId:external_exports.string().min(1)}),external_exports.strictObject({kind:external_exports.literal("runScope")}),external_exports.strictObject({kind:external_exports.literal("row"),rowKey:external_exports.string().min(1)}),external_exports.strictObject({kind:external_exports.literal("group"),groupKey:external_exports.string().min(1)})]),RUN_SCOPE_SUBJECT=Object.freeze({kind:"runScope"});var ResultKeySchema=external_exports.object({subject:ResultSubjectSchema,period:external_exports.string().min(1)});var FIGURE_PERIOD_MAX_LENGTH=256,FigureInputsInputSchema=external_exports.strictObject({runId:RunIdSchema,subject:ResultSubjectSchema,element:ReadElementIdSchema,period:external_exports.string().min(1).max(FIGURE_PERIOD_MAX_LENGTH).regex(READ_ELEMENT_ID_PATTERN,"A period may not hold a NUL or an unpaired surrogate")}),FIGURE_FACTOR_ROWS_MAX=20,FigureOriginSchema=external_exports.discriminatedUnion("kind",[external_exports.object({kind:external_exports.literal("dataset"),code:external_exports.string().min(1),versionId:external_exports.string().min(1).nullable(),column:external_exports.string().min(1).nullable()}),external_exports.object({kind:external_exports.literal("assetProperty"),propertyKey:external_exports.string().min(1),assetVersionId:external_exports.string().min(1).nullable(),datedValueId:external_exports.string().min(1).optional()}),external_exports.object({kind:external_exports.literal("calculationVersion"),declarationVersionId:external_exports.string().min(1),sheet:external_exports.string().min(1)}),external_exports.object({kind:external_exports.literal("notRecorded")})]),FigureInputSchema=external_exports.object({name:external_exports.string().min(1),value:FrozenCellSchema,unit:external_exports.string().min(1).nullable(),origin:FigureOriginSchema}),FigureMatchedRowSchema=external_exports.object({number:external_exports.number().int().positive(),cells:external_exports.record(external_exports.string(),FrozenCellSchema)}),FigureFactorSchema=external_exports.object({name:external_exports.string().min(1),text:external_exports.string().min(1),function:external_exports.string().min(1).nullable(),table:external_exports.string().min(1).nullable(),value:FrozenCellSchema,unit:external_exports.string().min(1).nullable(),origin:FigureOriginSchema,matchedRows:external_exports.array(FigureMatchedRowSchema).max(FIGURE_FACTOR_ROWS_MAX),matchedRowCount:external_exports.number().int().nonnegative()}),FigureComputedSchema=external_exports.object({name:external_exports.string().min(1),value:FrozenCellSchema,unit:external_exports.string().min(1).nullable()}),FIGURE_NOT_RECORDED_REASONS=["posted","declared-total","not-per-asset","pre-element-provenance","period-split","not-sealed","not-proven","not-chunked","asset-not-in-run","no-engine-facts","too-large","engine-feature-refused","engine-refused","overridden","figure-mismatch"],FigureNotRecordedReasonSchema=external_exports.enum(FIGURE_NOT_RECORDED_REASONS),FigureInputsSchema=external_exports.discriminatedUnion("kind",[external_exports.object({kind:external_exports.literal("explained"),runId:RunIdSchema,element:ReadElementIdSchema,figure:external_exports.union([external_exports.number(),external_exports.string(),external_exports.boolean()]),unit:external_exports.string().min(1).nullable(),formula:external_exports.string().min(1).nullable(),inputs:external_exports.array(FigureInputSchema),factors:external_exports.array(FigureFactorSchema),computed:external_exports.array(FigureComputedSchema),engineVersion:external_exports.string().min(1),explainedWith:external_exports.string().min(1)}),external_exports.object({kind:external_exports.literal("notRecorded"),runId:RunIdSchema,element:ReadElementIdSchema,reason:FigureNotRecordedReasonSchema,note:external_exports.string().min(1),code:external_exports.string().min(1).nullable()})]);var CrossRowConstructSchema=external_exports.enum(["rank","rowNumber","previousRow","nextRow","calculatorColumn"]),CrossRowReadSchema=external_exports.object({element:external_exports.string().min(1),constructs:external_exports.array(CrossRowConstructSchema).min(1)}),CrossRowUncheckedSheetSchema=external_exports.object({sheet:external_exports.string().min(1),reason:external_exports.string()});var DeclarationArchiveInputSchema=external_exports.strictObject({declarationId:DeclarationIdSchema,idempotencyKey:CallerMintedKeySchema2}),DeclarationArchiveStateSchema=external_exports.object({declarationId:DeclarationIdSchema,archived:external_exports.boolean(),archivedAt:external_exports.iso.datetime().nullable(),archivedBy:external_exports.string().min(1).nullable()}),DECLARATION_ARCHIVE_BLOCKED_MESSAGE="This calculation cannot be archived while a draft or active project uses it",DeclarationArchiveBlockedSchema=external_exports.object({reason:external_exports.literal("live-projects"),projects:external_exports.array(external_exports.object({projectId:ProjectIdSchema,name:external_exports.string(),status:external_exports.enum(["DRAFT","ACTIVE"])})).min(1)}),DECLARATION_ARCHIVE_KEY_REUSED_CODE="CALC_DECLARATION_ARCHIVE_KEY_REUSED",DECLARATION_ARCHIVE_CHANGED_CONCURRENTLY_CODE="CALC_DECLARATION_ARCHIVE_CHANGED_CONCURRENTLY",ArchiveSideSchema=external_exports.enum(["archived","live"]),DeclarationArchiveKeyReusedSchema=external_exports.object({code:external_exports.literal(DECLARATION_ARCHIVE_KEY_REUSED_CODE)}),DeclarationArchiveChangedConcurrentlySchema=external_exports.object({code:external_exports.literal(DECLARATION_ARCHIVE_CHANGED_CONCURRENTLY_CODE),declarationId:DeclarationIdSchema,observed:ArchiveSideSchema,to:ArchiveSideSchema}),DeclarationArchiveConflictSchema=external_exports.union([DeclarationArchiveBlockedSchema,DeclarationArchiveKeyReusedSchema,DeclarationArchiveChangedConcurrentlySchema]),DeclarationUnarchiveConflictSchema=external_exports.discriminatedUnion("code",[DeclarationArchiveKeyReusedSchema,DeclarationArchiveChangedConcurrentlySchema]),DECLARATION_ARCHIVED_CODE="CALC_DECLARATION_ARCHIVED";var NamespaceIdSchema=external_exports.string().min(1).brand(),NamespaceCodeSchema=external_exports.string().min(1).regex(/^[a-z0-9][a-z0-9-]*$/,"code must be URL-safe (lowercase alphanumeric + hyphen)"),INVISIBLE=/[\u200B-\u200D\u2060\uFEFF]/gu,LONE_SURROGATE=new RegExp("\\p{Surrogate}","u"),storable=name2=>!name2.includes("\0")&&!LONE_SURROGATE.test(name2),NamespaceNameSchema=external_exports.string().trim().min(1).max(200).refine(storable,"name holds a character that cannot be stored").refine(name2=>name2.replace(INVISIBLE,"").trim().length>0,"name must be visible"),NamespaceSchema=external_exports.object({id:NamespaceIdSchema,code:NamespaceCodeSchema,name:external_exports.string().min(1)}),CreateNamespaceInputSchema=external_exports.strictObject({code:NamespaceCodeSchema,name:NamespaceNameSchema,idempotencyKey:CallerMintedKeySchema2}),UpdateNamespaceInputSchema=external_exports.strictObject({id:NamespaceIdSchema,name:NamespaceNameSchema,idempotencyKey:CallerMintedKeySchema2}),DeleteNamespaceInputSchema=external_exports.strictObject({id:NamespaceIdSchema,idempotencyKey:CallerMintedKeySchema2}),NAMESPACE_NOT_FOUND_CODE="CALC_NAMESPACE_NOT_FOUND",NAMESPACE_NAME_TAKEN_CODE="CALC_NAMESPACE_NAME_TAKEN",NAMESPACE_NOT_EMPTY_CODE="CALC_NAMESPACE_NOT_EMPTY",NamespaceNotFoundSchema=external_exports.object({code:external_exports.literal(NAMESPACE_NOT_FOUND_CODE),namespaceId:NamespaceIdSchema}),NamespaceNameTakenSchema=external_exports.object({code:external_exports.literal(NAMESPACE_NAME_TAKEN_CODE),existing:NamespaceSchema}),NamespaceNotEmptySchema=external_exports.object({code:external_exports.literal(NAMESPACE_NOT_EMPTY_CODE),calculationCount:external_exports.number().int().min(1)});var MOVE_DECLARATIONS_MAX=500,MoveDeclarationsInputSchema=external_exports.strictObject({declarationIds:external_exports.array(DeclarationIdSchema).min(1).max(MOVE_DECLARATIONS_MAX),namespaceId:NamespaceIdSchema.nullable(),idempotencyKey:CallerMintedKeySchema2}),MoveDeclarationsResultSchema=external_exports.object({namespaceId:NamespaceIdSchema.nullable(),moved:external_exports.array(external_exports.object({declarationId:DeclarationIdSchema,from:NamespaceIdSchema.nullable()}))}),DECLARATION_MOVE_NOT_FOUND_CODE="CALC_DECLARATION_MOVE_NOT_FOUND",DECLARATION_MOVE_CATEGORY_NOT_FOUND_CODE="CALC_DECLARATION_MOVE_CATEGORY_NOT_FOUND",DeclarationMoveNotFoundSchema=external_exports.discriminatedUnion("code",[external_exports.object({code:external_exports.literal(DECLARATION_MOVE_NOT_FOUND_CODE),declarationIds:external_exports.array(DeclarationIdSchema).min(1)}),external_exports.object({code:external_exports.literal(DECLARATION_MOVE_CATEGORY_NOT_FOUND_CODE),namespaceId:NamespaceIdSchema})]);var DECLARATION_DRAFT_MAX_REVISION=2147483647,DeclarationDraftRevisionSchema=external_exports.number().int().positive().max(DECLARATION_DRAFT_MAX_REVISION),DeclarationDraftIdSchema=external_exports.string().min(1).brand(),DeclarationDraftRefSchema=external_exports.strictObject({draftId:DeclarationDraftIdSchema,revision:DeclarationDraftRevisionSchema});var REVERT_REASON_MAX=500,RevertedFromInputSchema=external_exports.strictObject({versionId:DeclarationVersionIdSchema,reason:external_exports.string().trim().min(1).max(REVERT_REASON_MAX)}),LineageRevertSchema=external_exports.object({versionId:DeclarationVersionIdSchema,version:external_exports.number().int().positive(),reason:external_exports.string().min(1)}),DraftAppendShape={fromDraft:DeclarationDraftRefSchema.optional(),revertedFrom:RevertedFromInputSchema.optional()};var DECLARATION_DRAFT_CONTENT_MAX_BYTES=16*1024*1024;var DeclarationDraftContentSchema=external_exports.record(external_exports.string(),external_exports.unknown()),DeclarationDraftSchema=external_exports.object({draftId:DeclarationDraftIdSchema,declarationId:DeclarationIdSchema,baseVersionId:DeclarationVersionIdSchema,baseVersion:external_exports.number().int().positive(),startedOnHeadId:DeclarationVersionIdSchema,startedOnHeadVersion:external_exports.number().int().positive(),content:external_exports.record(external_exports.string(),external_exports.unknown()),revision:DeclarationDraftRevisionSchema,savedAt:external_exports.iso.datetime(),savedBy:external_exports.string().min(1),savedByCaller:external_exports.boolean()}),GetDeclarationDraftInputSchema=external_exports.strictObject({declarationId:DeclarationIdSchema}),DeclarationDraftReadSchema=external_exports.object({draft:DeclarationDraftSchema.nullable()}),SaveDeclarationDraftInputSchema=external_exports.strictObject({declarationId:DeclarationIdSchema,baseVersionId:DeclarationVersionIdSchema,startedOnHeadId:DeclarationVersionIdSchema,content:DeclarationDraftContentSchema,expected:DeclarationDraftRefSchema.nullable()}),DiscardDeclarationDraftInputSchema=external_exports.strictObject({declarationId:DeclarationIdSchema,expected:DeclarationDraftRefSchema}),DiscardDeclarationDraftOutputSchema=external_exports.object({discarded:external_exports.boolean()}),DECLARATION_DRAFT_CHANGED_CODE="CALC_DECLARATION_DRAFT_CHANGED",DECLARATION_DRAFT_CHANGED_MESSAGE="This draft was changed by someone else since it was opened. Nothing was saved",DeclarationDraftChangedSchema=external_exports.object({code:external_exports.literal(DECLARATION_DRAFT_CHANGED_CODE),declarationId:DeclarationIdSchema,current:external_exports.object({draftId:DeclarationDraftIdSchema,revision:DeclarationDraftRevisionSchema,savedAt:external_exports.iso.datetime(),savedBy:external_exports.string().min(1),savedByCaller:external_exports.boolean()}).nullable()}),DeclarationDraftConflictSchema=external_exports.union([DeclarationDraftChangedSchema,external_exports.object({code:external_exports.literal(DECLARATION_ARCHIVED_CODE),declarationId:DeclarationIdSchema})]);var DECLARATION_HEAD_MOVED_MESSAGE="The calculation has a newer version than the one this was made from",DeclarationHeadMovedSchema=external_exports.object({reason:external_exports.literal("head-moved"),headId:DeclarationVersionIdSchema,headVersion:external_exports.number().int().positive()});var columnMap=value2=>boundedRecord3(external_exports.string(),value2,DECLARATION_COLUMNS_MAX),sourceShape2=DeclarationSheetSchema.shape,[pathSource,unionSource,groupBySource,crossJoinSource]=DeclarationSheetSourceSchema.options,DeclarationSheetSourceInputSchema=described(external_exports.union([pathSource,external_exports.looseObject({union:described(external_exports.union([external_exports.array(external_exports.unknown()).max(DECLARATION_SHEETS_MAX),columnMap(external_exports.unknown())]),unionSource.shape.union)}),external_exports.looseObject({groupBy:described(columnMap(external_exports.unknown()),groupBySource.shape.groupBy)}),external_exports.looseObject({crossJoin:described(columnMap(external_exports.unknown()),crossJoinSource.shape.crossJoin)})]),DeclarationSheetSourceSchema),DeclarationSummaryRowInputSchema=described(DeclarationSummaryRowSchema.extend({aggregations:described(columnMap(DeclarationSummaryAggregationSchema),DeclarationSummaryRowSchema.shape.aggregations)}),DeclarationSummaryRowSchema),DeclarationSheetInputSchema=described(DeclarationSheetSchema.extend({columns:described(external_exports.array(external_exports.string().min(1)).min(1).max(DECLARATION_COLUMNS_MAX),sourceShape2.columns),rowGenerators:described(external_exports.array(external_exports.string().min(1)).max(DECLARATION_COLUMNS_MAX).nullable().optional(),sourceShape2.rowGenerators),rows:described(external_exports.array(columnMap(external_exports.unknown())).max(DECLARATION_ROWS_MAX).nullable().optional(),sourceShape2.rows),source:DeclarationSheetSourceInputSchema.nullable().optional(),columnFormulas:described(columnMap(external_exports.string()).nullable().optional(),sourceShape2.columnFormulas),columnTypeHints:described(columnMap(DeclarationColumnTypeHintSchema).nullable().optional(),sourceShape2.columnTypeHints),columnTimezones:described(columnMap(external_exports.string()).nullable().optional(),sourceShape2.columnTimezones),staticCells:described(columnMap(DeclarationStaticCellSchema).nullable().optional(),sourceShape2.staticCells),summaryRows:described(external_exports.array(DeclarationSummaryRowInputSchema).max(DECLARATION_SHEETS_MAX).nullable().optional(),sourceShape2.summaryRows),literalOverrides:described(columnMap(external_exports.array(DeclarationLiteralOverrideSchema).max(DECLARATION_ROWS_MAX)).nullable().optional(),sourceShape2.literalOverrides),tableNames:described(looseList(external_exports.string().min(1),DECLARATION_SHEETS_MAX).optional(),sourceShape2.tableNames)}),DeclarationSheetSchema),pivotShape=DeclarationPivotSheetSchema.shape,DeclarationPivotRowColFieldInputSchema=described(DeclarationPivotRowColFieldSchema.extend({items:described(looseList(external_exports.unknown(),DECLARATION_ROWS_MAX).optional(),DeclarationPivotRowColFieldSchema.shape.items)}),DeclarationPivotRowColFieldSchema),pivotFields=(field,original)=>described(external_exports.array(field).max(DECLARATION_COLUMNS_MAX).nullable().optional(),original),DeclarationPivotSheetInputSchema=described(DeclarationPivotSheetSchema.extend({dataFields:described(external_exports.array(pivotShape.dataFields.element).min(1).max(DECLARATION_COLUMNS_MAX),pivotShape.dataFields),rowFields:pivotFields(DeclarationPivotRowColFieldInputSchema,pivotShape.rowFields),colFields:pivotFields(DeclarationPivotRowColFieldInputSchema,pivotShape.colFields),pageFields:pivotFields(pivotShape.pageFields.unwrap().unwrap().element,pivotShape.pageFields),calculatedFields:pivotFields(pivotShape.calculatedFields.unwrap().unwrap().element,pivotShape.calculatedFields)}),DeclarationPivotSheetSchema),executionShape=DeclarationExecutionSchema.shape,DeclarationExecutionInputSchema=described(DeclarationExecutionSchema.extend({orderBy:described(external_exports.union([external_exports.string(),external_exports.array(external_exports.string()).min(1).max(DECLARATION_COLUMNS_MAX)]).nullable().optional(),executionShape.orderBy),pipeline:described(looseList(external_exports.string().min(1),DECLARATION_SHEETS_MAX).optional(),executionShape.pipeline)}),DeclarationExecutionSchema),DeclarationInputSchema=described(DeclarationSchema.extend({sheets:described(external_exports.array(DeclarationSheetInputSchema).min(1).max(DECLARATION_SHEETS_MAX),DeclarationSchema.shape.sheets),pivotSheets:described(external_exports.array(DeclarationPivotSheetInputSchema).max(DECLARATION_SHEETS_MAX).nullable().optional(),DeclarationSchema.shape.pivotSheets),execution:described(DeclarationExecutionInputSchema.nullable().optional(),DeclarationSchema.shape.execution)}),DeclarationSchema);var FLAGGED_ELEMENT=ElementIdSchema.parse("__flagged__");var ReviewDecisionKindSchema=external_exports.enum(["accept","override"]);var PeriodReviewDecisionSchema=external_exports.strictObject({id:external_exports.string().min(1),periodId:PeriodIdSchema,runId:external_exports.string().min(1),assetId:external_exports.string().min(1),decision:ReviewDecisionKindSchema,reason:external_exports.string().min(1),decidedBy:external_exports.string().min(1),decidedAt:external_exports.string().min(1)}),DecideReviewInputSchema=external_exports.strictObject({periodId:PeriodIdSchema,runId:external_exports.string().min(1),assetId:external_exports.string().min(1).max(200),decision:ReviewDecisionKindSchema,reason:external_exports.string().trim().min(3).max(500),idempotencyKey:CallerMintedKeySchema2}),GetReviewInputSchema=external_exports.strictObject({periodId:PeriodIdSchema}),PeriodReviewSchema=external_exports.strictObject({periodId:PeriodIdSchema,runId:external_exports.string().min(1).nullable(),flaggedAssetIds:external_exports.array(external_exports.string().min(1)),unreadableAssetIds:external_exports.array(external_exports.string().min(1)),openAssetIds:external_exports.array(external_exports.string().min(1)),decisions:external_exports.array(PeriodReviewDecisionSchema)}),OpenExceptionsSchema=external_exports.strictObject({periodId:PeriodIdSchema,runId:external_exports.string().min(1).nullable(),assetIds:external_exports.array(external_exports.string().min(1))});var ResultValueSchema=external_exports.discriminatedUnion("kind",[external_exports.object({kind:external_exports.literal("quantity"),value:external_exports.number(),unit:external_exports.string().min(1)}),external_exports.object({kind:external_exports.literal("count"),value:external_exports.number().int()}),external_exports.object({kind:external_exports.literal("category"),value:external_exports.string().min(1)}),external_exports.object({kind:external_exports.literal("boolean"),value:external_exports.boolean()}),external_exports.object({kind:external_exports.literal("dataRecord"),value:external_exports.record(external_exports.string(),external_exports.unknown())}),external_exports.object({kind:external_exports.literal("timeseries"),points:external_exports.array(external_exports.object({at:external_exports.iso.datetime(),value:external_exports.number()}))})]),ResultValueInputSchema=external_exports.discriminatedUnion("kind",[external_exports.object({kind:external_exports.literal("quantity"),value:external_exports.number(),unit:external_exports.string().min(1)}),external_exports.object({kind:external_exports.literal("count"),value:external_exports.number().int()}),external_exports.object({kind:external_exports.literal("category"),value:external_exports.string().min(1)}),external_exports.object({kind:external_exports.literal("boolean"),value:external_exports.boolean()}),external_exports.object({kind:external_exports.literal("dataRecord"),value:boundedRecord3(external_exports.string(),external_exports.unknown(),DECLARATION_COLUMNS_MAX)}),external_exports.object({kind:external_exports.literal("timeseries"),points:external_exports.array(external_exports.object({at:external_exports.iso.datetime(),value:external_exports.number()})).max(RESULT_TIMESERIES_POINTS_MAX)})]);var UnitMapSchema=external_exports.record(ElementIdSchema,external_exports.string().trim().min(1)),UnitMapInputSchema=boundedRecord3(ElementIdSchema,external_exports.string().trim().min(1),DECLARATION_COLUMNS_MAX);var DataSourceSchema=external_exports.object({name:external_exports.string().min(1),rows:external_exports.array(external_exports.record(external_exports.string(),external_exports.unknown()))}),ExecuteOptionsSchema=external_exports.strictObject({periodKey:external_exports.string().min(1),tableDriven:external_exports.strictObject({identityElement:external_exports.string().min(1),periodKey:external_exports.string().min(1),subjectGrain:external_exports.enum(["asset","row"])}).optional()}),EngineInputTypesSchema=external_exports.record(external_exports.string(),external_exports.string()),EngineInputRowCountsSchema=external_exports.record(external_exports.string(),external_exports.number().int().nonnegative()),EngineInputFactsSchema=external_exports.object({inputTypes:EngineInputTypesSchema,inputRowCounts:EngineInputRowCountsSchema});function refineEngineInputFactsPaired(result,ctx){let types=result.inputTypes!==void 0;types!==(result.inputRowCounts!==void 0)&&ctx.addIssue({code:"custom",path:[types?"inputRowCounts":"inputTypes"],message:"the engine reported inputTypes and inputRowCounts only together, or neither"})}var RUN_INPUT_SHAPE_VERSION=2,RunInputSnapshotSchema=external_exports.strictObject({shapeVersion:external_exports.literal(RUN_INPUT_SHAPE_VERSION),execute:ExecuteOptionsSchema,declaration:external_exports.unknown(),dataSources:external_exports.array(DataSourceSchema.strict()).readonly(),unitMap:UnitMapSchema,reads:external_exports.array(EntityRefSchema.strict()).readonly(),assetVersions:external_exports.record(external_exports.string(),external_exports.strictObject({assetVersionId:external_exports.string(),templateVersionId:external_exports.string()})).optional(),assetDatedValues:external_exports.record(external_exports.string(),external_exports.record(external_exports.string(),external_exports.array(external_exports.string()).min(1).readonly())).optional(),units:external_exports.record(external_exports.string(),external_exports.string()).optional(),tables:external_exports.record(external_exports.string(),external_exports.strictObject({rowCount:external_exports.number().int(),window:external_exports.string()})).optional()}),ENGINE_INPUT_MAX_BYTES=2.5*1024*1024,RUN_INPUT_STORE_MAX_BYTES=128*1024*1024,RUN_INPUT_CHUNK_MAX_BYTES=32*1024*1024,RUN_INPUT_TABLE_MAX_BYTES=640*1024*1024,DATA_TABLE_SUPPORTED_ROWS=2e6,DATA_TABLE_SUPPORTED_VALUES=28e6,GetRunEngineInputInputSchema=external_exports.strictObject({runId:RunIdSchema}),RunEngineInputSchema=RunInputSnapshotSchema.extend({runId:RunIdSchema,engineVersion:external_exports.string().min(1),declarationVersionId:external_exports.string().min(1),declaration:DeclarationSchema,periodSplit:external_exports.strictObject({parts:external_exports.int().min(2)}).optional()});var EVALUATE_ROW_CAP=500;var EVALUATE_MESSAGES={dataTableCalculation:"this calculation runs over rows of a data table, so its rows come from that table rather than from typed inputs \u2014 evaluate a per-asset calculation, or preview this one against its data",unknownOutputs:(unknown2,outputs)=>`not an output this calculation computes: ${unknown2.join(", ")} \u2014 it computes: ${outputs.join(", ")||"none"}`,missingInputs:(row,names)=>`row ${String(row)}: no value given for ${names.join(", ")}`,ignoredNames:names=>`ignored, not an input this calculation reads: ${names.join(", ")}`,reservedName:name2=>`${name2} is a name the engine reserves for itself \u2014 give this input another name`,caseCollision:(row,spellings)=>`row ${String(row)} gives an input more than once, in different cases: ${spellings.map(names=>names.join(" / ")).join(", ")} \u2014 names are read regardless of case, so give each input once`,noValue:(row,elements2)=>`row ${String(row)}: the engine returned no value for ${elements2.join(", ")}`,referenceSheets:sheets=>`${sheets.join(", ")}: evaluated from the rows written in this calculation, not from a period's data \u2014 a run reads its pinned data instead`,nonFiniteResult:row=>`row ${String(row)} can't be computed: a formula divides by zero, or otherwise gives a result that isn't a finite number`,unresolved:(row,reason)=>`row ${String(row)} was not answered: another row evaluated with it gives a result that isn't a finite number, and ${reason==="budget"?"finding that row ran out of time \u2014 evaluate fewer rows at once":"the request was cancelled before that row was found"}`},EVALUATE_RESERVED_INPUT_NAMES=["__assetId__","__period__",FLAGGED_ELEMENT],RESERVED_FOLDED=new Set(EVALUATE_RESERVED_INPUT_NAMES.map(name2=>name2.toLowerCase())),EvaluateRowValuesSchema=boundedRecord3(external_exports.string().min(1),external_exports.number().finite(),DECLARATION_COLUMNS_MAX).superRefine((values2,context)=>{for(let name2 of Object.keys(values2))RESERVED_FOLDED.has(name2.toLowerCase())&&context.addIssue({code:"custom",message:EVALUATE_MESSAGES.reservedName(name2),path:[name2]})}),DeclarationEvaluateInputSchema=external_exports.strictObject({declaration:DeclarationInputSchema,unitMap:UnitMapInputSchema,engineVersion:external_exports.string().min(1),rows:external_exports.array(EvaluateRowValuesSchema).min(1,"give at least one row of input values").max(EVALUATE_ROW_CAP,`at most ${String(EVALUATE_ROW_CAP)} rows can be evaluated at once`),elements:external_exports.array(ElementIdSchema).min(1).max(DECLARATION_COLUMNS_MAX).optional(),period:external_exports.string().regex(PERIOD_TOKEN,"a period is a year (2025) or a month (2025-03)").optional()}),EvaluatedRowSchema=external_exports.object({status:ExecStatusSchema,values:external_exports.record(external_exports.string(),ResultValueSchema),missingInputs:external_exports.array(external_exports.string()),warnings:external_exports.array(external_exports.string()),errors:external_exports.array(external_exports.string())}),DeclarationEvaluateReportSchema=external_exports.object({status:ExecStatusSchema,rows:external_exports.array(EvaluatedRowSchema),warnings:external_exports.array(external_exports.string()),errors:external_exports.array(external_exports.string())});var CitationSchema2=external_exports.object({title:external_exports.string().trim().min(1).max(512),url:external_exports.string().trim().min(1).max(512)}),CitationsSchema=external_exports.array(CitationSchema2).max(50),DescriptionSchema=external_exports.string().trim().min(1).max(2e3);var CalculatorSheetShape=external_exports.looseObject({name:external_exports.string(),role:external_exports.literal("calculator"),columns:external_exports.array(external_exports.string()).default([]),columnFormulas:external_exports.record(external_exports.string(),external_exports.string()).nullish(),rowGenerators:external_exports.array(external_exports.string()).nullish(),columnTypeHints:external_exports.record(external_exports.string(),external_exports.unknown()).nullish().catch(void 0)}),SheetsShape=external_exports.looseObject({sheets:external_exports.array(external_exports.unknown())});var TABLE_NAME=String.raw`(?<!\w)[A-Za-z_]\w*`,thisRow=column2=>String.raw`\[\[#This Row\],\[${column2}\]\]`,FORMULA_TABLE_REF=new RegExp(String.raw`(${TABLE_NAME})\[([^@[\]][^\]]*)\]`,"g"),STRUCTURED_REF=new RegExp([`(?<thisRowTable>${TABLE_NAME})?${thisRow(String.raw`(?<thisRowColumn>[^\]]+)`)}`,String.raw`(?<atTable>${TABLE_NAME})?(?<!\[)\[@(?:\[(?<atBracketed>[^\]]+)\]|(?<atColumn>[^[\]]+))\]`,String.raw`(?<refTable>${TABLE_NAME})\[(?<refColumn>(?:\[[^\]]*\](?:\s*[,:]\s*\[[^\]]*\])*)|[^@[\]][^\]]*)\]`].join("|"),"gi");var A1_REF=new RegExp([String.raw`(?<![\w.$!'{])`,String.raw`(?:(?<sheet>'(?:[^']|'')+'|\w[\w.]*)!)?`,String.raw`(?<startAbs>\$?)(?<startColumn>[A-Za-z]{1,3})(?:(?<startRowAbs>\$?)(?<startRow>\d+))?`,String.raw`(?::(?<endAbs>\$?)(?<endColumn>[A-Za-z]{1,3})(?:(?<endRowAbs>\$?)(?<endRow>\d+))?)?`,String.raw`(?![\w(!.{$'])(?!\s*\()`].join(""),"g");var NUMBER=String.raw`\d+(?:\.\d+)?(?:[eE][+-]?\d+)?`,REF=String.raw`\[@([^\]]+)\]`,DIVISION_RE=new RegExp(String.raw`^(?:(${NUMBER})\*)?${REF}(?:\*(${NUMBER}))?/${REF}(?:\*(${NUMBER}))?$`);var NUMBER_CONSTANT_RE=new RegExp(`^-?${NUMBER}$`);var ElementRollupSchema=external_exports.enum(["adds-up","ratio","per-asset-only"]),NotSummedSchema=external_exports.enum(["ratio","per-asset-only"]);var RATIO_UNIT_FORMS=[/%/u,/\bpercent\b|\bpct\b/iu,/\bpp[mb]/iu,/\/|\bper\b/iu,/^tp[yda]$/iu,new RegExp("\\p{L}\\s*\\^?\\s*[-\u2212]\\s*[1-9]\\b","u"),/⁻/u];var TotalCandidateSchema=external_exports.object({element:external_exports.string().min(1),label:external_exports.string().min(1)}),NoHeadlineReasonSchema=external_exports.discriminatedUnion("kind",[external_exports.object({kind:external_exports.literal("designated-unfiled"),element:external_exports.string().min(1),label:external_exports.string().min(1)}),external_exports.object({kind:external_exports.literal("no-total-chosen"),element:external_exports.string().min(1),label:external_exports.string().min(1),candidates:external_exports.array(TotalCandidateSchema).min(2)}),external_exports.object({kind:external_exports.literal("no-terminal-filed")}),external_exports.object({kind:external_exports.literal("no-terminal")}),external_exports.object({kind:external_exports.literal("graph-unavailable")})]),TotalPickSchema=external_exports.object({kind:external_exports.literal("picked-first"),element:external_exports.string().min(1),label:external_exports.string().min(1),candidates:external_exports.array(TotalCandidateSchema).min(2)});var WorkbookOracleProvenanceSchema=external_exports.discriminatedUnion("status",[external_exports.object({status:external_exports.literal("derived"),unitCount:external_exports.number().int().nonnegative(),elementCount:external_exports.number().int().nonnegative(),elements:external_exports.array(external_exports.string()),keyColumn:external_exports.string().min(1).optional().describe("The calculator column each saved row is matched to its recomputed row on (e.g. `AssetId`, or the row-generator column)."),notCompared:external_exports.array(external_exports.string()).optional().describe("Formula columns left out of the comparison because the file carries no saved number for them in any row; `elements` are the ones compared.")}),external_exports.object({status:external_exports.literal("unavailable"),reason:external_exports.enum(["no-computed-values","incomplete-cached-values","unusable-row-key","no-row-key","unreadable"]),message:external_exports.string()})]);var ImportSheetRoleSchema=external_exports.enum(["data","lookup","ignore"]),EXCEL_SHEET_NAME_MAX=31,ImportSheetRolesSchema=boundedRecord3(external_exports.string().min(1).max(EXCEL_SHEET_NAME_MAX),ImportSheetRoleSchema,IMPORT_SHEET_ROLES_MAX),ImportSheetSchema=external_exports.object({name:external_exports.string().min(1),kind:external_exports.enum(["calculator","table","pivot"]),defaultRole:external_exports.enum(["calculator","data","lookup","pivot"]),role:external_exports.enum(["calculator","data","lookup","pivot","ignore"]),rowCount:external_exports.number().int().nonnegative()}),ImportCalculatorKeyColumnSchema=external_exports.string().min(1).describe("The calculator column the rows are named by \u2014 present only when a per-asset project run fills it and a formula reads it. In such a run it holds each row\u2019s Studio asset ID, so a lookup keyed on it matches only rows keyed by asset id. Absent for a row-generated calculator, a first column that is not all text (an input), a key with its own formula, or when no formula reads it. A project binding that writes this column takes precedence at run time.");var MAX_WORKBOOK_UPLOAD_BYTES=10*1024*1024,MAX_WORKBOOK_BASE64_CHARS=Math.ceil(MAX_WORKBOOK_UPLOAD_BYTES/3)*4+8,ImportSourceSchema=external_exports.discriminatedUnion("kind",[external_exports.strictObject({kind:external_exports.literal("declaration"),declaration:DeclarationInputSchema}),external_exports.strictObject({kind:external_exports.literal("workbookBytes"),filename:external_exports.string().min(1).optional(),contentBase64:external_exports.string().min(1).max(MAX_WORKBOOK_BASE64_CHARS),sheetRoles:ImportSheetRolesSchema.optional().describe("Per-sheet roles, `sheet name \u2192 data | lookup | ignore`, for the sheets that should differ from their default (a `Data__` / `Lookup__` prefix, else lookup). `ignore` leaves a sheet out entirely \u2014 the way to import past a pivot summary the calculation does not need. Send the SAME value to importInspect and importCommit: the committed calculation is the one that was inspected. A name the workbook lacks, the calculator sheet, or data/lookup on a pivot is refused (CALC_SHEET_ROLE_INVALID).")})]),ImportMappingEntrySchema=external_exports.object({element:ElementIdSchema,sheets:external_exports.array(external_exports.string().min(1)),resolution:external_exports.enum(["binding","unresolved","fileSupplied"]),suggestedBinding:BindingSchema.optional()}),ImportMappingProposalSchema=external_exports.array(ImportMappingEntrySchema),WriteFidelityOracleSchema=external_exports.object({perUnit:external_exports.array(boundedRecord3(external_exports.string(),external_exports.union([external_exports.string(),external_exports.number()]),DECLARATION_COLUMNS_MAX)).max(ORACLE_UNITS_MAX),facilityTotals:boundedRecord3(external_exports.string(),external_exports.number(),DECLARATION_COLUMNS_MAX).optional()});var HELD_INPUT_KINDS=["blocked","published-not-used","waiting"],HeldInputKindSchema=external_exports.enum(HELD_INPUT_KINDS),HeldInputLoadSchema=external_exports.object({datasetId:external_exports.string().min(1),versionId:external_exports.string().min(1),loadNumber:external_exports.number().int().positive()}),HeldInputSchema=external_exports.object({code:external_exports.string().min(1),datasetId:external_exports.string().min(1),kind:HeldInputKindSchema,used:HeldInputLoadSchema.nullable(),delivery:HeldInputLoadSchema,reasons:external_exports.array(external_exports.object({reason:external_exports.string().min(1),rows:external_exports.number().int().nonnegative()})),rowsInPeriod:external_exports.number().int().nonnegative(),undated:external_exports.boolean(),floor:external_exports.boolean(),blockingLabel:external_exports.string().min(1)});var instant=external_exports.iso.datetime({offset:!0}),FigureSchema=external_exports.strictObject({value:external_exports.number(),unit:external_exports.string().min(1).nullable()}),ReapprovalChangeUnavailableReasonSchema=external_exports.enum(["months-pending","no-months-total","no-filed-figure","unit-changed"]),ReapprovalChangeSchema=external_exports.discriminatedUnion("kind",[external_exports.strictObject({kind:external_exports.literal("stated"),filedTotal:FigureSchema,total:FigureSchema,delta:external_exports.number()}),external_exports.strictObject({kind:external_exports.literal("unavailable"),reason:ReapprovalChangeUnavailableReasonSchema})]),ReapprovalChildChangeSchema=external_exports.enum(["re-signed","added","removed"]),ReapprovalChildSchema=external_exports.strictObject({periodId:PeriodIdSchema,periodKey:external_exports.string().min(1),change:ReapprovalChildChangeSchema,version:external_exports.number().int().positive().nullable(),filedVersion:external_exports.number().int().positive().nullable()}).superRefine((child,ctx)=>{let fault=child.change==="re-signed"?child.version===null||child.filedVersion===null?"a re-signed child names the version now and the version vN stood over":void 0:child.change==="added"?child.filedVersion===null?void 0:"an added child was not stood over by vN":child.version===null?void 0:"a removed child has no standing version in the year";fault!==void 0&&ctx.addIssue({code:"custom",path:["change"],message:fault})}),common={filed:external_exports.strictObject({version:external_exports.number().int().positive(),closedAt:instant}),change:ReapprovalChangeSchema,changedChildren:external_exports.array(ReapprovalChildSchema),sentAt:instant.nullable()},ReapprovalSchema=external_exports.discriminatedUnion("state",[external_exports.strictObject({state:external_exports.literal("held"),...common}),external_exports.strictObject({state:external_exports.literal("ready"),since:instant,...common})]),ReapprovalReadInputSchema=external_exports.strictObject({periodId:PeriodIdSchema}),ReapprovalReadSchema=external_exports.strictObject({periodId:PeriodIdSchema,periodKey:external_exports.string().min(1),children:external_exports.array(external_exports.strictObject({periodKey:external_exports.string().min(1)})),reapproval:ReapprovalSchema.nullable()});var ToleranceSchema=external_exports.object({relative:external_exports.number().nonnegative(),absolute:external_exports.number().nonnegative()}),RoundingModeSchema=external_exports.enum(["none","regulatory"]),TolerancePolicySchema=external_exports.object({default:ToleranceSchema,perColumn:external_exports.record(external_exports.string(),ToleranceSchema).optional(),roundingMode:RoundingModeSchema.optional()}),TolerancePolicyInputSchema=TolerancePolicySchema.extend({perColumn:boundedRecord3(external_exports.string(),ToleranceSchema,DECLARATION_COLUMNS_MAX).optional()});var OverlapSourceSchema=external_exports.strictObject({projectId:ProjectIdSchema,projectName:external_exports.string().min(1),periodId:PeriodIdSchema,periodKey:external_exports.string().min(1)});function overlapSourcesCohere(sources){if(new Set(sources.map(source=>`${source.projectId}
|
|
449
449
|
${source.periodId}`)).size!==sources.length)return"a source project and period is named more than once";if(new Set(sources.map(source=>source.projectId)).size<2)return"an overlap names at least two different projects"}var IncomparableDifferenceSchema=external_exports.enum(["no-annual-run","no-primary-output","primary-output","unit","not-numeric","doubly-reached","missing-figure","behaviour"]),SideSchema=external_exports.strictObject({element:external_exports.string().min(1).nullable(),unit:external_exports.string().min(1).nullable()}),ReachedViaSchema=external_exports.strictObject({periodId:PeriodIdSchema,periodKey:external_exports.string().min(1)}),DoublyReachedSchema=external_exports.strictObject({periodId:PeriodIdSchema,periodKey:external_exports.string().min(1),paths:external_exports.array(external_exports.array(ReachedViaSchema)).min(2)}),MissingFigureSchema=external_exports.strictObject({periodId:PeriodIdSchema,periodKey:external_exports.string().min(1),projectId:ProjectIdSchema,projectName:external_exports.string().min(1)}),BehaviourPeriodSchema=external_exports.strictObject({periodId:PeriodIdSchema,periodKey:external_exports.string().min(1),projectId:ProjectIdSchema,projectName:external_exports.string().min(1),rollup:ElementRollupSchema}),BehaviourDifferenceSchema=external_exports.strictObject({annual:ElementRollupSchema,periods:external_exports.array(BehaviourPeriodSchema).min(1)}),IncomparableSchema=external_exports.strictObject({code:external_exports.string().min(1),message:external_exports.string().min(1),months:SideSchema,annual:SideSchema,differs:external_exports.array(IncomparableDifferenceSchema).min(1),doublyReached:external_exports.array(DoublyReachedSchema).min(1).optional(),missingFigures:external_exports.array(MissingFigureSchema).min(1).optional(),behaviours:BehaviourDifferenceSchema.optional()});function impliedDifferences(incomparable,annualRunPresent){let implied=new Set,{months,annual}=incomparable;return annualRunPresent?(months.element===null||annual.element===null)&&implied.add("no-primary-output"):implied.add("no-annual-run"),months.element!==null&&annual.element!==null&&(months.element!==annual.element&&implied.add("primary-output"),months.unit!==annual.unit&&implied.add("unit")),incomparable.doublyReached!==void 0&&implied.add("doubly-reached"),incomparable.missingFigures!==void 0&&implied.add("missing-figure"),incomparable.behaviours!==void 0&&implied.add("behaviour"),implied}var pathKey=path3=>path3.map(step=>step.periodId).join(`
|
|
450
450
|
`);function doublyReachedCoheres(reached){return new Set(reached.map(period=>period.periodId)).size!==reached.length?"a doubly reached period is named more than once":reached.some(period=>new Set(period.paths.map(pathKey)).size!==period.paths.length)?"a path to a doubly reached period is named more than once":void 0}function incomparableCoheres(incomparable,review){let{differs,annual,months}=incomparable;if(new Set(differs).size!==differs.length)return"a difference is named more than once";if(!review.annualRunPresent&&(annual.element!==null||annual.unit!==null))return"with no annual run the annual side is empty";if(review.annualRunPresent&&annual.element!==review.elementId)return"the annual side's element is the review's element";let implied=impliedDifferences(incomparable,review.annualRunPresent),stated=new Set(differs.filter(difference=>difference!=="not-numeric"));if(!(stated.size===implied.size&&[...implied].every(d=>stated.has(d))))return"differs is not what the two sides imply";if(differs.includes("not-numeric")&&(months.element===null||annual.element===null))return"not-numeric needs an element on both sides";let missing=missingFiguresCohere(incomparable.missingFigures,annual.element);if(missing!==void 0)return missing;let behaviours=behavioursCohere(incomparable.behaviours,annual.element);return behaviours!==void 0?behaviours:incomparable.doublyReached===void 0?void 0:doublyReachedCoheres(incomparable.doublyReached)}function missingFiguresCohere(missing,annualElement){if(missing!==void 0)return annualElement===null?"a missing figure needs an annual element to be missing for":new Set(missing.map(period=>period.periodId)).size===missing.length?void 0:"a period with no figure is named more than once"}function behavioursCohere(behaviours,annualElement){if(behaviours===void 0)return;if(annualElement===null)return"a behaviour difference needs an annual element";let{annual,periods}=behaviours;return new Set(periods.map(period=>period.periodId)).size!==periods.length?"a period whose behaviour differs is named more than once":periods.some(period=>period.rollup==="adds-up"==(annual==="adds-up"))?"a period named for its behaviour agrees with the annual run":void 0}var VarianceDigestSchema=external_exports.string().regex(/^[0-9a-f]{64}$/,"a variance digest is a lowercase hex sha256");function varianceSubjectKey(subject){switch(subject.kind){case"asset":return`asset:${encodableKey(subject.assetId)}`;case"group":return`group:${encodableKey(subject.groupKey)}`;case"runScope":return"runScope";default:return subject}}function encodableKey(key){if(key.includes(`
|