@maind-dev/cli 0.73.0 → 0.73.1

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/build/index.js CHANGED
@@ -20,7 +20,7 @@ var Fa=Object.defineProperty;var s=(e,t)=>Fa(e,"name",{value:t,configurable:!0})
20
20
  `);let a=e.defaultBranch!=null?`${e.ahead??"?"} ahead, ${e.behind??"?"} behind \`${e.defaultBranch}\``:"no upstream default branch resolved";if(o.push(`**Branch:** \`${e.branch??"?"}\` \u2014 ${a}`),o.push(`**Working tree:** ${e.uncommitted} uncommitted change${e.uncommitted===1?"":"s"}`),e.projectKey&&o.push(`**Project:** \`${e.projectKey.slice(0,12)}\u2026\` (sha256 of remote \u2014 URL never sent)`),o.push(""),t.available)if(t.prs.length===0)o.push("**Open PRs:** none");else{o.push("**Open PRs:**");for(let c of t.prs){let l=c.isCurrentBranch?` ${ly(c.ci)} CI:${c.ci} \xB7 this branch`:"";o.push(`- #${c.number} ${c.title}${l}`)}}else o.push("**Open PRs:** _unavailable (`gh` not installed / not authenticated)_");if(o.push(""),n?.checked)if(n.conflicts.length>0){o.push(`**\u26A0 Parallel sessions on this repo:** ${n.peersActive} active \u2014 path conflicts:`);for(let c of n.conflicts)o.push(`- \`${c.path}\`${c.focus?` \u2014 peer focus: ${c.focus}`:""}`);n.recommendation&&o.push(`- _${n.recommendation}_`)}else n.peersActive>0?o.push(`**Parallel sessions on this repo:** ${n.peersActive} active \u2014 no conflict on your changed paths.`):o.push("**Parallel sessions on this repo:** none.");else o.push("**Parallel sessions:** _not checked (no key / no changed paths / offline)._");if(o.push(""),i&&r.length>0){o.push("## Relevant git lessons (maind)");for(let c of r)o.push(`- **${c.title??c.id}**${c.id?` \`${c.id}\``:""}`);o.push("")}return o.push('_Full PR workflow: `activate_skill({id:"skill_pr_lifecycle"})`._'),o.push(""),o.join(`
21
21
  `)}s(uy,"renderMarkdown");function dy(e,t,n){return{schema:"maind.git-context/v1",generated_at:cc(),project_key:e.projectKey,branch:e.branch,default_branch:e.defaultBranch,ahead:e.ahead,behind:e.behind,uncommitted:e.uncommitted,open_prs:t.map(r=>({number:r.number,ci:r.ci,current_branch:r.isCurrentBranch})),peers_active:n?.checked?n.peersActive:null,path_conflicts:n?.conflicts.map(r=>r.path)??[]}}s(dy,"buildManifest");function Gi(e){return e instanceof Error?e.message:String(e)}s(Gi,"msg");function Vi(e){process.stderr.write(`maind git-context: ${e}
22
22
  `)}s(Vi,"warn");import{execFileSync as lv,spawnSync as uv}from"node:child_process";import{existsSync as dv,mkdtempSync as fv,rmSync as pv,writeFileSync as mv}from"node:fs";import{tmpdir as hv}from"node:os";import{dirname as gv,join as df}from"node:path";import{fileURLToPath as yv}from"node:url";import{mkdirSync as ov}from"node:fs";import{posix as Br}from"node:path";import{join as xy}from"node:path";import zi from"web-tree-sitter";function tr(e){return`${e}#<module>`}s(tr,"moduleKey");function nr(e,t,n){return`${e}#${t}:${n}`}s(nr,"symbolKey");function rr(e){let t=e.toLowerCase();return t.endsWith(".tsx")?"tsx":t.endsWith(".ts")||t.endsWith(".mts")||t.endsWith(".cts")?"typescript":t.endsWith(".js")||t.endsWith(".jsx")||t.endsWith(".mjs")||t.endsWith(".cjs")?"javascript":t.endsWith(".py")||t.endsWith(".pyi")?"python":null}s(rr,"languageForPath");function Wi(e){return e.toLowerCase().endsWith(".d.ts")}s(Wi,"isSkippablePath");function ir(){return{nodes:[],edges:[],refs:[],imports:[]}}s(ir,"newResult");function Xe(e){return e+1}s(Xe,"line1");function or(e){return(e.text.split(`
23
- `,1)[0]??"").trim().slice(0,200)}s(or,"signatureOf");function fy(e){if(!e)return null;switch(e.type){case"identifier":case"property_identifier":case"type_identifier":return e.text;case"member_expression":return e.childForFieldName("property")?.text??null;case"attribute":return e.childForFieldName("attribute")?.text??null;default:return null}}s(fy,"calleeName");function py(e,t){let n=new Set;for(let r of e.descendantsOfType(t)){let i=fy(r.childForFieldName("function"));i&&n.add(i)}return[...n]}s(py,"collectCallTargets");function Mt(e,t,n,r){for(let i of py(n,r))e.refs.push({fromKey:t,kind:"calls",targetName:i})}s(Mt,"addCallRefs");var uc="call";function dc(e,t){let n=ir();for(let r of e.namedChildren)my(r,t,n);return n}s(dc,"extractPython");function fc(e){return e.type==="decorated_definition"?e.childForFieldName("definition")??e:e}s(fc,"unwrapDecorated");function my(e,t,n){let r=fc(e);switch(r.type){case"import_statement":case"import_from_statement":{let o=(r.childForFieldName("module_name")??r.childForFieldName("name"))?.text??gy(r);o&&n.imports.push({fromModuleKey:t.moduleKey,specifier:o});return}case"function_definition":{let i=r.childForFieldName("name")?.text;if(!i)return;let o=sr(r,t,i,i,"function");n.nodes.push(o),n.edges.push({srcKey:t.moduleKey,dstKey:o.nodeKey,kind:"contains"});let a=r.childForFieldName("body");a&&Mt(n,o.nodeKey,a,uc);return}case"class_definition":hy(r,t,n);return;case"expression_statement":{let o=r.namedChildren.find(a=>a.type==="assignment")?.childForFieldName("left");if(o&&o.type==="identifier"){let a=sr(r,t,o.text,o.text,"variable");n.nodes.push(a),n.edges.push({srcKey:t.moduleKey,dstKey:a.nodeKey,kind:"contains"})}return}default:return}}s(my,"handleTopLevel");function hy(e,t,n){let r=e.childForFieldName("name")?.text;if(!r)return;let i=sr(e,t,r,r,"class");n.nodes.push(i),n.edges.push({srcKey:t.moduleKey,dstKey:i.nodeKey,kind:"contains"});let o=e.childForFieldName("superclasses");if(o){for(let c of o.namedChildren)if(c.type==="identifier")n.refs.push({fromKey:i.nodeKey,kind:"extends",targetName:c.text});else if(c.type==="attribute"){let l=c.childForFieldName("attribute")?.text;l&&n.refs.push({fromKey:i.nodeKey,kind:"extends",targetName:l})}}let a=e.childForFieldName("body");if(a)for(let c of a.namedChildren){let l=fc(c);if(l.type!=="function_definition")continue;let u=l.childForFieldName("name")?.text;if(!u)continue;let d=`${r}.${u}`,f=sr(l,t,u,d,"method");n.nodes.push(f),n.edges.push({srcKey:i.nodeKey,dstKey:f.nodeKey,kind:"contains"});let h=l.childForFieldName("body");h&&Mt(n,f.nodeKey,h,uc)}}s(hy,"addClass");function sr(e,t,n,r,i){return{nodeKey:nr(t.filePath,r,i),kind:i,name:n,qualifiedName:r,filePath:t.filePath,language:t.language,startLine:Xe(e.startPosition.row),endLine:Xe(e.endPosition.row),startByte:e.startIndex,endByte:e.endIndex,signature:or(e),doc:null}}s(sr,"makeNode");function gy(e){return e.descendantsOfType("dotted_name")[0]?.text??null}s(gy,"firstDottedName");var mc="call_expression";function hc(e,t){let n=ir();for(let r of e.namedChildren)by(r,t,n);return n}s(hc,"extractTypescript");function yy(e){return e.type==="export_statement"?e.childForFieldName("declaration")??e:e}s(yy,"unwrapExport");function by(e,t,n){let r=yy(e);switch(r.type){case"import_statement":{let i=r.childForFieldName("source")?.text;i&&n.imports.push({fromModuleKey:t.moduleKey,specifier:wy(i)});return}case"function_declaration":case"generator_function_declaration":{pc(r,t,n,"function");return}case"class_declaration":case"abstract_class_declaration":{_y(r,t,n);return}case"interface_declaration":qi(r,t,n,"interface");return;case"type_alias_declaration":qi(r,t,n,"type_alias");return;case"enum_declaration":qi(r,t,n,"enum");return;case"lexical_declaration":case"variable_declaration":{for(let i of r.namedChildren){if(i.type!=="variable_declarator")continue;let o=i.childForFieldName("name");if(!o||o.type!=="identifier")continue;let a=i.childForFieldName("value"),c=a?.type==="arrow_function"||a?.type==="function_expression"||a?.type==="function";pc(i,t,n,c?"function":"variable",o,a)}return}default:return}}s(by,"handleTopLevel");function pc(e,t,n,r,i,o){let c=(i??e.childForFieldName("name"))?.text;if(!c)return;let l=ar(e,t,c,c,r);n.nodes.push(l),n.edges.push({srcKey:t.moduleKey,dstKey:l.nodeKey,kind:"contains"});let u=o??e.childForFieldName("body")??e;r==="function"&&u&&Mt(n,l.nodeKey,u,mc)}s(pc,"addFunctionLike");function qi(e,t,n,r){let i=e.childForFieldName("name")?.text;if(!i)return;let o=ar(e,t,i,i,r);n.nodes.push(o),n.edges.push({srcKey:t.moduleKey,dstKey:o.nodeKey,kind:"contains"})}s(qi,"addSimpleNamed");function _y(e,t,n){let r=e.childForFieldName("name")?.text;if(!r)return;let i=ar(e,t,r,r,"class");n.nodes.push(i),n.edges.push({srcKey:t.moduleKey,dstKey:i.nodeKey,kind:"contains"});for(let a of e.descendantsOfType("class_heritage"))for(let c of a.namedChildren){let l=c.type==="implements_clause"?"implements":"extends";for(let u of c.descendantsOfType("type_identifier"))n.refs.push({fromKey:i.nodeKey,kind:l,targetName:u.text});for(let u of c.descendantsOfType("identifier"))n.refs.push({fromKey:i.nodeKey,kind:l,targetName:u.text})}let o=e.childForFieldName("body");if(o)for(let a of o.namedChildren){if(a.type!=="method_definition")continue;let c=a.childForFieldName("name")?.text;if(!c)continue;let l=`${r}.${c}`,u=ar(a,t,c,l,"method");n.nodes.push(u),n.edges.push({srcKey:i.nodeKey,dstKey:u.nodeKey,kind:"contains"});let d=a.childForFieldName("body");d&&Mt(n,u.nodeKey,d,mc)}}s(_y,"addClass");function ar(e,t,n,r,i){return{nodeKey:nr(t.filePath,r,i),kind:i,name:n,qualifiedName:r,filePath:t.filePath,language:t.language,startLine:Xe(e.startPosition.row),endLine:Xe(e.endPosition.row),startByte:e.startIndex,endByte:e.endIndex,signature:or(e),doc:null}}s(ar,"makeNode");function wy(e){return e.replace(/^["'`]|["'`]$/g,"")}s(wy,"stripQuotes");import{createRequire as ky}from"node:module";import{join as vy}from"node:path";var gc={typescript:"tree-sitter-typescript.wasm",tsx:"tree-sitter-tsx.wasm",javascript:"tree-sitter-javascript.wasm",python:"tree-sitter-python.wasm"},yc="tree-sitter.wasm";function bc(e,t){return t?vy(t,gc[e]):ky(import.meta.url).resolve(`tree-sitter-wasms/out/${gc[e]}`)}s(bc,"grammarPath");var Sy=["typescript","tsx","javascript","python"],cr=class{static{s(this,"TreeSitterParser")}initialized=!1;parser=null;grammars=new Map;assetDir;constructor(t={}){this.assetDir=t.assetDir}async init(){this.initialized||(await zi.init(this.assetDir?{locateFile:s(t=>xy(this.assetDir,t||yc),"locateFile")}:void 0),this.parser=new zi,this.initialized=!0)}supports(t){return Sy.includes(t)}async parse(t,n,r){await this.init();let i=this.parser;i.setLanguage(await this.grammar(r));let o=i.parse(n);if(!o)return{filePath:t,language:r,nodes:[],edges:[],refs:[],imports:[]};let a=o.rootNode,c=tr(t),l={nodeKey:c,kind:"module",name:t.split("/").pop()??t,qualifiedName:"<module>",filePath:t,language:r,startLine:1,endLine:Xe(a.endPosition.row),startByte:0,endByte:n.length,signature:null,doc:null},u={filePath:t,language:r,source:n,moduleKey:c},d=r==="python"?dc(a,u):hc(a,u);return o.delete(),{filePath:t,language:r,nodes:[l,...d.nodes],edges:d.edges,refs:d.refs,imports:d.imports}}async grammar(t){let n=this.grammars.get(t);return n||(n=await zi.Language.load(bc(t,this.assetDir)),this.grammars.set(t,n)),n}};import{readFileSync as zd}from"node:fs";import{posix as Yd}from"node:path";var p={};$g(p,{BRAND:()=>Xy,DIRTY:()=>pt,EMPTY_PATH:()=>$y,INVALID:()=>P,NEVER:()=>Nb,OK:()=>ce,ParseStatus:()=>ae,Schema:()=>K,ZodAny:()=>Qe,ZodArray:()=>Be,ZodBigInt:()=>ht,ZodBoolean:()=>gt,ZodBranded:()=>mn,ZodCatch:()=>At,ZodDate:()=>yt,ZodDefault:()=>Et,ZodDiscriminatedUnion:()=>dr,ZodEffects:()=>ke,ZodEnum:()=>St,ZodError:()=>de,ZodFirstPartyTypeKind:()=>M,ZodFunction:()=>pr,ZodIntersection:()=>kt,ZodIssueCode:()=>v,ZodLazy:()=>vt,ZodLiteral:()=>xt,ZodMap:()=>Ht,ZodNaN:()=>Vt,ZodNativeEnum:()=>Rt,ZodNever:()=>Re,ZodNull:()=>_t,ZodNullable:()=>Oe,ZodNumber:()=>mt,ZodObject:()=>fe,ZodOptional:()=>_e,ZodParsedType:()=>$,ZodPipeline:()=>hn,ZodPromise:()=>et,ZodReadonly:()=>$t,ZodRecord:()=>fr,ZodSchema:()=>K,ZodSet:()=>Gt,ZodString:()=>Je,ZodSymbol:()=>Bt,ZodTransformer:()=>ke,ZodTuple:()=>Ce,ZodType:()=>K,ZodUndefined:()=>bt,ZodUnion:()=>wt,ZodUnknown:()=>Ue,ZodVoid:()=>Kt,addIssueToContext:()=>A,any:()=>ob,array:()=>lb,bigint:()=>eb,boolean:()=>Tc,coerce:()=>Db,custom:()=>Ec,date:()=>tb,datetimeRegex:()=>Sc,defaultErrorMap:()=>Le,discriminatedUnion:()=>pb,effect:()=>Rb,enum:()=>vb,function:()=>_b,getErrorMap:()=>Lt,getParsedType:()=>Te,instanceof:()=>Jy,intersection:()=>mb,isAborted:()=>lr,isAsync:()=>Ft,isDirty:()=>ur,isValid:()=>Ze,late:()=>Zy,lazy:()=>wb,literal:()=>kb,makeIssue:()=>pn,map:()=>yb,nan:()=>Qy,nativeEnum:()=>xb,never:()=>ab,null:()=>ib,nullable:()=>Ab,number:()=>$c,object:()=>ub,objectUtil:()=>Yi,oboolean:()=>Ib,onumber:()=>Ob,optional:()=>Eb,ostring:()=>Cb,pipeline:()=>Tb,preprocess:()=>$b,promise:()=>Sb,quotelessJson:()=>Ry,record:()=>gb,set:()=>bb,setErrorMap:()=>Ay,strictObject:()=>db,string:()=>Ac,symbol:()=>nb,transformer:()=>Rb,tuple:()=>hb,undefined:()=>rb,union:()=>fb,unknown:()=>sb,util:()=>G,void:()=>cb});var G;(function(e){e.assertEqual=i=>{};function t(i){}s(t,"assertIs"),e.assertIs=t;function n(i){throw new Error}s(n,"assertNever"),e.assertNever=n,e.arrayToEnum=i=>{let o={};for(let a of i)o[a]=a;return o},e.getValidEnumValues=i=>{let o=e.objectKeys(i).filter(c=>typeof i[i[c]]!="number"),a={};for(let c of o)a[c]=i[c];return e.objectValues(a)},e.objectValues=i=>e.objectKeys(i).map(function(o){return i[o]}),e.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let o=[];for(let a in i)Object.prototype.hasOwnProperty.call(i,a)&&o.push(a);return o},e.find=(i,o)=>{for(let a of i)if(o(a))return a},e.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function r(i,o=" | "){return i.map(a=>typeof a=="string"?`'${a}'`:a).join(o)}s(r,"joinValues"),e.joinValues=r,e.jsonStringifyReplacer=(i,o)=>typeof o=="bigint"?o.toString():o})(G||(G={}));var Yi;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(Yi||(Yi={}));var $=G.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Te=s(e=>{switch(typeof e){case"undefined":return $.undefined;case"string":return $.string;case"number":return Number.isNaN(e)?$.nan:$.number;case"boolean":return $.boolean;case"function":return $.function;case"bigint":return $.bigint;case"symbol":return $.symbol;case"object":return Array.isArray(e)?$.array:e===null?$.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?$.promise:typeof Map<"u"&&e instanceof Map?$.map:typeof Set<"u"&&e instanceof Set?$.set:typeof Date<"u"&&e instanceof Date?$.date:$.object;default:return $.unknown}},"getParsedType");var v=G.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),Ry=s(e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),"quotelessJson"),de=class e extends Error{static{s(this,"ZodError")}get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}format(t){let n=t||function(o){return o.message},r={_errors:[]},i=s(o=>{for(let a of o.issues)if(a.code==="invalid_union")a.unionErrors.map(i);else if(a.code==="invalid_return_type")i(a.returnTypeError);else if(a.code==="invalid_arguments")i(a.argumentsError);else if(a.path.length===0)r._errors.push(n(a));else{let c=r,l=0;for(;l<a.path.length;){let u=a.path[l];l===a.path.length-1?(c[u]=c[u]||{_errors:[]},c[u]._errors.push(n(a))):c[u]=c[u]||{_errors:[]},c=c[u],l++}}},"processError");return i(this),r}static assert(t){if(!(t instanceof e))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,G.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=n=>n.message){let n={},r=[];for(let i of this.issues)if(i.path.length>0){let o=i.path[0];n[o]=n[o]||[],n[o].push(t(i))}else r.push(t(i));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};de.create=e=>new de(e);var Ey=s((e,t)=>{let n;switch(e.code){case v.invalid_type:e.received===$.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case v.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,G.jsonStringifyReplacer)}`;break;case v.unrecognized_keys:n=`Unrecognized key(s) in object: ${G.joinValues(e.keys,", ")}`;break;case v.invalid_union:n="Invalid input";break;case v.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${G.joinValues(e.options)}`;break;case v.invalid_enum_value:n=`Invalid enum value. Expected ${G.joinValues(e.options)}, received '${e.received}'`;break;case v.invalid_arguments:n="Invalid function arguments";break;case v.invalid_return_type:n="Invalid function return type";break;case v.invalid_date:n="Invalid date";break;case v.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:G.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case v.too_small:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:n="Invalid input";break;case v.too_big:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?n=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:n="Invalid input";break;case v.custom:n="Invalid input";break;case v.invalid_intersection_types:n="Intersection results could not be merged";break;case v.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case v.not_finite:n="Number must be finite";break;default:n=t.defaultError,G.assertNever(e)}return{message:n}},"errorMap"),Le=Ey;var _c=Le;function Ay(e){_c=e}s(Ay,"setErrorMap");function Lt(){return _c}s(Lt,"getErrorMap");var pn=s(e=>{let{data:t,path:n,errorMaps:r,issueData:i}=e,o=[...n,...i.path||[]],a={...i,path:o};if(i.message!==void 0)return{...i,path:o,message:i.message};let c="",l=r.filter(u=>!!u).slice().reverse();for(let u of l)c=u(a,{data:t,defaultError:c}).message;return{...i,path:o,message:c}},"makeIssue"),$y=[];function A(e,t){let n=Lt(),r=pn({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===Le?void 0:Le].filter(i=>!!i)});e.common.issues.push(r)}s(A,"addIssueToContext");var ae=class e{static{s(this,"ParseStatus")}constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){let r=[];for(let i of n){if(i.status==="aborted")return P;i.status==="dirty"&&t.dirty(),r.push(i.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){let r=[];for(let i of n){let o=await i.key,a=await i.value;r.push({key:o,value:a})}return e.mergeObjectSync(t,r)}static mergeObjectSync(t,n){let r={};for(let i of n){let{key:o,value:a}=i;if(o.status==="aborted"||a.status==="aborted")return P;o.status==="dirty"&&t.dirty(),a.status==="dirty"&&t.dirty(),o.value!=="__proto__"&&(typeof a.value<"u"||i.alwaysSet)&&(r[o.value]=a.value)}return{status:t.value,value:r}}},P=Object.freeze({status:"aborted"}),pt=s(e=>({status:"dirty",value:e}),"DIRTY"),ce=s(e=>({status:"valid",value:e}),"OK"),lr=s(e=>e.status==="aborted","isAborted"),ur=s(e=>e.status==="dirty","isDirty"),Ze=s(e=>e.status==="valid","isValid"),Ft=s(e=>typeof Promise<"u"&&e instanceof Promise,"isAsync");var D;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(D||(D={}));var we=class{static{s(this,"ParseInputLazyPath")}constructor(t,n,r,i){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=i}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},wc=s((e,t)=>{if(Ze(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let n=new de(e.common.issues);return this._error=n,this._error}}},"handleResult");function U(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:i}=e;if(t&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:i}:{errorMap:s((a,c)=>{let{message:l}=e;return a.code==="invalid_enum_value"?{message:l??c.defaultError}:typeof c.data>"u"?{message:l??r??c.defaultError}:a.code!=="invalid_type"?{message:c.defaultError}:{message:l??n??c.defaultError}},"customMap"),description:i}}s(U,"processCreateParams");var K=class{static{s(this,"ZodType")}get description(){return this._def.description}_getType(t){return Te(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:Te(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new ae,ctx:{common:t.parent.common,data:t.data,parsedType:Te(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let n=this._parse(t);if(Ft(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(t){let n=this._parse(t);return Promise.resolve(n)}parse(t,n){let r=this.safeParse(t,n);if(r.success)return r.data;throw r.error}safeParse(t,n){let r={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Te(t)},i=this._parseSync({data:t,path:r.path,parent:r});return wc(r,i)}"~validate"(t){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Te(t)};if(!this["~standard"].async)try{let r=this._parseSync({data:t,path:[],parent:n});return Ze(r)?{value:r.value}:{issues:n.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:n}).then(r=>Ze(r)?{value:r.value}:{issues:n.common.issues})}async parseAsync(t,n){let r=await this.safeParseAsync(t,n);if(r.success)return r.data;throw r.error}async safeParseAsync(t,n){let r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Te(t)},i=this._parse({data:t,path:r.path,parent:r}),o=await(Ft(i)?i:Promise.resolve(i));return wc(r,o)}refine(t,n){let r=s(i=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(i):n,"getIssueProperties");return this._refinement((i,o)=>{let a=t(i),c=s(()=>o.addIssue({code:v.custom,...r(i)}),"setError");return typeof Promise<"u"&&a instanceof Promise?a.then(l=>l?!0:(c(),!1)):a?!0:(c(),!1)})}refinement(t,n){return this._refinement((r,i)=>t(r)?!0:(i.addIssue(typeof n=="function"?n(r,i):n),!1))}_refinement(t){return new ke({schema:this,typeName:M.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:s(n=>this["~validate"](n),"validate")}}optional(){return _e.create(this,this._def)}nullable(){return Oe.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Be.create(this)}promise(){return et.create(this,this._def)}or(t){return wt.create([this,t],this._def)}and(t){return kt.create(this,t,this._def)}transform(t){return new ke({...U(this._def),schema:this,typeName:M.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let n=typeof t=="function"?t:()=>t;return new Et({...U(this._def),innerType:this,defaultValue:n,typeName:M.ZodDefault})}brand(){return new mn({typeName:M.ZodBranded,type:this,...U(this._def)})}catch(t){let n=typeof t=="function"?t:()=>t;return new At({...U(this._def),innerType:this,catchValue:n,typeName:M.ZodCatch})}describe(t){let n=this.constructor;return new n({...this._def,description:t})}pipe(t){return hn.create(this,t)}readonly(){return $t.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Ty=/^c[^\s-]{8,}$/i,Cy=/^[0-9a-z]+$/,Oy=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Iy=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Dy=/^[a-z0-9_-]{21}$/i,Ny=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,jy=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Py=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,My="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Xi,Ly=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Fy=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Uy=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,By=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Ky=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Hy=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,vc="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Gy=new RegExp(`^${vc}$`);function xc(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`);let n=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}s(xc,"timeRegexSource");function Vy(e){return new RegExp(`^${xc(e)}$`)}s(Vy,"timeRegex");function Sc(e){let t=`${vc}T${xc(e)}`,n=[];return n.push(e.local?"Z?":"Z"),e.offset&&n.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${n.join("|")})`,new RegExp(`^${t}$`)}s(Sc,"datetimeRegex");function Wy(e,t){return!!((t==="v4"||!t)&&Ly.test(e)||(t==="v6"||!t)&&Uy.test(e))}s(Wy,"isValidIP");function qy(e,t){if(!Ny.test(e))return!1;try{let[n]=e.split(".");if(!n)return!1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),i=JSON.parse(atob(r));return!(typeof i!="object"||i===null||"typ"in i&&i?.typ!=="JWT"||!i.alg||t&&i.alg!==t)}catch{return!1}}s(qy,"isValidJWT");function zy(e,t){return!!((t==="v4"||!t)&&Fy.test(e)||(t==="v6"||!t)&&By.test(e))}s(zy,"isValidCidr");var Je=class e extends K{static{s(this,"ZodString")}_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==$.string){let o=this._getOrReturnCtx(t);return A(o,{code:v.invalid_type,expected:$.string,received:o.parsedType}),P}let r=new ae,i;for(let o of this._def.checks)if(o.kind==="min")t.data.length<o.value&&(i=this._getOrReturnCtx(t,i),A(i,{code:v.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),r.dirty());else if(o.kind==="max")t.data.length>o.value&&(i=this._getOrReturnCtx(t,i),A(i,{code:v.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),r.dirty());else if(o.kind==="length"){let a=t.data.length>o.value,c=t.data.length<o.value;(a||c)&&(i=this._getOrReturnCtx(t,i),a?A(i,{code:v.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):c&&A(i,{code:v.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),r.dirty())}else if(o.kind==="email")Py.test(t.data)||(i=this._getOrReturnCtx(t,i),A(i,{validation:"email",code:v.invalid_string,message:o.message}),r.dirty());else if(o.kind==="emoji")Xi||(Xi=new RegExp(My,"u")),Xi.test(t.data)||(i=this._getOrReturnCtx(t,i),A(i,{validation:"emoji",code:v.invalid_string,message:o.message}),r.dirty());else if(o.kind==="uuid")Iy.test(t.data)||(i=this._getOrReturnCtx(t,i),A(i,{validation:"uuid",code:v.invalid_string,message:o.message}),r.dirty());else if(o.kind==="nanoid")Dy.test(t.data)||(i=this._getOrReturnCtx(t,i),A(i,{validation:"nanoid",code:v.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid")Ty.test(t.data)||(i=this._getOrReturnCtx(t,i),A(i,{validation:"cuid",code:v.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid2")Cy.test(t.data)||(i=this._getOrReturnCtx(t,i),A(i,{validation:"cuid2",code:v.invalid_string,message:o.message}),r.dirty());else if(o.kind==="ulid")Oy.test(t.data)||(i=this._getOrReturnCtx(t,i),A(i,{validation:"ulid",code:v.invalid_string,message:o.message}),r.dirty());else if(o.kind==="url")try{new URL(t.data)}catch{i=this._getOrReturnCtx(t,i),A(i,{validation:"url",code:v.invalid_string,message:o.message}),r.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(t.data)||(i=this._getOrReturnCtx(t,i),A(i,{validation:"regex",code:v.invalid_string,message:o.message}),r.dirty())):o.kind==="trim"?t.data=t.data.trim():o.kind==="includes"?t.data.includes(o.value,o.position)||(i=this._getOrReturnCtx(t,i),A(i,{code:v.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),r.dirty()):o.kind==="toLowerCase"?t.data=t.data.toLowerCase():o.kind==="toUpperCase"?t.data=t.data.toUpperCase():o.kind==="startsWith"?t.data.startsWith(o.value)||(i=this._getOrReturnCtx(t,i),A(i,{code:v.invalid_string,validation:{startsWith:o.value},message:o.message}),r.dirty()):o.kind==="endsWith"?t.data.endsWith(o.value)||(i=this._getOrReturnCtx(t,i),A(i,{code:v.invalid_string,validation:{endsWith:o.value},message:o.message}),r.dirty()):o.kind==="datetime"?Sc(o).test(t.data)||(i=this._getOrReturnCtx(t,i),A(i,{code:v.invalid_string,validation:"datetime",message:o.message}),r.dirty()):o.kind==="date"?Gy.test(t.data)||(i=this._getOrReturnCtx(t,i),A(i,{code:v.invalid_string,validation:"date",message:o.message}),r.dirty()):o.kind==="time"?Vy(o).test(t.data)||(i=this._getOrReturnCtx(t,i),A(i,{code:v.invalid_string,validation:"time",message:o.message}),r.dirty()):o.kind==="duration"?jy.test(t.data)||(i=this._getOrReturnCtx(t,i),A(i,{validation:"duration",code:v.invalid_string,message:o.message}),r.dirty()):o.kind==="ip"?Wy(t.data,o.version)||(i=this._getOrReturnCtx(t,i),A(i,{validation:"ip",code:v.invalid_string,message:o.message}),r.dirty()):o.kind==="jwt"?qy(t.data,o.alg)||(i=this._getOrReturnCtx(t,i),A(i,{validation:"jwt",code:v.invalid_string,message:o.message}),r.dirty()):o.kind==="cidr"?zy(t.data,o.version)||(i=this._getOrReturnCtx(t,i),A(i,{validation:"cidr",code:v.invalid_string,message:o.message}),r.dirty()):o.kind==="base64"?Ky.test(t.data)||(i=this._getOrReturnCtx(t,i),A(i,{validation:"base64",code:v.invalid_string,message:o.message}),r.dirty()):o.kind==="base64url"?Hy.test(t.data)||(i=this._getOrReturnCtx(t,i),A(i,{validation:"base64url",code:v.invalid_string,message:o.message}),r.dirty()):G.assertNever(o);return{status:r.value,value:t.data}}_regex(t,n,r){return this.refinement(i=>t.test(i),{validation:n,code:v.invalid_string,...D.errToObj(r)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...D.errToObj(t)})}url(t){return this._addCheck({kind:"url",...D.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...D.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...D.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...D.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...D.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...D.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...D.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...D.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...D.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...D.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...D.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...D.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...D.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...D.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...D.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...D.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n?.position,...D.errToObj(n?.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...D.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...D.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...D.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...D.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...D.errToObj(n)})}nonempty(t){return this.min(1,D.errToObj(t))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxLength(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}};Je.create=e=>new Je({checks:[],typeName:M.ZodString,coerce:e?.coerce??!1,...U(e)});function Yy(e,t){let n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,i=n>r?n:r,o=Number.parseInt(e.toFixed(i).replace(".","")),a=Number.parseInt(t.toFixed(i).replace(".",""));return o%a/10**i}s(Yy,"floatSafeRemainder");var mt=class e extends K{static{s(this,"ZodNumber")}constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==$.number){let o=this._getOrReturnCtx(t);return A(o,{code:v.invalid_type,expected:$.number,received:o.parsedType}),P}let r,i=new ae;for(let o of this._def.checks)o.kind==="int"?G.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),A(r,{code:v.invalid_type,expected:"integer",received:"float",message:o.message}),i.dirty()):o.kind==="min"?(o.inclusive?t.data<o.value:t.data<=o.value)&&(r=this._getOrReturnCtx(t,r),A(r,{code:v.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="max"?(o.inclusive?t.data>o.value:t.data>=o.value)&&(r=this._getOrReturnCtx(t,r),A(r,{code:v.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="multipleOf"?Yy(t.data,o.value)!==0&&(r=this._getOrReturnCtx(t,r),A(r,{code:v.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):o.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),A(r,{code:v.not_finite,message:o.message}),i.dirty()):G.assertNever(o);return{status:i.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,D.toString(n))}gt(t,n){return this.setLimit("min",t,!1,D.toString(n))}lte(t,n){return this.setLimit("max",t,!0,D.toString(n))}lt(t,n){return this.setLimit("max",t,!1,D.toString(n))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:D.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:D.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:D.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:D.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:D.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:D.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:D.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:D.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:D.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:D.toString(t)})}get minValue(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&G.isInteger(t.value))}get isFinite(){let t=null,n=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(t===null||r.value<t)&&(t=r.value)}return Number.isFinite(n)&&Number.isFinite(t)}};mt.create=e=>new mt({checks:[],typeName:M.ZodNumber,coerce:e?.coerce||!1,...U(e)});var ht=class e extends K{static{s(this,"ZodBigInt")}constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==$.bigint)return this._getInvalidInput(t);let r,i=new ae;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?t.data<o.value:t.data<=o.value)&&(r=this._getOrReturnCtx(t,r),A(r,{code:v.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="max"?(o.inclusive?t.data>o.value:t.data>=o.value)&&(r=this._getOrReturnCtx(t,r),A(r,{code:v.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="multipleOf"?t.data%o.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),A(r,{code:v.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):G.assertNever(o);return{status:i.value,value:t.data}}_getInvalidInput(t){let n=this._getOrReturnCtx(t);return A(n,{code:v.invalid_type,expected:$.bigint,received:n.parsedType}),P}gte(t,n){return this.setLimit("min",t,!0,D.toString(n))}gt(t,n){return this.setLimit("min",t,!1,D.toString(n))}lte(t,n){return this.setLimit("max",t,!0,D.toString(n))}lt(t,n){return this.setLimit("max",t,!1,D.toString(n))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:D.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:D.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:D.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:D.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:D.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:D.toString(n)})}get minValue(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}};ht.create=e=>new ht({checks:[],typeName:M.ZodBigInt,coerce:e?.coerce??!1,...U(e)});var gt=class extends K{static{s(this,"ZodBoolean")}_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==$.boolean){let r=this._getOrReturnCtx(t);return A(r,{code:v.invalid_type,expected:$.boolean,received:r.parsedType}),P}return ce(t.data)}};gt.create=e=>new gt({typeName:M.ZodBoolean,coerce:e?.coerce||!1,...U(e)});var yt=class e extends K{static{s(this,"ZodDate")}_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==$.date){let o=this._getOrReturnCtx(t);return A(o,{code:v.invalid_type,expected:$.date,received:o.parsedType}),P}if(Number.isNaN(t.data.getTime())){let o=this._getOrReturnCtx(t);return A(o,{code:v.invalid_date}),P}let r=new ae,i;for(let o of this._def.checks)o.kind==="min"?t.data.getTime()<o.value&&(i=this._getOrReturnCtx(t,i),A(i,{code:v.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),r.dirty()):o.kind==="max"?t.data.getTime()>o.value&&(i=this._getOrReturnCtx(t,i),A(i,{code:v.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),r.dirty()):G.assertNever(o);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:D.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:D.toString(n)})}get minDate(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t!=null?new Date(t):null}};yt.create=e=>new yt({checks:[],coerce:e?.coerce||!1,typeName:M.ZodDate,...U(e)});var Bt=class extends K{static{s(this,"ZodSymbol")}_parse(t){if(this._getType(t)!==$.symbol){let r=this._getOrReturnCtx(t);return A(r,{code:v.invalid_type,expected:$.symbol,received:r.parsedType}),P}return ce(t.data)}};Bt.create=e=>new Bt({typeName:M.ZodSymbol,...U(e)});var bt=class extends K{static{s(this,"ZodUndefined")}_parse(t){if(this._getType(t)!==$.undefined){let r=this._getOrReturnCtx(t);return A(r,{code:v.invalid_type,expected:$.undefined,received:r.parsedType}),P}return ce(t.data)}};bt.create=e=>new bt({typeName:M.ZodUndefined,...U(e)});var _t=class extends K{static{s(this,"ZodNull")}_parse(t){if(this._getType(t)!==$.null){let r=this._getOrReturnCtx(t);return A(r,{code:v.invalid_type,expected:$.null,received:r.parsedType}),P}return ce(t.data)}};_t.create=e=>new _t({typeName:M.ZodNull,...U(e)});var Qe=class extends K{static{s(this,"ZodAny")}constructor(){super(...arguments),this._any=!0}_parse(t){return ce(t.data)}};Qe.create=e=>new Qe({typeName:M.ZodAny,...U(e)});var Ue=class extends K{static{s(this,"ZodUnknown")}constructor(){super(...arguments),this._unknown=!0}_parse(t){return ce(t.data)}};Ue.create=e=>new Ue({typeName:M.ZodUnknown,...U(e)});var Re=class extends K{static{s(this,"ZodNever")}_parse(t){let n=this._getOrReturnCtx(t);return A(n,{code:v.invalid_type,expected:$.never,received:n.parsedType}),P}};Re.create=e=>new Re({typeName:M.ZodNever,...U(e)});var Kt=class extends K{static{s(this,"ZodVoid")}_parse(t){if(this._getType(t)!==$.undefined){let r=this._getOrReturnCtx(t);return A(r,{code:v.invalid_type,expected:$.void,received:r.parsedType}),P}return ce(t.data)}};Kt.create=e=>new Kt({typeName:M.ZodVoid,...U(e)});var Be=class e extends K{static{s(this,"ZodArray")}_parse(t){let{ctx:n,status:r}=this._processInputParams(t),i=this._def;if(n.parsedType!==$.array)return A(n,{code:v.invalid_type,expected:$.array,received:n.parsedType}),P;if(i.exactLength!==null){let a=n.data.length>i.exactLength.value,c=n.data.length<i.exactLength.value;(a||c)&&(A(n,{code:a?v.too_big:v.too_small,minimum:c?i.exactLength.value:void 0,maximum:a?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),r.dirty())}if(i.minLength!==null&&n.data.length<i.minLength.value&&(A(n,{code:v.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),r.dirty()),i.maxLength!==null&&n.data.length>i.maxLength.value&&(A(n,{code:v.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((a,c)=>i.type._parseAsync(new we(n,a,n.path,c)))).then(a=>ae.mergeArray(r,a));let o=[...n.data].map((a,c)=>i.type._parseSync(new we(n,a,n.path,c)));return ae.mergeArray(r,o)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:D.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:D.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:D.toString(n)}})}nonempty(t){return this.min(1,t)}};Be.create=(e,t)=>new Be({type:e,minLength:null,maxLength:null,exactLength:null,typeName:M.ZodArray,...U(t)});function Ut(e){if(e instanceof fe){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=_e.create(Ut(r))}return new fe({...e._def,shape:s(()=>t,"shape")})}else return e instanceof Be?new Be({...e._def,type:Ut(e.element)}):e instanceof _e?_e.create(Ut(e.unwrap())):e instanceof Oe?Oe.create(Ut(e.unwrap())):e instanceof Ce?Ce.create(e.items.map(t=>Ut(t))):e}s(Ut,"deepPartialify");var fe=class e extends K{static{s(this,"ZodObject")}constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let t=this._def.shape(),n=G.objectKeys(t);return this._cached={shape:t,keys:n},this._cached}_parse(t){if(this._getType(t)!==$.object){let u=this._getOrReturnCtx(t);return A(u,{code:v.invalid_type,expected:$.object,received:u.parsedType}),P}let{status:r,ctx:i}=this._processInputParams(t),{shape:o,keys:a}=this._getCached(),c=[];if(!(this._def.catchall instanceof Re&&this._def.unknownKeys==="strip"))for(let u in i.data)a.includes(u)||c.push(u);let l=[];for(let u of a){let d=o[u],f=i.data[u];l.push({key:{status:"valid",value:u},value:d._parse(new we(i,f,i.path,u)),alwaysSet:u in i.data})}if(this._def.catchall instanceof Re){let u=this._def.unknownKeys;if(u==="passthrough")for(let d of c)l.push({key:{status:"valid",value:d},value:{status:"valid",value:i.data[d]}});else if(u==="strict")c.length>0&&(A(i,{code:v.unrecognized_keys,keys:c}),r.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let d of c){let f=i.data[d];l.push({key:{status:"valid",value:d},value:u._parse(new we(i,f,i.path,d)),alwaysSet:d in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let u=[];for(let d of l){let f=await d.key,h=await d.value;u.push({key:f,value:h,alwaysSet:d.alwaysSet})}return u}).then(u=>ae.mergeObjectSync(r,u)):ae.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(t){return D.errToObj,new e({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:s((n,r)=>{let i=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:D.errToObj(t).message??i}:{message:i}},"errorMap")}:{}})}strip(){return new e({...this._def,unknownKeys:"strip"})}passthrough(){return new e({...this._def,unknownKeys:"passthrough"})}extend(t){return new e({...this._def,shape:s(()=>({...this._def.shape(),...t}),"shape")})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:s(()=>({...this._def.shape(),...t._def.shape()}),"shape"),typeName:M.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let r of G.objectKeys(t))t[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new e({...this._def,shape:s(()=>n,"shape")})}omit(t){let n={};for(let r of G.objectKeys(this.shape))t[r]||(n[r]=this.shape[r]);return new e({...this._def,shape:s(()=>n,"shape")})}deepPartial(){return Ut(this)}partial(t){let n={};for(let r of G.objectKeys(this.shape)){let i=this.shape[r];t&&!t[r]?n[r]=i:n[r]=i.optional()}return new e({...this._def,shape:s(()=>n,"shape")})}required(t){let n={};for(let r of G.objectKeys(this.shape))if(t&&!t[r])n[r]=this.shape[r];else{let o=this.shape[r];for(;o instanceof _e;)o=o._def.innerType;n[r]=o}return new e({...this._def,shape:s(()=>n,"shape")})}keyof(){return Rc(G.objectKeys(this.shape))}};fe.create=(e,t)=>new fe({shape:s(()=>e,"shape"),unknownKeys:"strip",catchall:Re.create(),typeName:M.ZodObject,...U(t)});fe.strictCreate=(e,t)=>new fe({shape:s(()=>e,"shape"),unknownKeys:"strict",catchall:Re.create(),typeName:M.ZodObject,...U(t)});fe.lazycreate=(e,t)=>new fe({shape:e,unknownKeys:"strip",catchall:Re.create(),typeName:M.ZodObject,...U(t)});var wt=class extends K{static{s(this,"ZodUnion")}_parse(t){let{ctx:n}=this._processInputParams(t),r=this._def.options;function i(o){for(let c of o)if(c.result.status==="valid")return c.result;for(let c of o)if(c.result.status==="dirty")return n.common.issues.push(...c.ctx.common.issues),c.result;let a=o.map(c=>new de(c.ctx.common.issues));return A(n,{code:v.invalid_union,unionErrors:a}),P}if(s(i,"handleResults"),n.common.async)return Promise.all(r.map(async o=>{let a={...n,common:{...n.common,issues:[]},parent:null};return{result:await o._parseAsync({data:n.data,path:n.path,parent:a}),ctx:a}})).then(i);{let o,a=[];for(let l of r){let u={...n,common:{...n.common,issues:[]},parent:null},d=l._parseSync({data:n.data,path:n.path,parent:u});if(d.status==="valid")return d;d.status==="dirty"&&!o&&(o={result:d,ctx:u}),u.common.issues.length&&a.push(u.common.issues)}if(o)return n.common.issues.push(...o.ctx.common.issues),o.result;let c=a.map(l=>new de(l));return A(n,{code:v.invalid_union,unionErrors:c}),P}}get options(){return this._def.options}};wt.create=(e,t)=>new wt({options:e,typeName:M.ZodUnion,...U(t)});var Fe=s(e=>e instanceof vt?Fe(e.schema):e instanceof ke?Fe(e.innerType()):e instanceof xt?[e.value]:e instanceof St?e.options:e instanceof Rt?G.objectValues(e.enum):e instanceof Et?Fe(e._def.innerType):e instanceof bt?[void 0]:e instanceof _t?[null]:e instanceof _e?[void 0,...Fe(e.unwrap())]:e instanceof Oe?[null,...Fe(e.unwrap())]:e instanceof mn||e instanceof $t?Fe(e.unwrap()):e instanceof At?Fe(e._def.innerType):[],"getDiscriminator"),dr=class e extends K{static{s(this,"ZodDiscriminatedUnion")}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==$.object)return A(n,{code:v.invalid_type,expected:$.object,received:n.parsedType}),P;let r=this.discriminator,i=n.data[r],o=this.optionsMap.get(i);return o?n.common.async?o._parseAsync({data:n.data,path:n.path,parent:n}):o._parseSync({data:n.data,path:n.path,parent:n}):(A(n,{code:v.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),P)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){let i=new Map;for(let o of n){let a=Fe(o.shape[t]);if(!a.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let c of a){if(i.has(c))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(c)}`);i.set(c,o)}}return new e({typeName:M.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...U(r)})}};function Zi(e,t){let n=Te(e),r=Te(t);if(e===t)return{valid:!0,data:e};if(n===$.object&&r===$.object){let i=G.objectKeys(t),o=G.objectKeys(e).filter(c=>i.indexOf(c)!==-1),a={...e,...t};for(let c of o){let l=Zi(e[c],t[c]);if(!l.valid)return{valid:!1};a[c]=l.data}return{valid:!0,data:a}}else if(n===$.array&&r===$.array){if(e.length!==t.length)return{valid:!1};let i=[];for(let o=0;o<e.length;o++){let a=e[o],c=t[o],l=Zi(a,c);if(!l.valid)return{valid:!1};i.push(l.data)}return{valid:!0,data:i}}else return n===$.date&&r===$.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}s(Zi,"mergeValues");var kt=class extends K{static{s(this,"ZodIntersection")}_parse(t){let{status:n,ctx:r}=this._processInputParams(t),i=s((o,a)=>{if(lr(o)||lr(a))return P;let c=Zi(o.value,a.value);return c.valid?((ur(o)||ur(a))&&n.dirty(),{status:n.value,value:c.data}):(A(r,{code:v.invalid_intersection_types}),P)},"handleParsed");return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([o,a])=>i(o,a)):i(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};kt.create=(e,t,n)=>new kt({left:e,right:t,typeName:M.ZodIntersection,...U(n)});var Ce=class e extends K{static{s(this,"ZodTuple")}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==$.array)return A(r,{code:v.invalid_type,expected:$.array,received:r.parsedType}),P;if(r.data.length<this._def.items.length)return A(r,{code:v.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),P;!this._def.rest&&r.data.length>this._def.items.length&&(A(r,{code:v.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let o=[...r.data].map((a,c)=>{let l=this._def.items[c]||this._def.rest;return l?l._parse(new we(r,a,r.path,c)):null}).filter(a=>!!a);return r.common.async?Promise.all(o).then(a=>ae.mergeArray(n,a)):ae.mergeArray(n,o)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};Ce.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ce({items:e,typeName:M.ZodTuple,rest:null,...U(t)})};var fr=class e extends K{static{s(this,"ZodRecord")}get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==$.object)return A(r,{code:v.invalid_type,expected:$.object,received:r.parsedType}),P;let i=[],o=this._def.keyType,a=this._def.valueType;for(let c in r.data)i.push({key:o._parse(new we(r,c,r.path,c)),value:a._parse(new we(r,r.data[c],r.path,c)),alwaysSet:c in r.data});return r.common.async?ae.mergeObjectAsync(n,i):ae.mergeObjectSync(n,i)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof K?new e({keyType:t,valueType:n,typeName:M.ZodRecord,...U(r)}):new e({keyType:Je.create(),valueType:t,typeName:M.ZodRecord,...U(n)})}},Ht=class extends K{static{s(this,"ZodMap")}get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==$.map)return A(r,{code:v.invalid_type,expected:$.map,received:r.parsedType}),P;let i=this._def.keyType,o=this._def.valueType,a=[...r.data.entries()].map(([c,l],u)=>({key:i._parse(new we(r,c,r.path,[u,"key"])),value:o._parse(new we(r,l,r.path,[u,"value"]))}));if(r.common.async){let c=new Map;return Promise.resolve().then(async()=>{for(let l of a){let u=await l.key,d=await l.value;if(u.status==="aborted"||d.status==="aborted")return P;(u.status==="dirty"||d.status==="dirty")&&n.dirty(),c.set(u.value,d.value)}return{status:n.value,value:c}})}else{let c=new Map;for(let l of a){let u=l.key,d=l.value;if(u.status==="aborted"||d.status==="aborted")return P;(u.status==="dirty"||d.status==="dirty")&&n.dirty(),c.set(u.value,d.value)}return{status:n.value,value:c}}}};Ht.create=(e,t,n)=>new Ht({valueType:t,keyType:e,typeName:M.ZodMap,...U(n)});var Gt=class e extends K{static{s(this,"ZodSet")}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==$.set)return A(r,{code:v.invalid_type,expected:$.set,received:r.parsedType}),P;let i=this._def;i.minSize!==null&&r.data.size<i.minSize.value&&(A(r,{code:v.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),n.dirty()),i.maxSize!==null&&r.data.size>i.maxSize.value&&(A(r,{code:v.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),n.dirty());let o=this._def.valueType;function a(l){let u=new Set;for(let d of l){if(d.status==="aborted")return P;d.status==="dirty"&&n.dirty(),u.add(d.value)}return{status:n.value,value:u}}s(a,"finalizeSet");let c=[...r.data.values()].map((l,u)=>o._parse(new we(r,l,r.path,u)));return r.common.async?Promise.all(c).then(l=>a(l)):a(c)}min(t,n){return new e({...this._def,minSize:{value:t,message:D.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:D.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}};Gt.create=(e,t)=>new Gt({valueType:e,minSize:null,maxSize:null,typeName:M.ZodSet,...U(t)});var pr=class e extends K{static{s(this,"ZodFunction")}constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==$.function)return A(n,{code:v.invalid_type,expected:$.function,received:n.parsedType}),P;function r(c,l){return pn({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Lt(),Le].filter(u=>!!u),issueData:{code:v.invalid_arguments,argumentsError:l}})}s(r,"makeArgsIssue");function i(c,l){return pn({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Lt(),Le].filter(u=>!!u),issueData:{code:v.invalid_return_type,returnTypeError:l}})}s(i,"makeReturnsIssue");let o={errorMap:n.common.contextualErrorMap},a=n.data;if(this._def.returns instanceof et){let c=this;return ce(async function(...l){let u=new de([]),d=await c._def.args.parseAsync(l,o).catch(m=>{throw u.addIssue(r(l,m)),u}),f=await Reflect.apply(a,this,d);return await c._def.returns._def.type.parseAsync(f,o).catch(m=>{throw u.addIssue(i(f,m)),u})})}else{let c=this;return ce(function(...l){let u=c._def.args.safeParse(l,o);if(!u.success)throw new de([r(l,u.error)]);let d=Reflect.apply(a,this,u.data),f=c._def.returns.safeParse(d,o);if(!f.success)throw new de([i(d,f.error)]);return f.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:Ce.create(t).rest(Ue.create())})}returns(t){return new e({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,r){return new e({args:t||Ce.create([]).rest(Ue.create()),returns:n||Ue.create(),typeName:M.ZodFunction,...U(r)})}},vt=class extends K{static{s(this,"ZodLazy")}get schema(){return this._def.getter()}_parse(t){let{ctx:n}=this._processInputParams(t);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};vt.create=(e,t)=>new vt({getter:e,typeName:M.ZodLazy,...U(t)});var xt=class extends K{static{s(this,"ZodLiteral")}_parse(t){if(t.data!==this._def.value){let n=this._getOrReturnCtx(t);return A(n,{received:n.data,code:v.invalid_literal,expected:this._def.value}),P}return{status:"valid",value:t.data}}get value(){return this._def.value}};xt.create=(e,t)=>new xt({value:e,typeName:M.ZodLiteral,...U(t)});function Rc(e,t){return new St({values:e,typeName:M.ZodEnum,...U(t)})}s(Rc,"createZodEnum");var St=class e extends K{static{s(this,"ZodEnum")}_parse(t){if(typeof t.data!="string"){let n=this._getOrReturnCtx(t),r=this._def.values;return A(n,{expected:G.joinValues(r),received:n.parsedType,code:v.invalid_type}),P}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){let n=this._getOrReturnCtx(t),r=this._def.values;return A(n,{received:n.data,code:v.invalid_enum_value,options:r}),P}return ce(t.data)}get options(){return this._def.values}get enum(){let t={};for(let n of this._def.values)t[n]=n;return t}get Values(){let t={};for(let n of this._def.values)t[n]=n;return t}get Enum(){let t={};for(let n of this._def.values)t[n]=n;return t}extract(t,n=this._def){return e.create(t,{...this._def,...n})}exclude(t,n=this._def){return e.create(this.options.filter(r=>!t.includes(r)),{...this._def,...n})}};St.create=Rc;var Rt=class extends K{static{s(this,"ZodNativeEnum")}_parse(t){let n=G.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==$.string&&r.parsedType!==$.number){let i=G.objectValues(n);return A(r,{expected:G.joinValues(i),received:r.parsedType,code:v.invalid_type}),P}if(this._cache||(this._cache=new Set(G.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let i=G.objectValues(n);return A(r,{received:r.data,code:v.invalid_enum_value,options:i}),P}return ce(t.data)}get enum(){return this._def.values}};Rt.create=(e,t)=>new Rt({values:e,typeName:M.ZodNativeEnum,...U(t)});var et=class extends K{static{s(this,"ZodPromise")}unwrap(){return this._def.type}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==$.promise&&n.common.async===!1)return A(n,{code:v.invalid_type,expected:$.promise,received:n.parsedType}),P;let r=n.parsedType===$.promise?n.data:Promise.resolve(n.data);return ce(r.then(i=>this._def.type.parseAsync(i,{path:n.path,errorMap:n.common.contextualErrorMap})))}};et.create=(e,t)=>new et({type:e,typeName:M.ZodPromise,...U(t)});var ke=class extends K{static{s(this,"ZodEffects")}innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===M.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:n,ctx:r}=this._processInputParams(t),i=this._def.effect||null,o={addIssue:s(a=>{A(r,a),a.fatal?n.abort():n.dirty()},"addIssue"),get path(){return r.path}};if(o.addIssue=o.addIssue.bind(o),i.type==="preprocess"){let a=i.transform(r.data,o);if(r.common.async)return Promise.resolve(a).then(async c=>{if(n.value==="aborted")return P;let l=await this._def.schema._parseAsync({data:c,path:r.path,parent:r});return l.status==="aborted"?P:l.status==="dirty"?pt(l.value):n.value==="dirty"?pt(l.value):l});{if(n.value==="aborted")return P;let c=this._def.schema._parseSync({data:a,path:r.path,parent:r});return c.status==="aborted"?P:c.status==="dirty"?pt(c.value):n.value==="dirty"?pt(c.value):c}}if(i.type==="refinement"){let a=s(c=>{let l=i.refinement(c,o);if(r.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return c},"executeRefinement");if(r.common.async===!1){let c=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return c.status==="aborted"?P:(c.status==="dirty"&&n.dirty(),a(c.value),{status:n.value,value:c.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(c=>c.status==="aborted"?P:(c.status==="dirty"&&n.dirty(),a(c.value).then(()=>({status:n.value,value:c.value}))))}if(i.type==="transform")if(r.common.async===!1){let a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Ze(a))return P;let c=i.transform(a.value,o);if(c instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:c}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>Ze(a)?Promise.resolve(i.transform(a.value,o)).then(c=>({status:n.value,value:c})):P);G.assertNever(i)}};ke.create=(e,t,n)=>new ke({schema:e,typeName:M.ZodEffects,effect:t,...U(n)});ke.createWithPreprocess=(e,t,n)=>new ke({schema:t,effect:{type:"preprocess",transform:e},typeName:M.ZodEffects,...U(n)});var _e=class extends K{static{s(this,"ZodOptional")}_parse(t){return this._getType(t)===$.undefined?ce(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};_e.create=(e,t)=>new _e({innerType:e,typeName:M.ZodOptional,...U(t)});var Oe=class extends K{static{s(this,"ZodNullable")}_parse(t){return this._getType(t)===$.null?ce(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Oe.create=(e,t)=>new Oe({innerType:e,typeName:M.ZodNullable,...U(t)});var Et=class extends K{static{s(this,"ZodDefault")}_parse(t){let{ctx:n}=this._processInputParams(t),r=n.data;return n.parsedType===$.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};Et.create=(e,t)=>new Et({innerType:e,typeName:M.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...U(t)});var At=class extends K{static{s(this,"ZodCatch")}_parse(t){let{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},i=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return Ft(i)?i.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new de(r.common.issues)},input:r.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new de(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};At.create=(e,t)=>new At({innerType:e,typeName:M.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...U(t)});var Vt=class extends K{static{s(this,"ZodNaN")}_parse(t){if(this._getType(t)!==$.nan){let r=this._getOrReturnCtx(t);return A(r,{code:v.invalid_type,expected:$.nan,received:r.parsedType}),P}return{status:"valid",value:t.data}}};Vt.create=e=>new Vt({typeName:M.ZodNaN,...U(e)});var Xy=Symbol("zod_brand"),mn=class extends K{static{s(this,"ZodBranded")}_parse(t){let{ctx:n}=this._processInputParams(t),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}},hn=class e extends K{static{s(this,"ZodPipeline")}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return s(async()=>{let o=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?P:o.status==="dirty"?(n.dirty(),pt(o.value)):this._def.out._parseAsync({data:o.value,path:r.path,parent:r})},"handleAsync")();{let i=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?P:i.status==="dirty"?(n.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:r.path,parent:r})}}static create(t,n){return new e({in:t,out:n,typeName:M.ZodPipeline})}},$t=class extends K{static{s(this,"ZodReadonly")}_parse(t){let n=this._def.innerType._parse(t),r=s(i=>(Ze(i)&&(i.value=Object.freeze(i.value)),i),"freeze");return Ft(n)?n.then(i=>r(i)):r(n)}unwrap(){return this._def.innerType}};$t.create=(e,t)=>new $t({innerType:e,typeName:M.ZodReadonly,...U(t)});function kc(e,t){let n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}s(kc,"cleanParams");function Ec(e,t={},n){return e?Qe.create().superRefine((r,i)=>{let o=e(r);if(o instanceof Promise)return o.then(a=>{if(!a){let c=kc(t,r),l=c.fatal??n??!0;i.addIssue({code:"custom",...c,fatal:l})}});if(!o){let a=kc(t,r),c=a.fatal??n??!0;i.addIssue({code:"custom",...a,fatal:c})}}):Qe.create()}s(Ec,"custom");var Zy={object:fe.lazycreate},M;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(M||(M={}));var Jy=s((e,t={message:`Input not instance of ${e.name}`})=>Ec(n=>n instanceof e,t),"instanceOfType"),Ac=Je.create,$c=mt.create,Qy=Vt.create,eb=ht.create,Tc=gt.create,tb=yt.create,nb=Bt.create,rb=bt.create,ib=_t.create,ob=Qe.create,sb=Ue.create,ab=Re.create,cb=Kt.create,lb=Be.create,ub=fe.create,db=fe.strictCreate,fb=wt.create,pb=dr.create,mb=kt.create,hb=Ce.create,gb=fr.create,yb=Ht.create,bb=Gt.create,_b=pr.create,wb=vt.create,kb=xt.create,vb=St.create,xb=Rt.create,Sb=et.create,Rb=ke.create,Eb=_e.create,Ab=Oe.create,$b=ke.createWithPreprocess,Tb=hn.create,Cb=s(()=>Ac().optional(),"ostring"),Ob=s(()=>$c().optional(),"onumber"),Ib=s(()=>Tc().optional(),"oboolean"),Db={string:s(e=>Je.create({...e,coerce:!0}),"string"),number:s(e=>mt.create({...e,coerce:!0}),"number"),boolean:s(e=>gt.create({...e,coerce:!0}),"boolean"),bigint:s(e=>ht.create({...e,coerce:!0}),"bigint"),date:s(e=>yt.create({...e,coerce:!0}),"date")};var Nb=P;var Ji=p.object({id:p.string().min(1),title:p.string().min(1).max(200),type:p.enum(["debugging_lesson","workflow_best_practice","convention","recipe","template"]),tier:p.enum(["community","curated"]),lesson_class:p.enum(["general","architecture"]).default("general"),quality_tier:p.enum(["hand-vetted","bulk-migrated","experimental"]).default("hand-vetted"),provenance:p.object({source:p.enum(["memory","vault","claude-md"]),source_id:p.string().min(1),migrated_at:p.string(),migrated_from_workspace:p.string().optional()}).optional(),context:p.object({tools:p.array(p.string()).default([]),languages:p.array(p.string()).default([]),platforms:p.array(p.string()).default([]),tags:p.array(p.string()).default([])}),summary:p.string().min(1).max(500),problem:p.string().optional(),solution:p.string().optional(),gotchas:p.array(p.string()).default([]),template_body:p.string().min(1).optional(),target_file:p.string().min(1).optional(),submitted_by:p.string().optional(),evidence:p.string().optional(),last_validated_at:p.string().optional(),tool_versions:p.record(p.string(),p.string()).optional(),upvotes:p.number().int().nonnegative().default(0),version:p.number().int().min(1).default(1),changed_at:p.string().optional(),changelog:p.string().max(500).optional(),revision_of:p.string().optional(),org_id:p.string().uuid().optional(),org_name:p.string().optional(),scope:p.literal("private").optional(),body:p.string().min(1)}).superRefine((e,t)=>{e.type==="template"&&(e.template_body||t.addIssue({code:p.ZodIssueCode.custom,path:["template_body"],message:"type=template requires non-empty template_body"}),e.target_file||t.addIssue({code:p.ZodIssueCode.custom,path:["target_file"],message:"type=template requires target_file (e.g. CLAUDE.md, AGENTS.md, .cursorrules)"}))});var jb=Ji.superRefine((e,t)=>{e.type!=="template"&&t.addIssue({code:p.ZodIssueCode.custom,path:["type"],message:'Template requires type === "template"'}),(!e.template_body||e.template_body.length===0)&&t.addIssue({code:p.ZodIssueCode.custom,path:["template_body"],message:"template_body is required and must be non-empty"}),(!e.target_file||e.target_file.length===0)&&t.addIssue({code:p.ZodIssueCode.custom,path:["target_file"],message:"target_file is required (e.g. CLAUDE.md, AGENTS.md, .cursorrules)"}),e.tier!=="curated"&&t.addIssue({code:p.ZodIssueCode.custom,path:["tier"],message:'Template tier must be "curated" (templates/ is curated-only by repo convention)'})});var Cc=["claude-code","claude-desktop","codex","copilot","cursor","windsurf","gemini-cli","zed","generic"],Oc=p.enum(Cc),Ic=["new_to_ai_agents","new_to_this_client","experienced"],Dc=p.enum(Ic),Qi=[{id:"model-selection",header:"Model selection"},{id:"effort-levels",header:"Effort levels"},{id:"modes",header:"Modes"},{id:"language",header:"Language"},{id:"context-economy",header:"Context economy"},{id:"permissions",header:"Permissions"},{id:"cost",header:"Cost"},{id:"hooks",header:"Hooks"},{id:"learnings",header:"Learnings"},{id:"mcp-snippet",header:"MCP snippet"},{id:"first-week",header:"First week"}],Nc=Qi.map(e=>e.header),jc=p.object({experience_level:p.array(Dc).default([]),stack_filters:p.array(p.string()).default([])}).default({experience_level:[],stack_filters:[]}),Pc=p.object({id:p.string().min(1),client:Oc,title:p.string().min(1),last_updated:p.string().regex(/^\d{4}-\d{2}-\d{2}$/,"last_updated must be ISO date YYYY-MM-DD"),applies_to:jc,version:p.number().int().min(1).default(1),changelog:p.string().max(500).optional()}),Pb=Pc.extend({body:p.string().min(1)});var Lc=["operating_procedure","code_review","communication_style"],mr=p.enum(Lc),Fc=["info","recommended","required"],hr=p.enum(Fc),Mb=["optional","default_on","mandatory"],Lb=p.enum(Mb),Uc=["claude-code","claude-desktop","copilot","cursor","windsurf","generic"],Bc=p.enum(Uc),Kc=["verify","contribute","mixed"],Hc=p.enum(Kc),gr=p.object({clients:p.array(Bc).default([]),stacks:p.array(p.string()).default([]),intents:p.array(Hc).default([])}).default({clients:[],stacks:[],intents:[]}),Fb=/^conv_[a-z0-9]+(_[a-z0-9]+)*$/,Ub=64,Mc=200,Bb=p.preprocess(e=>e instanceof Date&&!Number.isNaN(e.getTime())?e.toISOString().slice(0,10):e,p.string().regex(/^\d{4}-\d{2}-\d{2}$/,"changed_at must be ISO date YYYY-MM-DD")),Gc=p.object({id:p.string().min(5).max(Ub).regex(Fb,"id must match conv_<lowercase_alphanum_underscore>"),title:p.string().min(1).max(200),scope:mr,version:p.number().int().min(1),changed_at:Bb,changelog:p.string().max(500).optional(),applies_to:gr,severity:hr.default("recommended"),disableability:Lb.default("default_on"),summary:p.string().min(1).max(Mc,`summary must be \u2264 ${Mc} chars (rendered as one line in init-push)`),review_gate:p.object({enabled:p.boolean(),min_matched_symbols:p.number().int().min(1).max(8).default(2),hard:p.boolean().default(!1)}).optional(),gateway_gate:p.object({enabled:p.boolean(),deny_tools:p.array(p.string().min(1).max(128)).min(1).max(16),servers:p.array(p.string().min(1).max(64)).min(1).max(8).optional()}).optional()}),Kb=Gc.extend({body:p.string().min(1)});var eo=p.object({type:p.literal("text"),md:p.string().min(1).max(2e4)}),yr=p.number().min(0).max(1).optional(),to=p.object({type:p.literal("media"),kind:p.enum(["image","video"]),url:p.string().url().max(2048),alt:p.string().max(500).optional(),caption:p.string().max(500).optional(),fog:p.object({top:yr,right:yr,bottom:yr,left:yr}).optional()}),Vc=p.object({label:p.string().min(1).max(40),color:p.string().regex(/^#[0-9a-fA-F]{6}$/,"color must be a 6-digit hex like #a855f7")}),Wc=p.object({type:p.literal("accordion"),title:p.string().min(1).max(200),subtag:Vc.optional(),blocks:p.array(p.discriminatedUnion("type",[eo,to])).max(50)}),qc=p.discriminatedUnion("type",[eo,to,Wc]),Hb=p.array(qc).max(100);var zc=["free","solo_pro","team","enterprise"],Gb=p.enum(zc);var Yc=["solo_pro","team","enterprise"],Xc=p.enum(Yc),Vb=p.string().refine(e=>!Number.isNaN(Date.parse(e)),"must be ISO datetime"),Wb=p.object({user_id:p.string().uuid(),tier:Xc,reason:p.string().min(10,"Begr\xFCndung muss mindestens 10 Zeichen lang sein").max(500,"Begr\xFCndung darf maximal 500 Zeichen lang sein"),effective_until:Vb.nullable().optional(),auto_revoke_on_stripe:p.boolean().optional().default(!1)}).refine(e=>e.effective_until==null?!0:new Date(e.effective_until).getTime()>Date.now(),{path:["effective_until"],message:"Ablaufdatum muss in der Zukunft liegen"}),qb=p.object({override_id:p.string().uuid(),reason:p.string().min(3).max(200).optional()});var zb=p.string().refine(e=>!Number.isNaN(Date.parse(e)),"must be ISO datetime"),Yb=p.object({org_id:p.string().uuid(),seats:p.number().int("Seats m\xFCssen eine ganze Zahl sein").min(2,"Seats m\xFCssen mindestens 2 sein (1 entspricht dem Default ohne Override)"),reason:p.string().min(10,"Begr\xFCndung muss mindestens 10 Zeichen lang sein").max(500,"Begr\xFCndung darf maximal 500 Zeichen lang sein"),effective_until:zb.nullable().optional(),auto_revoke_on_stripe:p.boolean().optional().default(!1)}).refine(e=>e.effective_until==null?!0:new Date(e.effective_until).getTime()>Date.now(),{path:["effective_until"],message:"Ablaufdatum muss in der Zukunft liegen"}),Xb=p.object({override_id:p.string().uuid(),reason:p.string().min(3).max(200).optional()});var Zc=p.enum(["info","important","critical"]),Zb=p.enum(["pass","warn","fail"]),Jc=p.object({type:p.enum(["template","lesson"]),id:p.string().min(1)}),Qc=p.object({languages:p.array(p.string()).optional(),tools:p.array(p.string()).optional()}).optional(),el=p.discriminatedUnion("kind",[p.object({kind:p.literal("file-exists"),path:p.string().min(1)}),p.object({kind:p.literal("any-file-exists"),paths:p.array(p.string().min(1)).min(1)}),p.object({kind:p.literal("any-agent-config")}),p.object({kind:p.literal("file-size-budget"),field:p.enum(["claude_md","readme"]),max_chars:p.number().int().positive()}),p.object({kind:p.literal("readme-section-present"),headers:p.array(p.string().min(1)).min(1)}),p.object({kind:p.literal("adr-dir-present")}),p.object({kind:p.literal("git-present")}),p.object({kind:p.literal("quality-gates-configured"),pass_if_at_least:p.number().int().min(1).max(4).optional(),warn_if_at_least:p.number().int().min(0).max(4).optional()}),p.object({kind:p.literal("storage-risk-safe"),allow_unknown:p.boolean().optional()}),p.object({kind:p.literal("doc-path-discoverability")})]),tl=p.object({id:p.string().min(1),title:p.string().min(1),severity:Zc,weight:p.number().int().positive().max(100),applies_when:Qc,check:el,fail_message:p.string().min(1),warn_message:p.string().optional(),remediation:Jc.optional()}),Jb=p.object({version:p.literal(1),checks:p.array(tl).min(1)});var Qb=/^\d{4}-\d{2}-\d{2}$/;function e_(e){if(!Qb.test(e))return!1;let t=new Date(`${e}T00:00:00Z`);return!Number.isNaN(t.getTime())&&t.toISOString().slice(0,10)===e}s(e_,"isRealDate");var _r=p.string().refine(e_,{message:"expected a real calendar date as YYYY-MM-DD"}),nl=["exact","prefix"],rl=p.enum(nl),Ie=p.number().finite().min(0).refine(e=>Number.isInteger(e*1e4),{message:"at most four decimal places (NUMERIC(10,4))"}),il=p.object({model_pattern:p.string().min(1).max(100),match_kind:rl,valid_from:_r,valid_to:_r.nullable().optional(),input:Ie,output:Ie,cache_read:Ie,cache_write_5m:Ie,cache_write_1h:Ie,long_context:p.enum(["same_price","tiered"]).optional(),input_above_200k:Ie.optional(),output_above_200k:Ie.optional(),cache_read_above_200k:Ie.optional(),cache_write_5m_above_200k:Ie.optional(),cache_write_1h_above_200k:Ie.optional(),context_threshold_tokens:p.number().int().positive().nullable().optional(),source_url:p.string().url().max(500).nullable().optional(),note:p.string().max(500).nullable().optional()}).strict().refine(e=>!e.valid_to||e.valid_to>e.valid_from,{message:"valid_to must be after valid_from",path:["valid_to"]}).refine(e=>br(e)===0||br(e)===5,{message:"above-200k rates must be given for all five classes or none",path:["input_above_200k"]}).refine(e=>e.long_context==="tiered"||br(e)===0,{message:'above-200k rates require long_context: "tiered"',path:["long_context"]}).refine(e=>e.context_threshold_tokens==null||e.long_context==="tiered",{message:'context_threshold_tokens requires long_context: "tiered"',path:["context_threshold_tokens"]}).refine(e=>br(e)===0||e.context_threshold_tokens==null||e.context_threshold_tokens===2e5,{message:"above-rates are only supported at context_threshold_tokens: 200000 \u2014 the analyzer groups against that constant and cannot see another boundary",path:["context_threshold_tokens"]});function br(e){return[e.input_above_200k,e.output_above_200k,e.cache_read_above_200k,e.cache_write_5m_above_200k,e.cache_write_1h_above_200k].filter(t=>t!==void 0).length}s(br,"aboveRateCount");function t_(e){return`${e.model_pattern}|${e.match_kind}|${e.valid_from}`}s(t_,"rowKey");var n_=p.object({changelog:p.string().min(1).max(500),as_of:_r,source_url:p.string().url().max(500),rows:p.array(il).min(1)}).strict().superRefine((e,t)=>{let n=new Map;e.rows.forEach((i,o)=>{let a=t_(i),c=n.get(a);c!==void 0?t.addIssue({code:p.ZodIssueCode.custom,path:["rows",o],message:`duplicate key ${a} (first at rows[${c}])`}):n.set(a,o)});let r=new Map;e.rows.forEach((i,o)=>{let a=`${i.model_pattern}|${i.match_kind}`,c=r.get(a)??[];c.push({i:o,r:i}),r.set(a,c)});for(let i of r.values())if(!(i.length<2)){i.sort((o,a)=>o.r.valid_from.localeCompare(a.r.valid_from));for(let o=0;o<i.length-1;o++){let a=i[o],c=i[o+1];(!a.r.valid_to||a.r.valid_to>c.r.valid_from)&&t.addIssue({code:p.ZodIssueCode.custom,path:["rows",a.i,"valid_to"],message:`window overlaps the next one for ${a.r.model_pattern} (${a.r.match_kind}): must close on or before ${c.r.valid_from}`})}}});var k_=/^skill_[a-z0-9]+(_[a-z0-9]+)*$/,v_=64,cl=200,x_=1e3,ll=p.preprocess(e=>e instanceof Date&&!Number.isNaN(e.getTime())?e.toISOString().slice(0,10):e,p.string().regex(/^\d{4}-\d{2}-\d{2}$/,"changed_at must be ISO date YYYY-MM-DD")),no=p.enum(["low","medium","high"]),ul=p.object({owner:p.string().min(1).max(160).optional(),risk_level:no.optional(),reviewed_at:ll.optional()}).default({}),dl=p.object({tags:p.array(p.string()).default([]),platforms:p.array(p.string()).default([]),tools:p.array(p.string()).default([]),languages:p.array(p.string()).default([]),limit:p.number().int().min(1).max(15).default(8)}).default({tags:[],platforms:[],tools:[],languages:[],limit:8}),fl=p.object({lesson_query:dl,lesson_pins:p.array(p.string()).default([]),lesson_excludes:p.array(p.string()).default([]),convention_ids:p.array(p.string()).default([]),template_ids:p.array(p.string()).default([]),setup_guide_ids:p.array(p.string()).default([])}).default({lesson_query:{tags:[],platforms:[],tools:[],languages:[],limit:8},lesson_pins:[],lesson_excludes:[],convention_ids:[],template_ids:[],setup_guide_ids:[]}),pl=p.object({id:p.string().min(6).max(v_).regex(k_,"id must match skill_<lowercase_alphanum_underscore>"),title:p.string().min(1).max(200),version:p.number().int().min(1),changed_at:ll,tier:p.enum(["community","curated"]).default("curated"),summary:p.string().min(1).max(cl,`summary must be \u2264 ${cl} chars (rendered as one line in skill_index)`),description:p.string().max(x_).optional(),applies_to:gr,membership:fl,governance:ul}),S_=pl.extend({body:p.string().default(""),org_id:p.string().uuid().optional(),org_name:p.string().optional()});var ml=p.enum(["maind","agent-skill"]),hl=p.enum(["ready","needs_attention","blocked"]),gl=p.enum(["info","important","critical"]),yl=p.enum(["pass","warn","fail"]),bl=p.enum(["structure","governance","scope","membership","package","references"]),_l=p.object({id:p.string().min(1),title:p.string().min(1),status:yl,severity:gl,category:bl,field:p.string().nullable().optional(),message:p.string().min(1),hint:p.string().optional()}),R_=p.object({lesson_ids:p.array(p.string()).optional(),convention_ids:p.array(p.string()).optional(),template_ids:p.array(p.string()).optional(),setup_guide_ids:p.array(p.string()).optional()}).default({}),wl=p.object({name:p.string().min(1).max(64),description:p.string().min(1).max(1024),license:p.string().optional(),compatibility:p.union([p.string(),p.array(p.string())]).optional(),metadata:p.record(p.string()).default({}),"allowed-tools":p.union([p.string(),p.array(p.string())]).optional()}).passthrough(),E_=p.object({directory_name:p.string().min(1).max(120).optional(),frontmatter:wl,body:p.string().default(""),file_listing:p.array(p.string()).optional()}),A_=p.object({format:ml,subject:p.string().min(1),status:hl,summary:p.string().min(1),counts:p.object({pass:p.number().int().min(0),warn:p.number().int().min(0),fail:p.number().int().min(0)}),checks:p.array(_l),next_steps:p.array(p.string()),trust_note:p.string().min(1)});function yn(e){if(e===null)return"null";switch(typeof e){case"string":return JSON.stringify(e);case"boolean":return e?"true":"false";case"number":if(!Number.isFinite(e))throw new Error("canonicalJson: non-finite number is not representable");return JSON.stringify(e);case"object":break;default:throw new Error(`canonicalJson: unsupported type '${typeof e}'`)}if(Array.isArray(e))return`[${e.map(o=>{if(o===void 0)throw new Error("canonicalJson: undefined array element is not representable");return yn(o)}).join(",")}]`;let t=e;return`{${Object.keys(t).filter(i=>t[i]!==void 0).sort().map(i=>`${JSON.stringify(i)}:${yn(t[i])}`).join(",")}}`}s(yn,"canonicalJson");var vl=["sql_migration_added","security_definer_touched","rls_policy_changed","auth_config_changed","package_manifest_changed","ci_workflow_changed","env_or_secrets_file"],T_=p.enum(vl),xl=["verdict","advisory"],Sl=p.enum(xl),Rl=["block","warn","note"],Wt=p.enum(Rl),C_=p.object({convention_id:p.string().min(1).max(64),convention_version:p.number().int().min(1),severity:hr,scope:mr,grade:Sl,matched_symbols:p.array(p.string().min(1).max(512)).min(1).max(64),matched_changed_symbols:p.array(p.string().min(1).max(512)).max(64).default([]),summary:p.string().max(2e3),hard:p.boolean().optional()}),El=["open","warn","info"],Al=p.enum(El),$l=["introduced","pre_existing"],Tl=p.enum($l),Cl=["full","partial","none"],Ol=p.enum(Cl),Il=p.object({detector_id:p.string().regex(/^det_[a-z0-9_]{2,59}$/),detector_version:p.string().regex(/^\d+\.\d+\.\d+$/),rule_id:p.string().regex(/^[a-z][a-z0-9_]*\.[a-z][a-z0-9_]*$/).max(64),level:Al,baseline:Tl,evidence_hash:p.string().regex(/^[a-f0-9]{64}$/),count:p.number().int().min(1).max(1e5)}),wr={det_number_collisions:{major:1,rules:["number.collision"],default_action:"block",class:"objective",replay:"deterministic"},det_spec_drift:{major:1,rules:["spec.coverage","spec.fields","spec.order","spec.extra","spec.unrealized","spec.contract","spec.assertion"],default_action:"block",class:"objective",replay:"deterministic"},det_theme_class_drift:{major:1,rules:["theme.dead_class"],default_action:"block",class:"objective",replay:"deterministic"},det_table_acl_lint:{major:1,rules:["acl.missing_revoke"],default_action:"warn",class:"opinion",replay:"deterministic"},det_changelog_duplicates:{major:1,rules:["changelog.duplicate_heading"],default_action:"block",class:"objective",replay:"deterministic"},det_workflow_yaml:{major:1,rules:["workflow.unparsable_yaml"],default_action:"block",class:"objective",replay:"deterministic"},det_release_claims:{major:1,rules:["release.phantom","release.unpublished"],default_action:"block",class:"objective",replay:"environment"},det_agent_doc_prose:{major:1,rules:["agentdoc.added_prose"],default_action:"warn",class:"opinion",replay:"deterministic"}};function io(e){return Object.prototype.hasOwnProperty.call(wr,e)}s(io,"isKnownDetector");var Dl=p.object({version:p.literal(1).default(1),actions:p.object({required:Wt.default("block"),recommended:Wt.default("warn"),info:Wt.default("note")}).default({}),overrides:p.array(p.object({convention_id:p.string().min(1).max(64),action:Wt})).max(64).default([]),risk_flag_action:p.enum(["warn","note","ignore"]).default("warn"),detector_overrides:p.array(p.object({detector_id:p.string().regex(/^det_[a-z0-9_]{2,59}$/),action:Wt,reason:p.string().min(1).max(200)})).max(32).optional()}),O_=Dl.parse({});var kl={note:0,warn:1,block:2};function oo(e){let t=null;for(let n of e)(t===null||kl[n]>kl[t])&&(t=n);return t}s(oo,"strongestAction");var Nl=["ran","not_applicable","unavailable","ungraded"],jl=p.enum(Nl),Pl=p.object({detector_id:p.string().regex(/^det_[a-z0-9_]{2,59}$/),detector_version:p.string().regex(/^\d+\.\d+\.\d+$/),state:jl}),Ke=1e3,ro=p.string().regex(/^[a-f0-9]{40}$|^[a-f0-9]{64}$/,"expected a lowercase git object sha (40 or 64 hex)"),Ml=p.object({name:p.string().min(1).max(200),qualified_name:p.string().min(1).max(512).optional(),kind:p.string().min(1).max(64).optional(),language:p.string().min(1).max(32).optional(),change:p.enum(["added","modified","co_located"]).optional(),changed_line_count:p.number().int().min(0).max(1e4).optional()}),Ll=p.object({base_kind:p.enum(["uncommitted","ref"]),changed_file_count:p.number().int().min(0),stale_file_count:p.number().int().min(0),unindexed_file_count:p.number().int().min(0).optional(),truncated:p.boolean(),hunk_coverage:p.enum(["full","partial","none"]),detector_coverage:Ol}),I_=p.object({changed_symbols:p.array(Ml).max(Ke),risk_flags:p.array(p.string().max(64)).max(16),detector_findings:p.array(Il).max(64),detector_runs:p.array(Pl).min(1).max(32),diff_stats:Ll,commit_sha:ro.optional(),base_sha:ro.optional(),merge_base_sha:ro.optional(),dirty:p.boolean().optional(),code_index_version:p.string().min(1).max(32).optional()});var Fl=14,Ul=14,Bl=14,Kl=1,Hl=365,so=p.number().int().min(Kl).max(Hl),D_=["propose","direct"],N_="propose",Gl=["propose","direct"],Vl="propose",Wl=["propose","direct"],ql="propose",zl=["off","propose","direct"],j_=["member","admin","owner"],P_="member",Yl="off";var Xl="en",Zl=p.object({version:p.literal(1).default(1),at_risk_days:so.default(Fl),stagnation_days:so.default(Ul),agent_date_mode:p.enum(D_).default(N_),health_manual_ttl_days:so.default(Bl),agent_event_mode:p.enum(Gl).default(Vl),agent_update_mode:p.enum(Wl).default(ql),agent_pull_mode:p.enum(zl).default(Yl),org_wide_authoring_min_role:p.enum(j_).default(P_),planning_language:p.string().regex(/^[a-z]{2}$/,"two lowercase letters (ISO 639-1)").default(Xl)}),M_=Zl.parse({});var Jl=p.object({version:p.literal(1).default(1),org_visibility:p.boolean().default(!1),session_span_visibility:p.boolean().default(!0)}),L_=Jl.parse({});var Ql=p.object({tools:p.array(p.string()).default([]),languages:p.array(p.string()).default([]),platforms:p.array(p.string()).default([]),tags:p.array(p.string()).default([])}),eu=p.object({id:p.string().uuid(),user_id:p.string().uuid(),project:p.string().max(200).nullable().optional(),title:p.string().min(1).max(200),body:p.string().min(1).max(2e4),context:Ql.default({tools:[],languages:[],platforms:[],tags:[]}),created_at:p.string(),updated_at:p.string(),last_recalled_at:p.string().nullable().optional(),recall_count:p.number().int().nonnegative().default(0),graduated_draft_id:p.string().uuid().nullable().optional(),deleted_at:p.string().nullable().optional()}),F_=eu.pick({id:!0,project:!0,title:!0,body:!0,context:!0,created_at:!0,updated_at:!0,last_recalled_at:!0,recall_count:!0}).extend({score:p.number()}),U_=p.object({id:p.string().uuid(),title:p.string(),summary:p.string(),tags:p.array(p.string()).default([])});var B_=new Set(["|",">","|-",">-","|+",">+"]),K_=/^(\s*)(?:-\s+)?[A-Za-z_][\w.-]*:(\s*)(.*)$/;function kr(e){let t=[],n=null;return e.split(`
23
+ `,1)[0]??"").trim().slice(0,200)}s(or,"signatureOf");function fy(e){if(!e)return null;switch(e.type){case"identifier":case"property_identifier":case"type_identifier":return e.text;case"member_expression":return e.childForFieldName("property")?.text??null;case"attribute":return e.childForFieldName("attribute")?.text??null;default:return null}}s(fy,"calleeName");function py(e,t){let n=new Set;for(let r of e.descendantsOfType(t)){let i=fy(r.childForFieldName("function"));i&&n.add(i)}return[...n]}s(py,"collectCallTargets");function Mt(e,t,n,r){for(let i of py(n,r))e.refs.push({fromKey:t,kind:"calls",targetName:i})}s(Mt,"addCallRefs");var uc="call";function dc(e,t){let n=ir();for(let r of e.namedChildren)my(r,t,n);return n}s(dc,"extractPython");function fc(e){return e.type==="decorated_definition"?e.childForFieldName("definition")??e:e}s(fc,"unwrapDecorated");function my(e,t,n){let r=fc(e);switch(r.type){case"import_statement":case"import_from_statement":{let o=(r.childForFieldName("module_name")??r.childForFieldName("name"))?.text??gy(r);o&&n.imports.push({fromModuleKey:t.moduleKey,specifier:o});return}case"function_definition":{let i=r.childForFieldName("name")?.text;if(!i)return;let o=sr(r,t,i,i,"function");n.nodes.push(o),n.edges.push({srcKey:t.moduleKey,dstKey:o.nodeKey,kind:"contains"});let a=r.childForFieldName("body");a&&Mt(n,o.nodeKey,a,uc);return}case"class_definition":hy(r,t,n);return;case"expression_statement":{let o=r.namedChildren.find(a=>a.type==="assignment")?.childForFieldName("left");if(o&&o.type==="identifier"){let a=sr(r,t,o.text,o.text,"variable");n.nodes.push(a),n.edges.push({srcKey:t.moduleKey,dstKey:a.nodeKey,kind:"contains"})}return}default:return}}s(my,"handleTopLevel");function hy(e,t,n){let r=e.childForFieldName("name")?.text;if(!r)return;let i=sr(e,t,r,r,"class");n.nodes.push(i),n.edges.push({srcKey:t.moduleKey,dstKey:i.nodeKey,kind:"contains"});let o=e.childForFieldName("superclasses");if(o){for(let c of o.namedChildren)if(c.type==="identifier")n.refs.push({fromKey:i.nodeKey,kind:"extends",targetName:c.text});else if(c.type==="attribute"){let l=c.childForFieldName("attribute")?.text;l&&n.refs.push({fromKey:i.nodeKey,kind:"extends",targetName:l})}}let a=e.childForFieldName("body");if(a)for(let c of a.namedChildren){let l=fc(c);if(l.type!=="function_definition")continue;let u=l.childForFieldName("name")?.text;if(!u)continue;let d=`${r}.${u}`,f=sr(l,t,u,d,"method");n.nodes.push(f),n.edges.push({srcKey:i.nodeKey,dstKey:f.nodeKey,kind:"contains"});let h=l.childForFieldName("body");h&&Mt(n,f.nodeKey,h,uc)}}s(hy,"addClass");function sr(e,t,n,r,i){return{nodeKey:nr(t.filePath,r,i),kind:i,name:n,qualifiedName:r,filePath:t.filePath,language:t.language,startLine:Xe(e.startPosition.row),endLine:Xe(e.endPosition.row),startByte:e.startIndex,endByte:e.endIndex,signature:or(e),doc:null}}s(sr,"makeNode");function gy(e){return e.descendantsOfType("dotted_name")[0]?.text??null}s(gy,"firstDottedName");var mc="call_expression";function hc(e,t){let n=ir();for(let r of e.namedChildren)by(r,t,n);return n}s(hc,"extractTypescript");function yy(e){return e.type==="export_statement"?e.childForFieldName("declaration")??e:e}s(yy,"unwrapExport");function by(e,t,n){let r=yy(e);switch(r.type){case"import_statement":{let i=r.childForFieldName("source")?.text;i&&n.imports.push({fromModuleKey:t.moduleKey,specifier:wy(i)});return}case"function_declaration":case"generator_function_declaration":{pc(r,t,n,"function");return}case"class_declaration":case"abstract_class_declaration":{_y(r,t,n);return}case"interface_declaration":qi(r,t,n,"interface");return;case"type_alias_declaration":qi(r,t,n,"type_alias");return;case"enum_declaration":qi(r,t,n,"enum");return;case"lexical_declaration":case"variable_declaration":{for(let i of r.namedChildren){if(i.type!=="variable_declarator")continue;let o=i.childForFieldName("name");if(!o||o.type!=="identifier")continue;let a=i.childForFieldName("value"),c=a?.type==="arrow_function"||a?.type==="function_expression"||a?.type==="function";pc(i,t,n,c?"function":"variable",o,a)}return}default:return}}s(by,"handleTopLevel");function pc(e,t,n,r,i,o){let c=(i??e.childForFieldName("name"))?.text;if(!c)return;let l=ar(e,t,c,c,r);n.nodes.push(l),n.edges.push({srcKey:t.moduleKey,dstKey:l.nodeKey,kind:"contains"});let u=o??e.childForFieldName("body")??e;r==="function"&&u&&Mt(n,l.nodeKey,u,mc)}s(pc,"addFunctionLike");function qi(e,t,n,r){let i=e.childForFieldName("name")?.text;if(!i)return;let o=ar(e,t,i,i,r);n.nodes.push(o),n.edges.push({srcKey:t.moduleKey,dstKey:o.nodeKey,kind:"contains"})}s(qi,"addSimpleNamed");function _y(e,t,n){let r=e.childForFieldName("name")?.text;if(!r)return;let i=ar(e,t,r,r,"class");n.nodes.push(i),n.edges.push({srcKey:t.moduleKey,dstKey:i.nodeKey,kind:"contains"});for(let a of e.descendantsOfType("class_heritage"))for(let c of a.namedChildren){let l=c.type==="implements_clause"?"implements":"extends";for(let u of c.descendantsOfType("type_identifier"))n.refs.push({fromKey:i.nodeKey,kind:l,targetName:u.text});for(let u of c.descendantsOfType("identifier"))n.refs.push({fromKey:i.nodeKey,kind:l,targetName:u.text})}let o=e.childForFieldName("body");if(o)for(let a of o.namedChildren){if(a.type!=="method_definition")continue;let c=a.childForFieldName("name")?.text;if(!c)continue;let l=`${r}.${c}`,u=ar(a,t,c,l,"method");n.nodes.push(u),n.edges.push({srcKey:i.nodeKey,dstKey:u.nodeKey,kind:"contains"});let d=a.childForFieldName("body");d&&Mt(n,u.nodeKey,d,mc)}}s(_y,"addClass");function ar(e,t,n,r,i){return{nodeKey:nr(t.filePath,r,i),kind:i,name:n,qualifiedName:r,filePath:t.filePath,language:t.language,startLine:Xe(e.startPosition.row),endLine:Xe(e.endPosition.row),startByte:e.startIndex,endByte:e.endIndex,signature:or(e),doc:null}}s(ar,"makeNode");function wy(e){return e.replace(/^["'`]|["'`]$/g,"")}s(wy,"stripQuotes");import{createRequire as ky}from"node:module";import{join as vy}from"node:path";var gc={typescript:"tree-sitter-typescript.wasm",tsx:"tree-sitter-tsx.wasm",javascript:"tree-sitter-javascript.wasm",python:"tree-sitter-python.wasm"},yc="tree-sitter.wasm";function bc(e,t){return t?vy(t,gc[e]):ky(import.meta.url).resolve(`tree-sitter-wasms/out/${gc[e]}`)}s(bc,"grammarPath");var Sy=["typescript","tsx","javascript","python"],cr=class{static{s(this,"TreeSitterParser")}initialized=!1;parser=null;grammars=new Map;assetDir;constructor(t={}){this.assetDir=t.assetDir}async init(){this.initialized||(await zi.init(this.assetDir?{locateFile:s(t=>xy(this.assetDir,t||yc),"locateFile")}:void 0),this.parser=new zi,this.initialized=!0)}supports(t){return Sy.includes(t)}async parse(t,n,r){await this.init();let i=this.parser;i.setLanguage(await this.grammar(r));let o=i.parse(n);if(!o)return{filePath:t,language:r,nodes:[],edges:[],refs:[],imports:[]};let a=o.rootNode,c=tr(t),l={nodeKey:c,kind:"module",name:t.split("/").pop()??t,qualifiedName:"<module>",filePath:t,language:r,startLine:1,endLine:Xe(a.endPosition.row),startByte:0,endByte:n.length,signature:null,doc:null},u={filePath:t,language:r,source:n,moduleKey:c},d=r==="python"?dc(a,u):hc(a,u);return o.delete(),{filePath:t,language:r,nodes:[l,...d.nodes],edges:d.edges,refs:d.refs,imports:d.imports}}async grammar(t){let n=this.grammars.get(t);return n||(n=await zi.Language.load(bc(t,this.assetDir)),this.grammars.set(t,n)),n}};import{readFileSync as zd}from"node:fs";import{posix as Yd}from"node:path";var p={};$g(p,{BRAND:()=>Xy,DIRTY:()=>pt,EMPTY_PATH:()=>$y,INVALID:()=>P,NEVER:()=>Nb,OK:()=>ce,ParseStatus:()=>ae,Schema:()=>K,ZodAny:()=>Qe,ZodArray:()=>Be,ZodBigInt:()=>ht,ZodBoolean:()=>gt,ZodBranded:()=>mn,ZodCatch:()=>At,ZodDate:()=>yt,ZodDefault:()=>Et,ZodDiscriminatedUnion:()=>dr,ZodEffects:()=>ke,ZodEnum:()=>St,ZodError:()=>de,ZodFirstPartyTypeKind:()=>M,ZodFunction:()=>pr,ZodIntersection:()=>kt,ZodIssueCode:()=>v,ZodLazy:()=>vt,ZodLiteral:()=>xt,ZodMap:()=>Ht,ZodNaN:()=>Vt,ZodNativeEnum:()=>Rt,ZodNever:()=>Re,ZodNull:()=>_t,ZodNullable:()=>Oe,ZodNumber:()=>mt,ZodObject:()=>fe,ZodOptional:()=>_e,ZodParsedType:()=>$,ZodPipeline:()=>hn,ZodPromise:()=>et,ZodReadonly:()=>$t,ZodRecord:()=>fr,ZodSchema:()=>K,ZodSet:()=>Gt,ZodString:()=>Je,ZodSymbol:()=>Bt,ZodTransformer:()=>ke,ZodTuple:()=>Ce,ZodType:()=>K,ZodUndefined:()=>bt,ZodUnion:()=>wt,ZodUnknown:()=>Ue,ZodVoid:()=>Kt,addIssueToContext:()=>A,any:()=>ob,array:()=>lb,bigint:()=>eb,boolean:()=>Tc,coerce:()=>Db,custom:()=>Ec,date:()=>tb,datetimeRegex:()=>Sc,defaultErrorMap:()=>Le,discriminatedUnion:()=>pb,effect:()=>Rb,enum:()=>vb,function:()=>_b,getErrorMap:()=>Lt,getParsedType:()=>Te,instanceof:()=>Jy,intersection:()=>mb,isAborted:()=>lr,isAsync:()=>Ft,isDirty:()=>ur,isValid:()=>Ze,late:()=>Zy,lazy:()=>wb,literal:()=>kb,makeIssue:()=>pn,map:()=>yb,nan:()=>Qy,nativeEnum:()=>xb,never:()=>ab,null:()=>ib,nullable:()=>Ab,number:()=>$c,object:()=>ub,objectUtil:()=>Yi,oboolean:()=>Ib,onumber:()=>Ob,optional:()=>Eb,ostring:()=>Cb,pipeline:()=>Tb,preprocess:()=>$b,promise:()=>Sb,quotelessJson:()=>Ry,record:()=>gb,set:()=>bb,setErrorMap:()=>Ay,strictObject:()=>db,string:()=>Ac,symbol:()=>nb,transformer:()=>Rb,tuple:()=>hb,undefined:()=>rb,union:()=>fb,unknown:()=>sb,util:()=>G,void:()=>cb});var G;(function(e){e.assertEqual=i=>{};function t(i){}s(t,"assertIs"),e.assertIs=t;function n(i){throw new Error}s(n,"assertNever"),e.assertNever=n,e.arrayToEnum=i=>{let o={};for(let a of i)o[a]=a;return o},e.getValidEnumValues=i=>{let o=e.objectKeys(i).filter(c=>typeof i[i[c]]!="number"),a={};for(let c of o)a[c]=i[c];return e.objectValues(a)},e.objectValues=i=>e.objectKeys(i).map(function(o){return i[o]}),e.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let o=[];for(let a in i)Object.prototype.hasOwnProperty.call(i,a)&&o.push(a);return o},e.find=(i,o)=>{for(let a of i)if(o(a))return a},e.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function r(i,o=" | "){return i.map(a=>typeof a=="string"?`'${a}'`:a).join(o)}s(r,"joinValues"),e.joinValues=r,e.jsonStringifyReplacer=(i,o)=>typeof o=="bigint"?o.toString():o})(G||(G={}));var Yi;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(Yi||(Yi={}));var $=G.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Te=s(e=>{switch(typeof e){case"undefined":return $.undefined;case"string":return $.string;case"number":return Number.isNaN(e)?$.nan:$.number;case"boolean":return $.boolean;case"function":return $.function;case"bigint":return $.bigint;case"symbol":return $.symbol;case"object":return Array.isArray(e)?$.array:e===null?$.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?$.promise:typeof Map<"u"&&e instanceof Map?$.map:typeof Set<"u"&&e instanceof Set?$.set:typeof Date<"u"&&e instanceof Date?$.date:$.object;default:return $.unknown}},"getParsedType");var v=G.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),Ry=s(e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),"quotelessJson"),de=class e extends Error{static{s(this,"ZodError")}get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}format(t){let n=t||function(o){return o.message},r={_errors:[]},i=s(o=>{for(let a of o.issues)if(a.code==="invalid_union")a.unionErrors.map(i);else if(a.code==="invalid_return_type")i(a.returnTypeError);else if(a.code==="invalid_arguments")i(a.argumentsError);else if(a.path.length===0)r._errors.push(n(a));else{let c=r,l=0;for(;l<a.path.length;){let u=a.path[l];l===a.path.length-1?(c[u]=c[u]||{_errors:[]},c[u]._errors.push(n(a))):c[u]=c[u]||{_errors:[]},c=c[u],l++}}},"processError");return i(this),r}static assert(t){if(!(t instanceof e))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,G.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=n=>n.message){let n={},r=[];for(let i of this.issues)if(i.path.length>0){let o=i.path[0];n[o]=n[o]||[],n[o].push(t(i))}else r.push(t(i));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};de.create=e=>new de(e);var Ey=s((e,t)=>{let n;switch(e.code){case v.invalid_type:e.received===$.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case v.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,G.jsonStringifyReplacer)}`;break;case v.unrecognized_keys:n=`Unrecognized key(s) in object: ${G.joinValues(e.keys,", ")}`;break;case v.invalid_union:n="Invalid input";break;case v.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${G.joinValues(e.options)}`;break;case v.invalid_enum_value:n=`Invalid enum value. Expected ${G.joinValues(e.options)}, received '${e.received}'`;break;case v.invalid_arguments:n="Invalid function arguments";break;case v.invalid_return_type:n="Invalid function return type";break;case v.invalid_date:n="Invalid date";break;case v.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:G.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case v.too_small:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:n="Invalid input";break;case v.too_big:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?n=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:n="Invalid input";break;case v.custom:n="Invalid input";break;case v.invalid_intersection_types:n="Intersection results could not be merged";break;case v.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case v.not_finite:n="Number must be finite";break;default:n=t.defaultError,G.assertNever(e)}return{message:n}},"errorMap"),Le=Ey;var _c=Le;function Ay(e){_c=e}s(Ay,"setErrorMap");function Lt(){return _c}s(Lt,"getErrorMap");var pn=s(e=>{let{data:t,path:n,errorMaps:r,issueData:i}=e,o=[...n,...i.path||[]],a={...i,path:o};if(i.message!==void 0)return{...i,path:o,message:i.message};let c="",l=r.filter(u=>!!u).slice().reverse();for(let u of l)c=u(a,{data:t,defaultError:c}).message;return{...i,path:o,message:c}},"makeIssue"),$y=[];function A(e,t){let n=Lt(),r=pn({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===Le?void 0:Le].filter(i=>!!i)});e.common.issues.push(r)}s(A,"addIssueToContext");var ae=class e{static{s(this,"ParseStatus")}constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){let r=[];for(let i of n){if(i.status==="aborted")return P;i.status==="dirty"&&t.dirty(),r.push(i.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){let r=[];for(let i of n){let o=await i.key,a=await i.value;r.push({key:o,value:a})}return e.mergeObjectSync(t,r)}static mergeObjectSync(t,n){let r={};for(let i of n){let{key:o,value:a}=i;if(o.status==="aborted"||a.status==="aborted")return P;o.status==="dirty"&&t.dirty(),a.status==="dirty"&&t.dirty(),o.value!=="__proto__"&&(typeof a.value<"u"||i.alwaysSet)&&(r[o.value]=a.value)}return{status:t.value,value:r}}},P=Object.freeze({status:"aborted"}),pt=s(e=>({status:"dirty",value:e}),"DIRTY"),ce=s(e=>({status:"valid",value:e}),"OK"),lr=s(e=>e.status==="aborted","isAborted"),ur=s(e=>e.status==="dirty","isDirty"),Ze=s(e=>e.status==="valid","isValid"),Ft=s(e=>typeof Promise<"u"&&e instanceof Promise,"isAsync");var D;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(D||(D={}));var we=class{static{s(this,"ParseInputLazyPath")}constructor(t,n,r,i){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=i}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},wc=s((e,t)=>{if(Ze(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let n=new de(e.common.issues);return this._error=n,this._error}}},"handleResult");function U(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:i}=e;if(t&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:i}:{errorMap:s((a,c)=>{let{message:l}=e;return a.code==="invalid_enum_value"?{message:l??c.defaultError}:typeof c.data>"u"?{message:l??r??c.defaultError}:a.code!=="invalid_type"?{message:c.defaultError}:{message:l??n??c.defaultError}},"customMap"),description:i}}s(U,"processCreateParams");var K=class{static{s(this,"ZodType")}get description(){return this._def.description}_getType(t){return Te(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:Te(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new ae,ctx:{common:t.parent.common,data:t.data,parsedType:Te(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let n=this._parse(t);if(Ft(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(t){let n=this._parse(t);return Promise.resolve(n)}parse(t,n){let r=this.safeParse(t,n);if(r.success)return r.data;throw r.error}safeParse(t,n){let r={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Te(t)},i=this._parseSync({data:t,path:r.path,parent:r});return wc(r,i)}"~validate"(t){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Te(t)};if(!this["~standard"].async)try{let r=this._parseSync({data:t,path:[],parent:n});return Ze(r)?{value:r.value}:{issues:n.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:n}).then(r=>Ze(r)?{value:r.value}:{issues:n.common.issues})}async parseAsync(t,n){let r=await this.safeParseAsync(t,n);if(r.success)return r.data;throw r.error}async safeParseAsync(t,n){let r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Te(t)},i=this._parse({data:t,path:r.path,parent:r}),o=await(Ft(i)?i:Promise.resolve(i));return wc(r,o)}refine(t,n){let r=s(i=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(i):n,"getIssueProperties");return this._refinement((i,o)=>{let a=t(i),c=s(()=>o.addIssue({code:v.custom,...r(i)}),"setError");return typeof Promise<"u"&&a instanceof Promise?a.then(l=>l?!0:(c(),!1)):a?!0:(c(),!1)})}refinement(t,n){return this._refinement((r,i)=>t(r)?!0:(i.addIssue(typeof n=="function"?n(r,i):n),!1))}_refinement(t){return new ke({schema:this,typeName:M.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:s(n=>this["~validate"](n),"validate")}}optional(){return _e.create(this,this._def)}nullable(){return Oe.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Be.create(this)}promise(){return et.create(this,this._def)}or(t){return wt.create([this,t],this._def)}and(t){return kt.create(this,t,this._def)}transform(t){return new ke({...U(this._def),schema:this,typeName:M.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let n=typeof t=="function"?t:()=>t;return new Et({...U(this._def),innerType:this,defaultValue:n,typeName:M.ZodDefault})}brand(){return new mn({typeName:M.ZodBranded,type:this,...U(this._def)})}catch(t){let n=typeof t=="function"?t:()=>t;return new At({...U(this._def),innerType:this,catchValue:n,typeName:M.ZodCatch})}describe(t){let n=this.constructor;return new n({...this._def,description:t})}pipe(t){return hn.create(this,t)}readonly(){return $t.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Ty=/^c[^\s-]{8,}$/i,Cy=/^[0-9a-z]+$/,Oy=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Iy=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Dy=/^[a-z0-9_-]{21}$/i,Ny=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,jy=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Py=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,My="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Xi,Ly=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Fy=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Uy=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,By=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Ky=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Hy=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,vc="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Gy=new RegExp(`^${vc}$`);function xc(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`);let n=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}s(xc,"timeRegexSource");function Vy(e){return new RegExp(`^${xc(e)}$`)}s(Vy,"timeRegex");function Sc(e){let t=`${vc}T${xc(e)}`,n=[];return n.push(e.local?"Z?":"Z"),e.offset&&n.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${n.join("|")})`,new RegExp(`^${t}$`)}s(Sc,"datetimeRegex");function Wy(e,t){return!!((t==="v4"||!t)&&Ly.test(e)||(t==="v6"||!t)&&Uy.test(e))}s(Wy,"isValidIP");function qy(e,t){if(!Ny.test(e))return!1;try{let[n]=e.split(".");if(!n)return!1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),i=JSON.parse(atob(r));return!(typeof i!="object"||i===null||"typ"in i&&i?.typ!=="JWT"||!i.alg||t&&i.alg!==t)}catch{return!1}}s(qy,"isValidJWT");function zy(e,t){return!!((t==="v4"||!t)&&Fy.test(e)||(t==="v6"||!t)&&By.test(e))}s(zy,"isValidCidr");var Je=class e extends K{static{s(this,"ZodString")}_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==$.string){let o=this._getOrReturnCtx(t);return A(o,{code:v.invalid_type,expected:$.string,received:o.parsedType}),P}let r=new ae,i;for(let o of this._def.checks)if(o.kind==="min")t.data.length<o.value&&(i=this._getOrReturnCtx(t,i),A(i,{code:v.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),r.dirty());else if(o.kind==="max")t.data.length>o.value&&(i=this._getOrReturnCtx(t,i),A(i,{code:v.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),r.dirty());else if(o.kind==="length"){let a=t.data.length>o.value,c=t.data.length<o.value;(a||c)&&(i=this._getOrReturnCtx(t,i),a?A(i,{code:v.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):c&&A(i,{code:v.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),r.dirty())}else if(o.kind==="email")Py.test(t.data)||(i=this._getOrReturnCtx(t,i),A(i,{validation:"email",code:v.invalid_string,message:o.message}),r.dirty());else if(o.kind==="emoji")Xi||(Xi=new RegExp(My,"u")),Xi.test(t.data)||(i=this._getOrReturnCtx(t,i),A(i,{validation:"emoji",code:v.invalid_string,message:o.message}),r.dirty());else if(o.kind==="uuid")Iy.test(t.data)||(i=this._getOrReturnCtx(t,i),A(i,{validation:"uuid",code:v.invalid_string,message:o.message}),r.dirty());else if(o.kind==="nanoid")Dy.test(t.data)||(i=this._getOrReturnCtx(t,i),A(i,{validation:"nanoid",code:v.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid")Ty.test(t.data)||(i=this._getOrReturnCtx(t,i),A(i,{validation:"cuid",code:v.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid2")Cy.test(t.data)||(i=this._getOrReturnCtx(t,i),A(i,{validation:"cuid2",code:v.invalid_string,message:o.message}),r.dirty());else if(o.kind==="ulid")Oy.test(t.data)||(i=this._getOrReturnCtx(t,i),A(i,{validation:"ulid",code:v.invalid_string,message:o.message}),r.dirty());else if(o.kind==="url")try{new URL(t.data)}catch{i=this._getOrReturnCtx(t,i),A(i,{validation:"url",code:v.invalid_string,message:o.message}),r.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(t.data)||(i=this._getOrReturnCtx(t,i),A(i,{validation:"regex",code:v.invalid_string,message:o.message}),r.dirty())):o.kind==="trim"?t.data=t.data.trim():o.kind==="includes"?t.data.includes(o.value,o.position)||(i=this._getOrReturnCtx(t,i),A(i,{code:v.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),r.dirty()):o.kind==="toLowerCase"?t.data=t.data.toLowerCase():o.kind==="toUpperCase"?t.data=t.data.toUpperCase():o.kind==="startsWith"?t.data.startsWith(o.value)||(i=this._getOrReturnCtx(t,i),A(i,{code:v.invalid_string,validation:{startsWith:o.value},message:o.message}),r.dirty()):o.kind==="endsWith"?t.data.endsWith(o.value)||(i=this._getOrReturnCtx(t,i),A(i,{code:v.invalid_string,validation:{endsWith:o.value},message:o.message}),r.dirty()):o.kind==="datetime"?Sc(o).test(t.data)||(i=this._getOrReturnCtx(t,i),A(i,{code:v.invalid_string,validation:"datetime",message:o.message}),r.dirty()):o.kind==="date"?Gy.test(t.data)||(i=this._getOrReturnCtx(t,i),A(i,{code:v.invalid_string,validation:"date",message:o.message}),r.dirty()):o.kind==="time"?Vy(o).test(t.data)||(i=this._getOrReturnCtx(t,i),A(i,{code:v.invalid_string,validation:"time",message:o.message}),r.dirty()):o.kind==="duration"?jy.test(t.data)||(i=this._getOrReturnCtx(t,i),A(i,{validation:"duration",code:v.invalid_string,message:o.message}),r.dirty()):o.kind==="ip"?Wy(t.data,o.version)||(i=this._getOrReturnCtx(t,i),A(i,{validation:"ip",code:v.invalid_string,message:o.message}),r.dirty()):o.kind==="jwt"?qy(t.data,o.alg)||(i=this._getOrReturnCtx(t,i),A(i,{validation:"jwt",code:v.invalid_string,message:o.message}),r.dirty()):o.kind==="cidr"?zy(t.data,o.version)||(i=this._getOrReturnCtx(t,i),A(i,{validation:"cidr",code:v.invalid_string,message:o.message}),r.dirty()):o.kind==="base64"?Ky.test(t.data)||(i=this._getOrReturnCtx(t,i),A(i,{validation:"base64",code:v.invalid_string,message:o.message}),r.dirty()):o.kind==="base64url"?Hy.test(t.data)||(i=this._getOrReturnCtx(t,i),A(i,{validation:"base64url",code:v.invalid_string,message:o.message}),r.dirty()):G.assertNever(o);return{status:r.value,value:t.data}}_regex(t,n,r){return this.refinement(i=>t.test(i),{validation:n,code:v.invalid_string,...D.errToObj(r)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...D.errToObj(t)})}url(t){return this._addCheck({kind:"url",...D.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...D.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...D.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...D.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...D.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...D.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...D.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...D.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...D.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...D.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...D.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...D.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...D.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...D.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...D.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...D.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n?.position,...D.errToObj(n?.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...D.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...D.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...D.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...D.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...D.errToObj(n)})}nonempty(t){return this.min(1,D.errToObj(t))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxLength(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}};Je.create=e=>new Je({checks:[],typeName:M.ZodString,coerce:e?.coerce??!1,...U(e)});function Yy(e,t){let n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,i=n>r?n:r,o=Number.parseInt(e.toFixed(i).replace(".","")),a=Number.parseInt(t.toFixed(i).replace(".",""));return o%a/10**i}s(Yy,"floatSafeRemainder");var mt=class e extends K{static{s(this,"ZodNumber")}constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==$.number){let o=this._getOrReturnCtx(t);return A(o,{code:v.invalid_type,expected:$.number,received:o.parsedType}),P}let r,i=new ae;for(let o of this._def.checks)o.kind==="int"?G.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),A(r,{code:v.invalid_type,expected:"integer",received:"float",message:o.message}),i.dirty()):o.kind==="min"?(o.inclusive?t.data<o.value:t.data<=o.value)&&(r=this._getOrReturnCtx(t,r),A(r,{code:v.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="max"?(o.inclusive?t.data>o.value:t.data>=o.value)&&(r=this._getOrReturnCtx(t,r),A(r,{code:v.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="multipleOf"?Yy(t.data,o.value)!==0&&(r=this._getOrReturnCtx(t,r),A(r,{code:v.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):o.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),A(r,{code:v.not_finite,message:o.message}),i.dirty()):G.assertNever(o);return{status:i.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,D.toString(n))}gt(t,n){return this.setLimit("min",t,!1,D.toString(n))}lte(t,n){return this.setLimit("max",t,!0,D.toString(n))}lt(t,n){return this.setLimit("max",t,!1,D.toString(n))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:D.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:D.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:D.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:D.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:D.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:D.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:D.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:D.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:D.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:D.toString(t)})}get minValue(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&G.isInteger(t.value))}get isFinite(){let t=null,n=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(t===null||r.value<t)&&(t=r.value)}return Number.isFinite(n)&&Number.isFinite(t)}};mt.create=e=>new mt({checks:[],typeName:M.ZodNumber,coerce:e?.coerce||!1,...U(e)});var ht=class e extends K{static{s(this,"ZodBigInt")}constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==$.bigint)return this._getInvalidInput(t);let r,i=new ae;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?t.data<o.value:t.data<=o.value)&&(r=this._getOrReturnCtx(t,r),A(r,{code:v.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="max"?(o.inclusive?t.data>o.value:t.data>=o.value)&&(r=this._getOrReturnCtx(t,r),A(r,{code:v.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="multipleOf"?t.data%o.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),A(r,{code:v.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):G.assertNever(o);return{status:i.value,value:t.data}}_getInvalidInput(t){let n=this._getOrReturnCtx(t);return A(n,{code:v.invalid_type,expected:$.bigint,received:n.parsedType}),P}gte(t,n){return this.setLimit("min",t,!0,D.toString(n))}gt(t,n){return this.setLimit("min",t,!1,D.toString(n))}lte(t,n){return this.setLimit("max",t,!0,D.toString(n))}lt(t,n){return this.setLimit("max",t,!1,D.toString(n))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:D.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:D.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:D.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:D.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:D.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:D.toString(n)})}get minValue(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}};ht.create=e=>new ht({checks:[],typeName:M.ZodBigInt,coerce:e?.coerce??!1,...U(e)});var gt=class extends K{static{s(this,"ZodBoolean")}_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==$.boolean){let r=this._getOrReturnCtx(t);return A(r,{code:v.invalid_type,expected:$.boolean,received:r.parsedType}),P}return ce(t.data)}};gt.create=e=>new gt({typeName:M.ZodBoolean,coerce:e?.coerce||!1,...U(e)});var yt=class e extends K{static{s(this,"ZodDate")}_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==$.date){let o=this._getOrReturnCtx(t);return A(o,{code:v.invalid_type,expected:$.date,received:o.parsedType}),P}if(Number.isNaN(t.data.getTime())){let o=this._getOrReturnCtx(t);return A(o,{code:v.invalid_date}),P}let r=new ae,i;for(let o of this._def.checks)o.kind==="min"?t.data.getTime()<o.value&&(i=this._getOrReturnCtx(t,i),A(i,{code:v.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),r.dirty()):o.kind==="max"?t.data.getTime()>o.value&&(i=this._getOrReturnCtx(t,i),A(i,{code:v.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),r.dirty()):G.assertNever(o);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:D.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:D.toString(n)})}get minDate(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t!=null?new Date(t):null}};yt.create=e=>new yt({checks:[],coerce:e?.coerce||!1,typeName:M.ZodDate,...U(e)});var Bt=class extends K{static{s(this,"ZodSymbol")}_parse(t){if(this._getType(t)!==$.symbol){let r=this._getOrReturnCtx(t);return A(r,{code:v.invalid_type,expected:$.symbol,received:r.parsedType}),P}return ce(t.data)}};Bt.create=e=>new Bt({typeName:M.ZodSymbol,...U(e)});var bt=class extends K{static{s(this,"ZodUndefined")}_parse(t){if(this._getType(t)!==$.undefined){let r=this._getOrReturnCtx(t);return A(r,{code:v.invalid_type,expected:$.undefined,received:r.parsedType}),P}return ce(t.data)}};bt.create=e=>new bt({typeName:M.ZodUndefined,...U(e)});var _t=class extends K{static{s(this,"ZodNull")}_parse(t){if(this._getType(t)!==$.null){let r=this._getOrReturnCtx(t);return A(r,{code:v.invalid_type,expected:$.null,received:r.parsedType}),P}return ce(t.data)}};_t.create=e=>new _t({typeName:M.ZodNull,...U(e)});var Qe=class extends K{static{s(this,"ZodAny")}constructor(){super(...arguments),this._any=!0}_parse(t){return ce(t.data)}};Qe.create=e=>new Qe({typeName:M.ZodAny,...U(e)});var Ue=class extends K{static{s(this,"ZodUnknown")}constructor(){super(...arguments),this._unknown=!0}_parse(t){return ce(t.data)}};Ue.create=e=>new Ue({typeName:M.ZodUnknown,...U(e)});var Re=class extends K{static{s(this,"ZodNever")}_parse(t){let n=this._getOrReturnCtx(t);return A(n,{code:v.invalid_type,expected:$.never,received:n.parsedType}),P}};Re.create=e=>new Re({typeName:M.ZodNever,...U(e)});var Kt=class extends K{static{s(this,"ZodVoid")}_parse(t){if(this._getType(t)!==$.undefined){let r=this._getOrReturnCtx(t);return A(r,{code:v.invalid_type,expected:$.void,received:r.parsedType}),P}return ce(t.data)}};Kt.create=e=>new Kt({typeName:M.ZodVoid,...U(e)});var Be=class e extends K{static{s(this,"ZodArray")}_parse(t){let{ctx:n,status:r}=this._processInputParams(t),i=this._def;if(n.parsedType!==$.array)return A(n,{code:v.invalid_type,expected:$.array,received:n.parsedType}),P;if(i.exactLength!==null){let a=n.data.length>i.exactLength.value,c=n.data.length<i.exactLength.value;(a||c)&&(A(n,{code:a?v.too_big:v.too_small,minimum:c?i.exactLength.value:void 0,maximum:a?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),r.dirty())}if(i.minLength!==null&&n.data.length<i.minLength.value&&(A(n,{code:v.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),r.dirty()),i.maxLength!==null&&n.data.length>i.maxLength.value&&(A(n,{code:v.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((a,c)=>i.type._parseAsync(new we(n,a,n.path,c)))).then(a=>ae.mergeArray(r,a));let o=[...n.data].map((a,c)=>i.type._parseSync(new we(n,a,n.path,c)));return ae.mergeArray(r,o)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:D.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:D.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:D.toString(n)}})}nonempty(t){return this.min(1,t)}};Be.create=(e,t)=>new Be({type:e,minLength:null,maxLength:null,exactLength:null,typeName:M.ZodArray,...U(t)});function Ut(e){if(e instanceof fe){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=_e.create(Ut(r))}return new fe({...e._def,shape:s(()=>t,"shape")})}else return e instanceof Be?new Be({...e._def,type:Ut(e.element)}):e instanceof _e?_e.create(Ut(e.unwrap())):e instanceof Oe?Oe.create(Ut(e.unwrap())):e instanceof Ce?Ce.create(e.items.map(t=>Ut(t))):e}s(Ut,"deepPartialify");var fe=class e extends K{static{s(this,"ZodObject")}constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let t=this._def.shape(),n=G.objectKeys(t);return this._cached={shape:t,keys:n},this._cached}_parse(t){if(this._getType(t)!==$.object){let u=this._getOrReturnCtx(t);return A(u,{code:v.invalid_type,expected:$.object,received:u.parsedType}),P}let{status:r,ctx:i}=this._processInputParams(t),{shape:o,keys:a}=this._getCached(),c=[];if(!(this._def.catchall instanceof Re&&this._def.unknownKeys==="strip"))for(let u in i.data)a.includes(u)||c.push(u);let l=[];for(let u of a){let d=o[u],f=i.data[u];l.push({key:{status:"valid",value:u},value:d._parse(new we(i,f,i.path,u)),alwaysSet:u in i.data})}if(this._def.catchall instanceof Re){let u=this._def.unknownKeys;if(u==="passthrough")for(let d of c)l.push({key:{status:"valid",value:d},value:{status:"valid",value:i.data[d]}});else if(u==="strict")c.length>0&&(A(i,{code:v.unrecognized_keys,keys:c}),r.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let d of c){let f=i.data[d];l.push({key:{status:"valid",value:d},value:u._parse(new we(i,f,i.path,d)),alwaysSet:d in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let u=[];for(let d of l){let f=await d.key,h=await d.value;u.push({key:f,value:h,alwaysSet:d.alwaysSet})}return u}).then(u=>ae.mergeObjectSync(r,u)):ae.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(t){return D.errToObj,new e({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:s((n,r)=>{let i=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:D.errToObj(t).message??i}:{message:i}},"errorMap")}:{}})}strip(){return new e({...this._def,unknownKeys:"strip"})}passthrough(){return new e({...this._def,unknownKeys:"passthrough"})}extend(t){return new e({...this._def,shape:s(()=>({...this._def.shape(),...t}),"shape")})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:s(()=>({...this._def.shape(),...t._def.shape()}),"shape"),typeName:M.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let r of G.objectKeys(t))t[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new e({...this._def,shape:s(()=>n,"shape")})}omit(t){let n={};for(let r of G.objectKeys(this.shape))t[r]||(n[r]=this.shape[r]);return new e({...this._def,shape:s(()=>n,"shape")})}deepPartial(){return Ut(this)}partial(t){let n={};for(let r of G.objectKeys(this.shape)){let i=this.shape[r];t&&!t[r]?n[r]=i:n[r]=i.optional()}return new e({...this._def,shape:s(()=>n,"shape")})}required(t){let n={};for(let r of G.objectKeys(this.shape))if(t&&!t[r])n[r]=this.shape[r];else{let o=this.shape[r];for(;o instanceof _e;)o=o._def.innerType;n[r]=o}return new e({...this._def,shape:s(()=>n,"shape")})}keyof(){return Rc(G.objectKeys(this.shape))}};fe.create=(e,t)=>new fe({shape:s(()=>e,"shape"),unknownKeys:"strip",catchall:Re.create(),typeName:M.ZodObject,...U(t)});fe.strictCreate=(e,t)=>new fe({shape:s(()=>e,"shape"),unknownKeys:"strict",catchall:Re.create(),typeName:M.ZodObject,...U(t)});fe.lazycreate=(e,t)=>new fe({shape:e,unknownKeys:"strip",catchall:Re.create(),typeName:M.ZodObject,...U(t)});var wt=class extends K{static{s(this,"ZodUnion")}_parse(t){let{ctx:n}=this._processInputParams(t),r=this._def.options;function i(o){for(let c of o)if(c.result.status==="valid")return c.result;for(let c of o)if(c.result.status==="dirty")return n.common.issues.push(...c.ctx.common.issues),c.result;let a=o.map(c=>new de(c.ctx.common.issues));return A(n,{code:v.invalid_union,unionErrors:a}),P}if(s(i,"handleResults"),n.common.async)return Promise.all(r.map(async o=>{let a={...n,common:{...n.common,issues:[]},parent:null};return{result:await o._parseAsync({data:n.data,path:n.path,parent:a}),ctx:a}})).then(i);{let o,a=[];for(let l of r){let u={...n,common:{...n.common,issues:[]},parent:null},d=l._parseSync({data:n.data,path:n.path,parent:u});if(d.status==="valid")return d;d.status==="dirty"&&!o&&(o={result:d,ctx:u}),u.common.issues.length&&a.push(u.common.issues)}if(o)return n.common.issues.push(...o.ctx.common.issues),o.result;let c=a.map(l=>new de(l));return A(n,{code:v.invalid_union,unionErrors:c}),P}}get options(){return this._def.options}};wt.create=(e,t)=>new wt({options:e,typeName:M.ZodUnion,...U(t)});var Fe=s(e=>e instanceof vt?Fe(e.schema):e instanceof ke?Fe(e.innerType()):e instanceof xt?[e.value]:e instanceof St?e.options:e instanceof Rt?G.objectValues(e.enum):e instanceof Et?Fe(e._def.innerType):e instanceof bt?[void 0]:e instanceof _t?[null]:e instanceof _e?[void 0,...Fe(e.unwrap())]:e instanceof Oe?[null,...Fe(e.unwrap())]:e instanceof mn||e instanceof $t?Fe(e.unwrap()):e instanceof At?Fe(e._def.innerType):[],"getDiscriminator"),dr=class e extends K{static{s(this,"ZodDiscriminatedUnion")}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==$.object)return A(n,{code:v.invalid_type,expected:$.object,received:n.parsedType}),P;let r=this.discriminator,i=n.data[r],o=this.optionsMap.get(i);return o?n.common.async?o._parseAsync({data:n.data,path:n.path,parent:n}):o._parseSync({data:n.data,path:n.path,parent:n}):(A(n,{code:v.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),P)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){let i=new Map;for(let o of n){let a=Fe(o.shape[t]);if(!a.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let c of a){if(i.has(c))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(c)}`);i.set(c,o)}}return new e({typeName:M.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...U(r)})}};function Zi(e,t){let n=Te(e),r=Te(t);if(e===t)return{valid:!0,data:e};if(n===$.object&&r===$.object){let i=G.objectKeys(t),o=G.objectKeys(e).filter(c=>i.indexOf(c)!==-1),a={...e,...t};for(let c of o){let l=Zi(e[c],t[c]);if(!l.valid)return{valid:!1};a[c]=l.data}return{valid:!0,data:a}}else if(n===$.array&&r===$.array){if(e.length!==t.length)return{valid:!1};let i=[];for(let o=0;o<e.length;o++){let a=e[o],c=t[o],l=Zi(a,c);if(!l.valid)return{valid:!1};i.push(l.data)}return{valid:!0,data:i}}else return n===$.date&&r===$.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}s(Zi,"mergeValues");var kt=class extends K{static{s(this,"ZodIntersection")}_parse(t){let{status:n,ctx:r}=this._processInputParams(t),i=s((o,a)=>{if(lr(o)||lr(a))return P;let c=Zi(o.value,a.value);return c.valid?((ur(o)||ur(a))&&n.dirty(),{status:n.value,value:c.data}):(A(r,{code:v.invalid_intersection_types}),P)},"handleParsed");return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([o,a])=>i(o,a)):i(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};kt.create=(e,t,n)=>new kt({left:e,right:t,typeName:M.ZodIntersection,...U(n)});var Ce=class e extends K{static{s(this,"ZodTuple")}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==$.array)return A(r,{code:v.invalid_type,expected:$.array,received:r.parsedType}),P;if(r.data.length<this._def.items.length)return A(r,{code:v.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),P;!this._def.rest&&r.data.length>this._def.items.length&&(A(r,{code:v.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let o=[...r.data].map((a,c)=>{let l=this._def.items[c]||this._def.rest;return l?l._parse(new we(r,a,r.path,c)):null}).filter(a=>!!a);return r.common.async?Promise.all(o).then(a=>ae.mergeArray(n,a)):ae.mergeArray(n,o)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};Ce.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ce({items:e,typeName:M.ZodTuple,rest:null,...U(t)})};var fr=class e extends K{static{s(this,"ZodRecord")}get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==$.object)return A(r,{code:v.invalid_type,expected:$.object,received:r.parsedType}),P;let i=[],o=this._def.keyType,a=this._def.valueType;for(let c in r.data)i.push({key:o._parse(new we(r,c,r.path,c)),value:a._parse(new we(r,r.data[c],r.path,c)),alwaysSet:c in r.data});return r.common.async?ae.mergeObjectAsync(n,i):ae.mergeObjectSync(n,i)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof K?new e({keyType:t,valueType:n,typeName:M.ZodRecord,...U(r)}):new e({keyType:Je.create(),valueType:t,typeName:M.ZodRecord,...U(n)})}},Ht=class extends K{static{s(this,"ZodMap")}get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==$.map)return A(r,{code:v.invalid_type,expected:$.map,received:r.parsedType}),P;let i=this._def.keyType,o=this._def.valueType,a=[...r.data.entries()].map(([c,l],u)=>({key:i._parse(new we(r,c,r.path,[u,"key"])),value:o._parse(new we(r,l,r.path,[u,"value"]))}));if(r.common.async){let c=new Map;return Promise.resolve().then(async()=>{for(let l of a){let u=await l.key,d=await l.value;if(u.status==="aborted"||d.status==="aborted")return P;(u.status==="dirty"||d.status==="dirty")&&n.dirty(),c.set(u.value,d.value)}return{status:n.value,value:c}})}else{let c=new Map;for(let l of a){let u=l.key,d=l.value;if(u.status==="aborted"||d.status==="aborted")return P;(u.status==="dirty"||d.status==="dirty")&&n.dirty(),c.set(u.value,d.value)}return{status:n.value,value:c}}}};Ht.create=(e,t,n)=>new Ht({valueType:t,keyType:e,typeName:M.ZodMap,...U(n)});var Gt=class e extends K{static{s(this,"ZodSet")}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==$.set)return A(r,{code:v.invalid_type,expected:$.set,received:r.parsedType}),P;let i=this._def;i.minSize!==null&&r.data.size<i.minSize.value&&(A(r,{code:v.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),n.dirty()),i.maxSize!==null&&r.data.size>i.maxSize.value&&(A(r,{code:v.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),n.dirty());let o=this._def.valueType;function a(l){let u=new Set;for(let d of l){if(d.status==="aborted")return P;d.status==="dirty"&&n.dirty(),u.add(d.value)}return{status:n.value,value:u}}s(a,"finalizeSet");let c=[...r.data.values()].map((l,u)=>o._parse(new we(r,l,r.path,u)));return r.common.async?Promise.all(c).then(l=>a(l)):a(c)}min(t,n){return new e({...this._def,minSize:{value:t,message:D.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:D.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}};Gt.create=(e,t)=>new Gt({valueType:e,minSize:null,maxSize:null,typeName:M.ZodSet,...U(t)});var pr=class e extends K{static{s(this,"ZodFunction")}constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==$.function)return A(n,{code:v.invalid_type,expected:$.function,received:n.parsedType}),P;function r(c,l){return pn({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Lt(),Le].filter(u=>!!u),issueData:{code:v.invalid_arguments,argumentsError:l}})}s(r,"makeArgsIssue");function i(c,l){return pn({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Lt(),Le].filter(u=>!!u),issueData:{code:v.invalid_return_type,returnTypeError:l}})}s(i,"makeReturnsIssue");let o={errorMap:n.common.contextualErrorMap},a=n.data;if(this._def.returns instanceof et){let c=this;return ce(async function(...l){let u=new de([]),d=await c._def.args.parseAsync(l,o).catch(m=>{throw u.addIssue(r(l,m)),u}),f=await Reflect.apply(a,this,d);return await c._def.returns._def.type.parseAsync(f,o).catch(m=>{throw u.addIssue(i(f,m)),u})})}else{let c=this;return ce(function(...l){let u=c._def.args.safeParse(l,o);if(!u.success)throw new de([r(l,u.error)]);let d=Reflect.apply(a,this,u.data),f=c._def.returns.safeParse(d,o);if(!f.success)throw new de([i(d,f.error)]);return f.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:Ce.create(t).rest(Ue.create())})}returns(t){return new e({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,r){return new e({args:t||Ce.create([]).rest(Ue.create()),returns:n||Ue.create(),typeName:M.ZodFunction,...U(r)})}},vt=class extends K{static{s(this,"ZodLazy")}get schema(){return this._def.getter()}_parse(t){let{ctx:n}=this._processInputParams(t);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};vt.create=(e,t)=>new vt({getter:e,typeName:M.ZodLazy,...U(t)});var xt=class extends K{static{s(this,"ZodLiteral")}_parse(t){if(t.data!==this._def.value){let n=this._getOrReturnCtx(t);return A(n,{received:n.data,code:v.invalid_literal,expected:this._def.value}),P}return{status:"valid",value:t.data}}get value(){return this._def.value}};xt.create=(e,t)=>new xt({value:e,typeName:M.ZodLiteral,...U(t)});function Rc(e,t){return new St({values:e,typeName:M.ZodEnum,...U(t)})}s(Rc,"createZodEnum");var St=class e extends K{static{s(this,"ZodEnum")}_parse(t){if(typeof t.data!="string"){let n=this._getOrReturnCtx(t),r=this._def.values;return A(n,{expected:G.joinValues(r),received:n.parsedType,code:v.invalid_type}),P}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){let n=this._getOrReturnCtx(t),r=this._def.values;return A(n,{received:n.data,code:v.invalid_enum_value,options:r}),P}return ce(t.data)}get options(){return this._def.values}get enum(){let t={};for(let n of this._def.values)t[n]=n;return t}get Values(){let t={};for(let n of this._def.values)t[n]=n;return t}get Enum(){let t={};for(let n of this._def.values)t[n]=n;return t}extract(t,n=this._def){return e.create(t,{...this._def,...n})}exclude(t,n=this._def){return e.create(this.options.filter(r=>!t.includes(r)),{...this._def,...n})}};St.create=Rc;var Rt=class extends K{static{s(this,"ZodNativeEnum")}_parse(t){let n=G.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==$.string&&r.parsedType!==$.number){let i=G.objectValues(n);return A(r,{expected:G.joinValues(i),received:r.parsedType,code:v.invalid_type}),P}if(this._cache||(this._cache=new Set(G.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let i=G.objectValues(n);return A(r,{received:r.data,code:v.invalid_enum_value,options:i}),P}return ce(t.data)}get enum(){return this._def.values}};Rt.create=(e,t)=>new Rt({values:e,typeName:M.ZodNativeEnum,...U(t)});var et=class extends K{static{s(this,"ZodPromise")}unwrap(){return this._def.type}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==$.promise&&n.common.async===!1)return A(n,{code:v.invalid_type,expected:$.promise,received:n.parsedType}),P;let r=n.parsedType===$.promise?n.data:Promise.resolve(n.data);return ce(r.then(i=>this._def.type.parseAsync(i,{path:n.path,errorMap:n.common.contextualErrorMap})))}};et.create=(e,t)=>new et({type:e,typeName:M.ZodPromise,...U(t)});var ke=class extends K{static{s(this,"ZodEffects")}innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===M.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:n,ctx:r}=this._processInputParams(t),i=this._def.effect||null,o={addIssue:s(a=>{A(r,a),a.fatal?n.abort():n.dirty()},"addIssue"),get path(){return r.path}};if(o.addIssue=o.addIssue.bind(o),i.type==="preprocess"){let a=i.transform(r.data,o);if(r.common.async)return Promise.resolve(a).then(async c=>{if(n.value==="aborted")return P;let l=await this._def.schema._parseAsync({data:c,path:r.path,parent:r});return l.status==="aborted"?P:l.status==="dirty"?pt(l.value):n.value==="dirty"?pt(l.value):l});{if(n.value==="aborted")return P;let c=this._def.schema._parseSync({data:a,path:r.path,parent:r});return c.status==="aborted"?P:c.status==="dirty"?pt(c.value):n.value==="dirty"?pt(c.value):c}}if(i.type==="refinement"){let a=s(c=>{let l=i.refinement(c,o);if(r.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return c},"executeRefinement");if(r.common.async===!1){let c=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return c.status==="aborted"?P:(c.status==="dirty"&&n.dirty(),a(c.value),{status:n.value,value:c.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(c=>c.status==="aborted"?P:(c.status==="dirty"&&n.dirty(),a(c.value).then(()=>({status:n.value,value:c.value}))))}if(i.type==="transform")if(r.common.async===!1){let a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Ze(a))return P;let c=i.transform(a.value,o);if(c instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:c}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>Ze(a)?Promise.resolve(i.transform(a.value,o)).then(c=>({status:n.value,value:c})):P);G.assertNever(i)}};ke.create=(e,t,n)=>new ke({schema:e,typeName:M.ZodEffects,effect:t,...U(n)});ke.createWithPreprocess=(e,t,n)=>new ke({schema:t,effect:{type:"preprocess",transform:e},typeName:M.ZodEffects,...U(n)});var _e=class extends K{static{s(this,"ZodOptional")}_parse(t){return this._getType(t)===$.undefined?ce(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};_e.create=(e,t)=>new _e({innerType:e,typeName:M.ZodOptional,...U(t)});var Oe=class extends K{static{s(this,"ZodNullable")}_parse(t){return this._getType(t)===$.null?ce(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Oe.create=(e,t)=>new Oe({innerType:e,typeName:M.ZodNullable,...U(t)});var Et=class extends K{static{s(this,"ZodDefault")}_parse(t){let{ctx:n}=this._processInputParams(t),r=n.data;return n.parsedType===$.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};Et.create=(e,t)=>new Et({innerType:e,typeName:M.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...U(t)});var At=class extends K{static{s(this,"ZodCatch")}_parse(t){let{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},i=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return Ft(i)?i.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new de(r.common.issues)},input:r.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new de(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};At.create=(e,t)=>new At({innerType:e,typeName:M.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...U(t)});var Vt=class extends K{static{s(this,"ZodNaN")}_parse(t){if(this._getType(t)!==$.nan){let r=this._getOrReturnCtx(t);return A(r,{code:v.invalid_type,expected:$.nan,received:r.parsedType}),P}return{status:"valid",value:t.data}}};Vt.create=e=>new Vt({typeName:M.ZodNaN,...U(e)});var Xy=Symbol("zod_brand"),mn=class extends K{static{s(this,"ZodBranded")}_parse(t){let{ctx:n}=this._processInputParams(t),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}},hn=class e extends K{static{s(this,"ZodPipeline")}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return s(async()=>{let o=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?P:o.status==="dirty"?(n.dirty(),pt(o.value)):this._def.out._parseAsync({data:o.value,path:r.path,parent:r})},"handleAsync")();{let i=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?P:i.status==="dirty"?(n.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:r.path,parent:r})}}static create(t,n){return new e({in:t,out:n,typeName:M.ZodPipeline})}},$t=class extends K{static{s(this,"ZodReadonly")}_parse(t){let n=this._def.innerType._parse(t),r=s(i=>(Ze(i)&&(i.value=Object.freeze(i.value)),i),"freeze");return Ft(n)?n.then(i=>r(i)):r(n)}unwrap(){return this._def.innerType}};$t.create=(e,t)=>new $t({innerType:e,typeName:M.ZodReadonly,...U(t)});function kc(e,t){let n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}s(kc,"cleanParams");function Ec(e,t={},n){return e?Qe.create().superRefine((r,i)=>{let o=e(r);if(o instanceof Promise)return o.then(a=>{if(!a){let c=kc(t,r),l=c.fatal??n??!0;i.addIssue({code:"custom",...c,fatal:l})}});if(!o){let a=kc(t,r),c=a.fatal??n??!0;i.addIssue({code:"custom",...a,fatal:c})}}):Qe.create()}s(Ec,"custom");var Zy={object:fe.lazycreate},M;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(M||(M={}));var Jy=s((e,t={message:`Input not instance of ${e.name}`})=>Ec(n=>n instanceof e,t),"instanceOfType"),Ac=Je.create,$c=mt.create,Qy=Vt.create,eb=ht.create,Tc=gt.create,tb=yt.create,nb=Bt.create,rb=bt.create,ib=_t.create,ob=Qe.create,sb=Ue.create,ab=Re.create,cb=Kt.create,lb=Be.create,ub=fe.create,db=fe.strictCreate,fb=wt.create,pb=dr.create,mb=kt.create,hb=Ce.create,gb=fr.create,yb=Ht.create,bb=Gt.create,_b=pr.create,wb=vt.create,kb=xt.create,vb=St.create,xb=Rt.create,Sb=et.create,Rb=ke.create,Eb=_e.create,Ab=Oe.create,$b=ke.createWithPreprocess,Tb=hn.create,Cb=s(()=>Ac().optional(),"ostring"),Ob=s(()=>$c().optional(),"onumber"),Ib=s(()=>Tc().optional(),"oboolean"),Db={string:s(e=>Je.create({...e,coerce:!0}),"string"),number:s(e=>mt.create({...e,coerce:!0}),"number"),boolean:s(e=>gt.create({...e,coerce:!0}),"boolean"),bigint:s(e=>ht.create({...e,coerce:!0}),"bigint"),date:s(e=>yt.create({...e,coerce:!0}),"date")};var Nb=P;var Ji=p.object({id:p.string().min(1),title:p.string().min(1).max(200),type:p.enum(["debugging_lesson","workflow_best_practice","convention","recipe","template"]),tier:p.enum(["community","curated"]),lesson_class:p.enum(["general","architecture"]).default("general"),quality_tier:p.enum(["hand-vetted","bulk-migrated","experimental"]).default("hand-vetted"),provenance:p.object({source:p.enum(["memory","vault","claude-md"]),source_id:p.string().min(1),migrated_at:p.string(),migrated_from_workspace:p.string().optional()}).optional(),context:p.object({tools:p.array(p.string()).default([]),languages:p.array(p.string()).default([]),platforms:p.array(p.string()).default([]),tags:p.array(p.string()).default([])}),summary:p.string().min(1).max(500),problem:p.string().optional(),solution:p.string().optional(),gotchas:p.array(p.string()).default([]),template_body:p.string().min(1).optional(),target_file:p.string().min(1).optional(),submitted_by:p.string().optional(),evidence:p.string().optional(),last_validated_at:p.string().optional(),tool_versions:p.record(p.string(),p.string()).optional(),upvotes:p.number().int().nonnegative().default(0),version:p.number().int().min(1).default(1),changed_at:p.string().optional(),changelog:p.string().max(500).optional(),revision_of:p.string().optional(),org_id:p.string().uuid().optional(),org_name:p.string().optional(),scope:p.literal("private").optional(),body:p.string().min(1)}).superRefine((e,t)=>{e.type==="template"&&(e.template_body||t.addIssue({code:p.ZodIssueCode.custom,path:["template_body"],message:"type=template requires non-empty template_body"}),e.target_file||t.addIssue({code:p.ZodIssueCode.custom,path:["target_file"],message:"type=template requires target_file (e.g. CLAUDE.md, AGENTS.md, .cursorrules)"}))});var jb=Ji.superRefine((e,t)=>{e.type!=="template"&&t.addIssue({code:p.ZodIssueCode.custom,path:["type"],message:'Template requires type === "template"'}),(!e.template_body||e.template_body.length===0)&&t.addIssue({code:p.ZodIssueCode.custom,path:["template_body"],message:"template_body is required and must be non-empty"}),(!e.target_file||e.target_file.length===0)&&t.addIssue({code:p.ZodIssueCode.custom,path:["target_file"],message:"target_file is required (e.g. CLAUDE.md, AGENTS.md, .cursorrules)"}),e.tier!=="curated"&&t.addIssue({code:p.ZodIssueCode.custom,path:["tier"],message:'Template tier must be "curated" (templates/ is curated-only by repo convention)'})});var Cc=["claude-code","claude-desktop","codex","copilot","cursor","windsurf","gemini-cli","zed","generic"],Oc=p.enum(Cc),Ic=["new_to_ai_agents","new_to_this_client","experienced"],Dc=p.enum(Ic),Qi=[{id:"model-selection",header:"Model selection"},{id:"effort-levels",header:"Effort levels"},{id:"modes",header:"Modes"},{id:"language",header:"Language"},{id:"context-economy",header:"Context economy"},{id:"permissions",header:"Permissions"},{id:"cost",header:"Cost"},{id:"hooks",header:"Hooks"},{id:"learnings",header:"Learnings"},{id:"mcp-snippet",header:"MCP snippet"},{id:"first-week",header:"First week"}],Nc=Qi.map(e=>e.header),jc=p.object({experience_level:p.array(Dc).default([]),stack_filters:p.array(p.string()).default([])}).default({experience_level:[],stack_filters:[]}),Pc=p.object({id:p.string().min(1),client:Oc,title:p.string().min(1),last_updated:p.string().regex(/^\d{4}-\d{2}-\d{2}$/,"last_updated must be ISO date YYYY-MM-DD"),applies_to:jc,version:p.number().int().min(1).default(1),changelog:p.string().max(500).optional()}),Pb=Pc.extend({body:p.string().min(1)});var Lc=["operating_procedure","code_review","communication_style"],mr=p.enum(Lc),Fc=["info","recommended","required"],hr=p.enum(Fc),Mb=["optional","default_on","mandatory"],Lb=p.enum(Mb),Uc=["claude-code","claude-desktop","copilot","cursor","windsurf","generic"],Bc=p.enum(Uc),Kc=["verify","contribute","mixed"],Hc=p.enum(Kc),gr=p.object({clients:p.array(Bc).default([]),stacks:p.array(p.string()).default([]),intents:p.array(Hc).default([])}).default({clients:[],stacks:[],intents:[]}),Fb=/^conv_[a-z0-9]+(_[a-z0-9]+)*$/,Ub=64,Mc=200,Bb=p.preprocess(e=>e instanceof Date&&!Number.isNaN(e.getTime())?e.toISOString().slice(0,10):e,p.string().regex(/^\d{4}-\d{2}-\d{2}$/,"changed_at must be ISO date YYYY-MM-DD")),Gc=p.object({id:p.string().min(5).max(Ub).regex(Fb,"id must match conv_<lowercase_alphanum_underscore>"),title:p.string().min(1).max(200),scope:mr,version:p.number().int().min(1),changed_at:Bb,changelog:p.string().max(500).optional(),applies_to:gr,severity:hr.default("recommended"),disableability:Lb.default("default_on"),summary:p.string().min(1).max(Mc,`summary must be \u2264 ${Mc} chars (rendered as one line in init-push)`),review_gate:p.object({enabled:p.boolean(),min_matched_symbols:p.number().int().min(1).max(8).default(2),hard:p.boolean().default(!1)}).optional(),gateway_gate:p.object({enabled:p.boolean(),deny_tools:p.array(p.string().min(1).max(128)).min(1).max(16),servers:p.array(p.string().min(1).max(64)).min(1).max(8).optional()}).optional()}),Kb=Gc.extend({body:p.string().min(1)});var eo=p.object({type:p.literal("text"),md:p.string().min(1).max(2e4)}),yr=p.number().min(0).max(1).optional(),to=p.object({type:p.literal("media"),kind:p.enum(["image","video"]),url:p.string().url().max(2048),alt:p.string().max(500).optional(),caption:p.string().max(500).optional(),fog:p.object({top:yr,right:yr,bottom:yr,left:yr}).optional()}),Vc=p.object({label:p.string().min(1).max(40),color:p.string().regex(/^#[0-9a-fA-F]{6}$/,"color must be a 6-digit hex like #a855f7")}),Wc=p.object({type:p.literal("accordion"),title:p.string().min(1).max(200),subtag:Vc.optional(),blocks:p.array(p.discriminatedUnion("type",[eo,to])).max(50)}),qc=p.discriminatedUnion("type",[eo,to,Wc]),Hb=p.array(qc).max(100);var zc=["free","solo_pro","team","enterprise"],Gb=p.enum(zc);var Yc=["solo_pro","team","enterprise"],Xc=p.enum(Yc),Vb=p.string().refine(e=>!Number.isNaN(Date.parse(e)),"must be ISO datetime"),Wb=p.object({user_id:p.string().uuid(),tier:Xc,reason:p.string().min(10,"Begr\xFCndung muss mindestens 10 Zeichen lang sein").max(500,"Begr\xFCndung darf maximal 500 Zeichen lang sein"),effective_until:Vb.nullable().optional(),auto_revoke_on_stripe:p.boolean().optional().default(!1)}).refine(e=>e.effective_until==null?!0:new Date(e.effective_until).getTime()>Date.now(),{path:["effective_until"],message:"Ablaufdatum muss in der Zukunft liegen"}),qb=p.object({override_id:p.string().uuid(),reason:p.string().min(3).max(200).optional()});var zb=p.string().refine(e=>!Number.isNaN(Date.parse(e)),"must be ISO datetime"),Yb=p.object({org_id:p.string().uuid(),seats:p.number().int("Seats m\xFCssen eine ganze Zahl sein").min(2,"Seats m\xFCssen mindestens 2 sein (1 entspricht dem Default ohne Override)"),reason:p.string().min(10,"Begr\xFCndung muss mindestens 10 Zeichen lang sein").max(500,"Begr\xFCndung darf maximal 500 Zeichen lang sein"),effective_until:zb.nullable().optional(),auto_revoke_on_stripe:p.boolean().optional().default(!1)}).refine(e=>e.effective_until==null?!0:new Date(e.effective_until).getTime()>Date.now(),{path:["effective_until"],message:"Ablaufdatum muss in der Zukunft liegen"}),Xb=p.object({override_id:p.string().uuid(),reason:p.string().min(3).max(200).optional()});var Zc=p.enum(["info","important","critical"]),Zb=p.enum(["pass","warn","fail"]),Jc=p.object({type:p.enum(["template","lesson"]),id:p.string().min(1)}),Qc=p.object({languages:p.array(p.string()).optional(),tools:p.array(p.string()).optional()}).optional(),el=p.discriminatedUnion("kind",[p.object({kind:p.literal("file-exists"),path:p.string().min(1)}),p.object({kind:p.literal("any-file-exists"),paths:p.array(p.string().min(1)).min(1)}),p.object({kind:p.literal("any-agent-config")}),p.object({kind:p.literal("file-size-budget"),field:p.enum(["claude_md","readme"]),max_chars:p.number().int().positive()}),p.object({kind:p.literal("readme-section-present"),headers:p.array(p.string().min(1)).min(1)}),p.object({kind:p.literal("adr-dir-present")}),p.object({kind:p.literal("git-present")}),p.object({kind:p.literal("quality-gates-configured"),pass_if_at_least:p.number().int().min(1).max(4).optional(),warn_if_at_least:p.number().int().min(0).max(4).optional()}),p.object({kind:p.literal("storage-risk-safe"),allow_unknown:p.boolean().optional()}),p.object({kind:p.literal("doc-path-discoverability")})]),tl=p.object({id:p.string().min(1),title:p.string().min(1),severity:Zc,weight:p.number().int().positive().max(100),applies_when:Qc,check:el,fail_message:p.string().min(1),warn_message:p.string().optional(),remediation:Jc.optional()}),Jb=p.object({version:p.literal(1),checks:p.array(tl).min(1)});var Qb=/^\d{4}-\d{2}-\d{2}$/;function e_(e){if(!Qb.test(e))return!1;let t=new Date(`${e}T00:00:00Z`);return!Number.isNaN(t.getTime())&&t.toISOString().slice(0,10)===e}s(e_,"isRealDate");var _r=p.string().refine(e_,{message:"expected a real calendar date as YYYY-MM-DD"}),nl=["exact","prefix"],rl=p.enum(nl),Ie=p.number().finite().min(0).refine(e=>Number.isInteger(e*1e4),{message:"at most four decimal places (NUMERIC(10,4))"}),il=p.object({model_pattern:p.string().min(1).max(100),match_kind:rl,valid_from:_r,valid_to:_r.nullable().optional(),input:Ie,output:Ie,cache_read:Ie,cache_write_5m:Ie,cache_write_1h:Ie,long_context:p.enum(["same_price","tiered"]).optional(),input_above_200k:Ie.optional(),output_above_200k:Ie.optional(),cache_read_above_200k:Ie.optional(),cache_write_5m_above_200k:Ie.optional(),cache_write_1h_above_200k:Ie.optional(),context_threshold_tokens:p.number().int().positive().nullable().optional(),source_url:p.string().url().max(500).nullable().optional(),note:p.string().max(500).nullable().optional()}).strict().refine(e=>!e.valid_to||e.valid_to>e.valid_from,{message:"valid_to must be after valid_from",path:["valid_to"]}).refine(e=>br(e)===0||br(e)===5,{message:"above-200k rates must be given for all five classes or none",path:["input_above_200k"]}).refine(e=>e.long_context==="tiered"||br(e)===0,{message:'above-200k rates require long_context: "tiered"',path:["long_context"]}).refine(e=>e.context_threshold_tokens==null||e.long_context==="tiered",{message:'context_threshold_tokens requires long_context: "tiered"',path:["context_threshold_tokens"]}).refine(e=>br(e)===0||e.context_threshold_tokens==null||e.context_threshold_tokens===2e5,{message:"above-rates are only supported at context_threshold_tokens: 200000 \u2014 the analyzer groups against that constant and cannot see another boundary",path:["context_threshold_tokens"]});function br(e){return[e.input_above_200k,e.output_above_200k,e.cache_read_above_200k,e.cache_write_5m_above_200k,e.cache_write_1h_above_200k].filter(t=>t!==void 0).length}s(br,"aboveRateCount");function t_(e){return`${e.model_pattern}|${e.match_kind}|${e.valid_from}`}s(t_,"rowKey");var n_=p.object({changelog:p.string().min(1).max(500),as_of:_r,source_url:p.string().url().max(500),rows:p.array(il).min(1)}).strict().superRefine((e,t)=>{let n=new Map;e.rows.forEach((i,o)=>{let a=t_(i),c=n.get(a);c!==void 0?t.addIssue({code:p.ZodIssueCode.custom,path:["rows",o],message:`duplicate key ${a} (first at rows[${c}])`}):n.set(a,o)});let r=new Map;e.rows.forEach((i,o)=>{let a=`${i.model_pattern}|${i.match_kind}`,c=r.get(a)??[];c.push({i:o,r:i}),r.set(a,c)});for(let i of r.values())if(!(i.length<2)){i.sort((o,a)=>o.r.valid_from.localeCompare(a.r.valid_from));for(let o=0;o<i.length-1;o++){let a=i[o],c=i[o+1];(!a.r.valid_to||a.r.valid_to>c.r.valid_from)&&t.addIssue({code:p.ZodIssueCode.custom,path:["rows",a.i,"valid_to"],message:`window overlaps the next one for ${a.r.model_pattern} (${a.r.match_kind}): must close on or before ${c.r.valid_from}`})}}});var k_=/^skill_[a-z0-9]+(_[a-z0-9]+)*$/,v_=64,cl=200,x_=1e3,ll=p.preprocess(e=>e instanceof Date&&!Number.isNaN(e.getTime())?e.toISOString().slice(0,10):e,p.string().regex(/^\d{4}-\d{2}-\d{2}$/,"changed_at must be ISO date YYYY-MM-DD")),no=p.enum(["low","medium","high"]),ul=p.object({owner:p.string().min(1).max(160).optional(),risk_level:no.optional(),reviewed_at:ll.optional()}).default({}),dl=p.object({tags:p.array(p.string()).default([]),platforms:p.array(p.string()).default([]),tools:p.array(p.string()).default([]),languages:p.array(p.string()).default([]),limit:p.number().int().min(1).max(15).default(8)}).default({tags:[],platforms:[],tools:[],languages:[],limit:8}),fl=p.object({lesson_query:dl,lesson_pins:p.array(p.string()).default([]),lesson_excludes:p.array(p.string()).default([]),convention_ids:p.array(p.string()).default([]),template_ids:p.array(p.string()).default([]),setup_guide_ids:p.array(p.string()).default([])}).default({lesson_query:{tags:[],platforms:[],tools:[],languages:[],limit:8},lesson_pins:[],lesson_excludes:[],convention_ids:[],template_ids:[],setup_guide_ids:[]}),pl=p.object({id:p.string().min(6).max(v_).regex(k_,"id must match skill_<lowercase_alphanum_underscore>"),title:p.string().min(1).max(200),version:p.number().int().min(1),changed_at:ll,tier:p.enum(["community","curated"]).default("curated"),summary:p.string().min(1).max(cl,`summary must be \u2264 ${cl} chars (rendered as one line in skill_index)`),description:p.string().max(x_).optional(),applies_to:gr,membership:fl,governance:ul}),S_=pl.extend({body:p.string().default(""),org_id:p.string().uuid().optional(),org_name:p.string().optional()});var ml=p.enum(["maind","agent-skill"]),hl=p.enum(["ready","needs_attention","blocked"]),gl=p.enum(["info","important","critical"]),yl=p.enum(["pass","warn","fail"]),bl=p.enum(["structure","governance","scope","membership","package","references"]),_l=p.object({id:p.string().min(1),title:p.string().min(1),status:yl,severity:gl,category:bl,field:p.string().nullable().optional(),message:p.string().min(1),hint:p.string().optional()}),R_=p.object({lesson_ids:p.array(p.string()).optional(),convention_ids:p.array(p.string()).optional(),template_ids:p.array(p.string()).optional(),setup_guide_ids:p.array(p.string()).optional()}).default({}),wl=p.object({name:p.string().min(1).max(64),description:p.string().min(1).max(1024),license:p.string().optional(),compatibility:p.union([p.string(),p.array(p.string())]).optional(),metadata:p.record(p.string()).default({}),"allowed-tools":p.union([p.string(),p.array(p.string())]).optional()}).passthrough(),E_=p.object({directory_name:p.string().min(1).max(120).optional(),frontmatter:wl,body:p.string().default(""),file_listing:p.array(p.string()).optional()}),A_=p.object({format:ml,subject:p.string().min(1),status:hl,summary:p.string().min(1),counts:p.object({pass:p.number().int().min(0),warn:p.number().int().min(0),fail:p.number().int().min(0)}),checks:p.array(_l),next_steps:p.array(p.string()),trust_note:p.string().min(1)});function yn(e){if(e===null)return"null";switch(typeof e){case"string":return JSON.stringify(e);case"boolean":return e?"true":"false";case"number":if(!Number.isFinite(e))throw new Error("canonicalJson: non-finite number is not representable");return JSON.stringify(e);case"object":break;default:throw new Error(`canonicalJson: unsupported type '${typeof e}'`)}if(Array.isArray(e))return`[${e.map(o=>{if(o===void 0)throw new Error("canonicalJson: undefined array element is not representable");return yn(o)}).join(",")}]`;let t=e;return`{${Object.keys(t).filter(i=>t[i]!==void 0).sort().map(i=>`${JSON.stringify(i)}:${yn(t[i])}`).join(",")}}`}s(yn,"canonicalJson");var vl=["sql_migration_added","security_definer_touched","rls_policy_changed","auth_config_changed","package_manifest_changed","ci_workflow_changed","env_or_secrets_file"],T_=p.enum(vl),xl=["verdict","advisory"],Sl=p.enum(xl),Rl=["block","warn","note"],Wt=p.enum(Rl),C_=p.object({convention_id:p.string().min(1).max(64),convention_version:p.number().int().min(1),severity:hr,scope:mr,grade:Sl,matched_symbols:p.array(p.string().min(1).max(512)).min(1).max(64),matched_changed_symbols:p.array(p.string().min(1).max(512)).max(64).default([]),summary:p.string().max(2e3),hard:p.boolean().optional()}),El=["open","warn","info"],Al=p.enum(El),$l=["introduced","pre_existing"],Tl=p.enum($l),Cl=["full","partial","none"],Ol=p.enum(Cl),Il=p.object({detector_id:p.string().regex(/^det_[a-z0-9_]{2,59}$/),detector_version:p.string().regex(/^\d+\.\d+\.\d+$/),rule_id:p.string().regex(/^[a-z][a-z0-9_]*\.[a-z][a-z0-9_]*$/).max(64),level:Al,baseline:Tl,evidence_hash:p.string().regex(/^[a-f0-9]{64}$/),count:p.number().int().min(1).max(1e5)}),wr={det_number_collisions:{major:1,rules:["number.collision"],default_action:"block",class:"objective",replay:"deterministic"},det_spec_drift:{major:1,rules:["spec.coverage","spec.fields","spec.order","spec.extra","spec.unrealized","spec.contract","spec.assertion"],default_action:"block",class:"objective",replay:"deterministic"},det_theme_class_drift:{major:1,rules:["theme.dead_class"],default_action:"block",class:"objective",replay:"deterministic"},det_table_acl_lint:{major:1,rules:["acl.missing_revoke"],default_action:"warn",class:"opinion",replay:"deterministic"},det_changelog_duplicates:{major:1,rules:["changelog.duplicate_heading"],default_action:"block",class:"objective",replay:"deterministic"},det_workflow_yaml:{major:1,rules:["workflow.unparsable_yaml"],default_action:"block",class:"objective",replay:"deterministic"},det_release_claims:{major:1,rules:["release.phantom","release.unpublished","release.mislabelled"],default_action:"block",class:"objective",replay:"environment"},det_agent_doc_prose:{major:1,rules:["agentdoc.added_prose"],default_action:"warn",class:"opinion",replay:"deterministic"}};function io(e){return Object.prototype.hasOwnProperty.call(wr,e)}s(io,"isKnownDetector");var Dl=p.object({version:p.literal(1).default(1),actions:p.object({required:Wt.default("block"),recommended:Wt.default("warn"),info:Wt.default("note")}).default({}),overrides:p.array(p.object({convention_id:p.string().min(1).max(64),action:Wt})).max(64).default([]),risk_flag_action:p.enum(["warn","note","ignore"]).default("warn"),detector_overrides:p.array(p.object({detector_id:p.string().regex(/^det_[a-z0-9_]{2,59}$/),action:Wt,reason:p.string().min(1).max(200)})).max(32).optional()}),O_=Dl.parse({});var kl={note:0,warn:1,block:2};function oo(e){let t=null;for(let n of e)(t===null||kl[n]>kl[t])&&(t=n);return t}s(oo,"strongestAction");var Nl=["ran","not_applicable","unavailable","ungraded"],jl=p.enum(Nl),Pl=p.object({detector_id:p.string().regex(/^det_[a-z0-9_]{2,59}$/),detector_version:p.string().regex(/^\d+\.\d+\.\d+$/),state:jl}),Ke=1e3,ro=p.string().regex(/^[a-f0-9]{40}$|^[a-f0-9]{64}$/,"expected a lowercase git object sha (40 or 64 hex)"),Ml=p.object({name:p.string().min(1).max(200),qualified_name:p.string().min(1).max(512).optional(),kind:p.string().min(1).max(64).optional(),language:p.string().min(1).max(32).optional(),change:p.enum(["added","modified","co_located"]).optional(),changed_line_count:p.number().int().min(0).max(1e4).optional()}),Ll=p.object({base_kind:p.enum(["uncommitted","ref"]),changed_file_count:p.number().int().min(0),stale_file_count:p.number().int().min(0),unindexed_file_count:p.number().int().min(0).optional(),truncated:p.boolean(),hunk_coverage:p.enum(["full","partial","none"]),detector_coverage:Ol}),I_=p.object({changed_symbols:p.array(Ml).max(Ke),risk_flags:p.array(p.string().max(64)).max(16),detector_findings:p.array(Il).max(64),detector_runs:p.array(Pl).min(1).max(32),diff_stats:Ll,commit_sha:ro.optional(),base_sha:ro.optional(),merge_base_sha:ro.optional(),dirty:p.boolean().optional(),code_index_version:p.string().min(1).max(32).optional()});var Fl=14,Ul=14,Bl=14,Kl=1,Hl=365,so=p.number().int().min(Kl).max(Hl),D_=["propose","direct"],N_="propose",Gl=["propose","direct"],Vl="propose",Wl=["propose","direct"],ql="propose",zl=["off","propose","direct"],j_=["member","admin","owner"],P_="member",Yl="off";var Xl="en",Zl=p.object({version:p.literal(1).default(1),at_risk_days:so.default(Fl),stagnation_days:so.default(Ul),agent_date_mode:p.enum(D_).default(N_),health_manual_ttl_days:so.default(Bl),agent_event_mode:p.enum(Gl).default(Vl),agent_update_mode:p.enum(Wl).default(ql),agent_pull_mode:p.enum(zl).default(Yl),org_wide_authoring_min_role:p.enum(j_).default(P_),planning_language:p.string().regex(/^[a-z]{2}$/,"two lowercase letters (ISO 639-1)").default(Xl)}),M_=Zl.parse({});var Jl=p.object({version:p.literal(1).default(1),org_visibility:p.boolean().default(!1),session_span_visibility:p.boolean().default(!0)}),L_=Jl.parse({});var Ql=p.object({tools:p.array(p.string()).default([]),languages:p.array(p.string()).default([]),platforms:p.array(p.string()).default([]),tags:p.array(p.string()).default([])}),eu=p.object({id:p.string().uuid(),user_id:p.string().uuid(),project:p.string().max(200).nullable().optional(),title:p.string().min(1).max(200),body:p.string().min(1).max(2e4),context:Ql.default({tools:[],languages:[],platforms:[],tags:[]}),created_at:p.string(),updated_at:p.string(),last_recalled_at:p.string().nullable().optional(),recall_count:p.number().int().nonnegative().default(0),graduated_draft_id:p.string().uuid().nullable().optional(),deleted_at:p.string().nullable().optional()}),F_=eu.pick({id:!0,project:!0,title:!0,body:!0,context:!0,created_at:!0,updated_at:!0,last_recalled_at:!0,recall_count:!0}).extend({score:p.number()}),U_=p.object({id:p.string().uuid(),title:p.string(),summary:p.string(),tags:p.array(p.string()).default([])});var B_=new Set(["|",">","|-",">-","|+",">+"]),K_=/^(\s*)(?:-\s+)?[A-Za-z_][\w.-]*:(\s*)(.*)$/;function kr(e){let t=[],n=null;return e.split(`
24
24
  `).forEach((r,i)=>{let o=r.trim(),a=r.length-r.trimStart().length;if(n!==null){if(o===""||a>n)return;n=null}if(o===""||o.startsWith("#"))return;let c=K_.exec(r);if(!c)return;let l=c[3]??"";if(B_.has(l.trim())){n=a;return}let u=l.split(/\s+#/)[0].trim();u===""||`'"[{&*`.includes(u[0])||u.includes(": ")&&t.push({line:i+1,value:u})}),t}s(kr,"plainScalarViolations");function tt(e,t){let n=s(c=>{let[l,u=""]=c.split("-",2),d=l.split(".").map(f=>{let h=Number(f);return Number.isFinite(h)?h:0});for(;d.length<3;)d.push(0);return[d,u.length>0?u.split("."):[]]},"split"),[r,i]=n(e),[o,a]=n(t);for(let c=0;c<Math.max(r.length,o.length);c+=1){let l=(r[c]??0)-(o[c]??0);if(l!==0)return l<0?-1:1}if(i.length===0&&a.length===0)return 0;if(i.length===0)return 1;if(a.length===0)return-1;for(let c=0;c<Math.max(i.length,a.length);c+=1){let l=i[c],u=a[c];if(l===void 0)return-1;if(u===void 0)return 1;let d=/^\d+$/.test(l),f=/^\d+$/.test(u);if(d&&f){let h=Number(l)-Number(u);if(h!==0)return h<0?-1:1}else{if(d!==f)return d?-1:1;if(l!==u)return l<u?-1:1}}return 0}s(tt,"compareSemver");var tu="1";function nu(e){return[`${e.kind} ${e.qualifiedName}`,e.signature??"",e.doc??"",e.filePath].filter(t=>t.length>0).join(`
25
25
  `).slice(0,1e3)}s(nu,"nodeEmbedText");var ao=["function","method","class","interface","enum","type_alias"];function ru(e,t){let n=Math.min(e.length,t.length),r=0,i=0,o=0;for(let a=0;a<n;a++){let c=e[a],l=t[a];r+=c*l,i+=c*c,o+=l*l}return i===0||o===0?0:r/(Math.sqrt(i)*Math.sqrt(o))}s(ru,"cosineSimilarity");import{posix as co}from"node:path";var H_=new Set(["function","method","class","interface","enum","type_alias"]),vr=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".py"];function iu(e){let t=new Map,n=new Set;for(let r of e){if(n.add(r.filePath),!H_.has(r.kind))continue;let i=t.get(r.name);i?i.push(r.nodeKey):t.set(r.name,[r.nodeKey])}return{nameToKeys:t,files:n}}s(iu,"buildResolutionIndex");function ou(e,t){let n=new Set,r=[],i=new Set,o=s((a,c,l)=>{if(a===c)return;let u=`${a}\0${c}\0${l}`;n.has(u)||(n.add(u),r.push({srcKey:a,dstKey:c,kind:l}),i.add(a))},"push");for(let a of e.edges)o(a.srcKey,a.dstKey,a.kind);for(let a of e.nodes)i.add(a.nodeKey);for(let a of e.refs){let c=t.nameToKeys.get(a.targetName);!c||c.length!==1||o(a.fromKey,c[0],a.kind)}for(let a of e.imports){let c=G_(e.filePath,a.specifier,t.files);c&&o(a.fromModuleKey,tr(c),"imports")}return{filePath:e.filePath,srcKeys:[...i],edges:r}}s(ou,"resolveFileEdges");function G_(e,t,n){if(!t.startsWith("."))return null;let r=co.normalize(co.join(co.dirname(e),t)),i=[],o=vr.some(c=>r.endsWith(c));o&&i.push(r);let a=/\.(js|jsx|mjs|cjs)$/.exec(r);if(a){let c=r.slice(0,-a[0].length);for(let l of vr)i.push(c+l)}if(!o){for(let c of vr)i.push(r+c);for(let c of vr)i.push(`${r}/index${c}`)}for(let c of i)if(n.has(c))return c;return null}s(G_,"resolveImportTarget");import{execFileSync as X_}from"node:child_process";import{createHash as Z_}from"node:crypto";import{readFileSync as J_,readdirSync as Q_,statSync as ew}from"node:fs";import{posix as fo,sep as au}from"node:path";import{appendFileSync as V_,existsSync as su,mkdirSync as W_,readFileSync as q_}from"node:fs";import{join as z_}from"node:path";var xr=["code-index.sqlite","code-index.sqlite-wal","code-index.sqlite-shm","index-refresh.lock","conventions-cache.json","conventions-cache.json.*.tmp","context.md","manifest.json","git-context.md","review.md","review.json","review-comment.md","run-review.md","pr-body.md","HANDOFF-*.md"],lo=["# Written by the maind tools: machine-local files that must not be committed.","# Missing lines are appended, nothing is removed \u2014 your own lines stay.",'# Never "*": this directory also holds files that ARE committed (feature.json, gates.json \u2026).'],Y_=lo;function Tt(e,t={}){try{if(!su(e)){if(!t.create)return"skipped";W_(e,{recursive:!0})}let n=z_(e,".gitignore"),r=su(n)?q_(n,"utf8"):null,i=new Set((r??"").split(/\r?\n/).map(l=>l.trim().replace(/^!/,""))),o=xr.filter(l=>!i.has(l));if(o.length===0)return"unchanged";let a=r===null?[...Y_,...o]:o,c=r&&!r.endsWith(`
26
26
  `)?`
@@ -41,7 +41,7 @@ var Fa=Object.defineProperty;var s=(e,t)=>Fa(e,"name",{value:t,configurable:!0})
41
41
  `).filter(E=>E.trim().length>0).length,y=jw(e),g=He(T(e,["rev-parse","--show-toplevel"]))??e,b=Pw(T(e,["worktree","list","--porcelain"])??""),_=b[0]?.path??null,w=_!=null&&So(_,g),R=Math.max(0,b.length-1),S=null;if(_&&!So(_,g)){let E=s(j=>le(V.join(_,j))&&!le(V.join(g,j)),"here"),x=[...$u,...Lw(g),...Mw(g),...t.probePaths??[]];S={mainWorktreePath:_,currentWorktreePath:g,missing:[...new Set(x.filter(E))],missingDeps:Fw(g).filter(j=>E(j.dir))}}let q=Cw(g,e),C=t.includeRelease===!1?null:qw(e,o),k=[];return a&&(k=(T(e,["diff","--name-only","--diff-filter=A",`origin/${a}...HEAD`,"--","*supabase/migrations/*.sql"])??"").split(`
42
42
  `).map(x=>x.trim()).filter(x=>x.length>0)),{isRepo:!0,branch:o,defaultBranch:a,upstream:c,headMatchesUpstream:l,remoteTrackingExists:u,ahead:d,behind:f,uncommitted:m,detachedHead:i,inProgressOp:y,isSharedMainTree:w,otherWorktrees:R,worktreeParity:S,toolCopyDrift:q,stalePackageBuilds:Du(g),release:C,unmergedMigrations:k,hooks:_o(e)}}s(Iu,"gatherRepoHealthFacts");function So(e,t){let n=s(r=>r.replace(/\/+$/,""),"norm");return n(e)===n(t)}s(So,"samePath");var Bw=2e3,ko=64,Ru=4e3,Kw=3,Eu=400;function Hw(e){let t=new Set;xo(e,".")&&t.add(".");let n=[{rel:".",depth:0}],r=0;for(;n.length>0&&r<Eu;){let i=n.pop();if(i===void 0)break;if(i.depth>=Kw)continue;let o;try{o=Tr(V.join(e,i.rel),{withFileTypes:!0})}catch{continue}for(let a of o){if(!a.isDirectory()||a.name.startsWith(".")||a.name==="node_modules")continue;let c=i.rel==="."?a.name:V.join(i.rel,a.name);if(r+=1,r>=Eu)break;xo(e,c)&&t.add(c),n.push({rel:c,depth:i.depth+1})}}return[...t].sort()}s(Hw,"findWorkspaceRoots");function Gw(e){let t=[];try{let n=V.join(e,"pnpm-workspace.yaml");if(le(n)){let r=!1;for(let i of rt(n,"utf8").split(`
43
43
  `)){let o=i.replace(/#.*$/,"").trimEnd();if(/^packages\s*:/.test(o)){r=!0;continue}if(r){let a=/^\s+-\s*['"]?([^'"]+?)['"]?\s*$/.exec(o);a?t.push(a[1]):o.trim().length>0&&!/^\s/.test(o)&&(r=!1)}}}else{let r=V.join(e,"package.json");if(le(r)){let i=JSON.parse(rt(r,"utf8")),o=Array.isArray(i.workspaces)?i.workspaces:i.workspaces?.packages;Array.isArray(o)&&t.push(...o.filter(a=>typeof a=="string"))}}}catch{return[]}return t}s(Gw,"workspacePatternsAt");function Vw(e){let t=[];for(let n of Hw(e)){let r=n==="."?e:V.join(e,n),i=s(o=>n==="."?o:V.join(n,o),"prefix");for(let o of Gw(r)){if(t.length>=ko)break;if(!(o.startsWith("!")||o.includes("**")))try{if(o.endsWith("/*")){let a=o.slice(0,-2),c=V.join(r,a);if(!le(c))continue;for(let l of Tr(c,{withFileTypes:!0}))if(l.isDirectory()&&!l.name.startsWith(".")&&t.push(i(V.join(a,l.name))),t.length>=ko)break}else o.includes("*")||t.push(i(o))}catch{}}}return t.slice(0,ko)}s(Vw,"listWorkspacePackageDirs");function Au(e){let t=null,n=0,r=[e];for(;r.length>0&&n<Ru;){let i=r.pop();if(i===void 0)break;let o;try{o=Tr(i,{withFileTypes:!0})}catch{continue}for(let a of o){if(a.name.startsWith(".")||a.name==="node_modules")continue;let c=V.join(i,a.name);if(a.isDirectory())r.push(c);else if(a.isFile()){n+=1;try{let l=vo(c).mtimeMs;(t===null||l>t)&&(t=l)}catch{}if(n>=Ru)break}}}return t}s(Au,"newestMtimeUnder");function Ww(e,t){let n=new Set;for(let r of t)try{let i=V.join(e,r,"package.json");if(!le(i))continue;let o=JSON.parse(rt(i,"utf8"));for(let a of["dependencies","devDependencies","peerDependencies"]){let c=o[a];if(!(c===null||typeof c!="object"))for(let[l,u]of Object.entries(c))typeof u=="string"&&u.startsWith("workspace:")&&n.add(l)}}catch{}return n}s(Ww,"consumedWorkspaceNames");function Du(e){let t=[],n=Vw(e),r=Ww(e,n);for(let i of n)try{let o=V.join(e,i,"package.json");if(!le(o))continue;let a=JSON.parse(rt(o,"utf8"));if(typeof a.name!="string"||!r.has(a.name))continue;let c=s(_=>{if(typeof _!="string")return null;let w=_.replace(/^\.\//,"").split("/")[0];return w==="build"||w==="dist"?w:null},"builtSeg"),l=c(a.types??a.typings),u=c(a.main),d=l??u;if(d===null)continue;let f=l!==null&&u!==null?"both":l!==null?"types":"runtime",h=V.join(e,i,"src"),m=V.join(e,i,d);if(!le(h)||!le(m))continue;let y=Au(h),g=Au(m);if(y===null||g===null)continue;let b=y-g;b>Bw&&t.push({packageDir:i,buildDir:d,srcNewerByMs:Math.round(b),impact:f})}catch{}return t.sort((i,o)=>i.packageDir.localeCompare(o.packageDir))}s(Du,"gatherStalePackageBuilds");function qw(e,t){if(!t)return null;let n=zw(e,["pr","checks",t,"--json","bucket"]);if(n==null)return null;let r;try{r=JSON.parse(n)}catch{return null}if(r.length===0)return{prNumber:null,totalChecks:0,failedChecks:0,allRed:!1};let i=r.filter(o=>o.bucket==="fail").length;return{prNumber:null,totalChecks:r.length,failedChecks:i,allRed:i===r.length&&r.length>0}}s(qw,"gatherReleaseFact");function zw(e,t){try{return Ew("gh",t,{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,maxBuffer:8*1024*1024})}catch{return null}}s(zw,"runGh");async function Eo(e,t={}){let n=await Iu(e,t);if(!n.isRepo)return{ok:!1,verdict:"no_opinion",reason:"not_a_repository",findings:[],facts:n};let r=Cu(n),i=Ou(r);return{ok:i,verdict:i?"clean":"diverged",reason:null,findings:r,facts:n}}s(Eo,"checkDivergence");import{existsSync as Ao,readdirSync as Nu}from"node:fs";import{posix as De}from"node:path";var $o="could not diff against the base ref \u2014 everything reported as info";function To(e){return e.isRepo&&e.baseRef!==null&&!e.skipped.includes($o)}s(To,"isNumberCollisionsGraded");var Yw=/^(?<prefix>[A-Za-z][A-Za-z_.-]*?[-_])?(?<num>\d{2,})(?=[-_.])/,Co=3,ju=.8;function Pu(e,t={}){let n=t.minFiles??Co;return e.length<n?!1:new Set(e).size/e.length>=(t.minDistinctRatio??ju)}s(Pu,"isCounterNamespace");function Yt(e){return`${e.dir}#${e.prefix}`}s(Yt,"namespaceKey");function vn(e){let t=Yw.exec(e);return t?.groups?{prefix:t.groups.prefix??"",number:t.groups.num}:null}s(vn,"parseNumbered");function Mu(e){let t=[];if(!e.isRepo)return t;let n=new Set(e.addedPaths);for(let i of e.namespaces){let o=Yt(i),a=e.sightingsByNamespace.get(o);if(!a)continue;let c=new Set(a.keys());for(let[l,u]of a){let d=[...new Set(u.map(y=>y.path))];if(d.length<2)continue;let f=d.find(y=>n.has(y)),h=d.filter(y=>y!==f),m=`${i.prefix}${l}`;t.push(f?{id:`number.collision:${o}#${l}`,status:"open",namespace:i,number:l,title:`${m} is already taken`,detail:`This branch adds ${f}, but ${m} already exists as ${h.join(", ")}. A number is the reference key \u2014 links, commit messages and comments pointing at ${m} stop being unambiguous.`,ownPath:f,sightings:u.filter(y=>y.path!==f),suggestion:`${i.prefix}${Oo(c,l)}`,hint:"Rename yours (git mv) to the suggested number and update every reference: title/frontmatter, any index file, wiki-style links, and comments naming the old filename. Already-merged references (commit messages, applied migrations) stay as they are \u2014 they are history."}:{id:`number.collision:${o}#${l}`,status:"info",namespace:i,number:l,title:`${m} is used more than once (pre-existing)`,detail:`${m} is carried by ${d.length} files: ${d.join(", ")}.`,sightings:u,hint:"Not introduced by this branch \u2014 inventory, not a blocker."})}}let r={open:0,warn:1,info:2,passed:3};return t.sort((i,o)=>r[i.status]-r[o.status]||i.id.localeCompare(o.id))}s(Mu,"computeNumberCollisions");function Lu(e){return!e.some(t=>t.status==="open")}s(Lu,"isCollisionFree");function Oo(e,t){let n=0;for(let r of e){let i=Number(r);Number.isFinite(i)&&(n=Math.max(n,i))}return String(n+1).padStart(t.length,"0")}s(Oo,"suggestNextNumber");function Io(e){return e.replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\/+/,"")}s(Io,"normaliseRepoPath");function Fu(e,t){let n=Io(t),r={path:n,namespace:null,number:null,taken:!1,sightings:[],suggestion:null},i=vn(De.basename(n));if(!i)return r;let o=`${De.dirname(n)}#${i.prefix}`,a=e.namespaces.find(d=>Yt(d)===o)??null;if(!a)return{...r,number:i.number};let c=e.sightingsByNamespace.get(o)??new Map,l=new Set,u=[];for(let d of c.get(i.number)??[])d.path===n||l.has(d.path)||(l.add(d.path),u.push(d));return{path:n,namespace:a,number:i.number,taken:u.length>0,sightings:u,suggestion:Oo(c.keys(),i.number)}}s(Fu,"checkProposedNumber");function Cr(e){let t=e?.trim();return t||null}s(Cr,"trimOrNull");function zt(e){return e?e.split(`
44
- `).filter(Boolean):[]}s(zt,"lines");function Xw(e){let t=Cr(T(e,["symbolic-ref","--quiet","refs/remotes/origin/HEAD"]));if(t){let n=/refs\/remotes\/origin\/(.+)$/.exec(t);if(n)return n[1]}for(let n of["main","master"])if(T(e,["rev-parse","--verify","--quiet",`origin/${n}`])!==null)return n;return null}s(Xw,"resolveDefaultBranch");function Uu(e,t={}){let n=t.minFiles??Co,r=["ls-files","-z","--"];r.push(...t.dirs?.length?t.dirs:["."]);let i=T(e,r);if(i===null)return[];let o=new Map;for(let a of i.split("\0").filter(Boolean)){let c=De.dirname(a),l=vn(De.basename(a));if(!l)continue;let u=`${c}#${l.prefix}`,d=o.get(u);d?d.numbers.push(l.number):o.set(u,{dir:c,prefix:l.prefix,numbers:[l.number]})}return[...o.values()].filter(a=>Pu(a.numbers,{...t,minFiles:n})).map(a=>({dir:a.dir,prefix:a.prefix,fileCount:a.numbers.length,distinctRatio:new Set(a.numbers).size/a.numbers.length})).sort((a,c)=>Yt(a).localeCompare(Yt(c)))}s(Uu,"detectNamespaces");async function Do(e,t={}){let n=[];if(Cr(T(e,["rev-parse","--is-inside-work-tree"]))!=="true")return{isRepo:!1,defaultBranch:null,baseRef:null,namespaces:[],sightingsByNamespace:new Map,addedPaths:[],skipped:["not a git work tree"]};let i=Uu(e,t),o=new Map(i.map(m=>[Yt(m),m])),a=[...new Set(i.map(m=>m.dir))],c=new Map,l=s((m,y,g)=>{let b=De.dirname(m),_=vn(De.basename(m));if(!_)return;let w=`${b}#${_.prefix}`;if(!o.has(w))return;let R=c.get(w)??new Map,S=R.get(_.number)??[];S.push({kind:y,where:g,path:m}),R.set(_.number,S),c.set(w,R)},"record"),u=s((m,y,g)=>{if(a.length===0)return;let b=T(e,["ls-tree","-r","--name-only",m,"--",...a]);if(b===null){n.push(`could not read ${g}`);return}for(let _ of zt(b))l(_,y,g)},"scanTree");for(let m of a){let y=De.join(e,m);if(Ao(y))try{for(let g of Nu(y))l(`${m}/${g}`,"self","this worktree")}catch{n.push(`could not read ${m}`)}}let d=Xw(e),f=t.baseRef??(d?`origin/${d}`:null);if(f?u(f,"default_branch",f):n.push("no default branch resolvable (offline clone?) \u2014 base comparison skipped"),t.includeBranches!==!1){let m=Cr(T(e,["rev-parse","--abbrev-ref","HEAD"]));for(let y of zt(T(e,["for-each-ref","--format=%(refname:short)","refs/heads"])))y!==m&&u(y,"branch",`Branch ${y}`)}if(t.includeWorktrees!==!1){let m=Cr(T(e,["rev-parse","--show-toplevel"]));for(let y of zt(T(e,["worktree","list","--porcelain"]))){if(!y.startsWith("worktree "))continue;let g=y.slice(9).trim();if(!(!g||g===m||!Ao(g)))for(let b of a){let _=De.join(g,b);if(Ao(_))try{for(let w of Nu(_))l(`${b}/${w}`,"worktree",`Worktree ${g}`)}catch{n.push(`could not read ${b} in ${g}`)}}}}let h=[];if(f&&a.length>0){let m=T(e,["diff","--name-only","--diff-filter=A",`${f}...HEAD`,"--",...a]);m===null?n.push($o):h=zt(m);let y=T(e,["ls-files","--others","--exclude-standard","--",...a]);y!==null&&(h=[...h,...zt(y)]);let g=T(e,["diff","--cached","--name-only","--diff-filter=A","--",...a]);g!==null&&(h=[...h,...zt(g)])}return{isRepo:!0,defaultBranch:d,baseRef:f,namespaces:i,sightingsByNamespace:c,addedPaths:h,skipped:n}}s(Do,"gatherNumberCollisionFacts");async function xn(e,t={}){let n=await Do(e,t),r=Mu(n);return{ok:Lu(r),findings:r,facts:n}}s(xn,"checkNumberCollisions");async function No(e,t,n={}){let r=Io(t);if(!vn(De.basename(r)))return{path:r,namespace:null,number:null,taken:!1,sightings:[],suggestion:null};let i=await Do(e,{...n,dirs:n.dirs??[De.dirname(r)]});return Fu(i,r)}s(No,"checkNumberForPath");var Sn={det_number_collisions:{version:"1.2.0",rules:["number.collision"]},det_spec_drift:{version:"1.1.0",rules:["spec.coverage","spec.fields","spec.order","spec.extra","spec.unrealized","spec.contract","spec.assertion"]},det_theme_class_drift:{version:"1.1.0",rules:["theme.dead_class"]},det_table_acl_lint:{version:"1.0.0",rules:["acl.missing_revoke"]},det_changelog_duplicates:{version:"1.0.0",rules:["changelog.duplicate_heading"]},det_workflow_yaml:{version:"1.0.0",rules:["workflow.unparsable_yaml"]},det_release_claims:{version:"1.0.0",rules:["release.phantom","release.unpublished"]},det_agent_doc_prose:{version:"1.0.0",rules:["agentdoc.added_prose"]}};var jo="number.collision",Po="theme.dead_class",Mo="acl.missing_revoke";function Lo(e){return`spec.${e}`}s(Lo,"specDriftRuleId");function Xt(e,t={}){switch(e){case"open":return{level:"open",baseline:"introduced"};case"warn":return{level:"warn",baseline:"introduced"};case"info":return t.excepted?{level:"info",baseline:"introduced"}:{level:"open",baseline:"pre_existing"};default:throw new Error(`gradeEngineStatus: '${String(e)}' is not a finding status`)}}s(Xt,"gradeEngineStatus");function Zw(e,t){let n=Array.from(e),r=Array.from(t),i=Math.min(n.length,r.length);for(let o=0;o<i;o++){let a=(n[o].codePointAt(0)??0)-(r[o].codePointAt(0)??0);if(a!==0)return a}return n.length-r.length}s(Zw,"codePointCompare");function Bu(e){let t=e.map(n=>n.normalize("NFC"));return Array.from(new Set(t)).sort(Zw)}s(Bu,"normalizeEvidenceForHash");function Rn(e){return Pt(JSON.stringify(Bu(e)))}s(Rn,"hashDetectorEvidence");import{existsSync as Jw,readFileSync as Ku}from"node:fs";import{posix as Qw}from"node:path";var Wu=".maind/spec-contracts.json";function Ir(e,t){let n=e[t],r=t+1;for(;r<e.length;){let i=e[r];if(i==="\\"){r+=2;continue}if(i===n)return r+1;r++}return e.length}s(Ir,"endOfString");function Dr(e,t){if(e.startsWith("//",t)){let n=e.indexOf(`
44
+ `).filter(Boolean):[]}s(zt,"lines");function Xw(e){let t=Cr(T(e,["symbolic-ref","--quiet","refs/remotes/origin/HEAD"]));if(t){let n=/refs\/remotes\/origin\/(.+)$/.exec(t);if(n)return n[1]}for(let n of["main","master"])if(T(e,["rev-parse","--verify","--quiet",`origin/${n}`])!==null)return n;return null}s(Xw,"resolveDefaultBranch");function Uu(e,t={}){let n=t.minFiles??Co,r=["ls-files","-z","--"];r.push(...t.dirs?.length?t.dirs:["."]);let i=T(e,r);if(i===null)return[];let o=new Map;for(let a of i.split("\0").filter(Boolean)){let c=De.dirname(a),l=vn(De.basename(a));if(!l)continue;let u=`${c}#${l.prefix}`,d=o.get(u);d?d.numbers.push(l.number):o.set(u,{dir:c,prefix:l.prefix,numbers:[l.number]})}return[...o.values()].filter(a=>Pu(a.numbers,{...t,minFiles:n})).map(a=>({dir:a.dir,prefix:a.prefix,fileCount:a.numbers.length,distinctRatio:new Set(a.numbers).size/a.numbers.length})).sort((a,c)=>Yt(a).localeCompare(Yt(c)))}s(Uu,"detectNamespaces");async function Do(e,t={}){let n=[];if(Cr(T(e,["rev-parse","--is-inside-work-tree"]))!=="true")return{isRepo:!1,defaultBranch:null,baseRef:null,namespaces:[],sightingsByNamespace:new Map,addedPaths:[],skipped:["not a git work tree"]};let i=Uu(e,t),o=new Map(i.map(m=>[Yt(m),m])),a=[...new Set(i.map(m=>m.dir))],c=new Map,l=s((m,y,g)=>{let b=De.dirname(m),_=vn(De.basename(m));if(!_)return;let w=`${b}#${_.prefix}`;if(!o.has(w))return;let R=c.get(w)??new Map,S=R.get(_.number)??[];S.push({kind:y,where:g,path:m}),R.set(_.number,S),c.set(w,R)},"record"),u=s((m,y,g)=>{if(a.length===0)return;let b=T(e,["ls-tree","-r","--name-only",m,"--",...a]);if(b===null){n.push(`could not read ${g}`);return}for(let _ of zt(b))l(_,y,g)},"scanTree");for(let m of a){let y=De.join(e,m);if(Ao(y))try{for(let g of Nu(y))l(`${m}/${g}`,"self","this worktree")}catch{n.push(`could not read ${m}`)}}let d=Xw(e),f=t.baseRef??(d?`origin/${d}`:null);if(f?u(f,"default_branch",f):n.push("no default branch resolvable (offline clone?) \u2014 base comparison skipped"),t.includeBranches!==!1){let m=Cr(T(e,["rev-parse","--abbrev-ref","HEAD"]));for(let y of zt(T(e,["for-each-ref","--format=%(refname:short)","refs/heads"])))y!==m&&u(y,"branch",`Branch ${y}`)}if(t.includeWorktrees!==!1){let m=Cr(T(e,["rev-parse","--show-toplevel"]));for(let y of zt(T(e,["worktree","list","--porcelain"]))){if(!y.startsWith("worktree "))continue;let g=y.slice(9).trim();if(!(!g||g===m||!Ao(g)))for(let b of a){let _=De.join(g,b);if(Ao(_))try{for(let w of Nu(_))l(`${b}/${w}`,"worktree",`Worktree ${g}`)}catch{n.push(`could not read ${b} in ${g}`)}}}}let h=[];if(f&&a.length>0){let m=T(e,["diff","--name-only","--diff-filter=A",`${f}...HEAD`,"--",...a]);m===null?n.push($o):h=zt(m);let y=T(e,["ls-files","--others","--exclude-standard","--",...a]);y!==null&&(h=[...h,...zt(y)]);let g=T(e,["diff","--cached","--name-only","--diff-filter=A","--",...a]);g!==null&&(h=[...h,...zt(g)])}return{isRepo:!0,defaultBranch:d,baseRef:f,namespaces:i,sightingsByNamespace:c,addedPaths:h,skipped:n}}s(Do,"gatherNumberCollisionFacts");async function xn(e,t={}){let n=await Do(e,t),r=Mu(n);return{ok:Lu(r),findings:r,facts:n}}s(xn,"checkNumberCollisions");async function No(e,t,n={}){let r=Io(t);if(!vn(De.basename(r)))return{path:r,namespace:null,number:null,taken:!1,sightings:[],suggestion:null};let i=await Do(e,{...n,dirs:n.dirs??[De.dirname(r)]});return Fu(i,r)}s(No,"checkNumberForPath");var Sn={det_number_collisions:{version:"1.2.0",rules:["number.collision"]},det_spec_drift:{version:"1.1.0",rules:["spec.coverage","spec.fields","spec.order","spec.extra","spec.unrealized","spec.contract","spec.assertion"]},det_theme_class_drift:{version:"1.1.0",rules:["theme.dead_class"]},det_table_acl_lint:{version:"1.0.0",rules:["acl.missing_revoke"]},det_changelog_duplicates:{version:"1.0.0",rules:["changelog.duplicate_heading"]},det_workflow_yaml:{version:"1.0.0",rules:["workflow.unparsable_yaml"]},det_release_claims:{version:"1.1.0",rules:["release.phantom","release.unpublished","release.mislabelled"]},det_agent_doc_prose:{version:"1.0.0",rules:["agentdoc.added_prose"]}};var jo="number.collision",Po="theme.dead_class",Mo="acl.missing_revoke";function Lo(e){return`spec.${e}`}s(Lo,"specDriftRuleId");function Xt(e,t={}){switch(e){case"open":return{level:"open",baseline:"introduced"};case"warn":return{level:"warn",baseline:"introduced"};case"info":return t.excepted?{level:"info",baseline:"introduced"}:{level:"open",baseline:"pre_existing"};default:throw new Error(`gradeEngineStatus: '${String(e)}' is not a finding status`)}}s(Xt,"gradeEngineStatus");function Zw(e,t){let n=Array.from(e),r=Array.from(t),i=Math.min(n.length,r.length);for(let o=0;o<i;o++){let a=(n[o].codePointAt(0)??0)-(r[o].codePointAt(0)??0);if(a!==0)return a}return n.length-r.length}s(Zw,"codePointCompare");function Bu(e){let t=e.map(n=>n.normalize("NFC"));return Array.from(new Set(t)).sort(Zw)}s(Bu,"normalizeEvidenceForHash");function Rn(e){return Pt(JSON.stringify(Bu(e)))}s(Rn,"hashDetectorEvidence");import{existsSync as Jw,readFileSync as Ku}from"node:fs";import{posix as Qw}from"node:path";var Wu=".maind/spec-contracts.json";function Ir(e,t){let n=e[t],r=t+1;for(;r<e.length;){let i=e[r];if(i==="\\"){r+=2;continue}if(i===n)return r+1;r++}return e.length}s(Ir,"endOfString");function Dr(e,t){if(e.startsWith("//",t)){let n=e.indexOf(`
45
45
  `,t);return n===-1?e.length:n+1}if(e.startsWith("/*",t)){let n=e.indexOf("*/",t+2);return n===-1?e.length:n+2}return t+1}s(Dr,"skipComment");function En(e){return e==='"'||e==="'"||e==="`"}s(En,"isQuote");function Nr(e,t){return e[t]==="/"&&(e[t+1]==="/"||e[t+1]==="*")}s(Nr,"isCommentStart");function Or(e,t){let n=e[t];if(n!=="["&&n!=="{")return null;let r=0,i=t;for(;i<e.length;){let o=e[i];if(En(o)){i=Ir(e,i);continue}if(Nr(e,i)){i=Dr(e,i);continue}if(o==="["||o==="{")r++;else if((o==="]"||o==="}")&&(r--,r===0))return e.slice(t,i+1);i++}return null}s(Or,"sliceBalanced");function ek(e){let t=0;for(;;){for(;t<e.length&&/\s/.test(e[t]);)t++;if(Nr(e,t)){t=Dr(e,t);continue}break}return e.slice(t)}s(ek,"stripLeadingTrivia");function Zt(e){let t=[],n=0,r=0,i=0;for(;i<e.length;){let o=e[i];if(En(o)){i=Ir(e,i);continue}if(Nr(e,i)){i=Dr(e,i);continue}o==="["||o==="{"||o==="("?n++:o==="]"||o==="}"||o===")"?n--:o===","&&n===0&&(t.push(e.slice(r,i)),r=i+1),i++}return t.push(e.slice(r)),t.map(o=>ek(o).trim()).filter(o=>o.length>0)}s(Zt,"splitTopLevel");function qu(e){let t=Ir(e,0);return e.slice(1,t-1).replace(/\\(.)/g,(r,i)=>i==="n"?`
46
46
  `:i==="r"?"\r":i==="t"?" ":i)}s(qu,"readStringLiteral");function tk(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}s(tk,"escapeRe");function Uo(e,t){let r=new RegExp(String.raw`(?:^|[\s;({])(?:export\s+)?(?:const|let|var)\s+${tk(t)}\b`,"m").exec(e);if(!r)return null;let i=r.index+r[0].length,o=!1;for(;i<e.length;){let a=e[i];if(En(a)){i=Ir(e,i);continue}if(Nr(e,i)){i=Dr(e,i);continue}if(!o){if(a==="="&&e[i+1]!=="="&&!"=!<>".includes(e[i-1]??" "))o=!0;else if(a===";")return null;i++;continue}if(a==="[")return Or(e,i);if(a===";")return null;i++}return null}s(Uo,"findSymbolArray");function Bo(e){let t={};if(!e.startsWith("{"))return t;for(let n of Zt(e.slice(1,-1))){let r=/^(?:(['"])([^'"]+)\1|([A-Za-z_$][\w$]*))\s*:\s*([\s\S]*)$/.exec(n);if(!r)continue;let i=r[2]??r[3],o=r[4].trim();En(o[0]??"")&&(t[i]=qu(o))}return t}s(Bo,"parseObjectFields");function nk(e,t){if(!e.startsWith("{"))return null;for(let n of Zt(e.slice(1,-1))){let r=/^(?:(['"])([^'"]+)\1|([A-Za-z_$][\w$]*))\s*:\s*([\s\S]*)$/.exec(n);if(r&&(r[2]??r[3])===t)return r[4].trim()}return null}s(nk,"objectFieldRaw");function zu(e,t){if(!t)return{...e};let n={};for(let r of t)n[r]=e[r]??"";return n}s(zu,"pickFields");function Yu(){let e=new Map;return t=>{let n=t.join("\0"),r=e.get(n)??0;return e.set(n,r+1),r}}s(Yu,"makeOrdinals");function Xu(e,t){let n=Uo(e,t.symbol);if(n===null)return{records:[],error:`no array literal assigned to \`${t.symbol}\` in ${t.path}`,dropped:0};let r=Yu(),i=[],o=0;for(let a of Zt(n.slice(1,-1))){if(!a.startsWith("{")){o++;continue}let c=Bo(a),l=c[t.key_field];if(!l){o++;continue}let u=(t.partition_by??[]).map(d=>c[d]??"");i.push({key:l,fields:zu(c,t.fields),orderPath:u,ordinal:r(u)})}return i.length===0?{records:[],error:`\`${t.symbol}\` in ${t.path} yielded no parsable records`,dropped:o}:{records:i,error:null,dropped:o}}s(Xu,"extractObjectArray");function Zu(e,t){let n=Uo(e,t.symbol);if(n===null)return{records:[],error:`no array literal assigned to \`${t.symbol}\` in ${t.path}`,dropped:0};if(t.levels.length===0)return{records:[],error:`contract declares no levels for \`${t.symbol}\``,dropped:0};let r=Yu(),i=[],o=0,a=s((c,l,u)=>{let d=t.levels[l],f=l===t.levels.length-1;for(let h of Zt(c.slice(1,-1))){let m={...u},y=null;if(d.shape==="object"){if(!h.startsWith("{")){o++;continue}let g=Bo(h);for(let[b,_]of Object.entries(d.fields??{}))m[b]=g[String(_)]??"";if(!f&&typeof d.children=="string"){let b=nk(h,d.children);y=b&&b.startsWith("[")?Or(b,0):null}}else{if(!h.startsWith("[")){o++;continue}let g=Zt(h.slice(1,-1));for(let[b,_]of Object.entries(d.fields??{})){let w=g[Number(_)];m[b]=w!==void 0&&En(w[0]??"")?qu(w):""}if(!f&&typeof d.children=="number"){let b=g[d.children];y=b!==void 0&&b.startsWith("[")?Or(b,0):null}}if(f){let g=m[t.key_field];if(!g){o++;continue}let b=(t.partition_by??[]).map(_=>m[_]??"");i.push({key:g,fields:zu(m,t.fields),orderPath:b,ordinal:r(b)});continue}y!==null&&a(y,l+1,m)}},"walk");return a(n,0,{}),i.length===0?{records:[],error:`\`${t.symbol}\` in ${t.path} yielded no parsable records`,dropped:o}:{records:i,error:null,dropped:o}}s(Zu,"extractNestedList");function Hu(e,t){return t.extractor==="object-array"?Xu(e,t):Zu(e,t)}s(Hu,"extractRecords");function Ju(e,t,n){let r=e;return t.strip_prefix&&r.startsWith(t.strip_prefix)&&(r=r.slice(t.strip_prefix.length)),t.templates.some(i=>n.has(i.replace("{key}",r).replace(/\/{2,}/g,"/")))}s(Ju,"isGrounded");function Qu(e,t,n){return`spec.drift:${e}#${t}:${n}`}s(Qu,"findingId");function rk(e){return e.orderPath.join(" / ")||"(flat)"}s(rk,"partitionOf");function ed(e,t,n,r){let i=[],o=s((u,d,f,h,m,y)=>{i.push({id:Qu(e.id,u,f),contract:e.id,dimension:u,status:d,key:f,title:h,detail:m,hint:y})},"push"),a=new Map(n.map(u=>[u.key,u])),c=new Map(t.map(u=>[u.key,u]));for(let u of t){let d=a.get(u.key);if(!d){o("coverage","open",u.key,`${u.key} is declared by the specification but missing from the implementation`,`Partition ${rk(u)}, position ${u.ordinal+1}. The specification is the reference; add it or record an exception with a reason.`,"On a contradiction the specification wins \u2014 read it rather than a summary of it.");continue}for(let f of e.compare_fields??[]){let h=u.fields[f]??"",m=d.fields[f]??"";h!==m&&o("fields","open",`${u.key}.${f}`,`${u.key}: ${f} is "${m||"\u2014"}", the specification says "${h||"\u2014"}"`,`Field \`${f}\` disagrees between the two sides.`)}}let l=new Map;for(let u of t){let d=u.orderPath.join("\0"),f=l.get(d);f?f.push(u):l.set(d,[u])}for(let[u,d]of l){let f=d.filter(g=>a.has(g.key)).map(g=>g.key),h=n.filter(g=>g.orderPath.join("\0")===u).filter(g=>c.has(g.key)).map(g=>g.key),m=new Set(h),y=f.filter(g=>m.has(g));if(h.join("|")!==y.join("|")){let g=u.split("\0").join(" / ")||"(flat)";o("order","open",g,`Partition ${g}: sequence differs from the specification`,`implementation: ${h.join(" \u2192 ")}
47
47
  specification: ${y.join(" \u2192 ")}`,"Order is declared explicitly by the specification and is not derivable from a flat list.")}}for(let u of n)c.has(u.key)||o("extra","warn",u.key,`${u.key} is in the implementation but not declared by the specification`,"Deliberate? Then record it as an exception with a reason, so the next reader does not have to guess.");if(e.grounding)for(let u of new Set([...a.keys(),...c.keys()])){if(Ju(u,e.grounding,r))continue;let d=a.has(u);o("unrealized",d?"open":"warn",u,d?`${u} is referenced by the implementation but has no artefact`:`${u} is declared by the specification but not built yet`,d?`No file matches ${e.grounding.templates.join(" or ")} for this key \u2014 the reference points at nothing.`:"The specification is ahead of the code here. Legitimate, but it should be named.")}return i}s(ed,"compareContract");function ik(e,t,n){let r=[];for(let i of e.assertions??[]){let o=n.get(i.path);if(!o)continue;let a=o.indexOf(i.prefix);if(a===-1)continue;let c=/^\s*(\d+)/.exec(o.slice(a+i.prefix.length));if(!c)continue;let l=Number(c[1]),u=t[i.counts];l!==u&&r.push({id:`spec.drift:${e.id}#assertion:${i.path}`,contract:e.id,dimension:"assertion",status:"warn",key:i.path,title:`${i.path} states ${l} where the ${i.counts} side has ${u}`,detail:`Counted after "${i.prefix}". ${i.reason}`,hint:"Prose only \u2014 nothing behaves differently because of this number."})}return r}s(ik,"checkAssertions");function Gu(e,t){return{id:`contract.unreadable:${e}`,contract:e,dimension:"contract",status:"open",key:null,title:`Contract "${e}" could not be evaluated`,detail:t,hint:"This is NOT a drift finding. An anchor moved, or a declared file is gone \u2014 repair the contract in the manifest, then re-run. Nothing has been compared for this contract."}}s(Gu,"unreadable");var Vu={open:0,warn:1,info:2,passed:3};function td(e,t={}){let n=s(d=>({ok:!1,verdict:"no_opinion",reason:d,findings:[],contracts:[]}),"abstain");if(!e.isRepo)return n("not a git work tree");if(!e.manifest)return n(e.manifestError??`no contract could be read from ${e.manifestPath}`);let r=t.contracts?.length?e.manifest.contracts.filter(d=>t.contracts.includes(d.id)):e.manifest.contracts;if(r.length===0)return n(t.contracts?.length?`no contract in ${e.manifestPath} matches ${t.contracts.map(d=>`"${d}"`).join(", ")} \u2014 nothing was compared`:`${e.manifestPath} declares no contract \u2014 nothing was compared`);let i=s(d=>{let f=[],h=[];for(let m of r){let y=d.get(m.spec.path),g=d.get(m.impl.path);if(y==null||g==null){let R=y==null?m.spec.path:m.impl.path;f.push(Gu(m.id,`Declared file could not be read: ${R}`)),h.push({id:m.id,measured:!1,specRecords:0,implRecords:0,partial:!1});continue}let b=Hu(y,m.spec),_=Hu(g,m.impl);if(b.error||_.error){f.push(Gu(m.id,b.error??_.error??"unknown")),h.push({id:m.id,measured:!1,specRecords:0,implRecords:0,partial:!1});continue}let w=b.dropped>0||_.dropped>0;h.push({id:m.id,measured:!0,specRecords:b.records.length,implRecords:_.records.length,partial:w}),w&&f.push({id:`contract.partial:${m.id}`,contract:m.id,dimension:"contract",status:"warn",key:null,title:`Contract "${m.id}" was measured incompletely`,detail:`${b.dropped} specification and ${_.dropped} implementation entries could not be parsed and were skipped. Findings below are computed WITHOUT them.`,hint:"Not a drift finding. Check whether the declared shape still matches the file."}),f.push(...ed(m,b.records,_.records,e.files)),f.push(...ik(m,{spec:b.records.length,impl:_.records.length},d))}return{findings:f,contracts:h}},"runOnce"),o=i(e.sources),a=new Set;if(t.includeBaseline!==!1&&e.baseRef&&e.baselineSources.size>0)for(let d of i(e.baselineSources).findings)d.id.startsWith("contract.unreadable:")||a.add(d.id);let c=new Map;for(let d of r)for(let f of d.exceptions??[])c.set(Qu(d.id,f.dimension,f.key),f);let l=o.findings.map(d=>{let f=c.get(d.id);return f?{...d,status:"info",exceptionReason:f.reason}:a.has(d.id)?{...d,status:"info",detail:`${d.detail}
@@ -196,7 +196,7 @@ maind: and re-run \`maind launch claude\`. (Or launch without routing: \`maind l
196
196
  `,stderr:""}}let n=["maind: dry-run \u2014 nothing installed, written, or spawned.",`maind: config ${e.configPath} (${e.configSource})`,`maind: switchyard detected: ${e.switchyardDetected?"yes":"no"}`,`maind: would run: ${e.argv.join(" ")}`].join(`
197
197
  `);return{stdout:e.toml??`(using existing config: ${e.configPath})
198
198
  `,stderr:n+`
199
- `}}s(Wf,"renderDryRun");import{createRequire as Kv}from"node:module";function Hv(){return"0.73.0";try{return Kv(import.meta.url)("../package.json").version}catch{return"0.0.0-unknown"}}s(Hv,"resolveVersion");var Y=Hv();var Jv=5e3;function pe(e){process.stderr.write(`maind: ${e}
199
+ `}}s(Wf,"renderDryRun");import{createRequire as Kv}from"node:module";function Hv(){return"0.73.1";try{return Kv(import.meta.url)("../package.json").version}catch{return"0.0.0-unknown"}}s(Hv,"resolveVersion");var Y=Hv();var Jv=5e3;function pe(e){process.stderr.write(`maind: ${e}
200
200
  `)}s(pe,"err");function Qv(e){return e instanceof Error?e.message:String(e)}s(Qv,"msg");var ex=new Set(["--config","--route","--mcp-url"]);function zf(e){let t=s(i=>{let o=e.indexOf(i);if(!(o===-1||o+1>=e.length))return e[o+1]},"get"),n=s(i=>e.includes(i),"has"),r=null;for(let i=0;i<e.length;i++){let o=e[i];if(o.startsWith("-")){ex.has(o)&&i++;continue}r=o;break}return{agent:r,dryRun:n("--dry-run"),config:t("--config")??null,route:t("--route")??Df,direct:n("--direct"),noFallback:n("--no-fallback"),noInstall:n("--no-install"),json:n("--json"),mcpUrl:t("--mcp-url")??null}}s(zf,"parseLaunchArgs");var tx={probe(e,t){let n=qf(e,t,{stdio:["ignore","pipe","pipe"],encoding:"utf8",timeout:1e4}),r=n.status===0&&!n.error,i=typeof n.stdout=="string"?n.stdout.trim():"";return{ok:r,stdout:i.length>0?i:null}},install(e){return qf("uv",[...e],{stdio:["ignore","inherit","inherit"]}).status},spawnInteractive(e){let t=Date.now();return new Promise(n=>{let r=!1,i=Gv(e[0],e.slice(1),{stdio:"inherit",env:process.env}),o=s(()=>{},"onSigint"),a=s(d=>()=>{try{i.kill(d)}catch{}},"makeForward"),c=a("SIGTERM"),l=a("SIGHUP");process.on("SIGINT",o),process.on("SIGTERM",c),process.on("SIGHUP",l);let u=s(()=>{process.removeListener("SIGINT",o),process.removeListener("SIGTERM",c),process.removeListener("SIGHUP",l)},"cleanup");i.on("error",d=>{r||(r=!0,u(),n({code:null,signal:null,elapsedMs:Date.now()-t,spawnError:d.message}))}),i.on("exit",(d,f)=>{r||(r=!0,u(),n({code:d,signal:f,elapsedMs:Date.now()-t,spawnError:null}))})})},async fetchTemplate(e,t){let n;try{n=z()}catch(r){if(r instanceof Z)return null;throw r}try{let r=new ee({apiKey:n.apiKey,deviceId:n.deviceId,clientVersion:Y,mcpUrl:e??void 0,projectKey:t}),i=new Promise(a=>{setTimeout(()=>a(null),Jv).unref()}),o=r.callTool("get_template",{template_id:Nf}).then(a=>typeof a.template_body=="string"&&a.template_body.trim().length>0?a.template_body:null).catch(()=>null);return await Promise.race([o,i])}catch{return null}},writeConfig(e,t){let n=Zv(e);n&&n!=="."&&qv(n,{recursive:!0}),Yv(e,t,"utf8")},readFile(e){try{return zv(e,"utf8")}catch{return null}},fileExists(e){return Wv(e)},repoRoot(){try{let e=Vv("git",["rev-parse","--show-toplevel"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim();return e.length>0?e:null}catch{return null}},projectKey(){return Se().projectKey},userConfigDir(){return Zn()},homeDir(){return Xv()},env:process.env,platform:process.platform};function nx(e,t){return e!==null?Ps(e,".maind",$s):Ps(t,$s)}s(nx,"resolveRoutesPath");async function Yf(e,t=tx){let n=jf(e.agent);if(n.kind==="unknown")return pe(`usage: maind launch <agent> [--dry-run] [--config <path>] [--route <name>] [--direct] [--no-fallback] [--no-install] \u2014 supported: ${Ts.join(", ")}`),2;if(n.kind==="planned")return pe(`agent '${n.agent}' is planned but not yet supported \u2014 v1 supports: ${Ts.join(", ")}.`),2;if(e.json&&!e.dryRun)return pe("--json is only valid together with --dry-run (stdout belongs to the agent session)."),2;let r=n.agent;if(e.direct)return pe(Vf()),Xf(t,Ds(r));let i=Pf(t.env);i.warning!==null&&pe(i.warning);let o,a,c;if(e.config!==null){if(!t.fileExists(e.config))return pe(`config not found: ${e.config}`),2;let f=t.readFile(e.config);if(f===null||Ff(f,e.route)===null)return pe(`config ${e.config} is not valid routes TOML with a [routes.${e.route}] entry.`),2;o=e.config,a=null,c="flag"}else{let f=await t.fetchTemplate(e.mcpUrl,t.projectKey()),h=f===null?null:Lf(f,e.route);if(a=Mf(e.route,i,h),h!==null)c="template";else{c="builtin";let m=f===null?"no curated template (offline, unauthenticated, or not published)":`curated template unusable (missing route '${e.route}', or it pins its own targets)`;pe(`using builtin routing policy (${m}).`)}o=nx(t.repoRoot(),t.userConfigDir())}let l=Xr,u=t.probe(Xr,["--version"]).ok;if(e.dryRun){let f={agent:r,configPath:o,configSource:c,toml:a,argv:Is(l,r,e.route,o),backendKind:i.kind,switchyardDetected:u},h=Wf(f,e.json);return h.stderr.length>0&&process.stderr.write(h.stderr),process.stdout.write(h.stdout),0}if(!u){if(e.noInstall)return pe(`switchyard not found (--no-install). Install it with:
201
201
  maind: ${Zr}`),1;if(!t.probe("uv",["--version"]).ok)return pe(Kf()),1;if(pe(Bf()),t.install(If),t.probe(Xr,["--version"]).ok)u=!0;else{let f=Ps(t.homeDir(),".local","bin",t.platform==="win32"?"switchyard.exe":"switchyard");t.probe(f,["--version"]).ok&&(l=f,u=!0)}if(!u)return js(t,e,r,Hf())}if(c!=="flag"&&a!==null)try{t.writeConfig(o,a)}catch(f){return pe(`could not write ${o}: ${Qv(f)}`),1}let d=await t.spawnInteractive(Is(l,r,e.route,o));return d.spawnError!==null?js(t,e,r,`could not start switchyard (${d.spawnError})`):Uf(d.code,d.signal,d.elapsedMs)==="fallback-eligible"?js(t,e,r,`switchyard exited with code ${d.code} after ${(d.elapsedMs/1e3).toFixed(1)}s`):Ns(d.code,d.signal)}s(Yf,"runLaunch");async function js(e,t,n,r){return t.noFallback?(pe(`${r} (--no-fallback set \u2014 not degrading to a direct spawn).`),1):(process.stderr.write(Gf(r)+`
202
202
  `),Xf(e,Ds(n)))}s(js,"degradeOrFail");async function Xf(e,t){let n=await e.spawnInteractive(t);return n.spawnError!==null?(pe(`'${t[0]}' not found on PATH \u2014 install the agent CLI first (${n.spawnError}).`),1):Ns(n.code,n.signal)}s(Xf,"spawnAndPropagate");import{execFileSync as oa}from"node:child_process";import{cpSync as jS,existsSync as ia,mkdirSync as PS,realpathSync as MS}from"node:fs";import{dirname as jm,join as Im,resolve as Pm}from"node:path";function Zf(e,t){if(e!==null)return e.trim()==="0"?{kind:"none",reason:"no required checks"}:{kind:"watch"};let n=t();return n===null?{kind:"unknown",reason:"neither query could be answered"}:n.trim()==="0"?{kind:"none",reason:"no checks at all"}:{kind:"unknown",reason:`${n.trim()} check(s) exist, but the required-query failed`}}s(Zf,"classifyCheckCount");function Jf(e){switch(e.kind){case"watch":return"";case"none":return e.reason==="no checks at all"?"this repository reports NO checks at all \u2014 the merge rests on the local gate alone.":"no required checks are configured \u2014 nothing to wait for.";case"unknown":return`could not establish the required checks: ${e.reason}.`}}s(Jf,"checkCountLine");function Jr(e){if(!e)return null;let t=e.indexOf("=");if(t<=0)return null;let n=e.slice(0,t).trim(),r=e.slice(t+1).trim();return!n||!r?null:{gate:n,object:r}}s(Jr,"parseOverride");function rx(e){return e==="open"||e==="warn"}s(rx,"objectCarriesOverride");async function Qf(e,t,n){let r=[];for(let o of e)t.has(o.gate)||r.push(`--override ${o.gate}: not a gate declared in .maind/gates.json \u2014 only declared gates take an override`+(t.size>0?` (declared: ${[...t].join(", ")})`:""));let i=new Map;for(let o of new Set(e.map(a=>a.object))){let a=null;try{a=await n(o)}catch{a=null}let c=a?.key??o;a===null?r.push(`--override \u2026=${o}: the object could not be resolved \u2014 no override without proof that it is open`):rx(a.status)?i.set(o,a):r.push(`--override \u2026=${c}: the object is ${a.status} \u2014 it no longer tracks a red gate`)}return r.length>0?{kind:"refused",lines:r}:{kind:"ok",resolved:i}}s(Qf,"checkOverrides");function ep(e,t,n){let r=new Map(t.map(l=>[l.gate,l])),i=[],o=e.map(l=>{let u=r.get(l.id);if(!u)return l;let d=n.get(u.object);return!d||l.verdict!=="fail"||!l.blocking?l:(i.push({gate:l.id,object:d}),{...l,blocking:!1,note:`red, accepted \u2014 tracked by ${d.key??d.id}`})}),a=new Set(i.map(l=>l.gate)),c=t.filter(l=>!a.has(l.gate)).map(l=>({gate:l.gate,verdict:e.find(u=>u.id===l.gate)?.verdict??"absent"}));return{results:o,used:i,unused:c}}s(ep,"applyOverrides");function tp(e){return e.map(t=>t.verdict==="absent"?`--override ${t.gate}: the gate did not run \u2014 nothing was accepted`:`--override ${t.gate}: the gate is ${t.verdict==="pass"?"green":t.verdict}, not red \u2014 nothing was accepted, nothing recorded`)}s(tp,"unusedOverrideLines");function np(e,t){let n=e!==null&&e.trim().length>0;return t==="closes"?{kind:"decided",completes:!0}:t==="progress"?{kind:"decided",completes:!1}:n?{kind:"missing",objectId:e.trim()}:{kind:"decided",completes:!1}}s(np,"decideCompletion");function rp(e,t){return[`${e} is bound to work object ${t}, and the merge will be reported there.`,"Does this pull request FINISH that object? Say so \u2014 neither answer is assumed:"," --closes-object it does: the merge is reported as completion"," --progress-only one step of several: the merge is logged, the object stays open","Nothing was merged."]}s(rp,"missingCompletionLines");function ip(e,t){let n=e.replace(/\/+$/,""),r=t.replace(/\/+$/,"");return n===r||n.startsWith(`${r}/`)}s(ip,"cwdInside");async function op(e,t){if(e!==null&&e.trim().length>0)return{kind:"bound",objectId:e.trim()};let n=t.prNumber(),r=t.slug();if(n===null||r===null)return{kind:"unbound"};let i=`github:${r}#${n}`,o=null;try{o=await t.lookup(i)}catch{o=null}return o===null?{kind:"unbound"}:(t.write(o.id,o.key),{kind:"recovered",objectId:o.id,key:o.key,ref:i})}s(op,"recoverBinding");async function sp(e,t){let n=t.prNumber(),r=t.slug();if(n===null||r===null)return{kind:"no-pr"};let i=`github:${r}#${n}`,o=null;try{o=await t.lookup(i)}catch{o=null}return o!==null?o.id===e?{kind:"already",ref:i}:{kind:"mismatch",ref:i,other:o}:(await t.link(e,i),{kind:"link-attempted",ref:i})}s(sp,"ensurePrLinked");function ix(e){return/^[A-Za-z0-9_./-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}s(ix,"shellQuote");function ox(e,t){let n=t.replace(/^\/+|\/+$/g,"");return n.length===0?e:`${e.replace(/\/+$/,"")}/${n}`}s(ox,"joinAbs");function sx(e){return e.endsWith("/")?e:`${e}/`}s(sx,"withPrefix");function ax(e){let t=new Set;for(let r of e){let i=/^((?:[^/]+\/)*?)supabase\/(?:migrations|functions)\//.exec(r);i&&t.add(i[1])}let n=[];for(let r of[...t].sort()){let i=r.replace(/\/$/,"");n.push({when:`${r}supabase/migrations/`,run:"supabase db push",cwd:i}),n.push({when:`${r}supabase/functions/`,run:"supabase functions deploy {name}",cwd:i,each:"dir"})}return n}s(ax,"defaultPostMergeSteps");function ap(e,t,n){let r=e.map(a=>a.trim()).filter(a=>a.length>0),i=t??ax(r),o=[];for(let a of i){let c=sx(a.when),l=r.filter(m=>m.startsWith(c));if(l.length===0)continue;let u=`cd ${ix(ox(n,a.cwd??""))} && `,d=s((m,y)=>m===void 0?void 0:m.split("{name}").join(y),"fill");if(a.each!=="dir"){o.push({reason:`${l.length} file(s) under ${c}`+(a.note?` \u2014 ${a.note}`:""),command:a.run?u+a.run:null});continue}let f=[...new Set(l.map(m=>m.slice(c.length).split("/")[0]).filter(m=>m.length>0))].sort();for(let m of f.filter(y=>!y.startsWith("_"))){let y=d(a.note,m),g=d(a.run,m);o.push({reason:`${c}${m}/ changed`+(y?` \u2014 ${y}`:""),command:g?u+g:null})}let h=f.filter(m=>m.startsWith("_"));h.length>0&&o.push({reason:`${h.map(m=>`${c}${m}/`).join(", ")} changed \u2014 shared code, no target of its own: redeploy what imports it`,command:null})}return o}s(ap,"postMergeActions");function cp(e,t){if(e.length===0)return[];let n=[`the merge on ${t} needs steps it did not run \u2014 they are yours (nothing was executed):`];for(let r of e)n.push(` \u2022 ${r.reason}`),r.command&&n.push(` ${r.command}`);return n}s(cp,"postMergeLines");import{readFileSync as fp}from"node:fs";import{join as pp}from"node:path";var Ms={branchPrefix:"feat/",remote:"origin",baseBranch:null,postCreate:[],postMerge:null},Ln=".maind/feature.json";function lp(e){return!e||e.trim().length===0?"a feature name is required":e.startsWith("-")?`"${e}" must not start with a dash`:e.includes("..")?`"${e}" must not contain ".."`:/^[A-Za-z0-9._-]+$/.test(e)?null:`"${e}" may only contain letters, digits, dot, underscore and dash`}s(lp,"validateFeatureName");function Fn(e,t){return`${e.replace(/[/\\]+$/,"")}-${t}`}s(Fn,"worktreePathFor");function Qr(e,t){return`${e.branchPrefix}${t}`}s(Qr,"branchFor");function up(e,t){let n=lp(t.name);if(n)return{kind:"invalid-name",reason:n};let r=Fn(t.repoRoot,t.name);if(e.exists(r))return{kind:"path-exists",path:r};let i=Qr(t.cfg,t.name);if(e.branchExists(t.repoRoot,i))return{kind:"branch-exists",branch:i};let o=t.cfg.baseBranch??e.defaultBranch(t.repoRoot);if(!o)return{kind:"no-base-branch"};e.fetch(t.repoRoot,t.cfg.remote);let a=`${t.cfg.remote}/${o}`;return e.refExists(t.repoRoot,a)?e.worktreeAdd(t.repoRoot,r,i,a)?{kind:"ok",path:r,branch:i,startPoint:a,provisioned:t.requirements}:{kind:"worktree-failed",path:r,branch:i}:{kind:"start-point-missing",startPoint:a,remote:t.cfg.remote}}s(up,"planStart");function Ls(e,t){let n=lp(t.name);if(n)return{kind:"invalid-name",reason:n};let r=Fn(t.repoRoot,t.name),i=Qr(t.cfg,t.name),o=!1;if(e.exists(r)){if(e.isDirty(r)!==!1)return{kind:"dirty",path:r};if(!e.worktreeRemove(t.repoRoot,r))return{kind:"remove-failed",path:r};o=!0}if(!e.branchExists(t.repoRoot,i))return{kind:"ok",removedWorktree:o,deletedBranch:!1};if(e.branchDelete(t.repoRoot,i,!1))return{kind:"ok",removedWorktree:o,deletedBranch:!0,via:"fast-forward"};let a=e.branchHead(t.repoRoot,i),c=e.mergedPr(t.repoRoot,i);return c?c.state!=="MERGED"?{kind:"branch-unverified",branch:i,reason:`PR state is ${c.state}, not MERGED`}:!a||!c.headSha||c.headSha!==a?{kind:"branch-unverified",branch:i,reason:`the merged PR's head (${c.headSha??"unknown"}) is not the local head (${a??"unknown"})`}:e.branchDelete(t.repoRoot,i,!0)?{kind:"ok",removedWorktree:o,deletedBranch:!0,via:"squash-proof"}:{kind:"branch-unverified",branch:i,reason:"git refused to delete the branch"}:{kind:"branch-unverified",branch:i,reason:"no merged PR found for this branch"}}s(Ls,"planDone");function dp(e,t){let n=[];for(let r of e.worktreeList(t.repoRoot))!r.branch||!r.branch.startsWith(t.cfg.branchPrefix)||n.push({name:r.branch.slice(t.cfg.branchPrefix.length),branch:r.branch,path:r.path});return n.sort((r,i)=>r.name.localeCompare(i.name))}s(dp,"listFeatureWorktrees");function cx(e){let t=[];if(e===null||typeof e!="object"||Array.isArray(e))return{problems:["the manifest must be a JSON object"]};let n=e,r={...Ms},i=s((o,a)=>{if(!(o in n)||n[o]===void 0||n[o]===null)return;let c=n[o];if(typeof c!="string"){t.push(`"${o}" must be a string, got ${ei(c)}`);return}if(!a&&c.trim().length===0){t.push(`"${o}" must not be empty`);return}r[o]=c},"str");if(i("branchPrefix",!1),i("remote",!1),"baseBranch"in n&&n.baseBranch!==void 0){let o=n.baseBranch;o===null?r.baseBranch=null:typeof o=="string"&&o.trim().length>0?r.baseBranch=o:t.push(`"baseBranch" must be a non-empty string or null, got ${ei(o)}`)}if("postCreate"in n&&n.postCreate!==void 0&&n.postCreate!==null){let o=n.postCreate;!Array.isArray(o)||o.some(a=>typeof a!="string"||a.trim().length===0)?t.push(`"postCreate" must be an array of non-empty strings, got ${ei(o)}`):r.postCreate=o}if("postMerge"in n&&n.postMerge!==void 0&&n.postMerge!==null){let o=n.postMerge,a=s(c=>{if(c===null||typeof c!="object"||Array.isArray(c))return!0;let l=c;if(typeof l.when!="string"||l.when.trim().length===0)return!0;let u=s(d=>typeof d=="string"&&d.trim().length>0,"nonEmpty");return!!(l.run!==void 0&&!u(l.run)||l.note!==void 0&&!u(l.note)||l.run===void 0&&l.note===void 0||l.cwd!==void 0&&typeof l.cwd!="string"||l.each!==void 0&&l.each!=="dir"||l.each!=="dir"&&[l.run,l.note].some(d=>typeof d=="string"&&d.includes("{name}")))},"bad");!Array.isArray(o)||o.some(a)?t.push(`"postMerge" must be an array of {when, run?, note?, cwd?, each?: "dir"} with a non-empty when and at least one of run/note ({name} only together with each: "dir"), got ${ei(o)}`):r.postMerge=o.map(c=>({when:c.when,...typeof c.run=="string"?{run:c.run}:{},...typeof c.note=="string"?{note:c.note}:{},...typeof c.cwd=="string"?{cwd:c.cwd}:{},...c.each==="dir"?{each:"dir"}:{}}))}return t.length>0?{problems:t}:{cfg:r}}s(cx,"parseFeatureConfig");function ei(e){return e===null?"null":Array.isArray(e)?"an array":typeof e}s(ei,"describe");function mp(e){let t=pp(e,Ln),n;try{n=fp(t,"utf8")}catch{return{kind:"defaults",cfg:{...Ms}}}let r;try{r=JSON.parse(n)}catch(o){return{kind:"invalid",path:t,problems:[`not valid JSON: ${o.message}`]}}let i=cx(r);return"problems"in i?{kind:"invalid",path:t,problems:i.problems}:{kind:"loaded",cfg:i.cfg,path:t}}s(mp,"loadFeatureConfig");function lx(e){return e.split(`
@@ -339,7 +339,7 @@ Der Lauf hat keine Beschreibung hinterlassen (\`${gi}\` fehlt) \u2014 was ge\xE4
339
339
  verdict unknown = the ingest endpoint predates slice verdicts; redeploy mcp-client-metrics-ingest and re-run \u2014 re-running is safe, the server replaces.`),n}s(ZE,"renderSliceSummary");function JE(e){let t=e.rows.filter(r=>!r.context_ok&&r.slices>0).length,n=!e.contextAvailable&&t>0;return{unattributed:t,contextLost:n,exitCode:e.failed===0&&!n?0:1}}s(JE,"backfillOutcome");import{createRequire as h0}from"node:module";import{readFileSync as g0}from"node:fs";import{dirname as y0,join as b0}from"node:path";var Ye="@anthropic-ai/claude-agent-sdk",QE="0.3.258",Na=new Set([QE]),e0="dontAsk",Ia="PreToolUse",t0="Stop",n0="PostToolBatch";var r0="http";var i0="claude_code",o0="system",s0="init",Mi={success:"success",errorDuringExecution:"error_during_execution",errorMaxTurns:"error_max_turns",errorMaxBudget:"error_max_budget_usd",errorMaxStructuredOutputRetries:"error_max_structured_output_retries"};var a0={injectBeforeFirstTurn:!0,preToolDeny:!0,stopGate:!0,budget:!0,resume:!0,toolEvents:!0};function c0(e){return e.kind==="allow"?{}:e.kind==="warn"?{hookSpecificOutput:{hookEventName:Ia,additionalContext:e.reason}}:{hookSpecificOutput:{hookEventName:Ia,permissionDecision:"deny",permissionDecisionReason:_h(e)}}}s(c0,"toHookOutput");function l0(e){return e.kind==="finish"?{}:{decision:"block",reason:e.reason}}s(l0,"toStopHookOutput");function u0(e){return e?{continue:!1,stopReason:e.reason}:{}}s(u0,"toBatchHookOutput");function d0(e,t){return e===Mi.success?t==="refusal"?"refusal":"completed":e===Mi.errorMaxTurns?"max_turns":e===Mi.errorMaxBudget?"max_budget":"error"}s(d0,"toStopKind");function Da(e,t){let n=0,r=0,i=0,o=0,a=[];if(t&&typeof t=="object")for(let[c,l]of Object.entries(t)){if(!l||typeof l!="object")continue;let u={model:c,inputTokens:l.inputTokens??0,outputTokens:l.outputTokens??0,cacheReadInputTokens:l.cacheReadInputTokens??0,cacheCreationInputTokens:l.cacheCreationInputTokens??0};n+=u.inputTokens,r+=u.outputTokens,i+=u.cacheReadInputTokens,o+=u.cacheCreationInputTokens,c.trim().length>0&&a.push(u)}return{totalCostUsd:typeof e=="number"?e:0,inputTokens:n,outputTokens:r,cacheReadInputTokens:i,cacheCreationInputTokens:o,byModel:a}}s(Da,"toUsage");function f0(e){if(!e)return null;let t=new AbortController;return e.aborted?t.abort(e.reason):e.addEventListener("abort",()=>t.abort(e.reason),{once:!0}),t}s(f0,"controllerFor");function p0(e){let t=e.options,n=f0(e.signal);return{cwd:e.cwd,env:{...e.env},systemPrompt:{type:"preset",preset:i0,append:t.systemPromptAppend},settingSources:t.loadProjectSettings?["project"]:[],allowedTools:[...t.allowedTools],disallowedTools:[...t.disallowedTools],permissionMode:e0,...e.mcpServers?{mcpServers:Object.fromEntries(Object.entries(e.mcpServers).map(([r,i])=>[r,{type:r0,url:i.url,headers:{...i.headers}}]))}:{},...n?{abortController:n}:{},...t.maxTurns!==null?{maxTurns:t.maxTurns}:{},...t.maxBudgetUsd!==null?{maxBudgetUsd:t.maxBudgetUsd}:{}}}s(p0,"toSdkOptions");function Li(e){for(let t of e)if(!(t.type!==o0||t.subtype!==s0))return{model:fg(t.model),apiKeySource:fg(t.apiKeySource)};return{model:null,apiKeySource:null}}s(Li,"initInfoFrom");function fg(e){return typeof e=="string"&&e.trim().length>0?e:null}s(fg,"nonEmpty");function m0(e){let t=null;for(let o of e)o.type==="result"&&(t=o);if(!t)return null;let n=typeof t.subtype=="string"?t.subtype:"",r=typeof t.stop_reason=="string"?t.stop_reason:null,i=t.permission_denials;return{stop:d0(n,r),stopReason:r,numTurns:typeof t.num_turns=="number"?t.num_turns:0,durationMs:typeof t.duration_ms=="number"?t.duration_ms:0,usage:Da(t.total_cost_usd,t.modelUsage),permissionDenials:Array.isArray(i)?i.length:0,sessionId:typeof t.session_id=="string"?t.session_id:null,...Li(e),...n!==Mi.success?{errorText:typeof t.result=="string"?t.result:n}:{}}}s(m0,"resultFrom");function pg(e,t){return{id:`claude-agent-sdk@${t}`,capabilities:a0,async run(n){let r=p0(n);if(r.hooks={[Ia]:[{hooks:[async a=>c0(n.gate({tool:typeof a.tool_name=="string"?a.tool_name:"",input:a.tool_input&&typeof a.tool_input=="object"?a.tool_input:{}}))]}]},n.stop&&(r.hooks[t0]=[{hooks:[async a=>l0(await n.stop({repeated:a.stop_hook_active===!0,lastMessage:typeof a.last_assistant_message=="string"?a.last_assistant_message:null}))]}]),n.afterBatch){let a=n.afterBatch;r.hooks[n0]=[{hooks:[async()=>u0(a())]}]}let i=[];try{let a=!1;for await(let c of e({prompt:n.prompt,options:r})){if(i.push(c),!a&&n.onInit){let l=Li([c]);if(l.model!==null){a=!0;try{n.onInit({model:l.model,apiKeySource:l.apiKeySource})}catch{}}}if(n.signal?.aborted)break}}catch(a){return{stop:"error",stopReason:null,numTurns:0,durationMs:0,usage:Da(0,null),permissionDenials:0,sessionId:null,...Li(i),errorText:a instanceof Error?a.message:String(a)}}let o=m0(i);return o?n.signal?.aborted&&o.stop==="error"?{...o,stop:"aborted",errorText:String(n.signal.reason??"aborted")}:o:{stop:"error",stopReason:null,numTurns:0,durationMs:0,usage:Da(0,null),permissionDenials:0,sessionId:null,...Li(i),errorText:"Der Lauf endete ohne Ergebnis-Nachricht."}}}}s(pg,"createClaudeAgentSdkHarness");function _0(){try{let e=h0(import.meta.url).resolve(Ye),t=g0(b0(y0(e),"package.json"),"utf8"),n=JSON.parse(t);return n.name!==Ye?null:typeof n.version=="string"?n.version:null}catch{return null}}s(_0,"installedSdkVersion");function w0(e){return e!==null&&Na.has(e)}s(w0,"isSupportedVersion");async function mg(e={}){let t=(e.readVersion??_0)();if(t===null)return{ok:!1,version:null,reason:`${Ye} ist nicht installiert.`};if(!w0(t))return{ok:!1,version:t,reason:`${Ye}@${t} ist nicht gepr\xFCft. Unterst\xFCtzt: ${[...Na].join(", ")}. Der Adapter wird gegen genau diese Versionen getestet \u2014 eine ungepr\xFCfte Version k\xF6nnte Felder umbenannt haben, ohne dass es auffiele.`};let n;try{n=e.load?await e.load(Ye):await import(Ye)}catch(i){return{ok:!1,version:t,reason:`${Ye}@${t} lie\xDF sich nicht laden: ${String(i)}`}}let r=n?.query;return typeof r!="function"?{ok:!1,version:t,reason:`${Ye}@${t} exportiert kein aufrufbares \`query\`.`}:{ok:!0,version:t,harness:pg(r,t)}}s(mg,"probeSdk");import{appendFile as k0,mkdir as v0,open as x0,stat as S0}from"node:fs/promises";import{homedir as R0}from"node:os";import{join as hg}from"node:path";var gg=hg(R0(),".maind","kernel"),E0=hg(gg,"runs.jsonl"),A0={dir:gg,file:E0,mkdir:s(async e=>{await v0(e,{recursive:!0,mode:448})},"mkdir"),append:s(async(e,t)=>{await k0(e,t,{mode:384})},"append"),readTail:s(async(e,t)=>{try{let n=await S0(e),r=Math.max(0,n.size-t),i=await x0(e,"r");try{let o=Buffer.alloc(Math.min(t,n.size));return await i.read(o,0,o.length,r),{text:o.toString("utf8"),truncated:r>0}}finally{await i.close()}}catch{return null}},"readTail")};async function yg(e,t=A0){try{return await t.mkdir(t.dir),await t.append(t.file,JSON.stringify(e)+`
340
340
  `),!0}catch{return!1}}s(yg,"appendRunRecord");var T0=["review-gate","dispatch"],C0=["edit_outside_worktree","write_base_tree","force_push","secret_path"],O0=["mcp__maind__search_lessons","mcp__maind__get_lesson","mcp__maind__get_conventions"];function bg(e){return e.GITHUB_ACTIONS==="true"?"ci:github":"local"}s(bg,"defaultExecutor");function I0(e,t){return e?e==="local"?"local":/^(ci|runner|vendor):.+/.test(e)?e:bg(t):bg(t)}s(I0,"parseExecutor");function kg(e,t=process.env){let n=s(g=>{let b=e.indexOf(g);if(!(b===-1||b+1>=e.length))return e[b+1]},"get"),r=s(g=>e.includes(g),"has"),i=r("--listen"),o=s(g=>{let b=(g??"").trim();return b.length>0?b:null},"nonEmpty"),a=s(g=>g==="team"||g==="org"?g:"self","acceptOf"),c=new Set(["--base","--task","--task-file","--fail-on","--max-turns","--max-budget","--override","--executor","--review-out","--evidence-out","--project-key","--mcp-url"]);for(let g of["--max","--ttl","--renew","--name","--accept","--poll"])c.add(g);let l=null,u=null,d=r("--pull");for(let g=0;g<e.length;g+=1){let b=e[g];if(c.has(b)){g+=1;continue}if(!b.startsWith("--")){if(b==="object"){l="dispatch";let _=e[g+1];u=_&&!_.startsWith("--")?_:null;break}l=b==="review-gate"?"review-gate":null;break}}l===null&&(d||i)&&(l="dispatch");let f=l==="dispatch"?sh(u,d):null;l==="dispatch"&&f===null&&!i&&(l=null);let h={};for(let g=0;g<e.length;g+=1){if(e[g]!=="--override")continue;let b=e[g+1];if(!b)continue;let _=b.indexOf("=");if(_<=0)continue;let w=b.slice(0,_),R=b.slice(_+1).replace(/^"|"$/g,"");C0.includes(w)&&R.length>0&&(h[w]=R)}let m=n("--fail-on"),y=s(g=>{if(!g)return null;let b=Number(g);return Number.isFinite(b)&&b>0?b:null},"num");return{form:l,base:n("--base")??null,task:n("--task")??null,taskFile:n("--task-file")??null,failOn:m==="warn"?"warn":"block",maxTurns:y(n("--max-turns")),maxBudgetUsd:y(n("--max-budget")),overrides:h,projectSettings:r("--project-settings"),executor:I0(n("--executor"),t),reviewOut:n("--review-out")??".maind/run-review.md",evidenceOut:n("--evidence-out")??null,projectKey:n("--project-key")??null,mcpUrl:n("--mcp-url")??null,json:r("--json"),dryRun:r("--dry-run"),target:f,max:Math.max(1,Math.floor(y(n("--max"))??1)),ttlMinutes:Math.floor(y(n("--ttl"))??240),renewMinutes:Math.max(1,Math.floor(y(n("--renew"))??10)),listen:i,runnerName:o(n("--name")),acceptFrom:a(n("--accept")),pollSeconds:Math.max(2,Math.floor(y(n("--poll"))??10)),help:r("--help")||r("-h")}}s(kg,"parseRunArgs");var D0={probe:s(()=>mg(),"probe"),closing:s(e=>Ah(e),"closing"),fetchContext:s(async e=>{let t=z(),r=await new ee({apiKey:t.apiKey,deviceId:t.deviceId,clientVersion:Y,mcpUrl:e.mcpUrl??void 0,projectKey:e.projectKey}).callTool("get_conventions",{}),i=Array.isArray(r.conventions)?r.conventions:[],o=i.filter(c=>typeof c.id=="string").map(c=>`${c.id}@${typeof c.version=="number"?c.version:"?"}`),a=i.filter(c=>typeof c.summary=="string").map(c=>`- ${String(c.summary)}`).join(`
341
341
  `);return{briefing:a.length>0?a:null,conventions:o}},"fetchContext"),mcpServer:s(e=>{let t=z(),n={authorization:`Bearer ${t.apiKey}`,"x-maind-client-family":"maind-cli","x-maind-client-version":Y};return t.deviceId&&(n["x-maind-device-id"]=t.deviceId),e.projectKey&&(n["x-maind-project-key"]=e.projectKey),{url:e.mcpUrl??process.env.MAIND_MCP_URL??"https://mcp.maind.dev/mcp",headers:n}},"mcpServer"),readRepoInstructions:s(e=>{let t=[];for(let n of["CLAUDE.md","AGENTS.md"])try{t.push(wg(`${e}/${n}`,"utf8"))}catch{}return t},"readRepoInstructions"),resolveRepoRoot:s(e=>{try{return _g("git",["-C",e,"rev-parse","--show-toplevel"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()}catch{return null}},"resolveRepoRoot"),appendRecord:s(e=>yg(e),"appendRecord"),now:s(()=>new Date().toISOString(),"now"),cwd:s(()=>process.cwd(),"cwd"),env:process.env,out:s(e=>process.stdout.write(e),"out"),warn:s(e=>process.stderr.write(`maind run: ${e}
342
- `),"warn")},Fi=["usage: maind run review-gate [--base <ref>] [--task <text>] [--dry-run]"," maind run object <MAI-n|uuid> [--ttl <min>] [--renew <min>] [--max-budget <usd>] [--dry-run]"," maind run --pull [--max <n>] [--ttl <min>] [--renew <min>] [--max-budget <usd>]"," maind run --listen --name <n> [--accept self|team|org] [--poll <s>] [--ttl <min>] [--renew <min>] [--max-budget <usd>]"];function ja(e,t){e.warn(t);for(let n of Fi)e.warn(n);return 2}s(ja,"usage");async function vg(e,t=D0){if(e.help){for(let C of Fi)t.out(`${C}
342
+ `),"warn")},Fi=["usage: maind run review-gate [--base <ref>] [--task <text> | --task-file <path>] [--fail-on block|warn]"," [--max-turns <n>] [--max-budget <usd>] [--dry-run]"," maind run object <MAI-n|uuid> [--ttl <min>] [--renew <min>] [--fail-on block|warn]"," [--max-turns <n>] [--max-budget <usd>] [--evidence-out <dir>] [--dry-run]"," maind run --pull [--max <n>] [--ttl <min>] [--renew <min>] [--fail-on block|warn]"," [--max-turns <n>] [--max-budget <usd>] [--evidence-out <dir>]"," maind run --listen --name <n> [--accept self|team|org] [--poll <s>] [--ttl <min>] [--renew <min>] [--max-budget <usd>]"];function ja(e,t){e.warn(t);for(let n of Fi)e.warn(n);return 2}s(ja,"usage");async function vg(e,t=D0){if(e.help){for(let C of Fi)t.out(`${C}
343
343
  `);return 0}if(!e.form)return ja(t,"missing or unknown form.");if(!T0.includes(e.form))return ja(t,`form '${e.form}' is not implemented yet (review-gate, object <key>, --pull, --listen).`);if(e.form==="dispatch"){if(!e.listen&&!e.target)return ja(t,"dispatch needs `object <MAI-n|uuid>`, `--pull` or `--listen --name <n>`.");let C={...t,plan:Th(j0(e)),repo:Ch,projectKeyOf:s(k=>{let E=P0(k);return E?ue(E):null},"projectKeyOf"),newSessionId:s(()=>$0(),"newSessionId"),onSignal:s((k,E)=>{process.on(k,E)},"onSignal"),offSignal:s((k,E)=>{process.off(k,E)},"offSignal"),sleep:s((k,E)=>new Promise(x=>{if(E.aborted)return x();let j=setTimeout(H,k);function H(){clearTimeout(j),E.removeEventListener("abort",H),x()}s(H,"done"),E.addEventListener("abort",H,{once:!0}),j.unref?.()}),"sleep"),every:s((k,E)=>{let x=setInterval(E,k);return x.unref(),{clear:s(()=>clearInterval(x),"clear")}},"every"),reportCost:s(async k=>{let E=z();await dn({endpoint:Oa(),apiKey:E.apiKey,deviceId:E.deviceId},k.analytics,null,void 0,"live_bridge",{slices:k.slices,context_ok:!0})},"reportCost")};return e.listen?Ih(e,C):Oh(e,C)}let n=t.now(),r=t.cwd(),i={denies:{},warns:{},overrides:e.overrides},o={},a=s(async(C,k)=>{let E;try{E=Ai({form:e.form,executor:e.executor,cliVersion:Y,harnessId:"unknown",harnessVersion:"unknown",model:null,authSource:null,effort:null,contextDigest:"0".repeat(64),contextPartial:e.projectSettings,conventions:[],commitSha:null,projectKey:e.projectKey,outcome:C,gates:i,tools:o,harness:null,startedAt:n,endedAt:t.now(),...k})}catch(x){return t.warn(`could not build a run record: ${x instanceof Error?x.message:String(x)}`),2}return await t.appendRecord(E)||t.warn(`could not write the run record to ~/.maind/kernel/runs.jsonl (outcome: ${C}).`),e.json&&t.out(JSON.stringify(E)+`
344
344
  `),Wn(C)},"finish"),c=t.resolveRepoRoot(r);if(!c)return t.warn("not a git repository \u2014 the review gate is diff-based."),a("unavailable",{note:"not a git repository"});let l;try{l=await t.fetchContext({mcpUrl:e.mcpUrl,projectKey:e.projectKey})}catch(C){let k=`policy unavailable: ${C instanceof Error?C.message:String(C)}`;return t.warn(k),a("unavailable",{note:k})}let u=e.task??(e.taskFile?N0(e.taskFile):null)??"Review the pending change set against the conventions in effect. Do not modify files.",d=hi({briefing:l.briefing,conventions:l.conventions,task:u,repoInstructions:t.readRepoInstructions(c),projectSettingsLoaded:e.projectSettings}),f=xi({form:e.form,briefing:l.briefing,conventions:l.conventions,task:u,repoInstructions:t.readRepoInstructions(c),worktreeRoot:c,baseTreeRoot:null,mcpTools:O0,loadProjectSettings:e.projectSettings,maxTurns:e.maxTurns,maxBudgetUsd:e.maxBudgetUsd});if(e.dryRun)return t.out(f.systemPromptAppend+`
345
345
  `),t.out(`