pando-ai 0.3.3 → 0.3.4
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/dist/cli.js
CHANGED
|
@@ -865,7 +865,7 @@ ${r.join(`
|
|
|
865
865
|
`},"replace-body":{op:"replace-body",path:"src/app.ts#FD:0",expectedHash:"p123:c456",with:"console.log(1);"},"filter-map-reduce":{op:"filter-map-reduce",query:{lang:["ts","js"],scope:{workspace:!0},datalog:{query:'[:find ?n :where [?n :node/name "init"]]',bindings:["?n"],result:{nodeVar:"?n"}},page:{limit:20,cursor:null}},transforms:[{op:"replace",path:"$MATCH",with:"function initApp() {}"}]},"diff-snapshots":{op:"diff-snapshots",head:"S_current",base:"S_previous"},"set-enabled-languages":{op:"set-enabled-languages"},"get-snapshot-trailers":{op:"get-snapshot-trailers",snapshotId:"S_current",keys:["message"]},"get-snapshot-file":{op:"get-snapshot-file",snapshotId:"S_current",path:"src/app.ts"},"snapshot-worktree":{op:"snapshot-worktree",message:"checkpoint"},"restore-snapshot":{op:"restore-snapshot",snapshotId:"S_previous"},"restore-files":{op:"restore-files",snapshotId:"S_previous",files:["src/app.ts"]},"add-exclude-dir":{op:"add-exclude-dir",directory:"dist/"},"remove-exclude-dir":{op:"remove-exclude-dir",directory:"dist/"}}});var wS={};Lt(wS,{SnapshotService:()=>_S});var yC,xS,_S,vS=ne(()=>{"use strict";yC=B(require("path")),xS=B(require("fs"));sa();_S=class{static async takeSnapshotNow(e,t,r,s,i,o,a){ct(a,"Snapshot cancelled");let c=f=>f.replace(/^\.\//,"").replace(/\\/g,"/"),l=Array.from(new Set((t||[]).map(c))).filter(Boolean),u=[];for(let f=0;f<l.length;f++){f>0&&f%128===0&&await Pu(a),ct(a,"Snapshot cancelled");let m=l[f],h=yC.default.join(e,m);xS.default.existsSync(h)&&xS.default.statSync(h).isFile()&&u.push(m)}let{openSnapshotsDb:d}=(hi(),be(mo)),p=d(e);try{ct(a,"Snapshot cancelled");let{SnapshotManager:f}=(Nm(),be(Am)),m=new f(p,e),h={"AST-Op":r,"AST-Receipt":JSON.stringify(s||{})};if(i)for(let[b,S]of Object.entries(i))h[b]=S;let{snapshotId:g,parentId:y}=await m.createSnapshotFromFiles(u,{op:r,description:"apply",params:h,dbWrite:"immediate",deleted:Array.isArray(o)?o:void 0},a);ct(a,"Snapshot cancelled");try{await m.indexSnapshotBlobsNodes(p,g,y),console.info(`[SnapshotService] Blob node index updated snapshot=${g} parent=${y||"none"}`)}catch(b){console.log(`[SnapshotService] Blob node indexing failed snapshot=${g}: ${b?.message||b}`)}return{snapshotId:g,parentId:y}}finally{try{p.close()}catch{}}}}});var bC={};Lt(bC,{TypeInference:()=>RS});var Br,RS,SC=ne(()=>{"use strict";Br=require("ts-morph"),RS=class{static{this.typeCache=new Map}static{this.MAX_CACHE_SIZE=1e3}static getCacheKey(e){let t=e.getSourceFile(),r=e.getStart(),s=e.getEnd();return`${t.getFilePath()}:${r}-${s}`}static clearCache(){this.typeCache.clear()}static addToCache(e,t){this.typeCache.size>=this.MAX_CACHE_SIZE&&Array.from(this.typeCache.keys()).slice(0,100).forEach(s=>this.typeCache.delete(s)),this.typeCache.set(e,t)}static inferIdentifierType(e){let t=this.getCacheKey(e),r=this.typeCache.get(t);if(r)return r;try{let s=e.getSymbol();if(s){let c=s.getTypeAtLocation(e),l=this.typeToString(c);return this.addToCache(t,l),l}let i=e.getDefinitions();if(i.length>0){let l=i[0].getDeclarationNode();if(l){if(Br.Node.isVariableDeclaration(l))return this.inferVariableType(l);if(Br.Node.isParameterDeclaration(l))return this.inferParameterType(l)}}let o=e.getParent();if(Br.Node.isPropertyAccessExpression(o))return this.inferPropertyAccessType(o);let a="any";return this.addToCache(t,a),a}catch{return this.addToCache(t,"any"),"any"}}static inferVariableType(e){let t=e.getTypeNode();if(t)return t.getText();let r=e.getInitializer();return r?this.inferExpressionType(r):"any"}static inferParameterType(e){let t=e.getTypeNode();if(t)return t.getText();let r=e.getInitializer();return r?this.inferExpressionType(r):"any"}static inferExpressionType(e){try{let t=e.getType();return this.typeToString(t)}catch{if(Br.Node.isStringLiteral(e))return"string";if(Br.Node.isNumericLiteral(e))return"number";if(Br.Node.isTrueLiteral(e)||Br.Node.isFalseLiteral(e))return"boolean";if(Br.Node.isArrayLiteralExpression(e)){let t=e.getElements();return t.length>0?`${this.inferExpressionType(t[0])}[]`:"any[]"}else{if(Br.Node.isObjectLiteralExpression(e))return this.inferObjectLiteralType(e);if(Br.Node.isCallExpression(e))return this.inferCallExpressionType(e)}return"any"}}static inferPropertyAccessType(e){try{let t=e.getType();return this.typeToString(t)}catch{let t=e.getName();return t==="length"?"number":t==="toString"?"() => string":t.startsWith("is")||t.startsWith("has")?"boolean":"any"}}static inferObjectLiteralType(e){let t=e.getProperties();if(t.length===0)return"{}";let r=[];for(let s of t.slice(0,3))if(Br.Node.isPropertyAssignment(s)){let i=s.getName(),o=s.getInitializer();if(o){let a=this.inferExpressionType(o);r.push(`${i}: ${a}`)}}return t.length>3&&r.push("..."),`{ ${r.join(", ")} }`}static inferCallExpressionType(e){try{let t=e.getReturnType();return this.typeToString(t)}catch{let t=e.getExpression().getText();return t.includes("fetch")?"Promise<Response>":t.includes("getElementById")?"HTMLElement | null":t.includes("querySelector")?"Element | null":t.includes("parseInt")?"number":t.includes("JSON.parse")?"any":t.includes("JSON.stringify")?"string":"any"}}static typeToString(e){if(!e)return"any";if(e.isLiteral()){if(e.isStringLiteral())return"string";if(e.isNumberLiteral())return"number";if(e.isBooleanLiteral())return"boolean"}let r=e.getText().replace(/import\([^)]*\)\./g,"").replace(/\n/g," ").replace(/\s+/g," ").trim();if(r.length>50){if(r.includes("Promise<")){let s=r.match(/Promise<([^>]+)>/);if(s)return`Promise<${this.simplifyType(s[1])}>`}if(e.isArray()){let s=e.getArrayElementType();if(s)return`${this.typeToString(s)}[]`}return"any"}return r}static simplifyType(e){return e=e.replace(/import\([^)]*\)\./g,""),e=e.replace(/\w+\./g,""),e.split("|").length>3?"any":e}static inferParameterTypes(e,t){let r=[];t.forEachDescendant(s=>{if(Br.Node.isIdentifier(s)){let i=s.getText();if(e.includes(i)&&!r.find(o=>o.name===i)){let o=this.inferIdentifierType(s);r.push({name:i,type:o})}}});for(let s of e)r.find(i=>i.name===s)||r.push({name:s,type:"any"});return r}static inferReturnType(e){for(let r of e){let s=[];if(r.forEachDescendant(i=>{Br.Node.isReturnStatement(i)&&s.push(i)}),s.length>0){let o=s[0].getExpression();if(o){let a=this.inferExpressionType(o);if(a!=="any")return a}}}let t=e.map(r=>r.getText()).join(`
|
|
866
866
|
`);return t.includes("return results")||t.includes("return items")?"any[]":t.includes("return true")||t.includes("return false")?"boolean":t.includes("return")&&!t.includes("return;")?"any":"void"}}});var vC={};Lt(vC,{TextFileEditExecutor:()=>ES});function xC(n){return wC.default.createHash("sha256").update(n,"utf8").digest("hex")}function jB(n){return n.replace(/\\/g,"/")}function _C(n,e){let t=Na.default.relative(n,e);return t===""||!!t&&!t.startsWith("..")&&!Na.default.isAbsolute(t)}function LB(n,e){let t=String(e||"").trim();if(!t)return{abs:n,rel:"",error:'Parameter "file" is required.'};if(t.includes("\0"))return{abs:n,rel:"",error:'Parameter "file" contains an invalid NUL byte.'};let r=Na.default.resolve(n),s=Na.default.resolve(r,t);if(!_C(r,s))return{abs:s,rel:"",error:"Text edits are restricted to files inside the workspace root."};let i=jB(Na.default.relative(r,s)),o=i.split("/").filter(Boolean);if(o[0]!==".clj-kondo")return{abs:s,rel:i,error:"edit-file-text is restricted to .clj-kondo config and hook files."};if(o.includes(".cache"))return{abs:s,rel:i,error:"edit-file-text refuses .clj-kondo/.cache files."};let a=Na.default.extname(i).toLowerCase();if(!(i===".clj-kondo/config.edn"||a===".edn"||a===".clj"||a===".cljc"||a===".cljs"))return{abs:s,rel:i,error:"edit-file-text only supports .clj-kondo EDN and Clojure hook/source files."};try{let l=(Hc.default.realpathSync.native??Hc.default.realpathSync)(r),u=(Hc.default.realpathSync.native??Hc.default.realpathSync)(s);if(!_C(l,u))return{abs:s,rel:i,error:"Resolved file path escapes the workspace root."}}catch{return{abs:s,rel:i,error:"edit-file-text requires an existing regular file."}}try{if(!Hc.default.statSync(s).isFile())return{abs:s,rel:i,error:"edit-file-text target must be a regular file."}}catch{return{abs:s,rel:i,error:"edit-file-text requires an existing regular file."}}return{abs:s,rel:i}}function zB(n,e){let t=n,r=0;for(let s=0;s<e.length;s+=1){let i=e[s];if(typeof i?.old!="string"||typeof i?.new!="string")return{text:t,applied:r,error:`replacements[${s}] requires string old and new fields.`};if(i.old.length===0)return{text:t,applied:r,error:`replacements[${s}].old must be non-empty.`};let o=t.split(i.old).length-1;if(o===0)return{text:t,applied:r,error:`replacements[${s}].old was not found.`};if(!i.replaceAll&&o!==1)return{text:t,applied:r,error:`replacements[${s}].old matched ${o} times; set replaceAll=true or use a more specific old string.`};t=i.replaceAll?t.split(i.old).join(i.new):t.replace(i.old,i.new),r+=i.replaceAll?o:1}return{text:t,applied:r}}function BB(n,e){let t=[];for(let s=0;s<e.length;s+=1){let i=e[s];if(!i||typeof i.with!="string")return{text:n,applied:0,error:`edits[${s}] requires a string with field.`};let o=Number(i.start),a=Number(i.end);if(!Number.isInteger(o)||!Number.isInteger(a)||o<0||a<o||a>n.length)return{text:n,applied:0,error:`edits[${s}] has invalid character offsets.`};t.push({...i,start:o,end:a,index:s})}t.sort((s,i)=>i.start-s.start);for(let s=1;s<t.length;s+=1)if(t[s].end>t[s-1].start)return{text:n,applied:0,error:`edits[${t[s].index}] overlaps another edit.`};let r=n;for(let s of t)r=r.slice(0,s.start)+s.with+r.slice(s.end);return{text:r,applied:t.length}}var wC,Hc,Na,ES,RC=ne(()=>{"use strict";wC=B(require("crypto")),Hc=B(require("fs")),Na=B(require("path"));Er();ES=class{static async execute(e,t){let r=LB(t.projectRoot,e.file);if(r.error)return{success:!1,error:r.error,error_code:"validation_failed"};let s=String(e.expectedSha256||"").trim().toLowerCase();if(!/^[a-f0-9]{64}$/.test(s))return{success:!1,error:"expectedSha256 must be a 64-character lowercase hex SHA-256 of the current file text.",error_code:"validation_failed"};let i=Pe(r.abs),o=xC(i);if(o!==s)return{success:!1,error:"SHA-256 mismatch for text edit target. Re-read the file and retry with the current expectedSha256.",error_code:"hash_mismatch",details:{file:r.rel,expectedSha256:s,actualSha256:o}};if([typeof e.content=="string",Array.isArray(e.replacements),Array.isArray(e.edits)].filter(Boolean).length!==1)return{success:!1,error:"Provide exactly one of content, replacements, or edits.",error_code:"validation_failed"};let c=i,l=1;if(typeof e.content=="string")c=e.content;else if(Array.isArray(e.replacements)){if(e.replacements.length===0)return{success:!1,error:"replacements must be non-empty.",error_code:"validation_failed"};let d=zB(i,e.replacements);if(d.error)return{success:!1,error:d.error,error_code:"validation_failed",details:{file:r.rel}};c=d.text,l=d.applied}else if(Array.isArray(e.edits)){if(e.edits.length===0)return{success:!1,error:"edits must be non-empty.",error_code:"validation_failed"};let d=BB(i,e.edits);if(d.error)return{success:!1,error:d.error,error_code:"validation_failed",details:{file:r.rel}};c=d.text,l=d.applied}if(c===i)return{success:!0,message:"No text changes were needed.",details:{changedFiles:[],allChangedFiles:[],file:r.rel,appliedEdits:0,sha256:o}};cn(r.abs,c);let u=xC(c);return{success:!0,message:`Edited ${r.rel}`,details:{changedFiles:[r.rel],allChangedFiles:[r.rel],file:r.rel,appliedEdits:l,previousSha256:o,sha256:u,receipt:{op:"edit-file-text",target:r.rel,appliedEdits:l,previousSha256:o,sha256:u,textOnly:!0}}}}}});var EC=ne(()=>{"use strict"});var kC={};Lt(kC,{AtomicExecutor:()=>kS});var kS,TC=ne(()=>{"use strict";Hl();eS();Yu();sd();nd();EC();kS=class{static async execute(e,t,r,s){let i=String(e.op||""),o=["find-nodes"],a=i==="add-code"?"insert":i==="replace-body"?"replace":i;if(a!=="find-nodes"){let d=!o.includes(a),p=a==="insert"&&e.createFileIfMissing===!0;if(d&&!p&&!("expectedHash"in e))return{success:!1,error:`Operation ${e.op} requires expectedHash field.`}}let c;switch(a){case"find-nodes":c=await Ta.execute(e,t,r);break;case"insert":c=await Bi.execute({...e,op:"insert"},t,r);break;case"replace":i==="replace-body"||e.scope==="body"?c=await td.execute({...e,op:"replace",scope:"body"},t,r):c=await rd.execute({...e,op:"replace"},t,r);break;default:c={success:!1,error:`Atomic operation ${e.op} not yet implemented`};break}let u=zs.getInstance(t.projectRoot).getStatus();if(u.isIndexing){c.indexingStatus=u;let d="Warning: Reindexing in progress, results might not be complete or up to date.";if(u.totalFiles&&u.filesProcessed!==void 0){let p=u.totalFiles-u.filesProcessed;if(d+=` ${p} files remaining`,u.estimatedSecondsRemaining)if(u.estimatedSecondsRemaining<60)d+=` (est. ${u.estimatedSecondsRemaining}s)`;else{let f=Math.ceil(u.estimatedSecondsRemaining/60);d+=` (est. ${f} minute${f>1?"s":""})`}}c.message?c.message+=" "+d:c.message=d}return c}}});function V(n,e){ee("CodeEngine",n,e)}function An(...n){if(n.length===0)return;let[e,...t]=n;if(typeof e=="string"){if(t.length===0){ee("CodeEngine",e);return}if(t.length===1){ee("CodeEngine",e,t[0]);return}ee("CodeEngine",e,t);return}ee("CodeEngine","log",n)}function Nn(n,e){if(!Ht())return;let t=e&&typeof e=="object"&&!Array.isArray(e)?{pid:process.pid,...e}:{pid:process.pid,details:e};ee("CodeEngineReindex",n,t)}function qB(n){return n===void 0||n===0||n===1}function HB(n){let e=String(n??"").replace(/\s+/g," ").trim();return e?e.length>160?`${e.slice(0,157)}...`:e:"Unknown diagnostic"}function WB(n){let e=n.flatMap(r=>(r.topNewDiagnostics||[]).map(s=>`${r.path}:${s.line+1}:${s.column+1} ${s.message}`)).slice(0,3);return e.length>0?`Post-operation validation failed; changes rolled back. Top new diagnostics: ${e.join(" | ")}`:`Post-operation validation failed; changes rolled back. Changed files introduced diagnostics: ${n.slice(0,3).map(r=>{let s=Number(r.newDiagnostics||0);return`${r.path} (${r.errors} error(s)${s>0?`, ${s} new`:""})`}).join("; ")}`}function as(n){return require("path").resolve(n)}function UB(n){let e=n;if(typeof e.getNameNode=="function"){let t=e.getNameNode();if(t)return t.getStart()}if(typeof e.getName=="function"){let t=e.getName();if(t&&typeof t=="string"){let r=n.getFirstDescendant?.(s=>s.getText?.()===t);if(r&&typeof r.getStart=="function")return r.getStart()}}return null}var TS,PS,PC,Bl,ny=ne(()=>{"use strict";TS=require("child_process"),PS=B(require("fs"));IR();Ol();Nk();mb();oT();ea();Wy();Hl();_n();Gg();It();sa();uu();Wo();Yo();zn();Jn();rS();UP();sC();lC();Mm();dC();Vr();gC();jc();ba();ur();PC="language_support_reconcile";Bl=class n{constructor(e,t,r){this.operationCount=0;this.modifyingOpActive=!1;this.operationResetController=new AbortController;this.workspaceSyncController=new AbortController;this.refreshingInProgress=!1;this.refreshingFiles=[];this.pendingProjectSync=null;this.pendingLspWorkspaceSync=null;this.batchInProgress=!1;this.batchRunner=null;this.queuedBatch=null;this.indexExcludeDirs=[];this.pendingStatusReindex=[];this.indexingInProgress=!1;this.pendingFullReindex=!1;this.languageSupportReconcileTask=null;this.languageSupportReconcileQueued=!1;this.initialSnapshotTask=null;this.transientIndexers=new Set;let s=Rp("CodeEngineInit");s("start",{projectPath:e,hasTestProject:!!t}),this.testProject=t;let i=this.resolveInitialProjectPath(e);this.projectPath=i,s("projectPath.set",{projectPath:this.projectPath}),s("projectInit.start"),this.project=Ls.initializeProject(this.projectPath,this.testProject),s("projectInit.complete",{sourceFiles:this.project.getSourceFiles().length}),this.snapshotter=new zf(this.projectPath,()=>this.indexExcludeDirs.slice()),s("snapshotter.ready"),this.indexExcludeDirs=Hs(this.projectPath),V("Loaded indexExcludeDirs",this.indexExcludeDirs),s("indexExcludes.loaded",{count:this.indexExcludeDirs.length}),this.languageSupport=r?.languageSupport,this.lspHost=r?.lspHost;try{V("constructor runtime wiring",{projectPath:this.projectPath,hasLanguageSupport:!!this.languageSupport,hasLspHost:!!this.lspHost})}catch{}s("initializeXXHash.start"),this.xxHashReady=(async()=>{try{await Sb(),s("initializeXXHash.complete")}catch(o){throw An("FATAL: Failed to initialize xxHash:",o),o}})(),r?.enableASTStorage&&V("\u{1F4DD} Incremental AST indexing configured. Call startIndexing() when ready.")}static{this.DIAGNOSTIC_VALIDATION_TIMEOUT_MS=Math.max(500,Number(process.env.PANDO_DIAGNOSTIC_VALIDATION_TIMEOUT_MS||"3000"))}static{this.LARGE_INCREMENTAL_BATCH_FILES=Math.max(1e3,Number(process.env.PANDO_INCREMENTAL_FULL_REINDEX_FILE_THRESHOLD||"5000"))}static{this.LARGE_INCREMENTAL_BATCH_PERCENT=Math.max(1,Number(process.env.PANDO_INCREMENTAL_FULL_REINDEX_PERCENT_THRESHOLD||"15"))}static{this.PROJECT_SYNC_HEARTBEAT_MS=Math.max(1e3,Number(process.env.PANDO_PROJECT_SYNC_HEARTBEAT_MS||"5000"))}static{this.PROJECT_SYNC_SUPERSEDE_SETTLE_MS=Math.max(25,Number(process.env.PANDO_PROJECT_SYNC_SUPERSEDE_SETTLE_MS||"250"))}static{this.RESTORE_FAST_PATH_MAX_AGE_MS=Math.max(1e3,Number(process.env.PANDO_RESTORE_FAST_PATH_MAX_AGE_MS||"300000"))}cancelWorkspaceSync(e){let t=this.workspaceSyncController;if(this.workspaceSyncController=new AbortController,!t.signal.aborted)try{t.abort(Gn(e,"Workspace sync cancelled"))}catch{try{t.abort()}catch{}}}clearPendingProjectSyncState(e){e&&this.pendingProjectSyncToken!==e||(this.pendingProjectSync=null,this.pendingProjectSyncToken=void 0,this.pendingProjectSyncId=void 0,this.pendingProjectSyncEnqueuedAt=void 0,this.pendingProjectSyncReason=void 0)}invalidateRestoreFastPathState(e,t){this.restoreFastPathState&&(V("[RestoreFastPath] invalidated",{reason:e,currentSnapshotId:this.restoreFastPathState.currentSnapshotId,sourceOp:this.restoreFastPathState.sourceOp??null,ageMs:Date.now()-this.restoreFastPathState.createdAt,...t||{}}),this.restoreFastPathState=void 0)}recordRestoreFastPathState(e,t){let r=typeof t?.snapshotAfter=="string"?String(t.snapshotAfter).trim():"";if(!r||r==="<none>"){this.invalidateRestoreFastPathState("missing-snapshot-after",{op:e??null,success:!!t?.success});return}this.restoreFastPathState={currentSnapshotId:r,sourceOp:e??null,createdAt:Date.now()},V("[RestoreFastPath] state.recorded",{currentSnapshotId:r,sourceOp:e??null})}installRestoreFastPathMetadata(e,t){let r=this.restoreFastPathState;if(!r){t.clearOperationMetadata(e,od);return}let s=Date.now()-r.createdAt;if(s>n.RESTORE_FAST_PATH_MAX_AGE_MS){this.invalidateRestoreFastPathState("stale",{ageMs:s}),t.clearOperationMetadata(e,od);return}t.setOperationMetadata(e,od,r),V("[RestoreFastPath] metadata.installed",{currentSnapshotId:r.currentSnapshotId,sourceOp:r.sourceOp??null,ageMs:s})}async supersedePendingProjectSyncForRestore(e){let t=this.pendingProjectSync;if(!t)return;let r=Date.now();V("[ProjectSync] superseding for restore",{operation:e??null,syncId:this.pendingProjectSyncId??null,reason:this.pendingProjectSyncReason??null,queuedForMs:this.pendingProjectSyncEnqueuedAt?Date.now()-this.pendingProjectSyncEnqueuedAt:null,queuedBatch:this.describeQueuedBatch(),batchInProgress:this.batchInProgress,batchPhase:this.batchPhase??null}),this.queuedBatch=null,this.clearPendingProjectSyncState(),this.cancelWorkspaceSync(`${String(e||"restore-snapshot")} superseded pending project sync`);let s=n.PROJECT_SYNC_SUPERSEDE_SETTLE_MS,i,o=new Promise(a=>{i=setTimeout(()=>a("timeout"),s),i.unref?.()});try{let a=await Promise.race([t.then(()=>"settled").catch(c=>(Mi(c)||V("[ProjectSync] supersede settle saw failure",{operation:e??null,message:c?.message||String(c)}),"settled")),o]);V("[ProjectSync] supersede settle complete",{operation:e??null,settled:a,settleTimeoutMs:s,durationMs:Date.now()-r})}finally{i&&clearTimeout(i)}}async collectDiagnostics(e,t){let r=Date.now();try{V("collectDiagnostics:start",{projectPath:this.projectPath,files:t,hasEngineLspHost:!!this.lspHost,hasContextLspHost:!!e.lsp})}catch{}if(!e.lsp)if(this.lspHost)e.setLspHost(this.lspHost);else try{let{CodeEngineFactory:u}=(ms(),be(cc)),d=u.getEngineOptions(this.projectPath);d?.lspHost&&e.setLspHost(d.lspHost),V("collectDiagnostics:recoveredRuntimeOptions",{projectPath:this.projectPath,hasStoredLspHost:!!d?.lspHost})}catch{}let s=e.lsp;try{V("collectDiagnostics:resolvedHost",{projectPath:this.projectPath,hasLspHost:!!s})}catch{}let i=new Map,o=require("path"),a=require("fs"),{resolveLanguageIdForPath:c}=(zn(),be(Dy)),{getClojureDiagnostics:l}=(Ws(),be(Sk));for(let u of t){let d=Date.now(),p=o.isAbsolute(u)?u:o.join(this.projectPath,u);if(!a.existsSync(p))continue;let f;try{f=c(p);let m;if(f==="clojure")m=l(this.projectPath,p);else{if(!s)continue;m=await Promise.race([s.diagnostics(p),new Promise((b,S)=>setTimeout(()=>S(new Error("__pando_diag_timeout__")),n.DIAGNOSTIC_VALIDATION_TIMEOUT_MS))])}let h=new Set,g=[],y=0;for(let b of m||[]){let S=b.severity;if(qB(S)){y+=1;let _=b.range,R=`${b.message??""}|${_?.start?.line??0}:${_?.start?.character??0}-${_?.end?.line??0}:${_?.end?.character??0}`;h.add(R),g.length<10&&g.push({signature:R,message:HB(b.message),line:Number(_?.start?.line??0),column:Number(_?.start?.character??0)})}}i.set(u,{errors:y,signatures:h,diagnostics:g})}catch(m){if(String(m?.message||m||"")==="__pando_diag_timeout__"){i.set(u,{errors:0,signatures:new Set,skipped:!0});continue}i.set(u,{errors:1,signatures:new Set(["diagnostics_error"])})}finally{let m=Date.now()-d;m>1e3&&V("collectDiagnostics:file.slow",{projectPath:this.projectPath,file:u,lang:f??null,durationMs:m})}}return V("collectDiagnostics:complete",{projectPath:this.projectPath,files:t.length,captured:i.size,durationMs:Date.now()-r}),i}async validateChangedFiles(e,t,r){try{V("validateChangedFiles:start",{projectPath:this.projectPath,changedFiles:t,hasEngineLspHost:!!this.lspHost,hasContextLspHost:!!e.lsp})}catch{}if(!e.lsp)if(this.lspHost)e.setLspHost(this.lspHost);else try{let{CodeEngineFactory:l}=(ms(),be(cc)),u=l.getEngineOptions(this.projectPath);u?.lspHost&&e.setLspHost(u.lspHost),V("validateChangedFiles:recoveredRuntimeOptions",{projectPath:this.projectPath,hasStoredLspHost:!!u?.lspHost})}catch{}let{resolveLanguageIdForPath:s}=(zn(),be(Dy)),i=t.some(l=>{let u=require("path").isAbsolute(l)?l:require("path").join(this.projectPath,l);return s(u)!=="clojure"});if(!e.lsp&&i){try{V("validateChangedFiles:skippedNoHost",{projectPath:this.projectPath})}catch{}return{ok:!0,skipped:!0,warning:"Post-operation validation skipped: no active LSP host."}}let o=await this.collectDiagnostics(e,t),a=[],c=[];for(let l of t){let u=o.get(l);if(!u)continue;let d=r?.get(l);if(!d)continue;if(d.skipped||u.skipped){c.push(l);continue}let p=Array.from(u.signatures).filter(f=>!d.signatures.has(f)).length;if(u.errors>d.errors||p>0){let f=(u.diagnostics||[]).filter(m=>!d.signatures.has(m.signature)).slice(0,3).map(({signature:m,...h})=>h);a.push({path:l,errors:u.errors,newDiagnostics:p,topNewDiagnostics:f})}}if(a.length>0){let l=a.flatMap(u=>(u.topNewDiagnostics||[]).map(d=>`${u.path}:${d.line+1}:${d.column+1} ${d.message}`)).slice(0,3);return{ok:!1,errors:a,topDiagnostics:l,error:WB(a)}}return c.length>0?{ok:!0,skipped:!0,warning:`Post-operation validation skipped for ${c.length} file(s) because diagnostics did not respond within ${n.DIAGNOSTIC_VALIDATION_TIMEOUT_MS}ms.`}:{ok:!0}}extractTouchedFiles(e){let t=new Set,r=i=>{if(typeof i!="string"||!i.trim())return;let o=i.split("#")[0];o&&t.add(o)},s=i=>{if(typeof i=="string"){r(i);return}if(i&&typeof i=="object"){let o=i;r(o.before),r(o.after),r(o.start),r(o.end),r(o.bodyStartOf),r(o.bodyEndOf)}};if(r(e?.path),Array.isArray(e?.path))for(let i of e.path)r(i);if(r(e?.of),s(e?.to),Array.isArray(e?.files))for(let i of e.files)r(i);return Array.from(t)}async preflightExpectedHashCheck(e,t,r){let s=typeof e?.expectedHash=="string"?e.expectedHash.trim():"";if(!s||s.includes("@"))return{ok:!0};let i=Ob(e),o=typeof i=="string"&&/:FunctionArity(?:@|$)/.test(i);try{if(!o&&await Si(t,e,r))return{ok:!0}}catch(a){return{ok:!1,error:a?.message||String(a)}}if(typeof i!="string"||!i.includes("#"))return{ok:!0};try{let a=await zr(this.projectPath,i);if(!a)return{ok:!0};let c=et(i,a.text),l=s.startsWith("@")?s:`@${s}`,u=nn(l,c);if(u.type!=="MATCH")return{ok:!1,error:`Hash mismatch (${u.type}). Re-run find-nodes to refresh the target.`}}catch{return{ok:!0}}return{ok:!0}}get indexer(){return this._indexer||(this._indexer=new aa(this.projectPath,void 0,{excludeDirs:this.indexExcludeDirs,languageSupport:this.languageSupport})),this._indexer}createTransientIndexer(e="transient"){let t=gs(),r=ys("indexer-worker");V("[IndexerDiag] createTransientIndexer",{projectPath:this.projectPath,reason:e,activeTransientIndexers:this.transientIndexers.size,workerScript:r,workerScriptExists:r?PS.default.existsSync(r):!1,runtimePaths:t,env:{runtimeRoot:process.env.PANDO_RUNTIME_ROOT??null,workerRoot:process.env.PANDO_WORKER_SCRIPT_DIR??null}});let s=new aa(this.projectPath,void 0,{excludeDirs:this.indexExcludeDirs,languageSupport:this.languageSupport});return this.transientIndexers.add(s),s}disposeTransientIndexer(e,t="transient indexer complete"){if(e){V("[IndexerDiag] disposeTransientIndexer",{projectPath:this.projectPath,reason:t,activeTransientIndexers:this.transientIndexers.size}),this.transientIndexers.delete(e);try{e.dispose(t)}catch{}}}async withTransientIndexer(e,t="transient run"){let r=this.createTransientIndexer(t);try{return await e(r)}finally{this.disposeTransientIndexer(r,t)}}cancelIndexing(e){if(this._indexer)try{this._indexer.cancelIndexing(e)}catch{}for(let t of Array.from(this.transientIndexers))try{t.cancelIndexing(e)}catch{}}cancelActiveOperations(e){let t=this.operationResetController;if(this.operationResetController=new AbortController,!t.signal.aborted)try{t.abort(Gn(e,"Operation cancelled"))}catch{try{t.abort()}catch{}}}dispose(){this.cancelActiveOperations("engine dispose"),this.cancelWorkspaceSync("engine dispose"),this.cancelIndexing("dispose");try{zs.getInstance(this.projectPath).reset()}catch{}try{let{SnapshotStatusTracker:e}=(ra(),be(na));e.getInstance(this.projectPath).complete()}catch{}try{let{FTSStatusTracker:e}=(Su(),be(Ef));e.getInstance(this.projectPath).complete()}catch{}if(this._indexer&&typeof this._indexer.dispose=="function")try{this._indexer.dispose("engine dispose")}catch{}this._indexer=void 0;for(let e of Array.from(this.transientIndexers))this.disposeTransientIndexer(e,"engine dispose");if(this.snapshotter){try{this.snapshotter.dispose()}catch{}this.snapshotter=void 0}}async drainPendingProjectSync(e="external wait"){let t=this.pendingProjectSync;t&&(V("[ProjectSync] drain requested",{reason:e,syncId:this.pendingProjectSyncId??null,pendingReason:this.pendingProjectSyncReason??null,queuedForMs:this.pendingProjectSyncEnqueuedAt?Date.now()-this.pendingProjectSyncEnqueuedAt:null,batchInProgress:this.batchInProgress,batchPhase:this.batchPhase??null}),await t,V("[ProjectSync] drain complete",{reason:e,syncId:this.pendingProjectSyncId??null,pendingReason:this.pendingProjectSyncReason??null}))}setRuntimeOptions(e){this.languageSupport=e?.languageSupport,this.lspHost=e?.lspHost;try{V("setRuntimeOptions",{projectPath:this.projectPath,hasLanguageSupport:!!this.languageSupport,hasLspHost:!!this.lspHost})}catch{}}getIndexingStore(){return this.indexingStore||(this.indexingStore=new rr(this.projectPath)),this.indexingStore}readLanguageSupportReconcileState(){try{let e=this.getIndexingStore().getIndexerMeta(PC);if(!e)return null;let t=JSON.parse(e);if(!t||typeof t!="object")return null;let r=t.state==="pending"||t.state==="applying"||t.state==="applied"?t.state:null;return r?{state:r,desiredEnabledLanguages:Array.isArray(t.desiredEnabledLanguages)?t.desiredEnabledLanguages.filter(s=>typeof s=="string"):[],appliedEnabledLanguages:Array.isArray(t.appliedEnabledLanguages)?t.appliedEnabledLanguages.filter(s=>typeof s=="string"):[],updatedAt:typeof t.updatedAt=="number"?t.updatedAt:Date.now(),message:typeof t.message=="string"?t.message:"",startedAt:typeof t.startedAt=="number"?t.startedAt:void 0,completedAt:typeof t.completedAt=="number"?t.completedAt:void 0,purgedIndexedFiles:typeof t.purgedIndexedFiles=="number"?t.purgedIndexedFiles:void 0,coldWorkspace:typeof t.coldWorkspace=="boolean"?t.coldWorkspace:void 0,pendingRestart:typeof t.pendingRestart=="boolean"?t.pendingRestart:void 0,lastError:typeof t.lastError=="string"?t.lastError:void 0}:null}catch{return null}}writeLanguageSupportReconcileState(e){this.getIndexingStore().setIndexerMeta(PC,`${JSON.stringify(e)}
|
|
867
867
|
`)}hasCompletedIndexRun(){try{let e=this.getIndexingStore();if(e.getIndexingSession()?.run_state==="completed")return!0;let r=e.getIndexerMeta("indexing_session_stats");if(r)try{if(JSON.parse(r)?.runState==="completed")return!0}catch{}return!1}catch{return!1}}async waitForIndexingToSettle(e=3e4){let t=Date.now()+Math.max(1e3,e);for(;this.indexingInProgress&&Date.now()<t;)await new Promise(r=>setTimeout(r,100));return!this.indexingInProgress}enqueueLanguageSupportReconcile(){if(this.languageSupportReconcileTask){this.languageSupportReconcileQueued=!0;return}this.languageSupportReconcileTask=(async()=>{do this.languageSupportReconcileQueued=!1,await this.runLanguageSupportReconcile();while(this.languageSupportReconcileQueued)})().catch(e=>{let t=qo(this.projectPath).enabledLanguages;this.writeLanguageSupportReconcileState({state:"pending",desiredEnabledLanguages:t,appliedEnabledLanguages:this.readLanguageSupportReconcileState()?.appliedEnabledLanguages??t,updatedAt:Date.now(),message:"Language support reconcile failed; config is saved but not fully applied yet.",lastError:e instanceof Error?e.message:String(e)}),V("language support reconcile failed",{projectPath:this.projectPath,error:e instanceof Error?e.message:String(e)})}).finally(()=>{this.languageSupportReconcileTask=null,this.languageSupportReconcileQueued&&this.enqueueLanguageSupportReconcile()})}async runLanguageSupportReconcile(){let e=qo(this.projectPath).enabledLanguages,t=this.readLanguageSupportReconcileState();this.languageSupport=Ho(this.projectPath);let r=Date.now();if(this.writeLanguageSupportReconcileState({state:"applying",desiredEnabledLanguages:e,appliedEnabledLanguages:t?.appliedEnabledLanguages??e,updatedAt:r,startedAt:r,message:"Applying language support configuration in the background."}),!this.hasCompletedIndexRun()){this.writeLanguageSupportReconcileState({state:"applied",desiredEnabledLanguages:e,appliedEnabledLanguages:e,updatedAt:Date.now(),startedAt:r,completedAt:Date.now(),coldWorkspace:!0,message:"Applied to future indexing; no completed index existed yet."});return}let s=bs(this.languageSupport),i=this.collectIndexedFileRels().filter(l=>{let u=require("path").extname(l).toLowerCase();return!s.has(u)});if(this.cancelIndexing("language support changed"),this._indexer){try{this._indexer.dispose("language support changed")}catch{}this._indexer=void 0}for(let l of Array.from(this.transientIndexers))this.disposeTransientIndexer(l,"language support changed");let o=await this.waitForIndexingToSettle(),a=0;i.length>0&&(a=await this.withTransientIndexer(l=>l.purgeDeleted(i),"purge disabled language files"));let c=!1;o?await this.startIndexing():(c=!0,this.pendingFullReindex=!0),this.writeLanguageSupportReconcileState({state:"applied",desiredEnabledLanguages:e,appliedEnabledLanguages:e,updatedAt:Date.now(),startedAt:r,completedAt:Date.now(),purgedIndexedFiles:a,pendingRestart:c,message:c?"Applied config and purged disabled-language files; a restart of indexing is queued.":"Applied config and reconciled index state."})}computeIndexingEta(){try{let e=this.getIndexingStore(),t=e.getThroughput(),r=e.getPendingStats(),s=typeof t.avg_files_per_sec=="number"&&t.avg_files_per_sec>0?t.avg_files_per_sec:null;if(s&&r.count>0)return{seconds:Math.max(1,Math.ceil(r.count/s)),basis:"files"};let i=typeof t.avg_bytes_per_sec=="number"&&t.avg_bytes_per_sec>0?t.avg_bytes_per_sec:null;if(i&&r.known_bytes>0)return{seconds:Math.max(1,Math.ceil(r.known_bytes/i)),basis:"bytes"}}catch(e){try{ee("CodeEngine","computeIndexingEta failed",{error:e?.message||e})}catch{}}return null}isPathExcludedForIndex(e){let t=Date.now(),r=ok(this.projectPath,this.indexExcludeDirs,e),s=Date.now()-t;return V("isPathExcludedForIndex result",{absPath:e,excluded:r,entries:this.indexExcludeDirs}),s>50&&V("[BatchQueue] isPathExcludedForIndex slow",{absPath:e,excluded:r,elapsedMs:s,entries:this.indexExcludeDirs}),r}finishBatch(e,t){let r=this.batchStartMs?Date.now()-this.batchStartMs:null;V("[BatchQueue] finishBatch",{reason:e,elapsedMs:r,phase:this.batchPhase??null,phaseElapsedMs:this.batchPhaseStartMs?Date.now()-this.batchPhaseStartMs:null,...t||{}}),this.batchInProgress=!1,this.batchStartMs=void 0,this.batchPhase=void 0,this.batchPhaseStartMs=void 0,this.batchWatchdogTimer&&(clearInterval(this.batchWatchdogTimer),this.batchWatchdogTimer=void 0),V("[BatchQueue] finishBatch complete",{batchInProgress:this.batchInProgress,indexingInProgress:this.indexingInProgress,refreshingInProgress:this.refreshingInProgress,queuedBatch:this.describeQueuedBatch(),pendingFullReindex:this.pendingFullReindex,pendingStatusReindex:this.pendingStatusReindex.length,watchdogActive:!!this.batchWatchdogTimer})}describeQueuedBatch(){return this.queuedBatch?{created:this.queuedBatch.created.size,modified:this.queuedBatch.modified.size,deleted:this.queuedBatch.deleted.size}:null}mergeQueuedBatch(e,t){this.queuedBatch?this.queuedBatch.source==="post-write-sync"&&t!=="post-write-sync"&&(this.queuedBatch.source=t):this.queuedBatch={created:new Set,modified:new Set,deleted:new Set,source:t};let r=this.queuedBatch,s=a=>{let c=as(a);r.deleted.delete(c),r.modified.delete(c),r.created.add(c)},i=a=>{let c=as(a);r.deleted.has(c)||r.created.has(c)||r.modified.add(c)},o=a=>{let c=as(a);r.created.delete(c),r.modified.delete(c),r.deleted.add(c)};for(let a of e.created)s(a);for(let a of e.modified)i(a);for(let a of e.deleted)o(a);return this.describeQueuedBatch()??{created:0,modified:0,deleted:0}}takeQueuedBatch(){if(!this.queuedBatch)return null;let e={created:Array.from(this.queuedBatch.created),modified:Array.from(this.queuedBatch.modified),deleted:Array.from(this.queuedBatch.deleted),source:this.queuedBatch.source};return this.queuedBatch=null,e.created.length+e.modified.length+e.deleted.length>0?e:null}shouldEscalateBatchToFullReindex(e){if(e>=n.LARGE_INCREMENTAL_BATCH_FILES)return{should:!0,reason:`file-count:${e}>=${n.LARGE_INCREMENTAL_BATCH_FILES}`};if(e<1e3)return{should:!1};try{let t=new rr(this.projectPath).getAllKnownFiles().size,r=Math.max(1,Math.ceil(t*n.LARGE_INCREMENTAL_BATCH_PERCENT/100));if(t>0&&e>=r)return{should:!0,reason:`file-percent:${e}/${t}>=${n.LARGE_INCREMENTAL_BATCH_PERCENT}%`,knownFiles:t}}catch{}return{should:!1}}ensureBatchRunner(){if(this.batchRunner)return this.batchRunner;if(this.indexingInProgress)return Promise.resolve();let e=this.runBatchRunnerLoop().catch(t=>{An("[BatchQueue] runner failed",t?.message||t)}).finally(()=>{this.batchRunner===e&&(this.batchRunner=null),this.queuedBatch&&!this.indexingInProgress&&this.ensureBatchRunner()});return this.batchRunner=e,e}async runBatchRunnerLoop(){for(;;){if(this.indexingInProgress)return;let e=this.takeQueuedBatch();if(!e)return;await this.processQueuedBatch(e,this.workspaceSyncController.signal)}}filterExcludedAbsolutePaths(e){if(!this.indexExcludeDirs.length)return e;V("filterExcludedAbsolutePaths input",{count:e.length,sample:e.slice(0,10)});let t=e.filter(r=>!this.isPathExcludedForIndex(r));return V("filterExcludedAbsolutePaths output",{count:t.length,excluded:e.length-t.length,sample:t.slice(0,10)}),t}async handleAddExcludeDir(e){let t=typeof e.directory=="string"?e.directory.trim():"";if(!t)return{success:!1,error:"Parameter 'directory' is required"};let r=gf(this.projectPath,[t]);if(r.length===0)return{success:!1,error:"Directory must be inside the workspace root",details:{directory:t}};let s=r[0];if(V("handleAddExcludeDir normalized entry",{dirInput:t,normalizedEntry:s}),this.indexExcludeDirs.includes(s))return{success:!0,details:{alreadyExcluded:!0,excludeDirs:this.indexExcludeDirs}};let i=[];try{i=(await this.withTransientIndexer(l=>l.scanFiles({relativeDirs:[s]}))).map(l=>l.relPath)}catch(c){return{success:!1,error:`Failed to scan target directory: ${c?.message||c}`}}let o=sk(this.projectPath,s,this.indexExcludeDirs);V("handleAddExcludeDir updated exclude list",o),By(this.projectPath,o),this.indexExcludeDirs=Hs(this.projectPath),V("handleAddExcludeDir reloaded exclude list",this.indexExcludeDirs);let a=0;if(i.length)try{a=await this.withTransientIndexer(c=>c.purgeDeleted(i))}catch(c){return{success:!1,error:`Failed to purge excluded files: ${c?.message||c}`}}return{success:!0,details:{excludeDirs:this.indexExcludeDirs,newlyExcluded:s,purged:a,candidatesRemoved:i.length}}}async handleRemoveExcludeDir(e){let t=typeof e.directory=="string"?e.directory.trim():"";if(!t)return{success:!1,error:"Parameter 'directory' is required"};let r=gf(this.projectPath,[t]);if(r.length===0)return{success:!1,error:"Directory must be inside the workspace root",details:{directory:t}};let s=r[0];if(V("handleRemoveExcludeDir normalized entry",{dirInput:t,normalizedEntry:s}),s===".clj-kondo")return{success:!0,details:{removed:!1,protectedDefault:!0,excludeDirs:this.indexExcludeDirs,message:".clj-kondo remains excluded from semantic indexing by default; use edit-file-text for supported .clj-kondo config/hook edits. .clj-kondo/.cache is always hard-ignored."}};if(!this.indexExcludeDirs.includes(s))return{success:!0,details:{removed:!1,excludeDirs:this.indexExcludeDirs}};let i=ik(this.projectPath,s,this.indexExcludeDirs);V("handleRemoveExcludeDir updated list",i),By(this.projectPath,i),this.indexExcludeDirs=Hs(this.projectPath),V("handleRemoveExcludeDir reloaded exclude list",this.indexExcludeDirs);let o=[];try{let c=await this.withTransientIndexer(l=>l.scanFiles({relativeDirs:[s]}));o=this.filterExcludedAbsolutePaths(c.map(l=>as(l.absPath)))}catch(c){return{success:!1,error:`Failed to scan newly included directory: ${c?.message||c}`}}let a=0;if(o.length){try{a=(await this.withTransientIndexer(l=>l.indexFiles(o.map(u=>as(u))))).processed}catch(c){return{success:!1,error:`Failed to index newly included files: ${c?.message||c}`}}try{await this.refreshFilesFromDisk(o)}catch(c){An("[ExcludeDirs] refresh failed",c?.message||c)}}return{success:!0,details:{excludeDirs:this.indexExcludeDirs,newlyIncluded:s,indexed:a,candidates:o.length}}}handleGetProjectRoot(){try{return{success:!0,details:{root:this.projectPath}}}catch(e){return{success:!1,error:`Failed to read project root: ${e?.message||e}`}}}collectIndexedFileRels(){let e=new Set,t=[];try{t=PS.default.readdirSync(ft(this.projectPath)).filter(s=>s.startsWith(".pando-index-chunk-")&&s.endsWith(".db")).map(s=>require("path").join(ft(this.projectPath),s)).sort((s,i)=>s.localeCompare(i))}catch{t=[]}if(t.length===0)return[];let{default:r}=(Jt(),be(Fr));for(let s of t){let i;try{i=new r(s,{readonly:!0,fileMustExist:!0});let o=i.prepare("SELECT df.path AS path FROM files f JOIN dict_files df ON f.file_id = df.id").all();for(let a of o)typeof a.path=="string"&&a.path.length>0&&e.add(a.path)}catch{}finally{try{i?.close?.()}catch{}}}return Array.from(e)}async handleSetEnabledLanguages(e){let t;try{t=qo(this.projectPath)}catch(a){return{success:!1,error:`Failed to read enabled languages: ${a?.message||a}`}}if(!("languages"in e)||e.languages==null)return{success:!0,details:{...t,languageSupportChanged:!1}};if(!Array.isArray(e.languages))return{success:!0,details:{...t,valid:!1,error:"Parameter 'languages' must be an array when provided.",languageSupportChanged:!1}};let r=new Set(t.availableLanguages),s=e.languages.filter(a=>typeof a!="string"||!r.has(a));if(s.length>0)return{success:!0,details:{...t,valid:!1,error:"Invalid enabled language value.",invalidLanguages:s,languageSupportChanged:!1}};let i=cy(this.projectPath,e.languages),o=JSON.stringify(t.enabledLanguages)===JSON.stringify(i.enabledLanguages);return this.languageSupport=Ho(this.projectPath),o?this.writeLanguageSupportReconcileState({state:"applied",desiredEnabledLanguages:i.enabledLanguages,appliedEnabledLanguages:i.enabledLanguages,updatedAt:Date.now(),completedAt:Date.now(),message:"Language support config already applied."}):(this.writeLanguageSupportReconcileState({state:"pending",desiredEnabledLanguages:i.enabledLanguages,appliedEnabledLanguages:this.readLanguageSupportReconcileState()?.appliedEnabledLanguages??t.enabledLanguages,updatedAt:Date.now(),message:"Language support config saved; reconcile is queued."}),this.enqueueLanguageSupportReconcile()),{success:!0,details:{...i,languageSupportChanged:!o,reconcileScheduled:!o,reconcileState:o?"applied":"pending"}}}async handleSnapshotWorktree(e,t){let r=typeof e.message=="string"?e.message.trim():"",s=e.trailers&&typeof e.trailers=="object"?e.trailers:{},i=(()=>{try{return(ra(),be(na)).SnapshotStatusTracker.getInstance(this.projectPath)}catch{return null}})();if(i&&i.isSnapshotting)return{success:!1,error:"Snapshotting in progress; retry shortly."};let{openSnapshotsDb:o}=(hi(),be(mo)),a=o(this.projectPath);try{ct(t,"snapshot-worktree cancelled");let l=a.prepare("SELECT snapshot_id FROM snapshots ORDER BY timestamp DESC, rowid DESC LIMIT 1").get()?.snapshot_id,u=Kr(this.projectPath,this.indexExcludeDirs),d=ek(this.projectPath,{shouldExclude:u??void 0,gitignoreRoot:this.projectPath}),p=require("path"),f=require("fs"),m=require("crypto"),h=d.map(x=>p.relative(this.projectPath,x).replace(/\\/g,"/")).filter(Boolean).sort((x,v)=>x.localeCompare(v));await Pu(t);let g=l?(Js(),be(Li)).computeEffectiveMap(a,l):new Map,y=x=>{let v=Buffer.from(`blob ${x.length}\0`,"utf8");return m.createHash("sha1").update(v).update(x).digest("hex")},b=[],S=new Set;for(let x=0;x<h.length;x++){x>0&&x%64===0&&await Pu(t),ct(t,"snapshot-worktree cancelled");let v=h[x];S.add(v);let F=p.join(this.projectPath,v),D="";try{D=y(f.readFileSync(F))}catch{D=""}let N=g.get(v)?.oid;(!l||N==null||N!==D)&&b.push(v)}ct(t,"snapshot-worktree cancelled");let _=l?Array.from(g.keys()).filter(x=>!S.has(x)).sort((x,v)=>x.localeCompare(v)):[],R={op:"snapshot-worktree",message:r||void 0,timestamp:Date.now(),scannedFilesCount:h.length,changedFilesCount:b.length,deletedFilesCount:_.length};if(b.length===0&&_.length===0){try{i?.complete()}catch{}return{success:!0,snapshotBefore:l||"<none>",snapshotAfter:l||"<none>",details:{receipt:R,changedFiles:[],deletedFiles:[],snapshotSkipped:!0,message:"No changes detected since the latest Pando snapshot."}}}let{SnapshotService:T}=(vS(),be(wS)),E={};r&&(E["AST-Message"]=r);for(let[x,v]of Object.entries(s))v!=null&&(E[String(x)]=String(v));try{i?.start(b.length,_.length)}catch{}try{let{snapshotId:x,parentId:v}=await T.takeSnapshotNow(this.projectPath,b,"snapshot-worktree",R,E,_,t);try{i?.complete()}catch{}return{success:!0,snapshotBefore:v||l||"<none>",snapshotAfter:x,details:{receipt:R,changedFiles:b,deletedFiles:_}}}catch(x){try{i?.complete()}catch{}throw x}}catch(c){try{i?.complete()}catch{}throw c}finally{try{a.close()}catch{}}}getWorktreeChanges(e){try{let t=(0,TS.execFileSync)("git",["rev-parse","--show-prefix"],{cwd:e,encoding:"utf8"}).toString().replace(/\r?\n/g,""),s=(0,TS.execFileSync)("git",["status","--porcelain","-z"],{cwd:e,encoding:"utf8"}).toString().split("\0").filter(Boolean),i=new Set,o=new Set,a=l=>l.replace(/^\.\//,"").replace(/\\/g,"/"),c=l=>{if(!t)return a(l);let u=a(l);return u.startsWith(t)?u.slice(t.length):u};for(let l of s){if(l.length<3)continue;let u=l.slice(0,2),d=l.slice(3);if(!d)continue;let p=u.includes("D"),f=d.split(" -> "),m=c(f[f.length-1].trim());if(m&&(i.add(m),p&&o.add(m)),f.length>1){let h=c(f[0].trim());h&&o.add(h)}}return{ok:!0,changedFiles:Array.from(i),deletedFiles:Array.from(o)}}catch(t){return{ok:!1,error:`Failed to read git worktree status: ${t instanceof Error?t.message:String(t)}`}}}resolveInitialProjectPath(e){return e}evaluateIndexStatus(){let e=require("fs"),t=require("path");try{let{FileChunkMappingStore:r}=(ea(),be(Hy)),i=new r(this.projectPath).all();if(!i||i.length===0)return{resetAll:!1,reindexAbs:[]};let o=/^\.pando-index-chunk-(\d+)\.db$/,a=e.readdirSync(ft(this.projectPath)),c=new Map;for(let m of a){let h=o.exec(m);if(!h)continue;let g=Number(h[1]);c.set(g,t.join(ft(this.projectPath),m))}if(c.size===0)return V("evaluateIndexStatus missing chunk databases",{mappingCount:i.length}),{resetAll:!0,reindexAbs:[]};let{default:l}=(Jt(),be(Fr)),u=new Map,d=new Set,p=0;for(let[m,h]of c){let g;try{An(`[IndexStatus] open chunk db :: ${h}`),g=new l(h);let y=g.prepare("SELECT COUNT(*) AS c FROM files").get();p+=Number(y?.c||0);let b=g.prepare("SELECT df.path AS file_path, f.status FROM files f JOIN dict_files df ON df.id = f.file_id").all();if(b&&b.length){let S=u.get(m);S||(S=new Set,u.set(m,S));for(let _ of b){let R=String(_.file_path);d.add(R),(!_.status||String(_.status).toLowerCase()!=="completed")&&S.add(R)}S.size===0&&u.delete(m)}}catch(y){return An("[IndexStatus] failed to inspect chunk",h,y?.message||y),{resetAll:!0,reindexAbs:[]}}finally{if(g)try{g.close()}catch{}}}for(let m of i)if(!d.has(m.file_path)){let h=u.get(m.chunk_id);h||(h=new Set,u.set(m.chunk_id,h)),h.add(m.file_path)}let f=[];for(let[m,h]of u){let g=c.get(m);if(!g)return V("evaluateIndexStatus missing db path for chunk",{chunkId:m}),{resetAll:!0,reindexAbs:[]};let y=Array.from(h);if(y.length){try{this.purgeFilesFromChunk(g,y)}catch(b){return An("[IndexStatus] failed to purge chunk before reindex",g,b?.message||b),{resetAll:!0,reindexAbs:[]}}for(let b of y)f.push(t.join(this.projectPath,b))}}return p===0&&f.length===0?(V("evaluateIndexStatus empty index with no remediation",{mappingCount:i.length}),{resetAll:!0,reindexAbs:[]}):{resetAll:!1,reindexAbs:f}}catch(r){return An("[IndexStatus] unable to evaluate status table",r?.message||r),{resetAll:!0,reindexAbs:[]}}}purgeFilesFromChunk(e,t){if(!t||t.length===0)return;let{default:r}=(Jt(),be(Fr)),s=new r(e);try{s.transaction(a=>{let c=u=>{for(let d=0;d<a.length;d+=200){let p=a.slice(d,d+200);p.length!==0&&u(p)}},l=(u,d="file_id")=>{c(p=>{let f=p.map(h=>s.prepare("SELECT id FROM dict_files WHERE path = ?").get(h)).map(h=>h?.id).filter(h=>typeof h=="number");if(!f.length)return;let m=f.map(()=>"?").join(",");s.prepare(`DELETE FROM ${u} WHERE ${d} IN (${m})`).run(...f)})};l("nodes"),l("exports"),l("files"),l("file_imports"),l("file_import_bindings"),c(u=>{let d=u.map(f=>s.prepare("SELECT id FROM dict_files WHERE path = ?").get(f)).map(f=>f?.id).filter(f=>typeof f=="number");if(!d.length)return;let p=d.map(()=>"?").join(",");s.prepare(`DELETE FROM file_deps WHERE src_file_id IN (${p})`).run(...d)})})(t),V("purgeFilesFromChunk removed stale entries",{dbPath:e,count:t.length})}catch(i){throw An("[IndexStatus] failed to purge chunk entries",e,i?.message||i),i}finally{try{s.close()}catch{}}}prepareIndexingRun(){let e=require("fs");if(!(()=>{try{return e.existsSync(this.projectPath)}catch{return!1}})()){V("prepareIndexingRun skipped; project root missing",{projectPath:this.projectPath}),this.pendingStatusReindex=[];return}let r=ft(this.projectPath);V("prepareIndexingRun start",{dotPando:r});try{e.mkdirSync(r,{recursive:!0})}catch{}this.pendingStatusReindex=[]}async startIndexing(){let e=this.operationResetController.signal;V("[DEBUG] startIndexing ENTRY",{projectPath:this.projectPath,indexingInProgress:this.indexingInProgress}),V("\u{1F680} Starting AST indexing...");try{if(ct(e,"Indexing cancelled before start"),this.indexingInProgress){this.pendingFullReindex=!0,V("startIndexing skipped (already running)",{projectPath:this.projectPath}),V("[DEBUG] startIndexing EXIT (already in progress)");return}this.indexingInProgress=!0;let t=Math.random().toString(36).slice(2,8);V("startIndexing begin",{projectPath:this.projectPath,runId:t}),V("[DEBUG] startIndexing about to call initializeASTStorage"),await this.initializeASTStorage(e),ct(e,"Indexing cancelled"),this.scheduleInitialSnapshotAfterIndex("post-root-check",e),ct(e,"Indexing cancelled"),V("startIndexing end",{projectPath:this.projectPath,runId:t}),V("[DEBUG] startIndexing completed successfully"),V("\u2705 AST indexing completed successfully")}catch(t){if(Mi(t))V("startIndexing aborted",{projectPath:this.projectPath,error:t instanceof Error?t.message:String(t)});else{let r=t instanceof Error?t.message:String(t);V("[DEBUG] startIndexing caught error",{error:r}),An("\u274C Failed to initialize AST storage:",t)}}finally{if(this.indexingInProgress=!1,V("INDEXING DONE",{projectPath:this.projectPath}),e.aborted&&(this.pendingFullReindex=!1),this.pendingFullReindex){this.pendingFullReindex=!1,V("queued full reindex starting",{projectPath:this.projectPath}),await this.startIndexing();return}this.queuedBatch&&!e.aborted&&this.ensureBatchRunner()}}readSnapshotCount(){try{let{openSnapshotsDb:e}=(hi(),be(mo)),t=e(this.projectPath,{readonly:!0});try{return Number(t.prepare("SELECT COUNT(*) AS c FROM snapshots").get()?.c??0)}finally{try{t.close()}catch{}}}catch(e){return An("\u26A0\uFE0F Failed to inspect snapshot count",e?.message||e),null}}scheduleInitialSnapshotAfterIndex(e,t,r){let s=require("fs"),i=require("path");if(!s.existsSync(this.projectPath))return"unavailable";if(this.initialSnapshotTask)return V("initial snapshot already scheduled",{projectPath:this.projectPath,reason:e}),"inflight";let o=this.readSnapshotCount();if(o==null)return"unavailable";if(o>0)return"existing";let{SnapshotStatusTracker:a}=(ra(),be(na)),c=a.getInstance(this.projectPath),l=ft(this.projectPath),u=i.join(l,"history"),d=jn(this.projectPath,0);return c.start(0,0),this.initialSnapshotTask=(async()=>{let p=Date.now();try{ct(t,"Initial snapshot cancelled"),V("\u{1F504} Starting initial snapshot after indexing...",{projectPath:this.projectPath,reason:e}),V(`[SnapshotDiag] ${e==="full-index"?"fullIndex":"postIndex"}.preSnapshot`,{projectPath:this.projectPath,pandoDataDir:l,historyDir:u,historyExists:s.existsSync(u),dbPath:d});let f=Array.isArray(r)?r:[],m=f.length>0&&typeof this.snapshotter.snapshotAllWithCaptured=="function"?await this.snapshotter.snapshotAllWithCaptured(f,"ast: initial snapshot (captured-indexed-files)",t):await this.snapshotter.snapshotAll("ast: initial snapshot (serial)",t),h=Date.now()-p;V("\u2705 snapshotAll complete",{elapsedMs:h,capturedFiles:f.length}),V(`[SnapshotDiag] ${e==="full-index"?"fullIndex":"postIndex"}.postSnapshot`,{snapshotId:m?.snapshotId,parent:m?.parent,historyExists:s.existsSync(u)}),V("\u2705 Initial snapshot created and recorded",{snapshotId:m?.snapshotId})}catch(f){Mi(f)?V("initial snapshot aborted",{projectPath:this.projectPath,reason:e,error:f instanceof Error?f.message:String(f)}):(An("\u26A0\uFE0F initial snapshot failed",f?.message,f?.stack),V("[SnapshotDiag] initialSnapshot.error",{projectPath:this.projectPath,reason:e,message:f?.message||String(f),stack:f?.stack,historyExists:s.existsSync(u),dbPath:d}))}finally{try{c.complete()}catch{}this.initialSnapshotTask=null}})(),this.initialSnapshotTask.catch(()=>{}),"scheduled"}async processQueuedBatch(e,t){let r=Date.now(),s=`${ft(this.projectPath)}/`,i=b=>{let S=0,_=0,R=[],T=[];for(let E of b){if(E.startsWith(s)){S++,R.length<10&&R.push(E);continue}this.isPathExcludedForIndex(E)&&(_++,T.length<10&&T.push(E))}return{internal:S,excluded:_,internalSample:R,excludedSample:T}},o=i(e.created),a=i(e.modified),c=i(e.deleted);Nn("code-engine.batch.start",{projectRoot:this.projectPath,created:e.created.length,modified:e.modified.length,deleted:e.deleted.length,createdSample:e.created.slice(0,20),modifiedSample:e.modified.slice(0,20),deletedSample:e.deleted.slice(0,20),internalCounts:{created:o.internal,modified:a.internal,deleted:c.internal},excludedCounts:{created:o.excluded,modified:a.excluded,deleted:c.excluded},internalSample:[...o.internalSample,...a.internalSample,...c.internalSample].slice(0,20),excludedSample:[...o.excludedSample,...a.excludedSample,...c.excludedSample].slice(0,20),queuedAfterTake:this.describeQueuedBatch()}),V("batch-change event",{created:e.created.length,modified:e.modified.length,deleted:e.deleted.length}),this.batchInProgress=!0,this.batchStartMs=Date.now(),this.batchPhase="start",this.batchPhaseStartMs=Date.now(),this.batchWatchdogTimer||(this.batchWatchdogTimer=setInterval(()=>{let b=this.batchStartMs?Date.now()-this.batchStartMs:null,S=this.batchPhaseStartMs?Date.now()-this.batchPhaseStartMs:null;V("[BatchQueue] watchdog",{batchInProgress:this.batchInProgress,batchStartMs:this.batchStartMs??null,elapsedMs:b,phase:this.batchPhase??null,phaseElapsedMs:S,queuedBatch:this.describeQueuedBatch()})},1e4));let l=()=>{let b=process.memoryUsage(),S=_=>Math.round(_/(1024*1024));return`rss=${S(b.rss)}MB heapUsed=${S(b.heapUsed)}MB heapTotal=${S(b.heapTotal)}MB ext=${S(b.external)}MB`};this.batchPhase="filtering",this.batchPhaseStartMs=Date.now(),V("[BatchQueue] filtering start",{created:e.created.length,modified:e.modified.length,deleted:e.deleted.length});let u=(b,S)=>{let _=Date.now(),R=b.length,T=0,E=0,x=[];for(let F of b){if(F.startsWith(s)){T++;continue}if(this.isPathExcludedForIndex(F)){E++;continue}x.push(F)}let v=Date.now()-_;return V("[BatchQueue] filterList done",{label:S,input:R,output:x.length,internalSkipped:T,excludedSkipped:E,elapsedMs:v,sample:x.slice(0,10)}),x};e={created:u(e.created,"created"),modified:u(e.modified,"modified"),deleted:u(e.deleted,"deleted"),source:e.source},Nn("code-engine.batch.afterFilter",{projectRoot:this.projectPath,created:e.created.length,modified:e.modified.length,deleted:e.deleted.length,createdSample:e.created.slice(0,20),modifiedSample:e.modified.slice(0,20),deletedSample:e.deleted.slice(0,20)});let d=e.created.length+e.modified.length+e.deleted.length;if(d===0){Nn("code-engine.batch.filteredToZero",{projectRoot:this.projectPath,elapsedMs:Date.now()-r}),this.finishBatch("no-work-after-filtering");return}this.scheduleLspWorkspaceSync(e,"watcher-batch");let p=this.batchPhaseStartMs?Date.now()-this.batchPhaseStartMs:null;V("[BatchQueue] filtering complete",{created:e.created.length,modified:e.modified.length,deleted:e.deleted.length,elapsedMs:p});let f=this.shouldEscalateBatchToFullReindex(d);if(f.should){Nn("code-engine.batch.fullReindexFallback",{projectRoot:this.projectPath,created:e.created.length,modified:e.modified.length,deleted:e.deleted.length,totalFiles:d,reason:f.reason,knownFiles:f.knownFiles??null}),V("[BatchQueue] large batch fallback",{totalFiles:d,reason:f.reason,knownFiles:f.knownFiles??null}),this.finishBatch("large-batch-full-reindex",{totalFiles:d,reason:f.reason,knownFiles:f.knownFiles??null}),await this.startIndexing();return}try{let b=S=>S.length<=10?S:[...S.slice(0,10),`... +${S.length-10} more`];V("batch-change filtered",{internalDbPrefix:s,created:b(e.created),modified:b(e.modified),deleted:b(e.deleted)}),Nn("code-engine.batch.filtered",{projectRoot:this.projectPath,created:e.created.length,modified:e.modified.length,deleted:e.deleted.length,createdSample:e.created.slice(0,20),modifiedSample:e.modified.slice(0,20),deletedSample:e.deleted.slice(0,20)})}catch{}let m=Date.now();V("\u{1F680} Processing batch",{files:d,mem:l()});let h=b=>b.length<=20?b:[...b.slice(0,20),`... +${b.length-20} more`];e.created.length&&V("batch created",{files:h(e.created)}),e.modified.length&&V("batch modified",{files:h(e.modified)}),e.deleted.length&&V("batch deleted",{files:h(e.deleted)});for(let b of e.deleted){let S=this.project.getSourceFile(b);S&&this.project.removeSourceFile(S)}let g=[...e.created,...e.modified];g.length&&V("batch reindex targets",{files:h(g)});let y=!1;try{ct(t,"Batch indexing cancelled"),this.batchPhase="applyExplicitChanges",this.batchPhaseStartMs=Date.now(),V("[BatchQueue] applyExplicitChanges start",{created:e.created.length,modified:e.modified.length,deleted:e.deleted.length});let b=this.createTransientIndexer(),S=Math.max(3e4,Number(process.env.PANDO_PROCESS_CHANGES_TIMEOUT_MS||18e4)),_=e.created.map(M=>as(M)),R=e.modified.map(M=>as(M)),T=e.deleted.map(M=>as(M));Nn("code-engine.batch.applyExplicitChanges.invoke",{projectRoot:this.projectPath,created:_.length,modified:R.length,deleted:T.length,timeoutMs:S});let E,x=()=>{try{b.cancelIndexing("Batch indexing cancelled")}catch{}},v=t.aborted?(()=>{}):(t.addEventListener("abort",x,{once:!0}),()=>{try{t.removeEventListener("abort",x)}catch{}}),F=new Promise((M,P)=>{E=setTimeout(()=>{try{b.cancelIndexing(`applyExplicitChanges timeout after ${S}ms`)}catch{}Nn("code-engine.batch.applyExplicitChanges.timeout",{projectRoot:this.projectPath,created:_.length,modified:R.length,deleted:T.length,timeoutMs:S}),P(new Error(`applyExplicitChanges timed out after ${S}ms`))},S),E.unref?.()}),D,N=sb(t,"Batch indexing cancelled",()=>{try{b.cancelIndexing("Batch indexing cancelled")}catch{}});try{D=await Promise.race([b.applyExplicitChanges({created:_.length?_:void 0,modified:R.length?R:void 0,deleted:T.length?T:void 0},{resetModifiedToLight:e.source!=="post-write-sync"}),N.promise,F])}finally{N.cleanup(),v(),E&&clearTimeout(E),this.disposeTransientIndexer(b,"batch applyExplicitChanges complete")}ct(t,"Batch indexing cancelled");let C=this.batchPhaseStartMs?Date.now()-this.batchPhaseStartMs:null;V("[BatchQueue] applyExplicitChanges done",{elapsedMs:C,indexed:D.indexed,purged:D.purged,needsFullReindex:D.needsFullReindex??!1}),Nn("code-engine.batch.applyExplicitChanges.complete",{projectRoot:this.projectPath,created:e.created.length,modified:e.modified.length,deleted:e.deleted.length,elapsedMs:this.batchPhaseStartMs?Date.now()-this.batchPhaseStartMs:null,indexed:D.indexed,purged:D.purged,needsFullReindex:D.needsFullReindex??!1}),y=D.needsFullReindex===!0;let O=(Date.now()-m)/1e3;V("\u2705 Explicit batch applied",{durationSeconds:Number(O.toFixed(1)),mem:l()})}catch(b){if(Mi(b)){this.finishBatch("batch-cancelled",{created:e.created.length,modified:e.modified.length,deleted:e.deleted.length});return}Nn("code-engine.batch.applyExplicitChanges.failed",{projectRoot:this.projectPath,created:e.created.length,modified:e.modified.length,deleted:e.deleted.length,elapsedMs:this.batchPhaseStartMs?Date.now()-this.batchPhaseStartMs:null,error:b?.message||String(b)});let S=this.batchPhaseStartMs?Date.now()-this.batchPhaseStartMs:null;V("[BatchQueue] applyExplicitChanges failed",{elapsedMs:S,error:b?.message||String(b)}),An("\u274C Failed to process queued batch:",b)}if(this.finishBatch(y?"apply-explicit-needs-full-reindex":"batch-complete",{created:e.created.length,modified:e.modified.length,deleted:e.deleted.length}),!y)try{g.length>0&&(this.batchPhase="refreshFiles",this.batchPhaseStartMs=Date.now(),await this.refreshFilesFromDisk(g,t),Nn("code-engine.batch.refreshFiles.complete",{projectRoot:this.projectPath,files:g.length,elapsedMs:this.batchPhaseStartMs?Date.now()-this.batchPhaseStartMs:null,batchElapsedMs:Date.now()-r}),V("[Batch] Post-index refresh done",{files:g.length}))}catch(b){if(Mi(b)){Nn("code-engine.batch.refreshFiles.aborted",{projectRoot:this.projectPath,files:g.length,elapsedMs:this.batchPhaseStartMs?Date.now()-this.batchPhaseStartMs:null,batchElapsedMs:Date.now()-r}),V("[Batch] Post-index refresh aborted",{files:g.length});return}Nn("code-engine.batch.refreshFiles.failed",{projectRoot:this.projectPath,error:b?.message||String(b),batchElapsedMs:Date.now()-r}),An("[Batch] Post-index refresh failed",b?.message||b)}Nn("code-engine.batch.complete",{projectRoot:this.projectPath,created:e.created.length,modified:e.modified.length,deleted:e.deleted.length,elapsedMs:Date.now()-r,fullReindexTriggered:y}),y&&(V("\u{1F504} Critical index files deleted, triggering full reindex..."),await this.startIndexing())}isIndexingInProgress(){return this.indexingInProgress}async initializeASTStorage(e){V("\u{1F504} Initializing AST storage (single-pass, incremental)..."),V("initializeASTStorage begin",{projectPath:this.projectPath}),V("initializeASTStorage start",{excludes:this.indexExcludeDirs});let t=require("fs"),r=require("path");if(ct(e,"Indexing cancelled"),!(()=>{try{return t.existsSync(this.projectPath)}catch{return!1}})()){V("initializeASTStorage skipped; project root missing",{projectPath:this.projectPath});return}this.prepareIndexingRun();let i=this.createTransientIndexer();try{let o=i.checkAndCleanupIfNeeded();V("initializeASTStorage integrity",{projectPath:this.projectPath,needsReindex:o});let a=jn(this.projectPath,0),c=ft(this.projectPath),l=r.join(c,"history"),u=!o&&t.existsSync(a)&&t.statSync(a).size>0,d=null;V("initializeASTStorage DB status",{dbPath:a,dbExists:u}),V("initializeASTStorage dbStatus",{projectPath:this.projectPath,exists:u});try{let w={projectPath:this.projectPath,dbPath:a,pandoDataDir:c,historyDir:l,dbExists:u,needsReindex:o,historyExists:t.existsSync(l)};try{let{openSnapshotsDb:I}=(hi(),be(mo)),k=I(this.projectPath,{readonly:!0});try{let $=Number(k.prepare("SELECT COUNT(*) AS c FROM snapshots").get()?.c??-1);d=$>=0?$:null,w.snapshots=$,w.snapshot_members=Number(k.prepare("SELECT COUNT(*) AS c FROM snapshot_members").get()?.c??-1),w.snapshot_meta=Number(k.prepare("SELECT COUNT(*) AS c FROM snapshot_meta").get()?.c??-1)}finally{try{k.close()}catch{}}}catch(I){w.snapshotCountReadError=I?.message||String(I)}V("[SnapshotDiag] initializeASTStorage.entry",w)}catch{}let p=u&&d===0;p&&V("[SnapshotDiag] missingInitialSnapshot forcing full index path",{projectPath:this.projectPath,dbPath:a,snapshots:d});let f=this.pendingStatusReindex.slice();if(this.pendingStatusReindex=[],!u||p){if(this.indexingInProgress&&this.pendingFullReindex){V("initializeASTStorage fullIndex skipped (reindex queued)",{projectPath:this.projectPath});return}V(`\u{1F4C0} ${o?"Index integrity repair":p?"Initial snapshot missing":"No existing DB detected"}. Running full index-all...`),V("initializeASTStorage fullIndex start",{projectPath:this.projectPath});let I=Date.now(),k=sb(e,"Indexing cancelled",()=>{try{i.cancelIndexing("Indexing cancelled")}catch{}}),$;try{$=await Promise.race([i.indexAll(void 0,{captureContents:!0}),k.promise])}finally{k.cleanup()}ct(e,"Indexing cancelled");let L=Date.now()-I;V("\u2705 indexAll complete",{elapsedMs:L}),V("initializeASTStorage fullIndex done",{projectPath:this.projectPath});let j=this.scheduleInitialSnapshotAfterIndex("full-index",e,Array.isArray($?.captures)?$.captures:void 0);V("\u2705 Full indexing complete!",{dbPath:a,initialSnapshotState:j}),V("initializeASTStorage end",{projectPath:this.projectPath});return}V("\u{1F9EE} Existing DB found. Computing incremental changes...");try{let{default:w}=(Jt(),be(Fr)),I=new w(a,{readonly:!0}),k=Number(I.prepare("SELECT COUNT(*) AS c FROM snapshots").get()?.c??-1),$=Number(I.prepare("SELECT COUNT(*) AS c FROM snapshot_members").get()?.c??-1);I.close(),k===0&&V("[SnapshotDiag] incrementalPathWithNoSnapshots",{projectPath:this.projectPath,dbPath:a,snapshots:k,snapshot_members:$,historyExists:t.existsSync(l)})}catch(w){An("[SnapshotDiag] incrementalSnapshotCheck.error",w?.message||w)}V("initializeASTStorage incremental start",{projectPath:this.projectPath}),V("BUILD_STAMP incremental-logs-v1");let m=w=>r.relative(this.projectPath,w).replace(/\\/g,"/");V("workerScan:start",{projectPath:this.projectPath});let h=Date.now(),g=await this.withTransientIndexer(w=>w.scanFiles());V("workerScan:done",{count:g.length,elapsedMs:Date.now()-h,projectPath:this.projectPath});let y=new Set,b=new Map;for(let w of g){let I=w.relPath||m(w.absPath);!I||I.startsWith("..")||(y.add(I),b.set(I,{mtime:Math.floor(w.mtime),size:w.size}))}V("incremental diskMeta built",{projectPath:this.projectPath,count:b.size,source:"workerScan"});let{FileChunkMappingStore:S}=(ea(),be(Hy)),_=new S(this.projectPath),R=[],T=process.env.REINDEX_ON_MTIME_DECREASE==="1",E=f.slice(),x={missingMapping:0,sizeChanged:0,mtimeIncreased:0,mtimeDecreased:0},v=[],F=Math.max(0,Math.min(100,Number(process.env.PANDO_INDEX_DIAG_LIMIT||"25"))),D=(w,I,k,$)=>{v.length>=F||v.push({rel:w,reason:I,disk:{mtime:k?.mtime??0,size:k?.size??0},chunk:$?{last_modified:$.last_modified??0,file_size:$.file_size??0}:void 0})};V("incremental map.all start",{projectPath:this.projectPath});let N=Date.now(),C=_.all(),O=C.length,M=new Map;for(let w of C)M.set(w.file_path,w);V("incremental map.all done",{projectPath:this.projectPath,elapsedMs:Date.now()-N,count:O}),V("incremental map lookup loop start",{projectPath:this.projectPath,count:b.size});let P=Date.now();for(let[w,I]of b){let k=M.get(w);if(!k){x.missingMapping++,D(w,"missingMapping",I),R.push(r.join(this.projectPath,w));continue}let $=(I.mtime||0)>(k.last_modified||0),L=(I.mtime||0)<(k.last_modified||0),j=(I.size||0)!==(k.file_size||0);j&&x.sizeChanged++,$&&x.mtimeIncreased++,L&&x.mtimeDecreased++,(j||$||T&&L)&&(D(w,j?"sizeChanged":$?"mtimeIncreased":"mtimeDecreased",I,k),R.push(r.join(this.projectPath,w)))}if(V("incremental map lookup loop done",{projectPath:this.projectPath,elapsedMs:Date.now()-P,staleOrNew:R.length}),E.length){let w=new Set(R.map(k=>as(k))),I=0;for(let k of E){let $=as(k);if(!w.has($)){let L=m(k),j=b.get(L)||{mtime:0,size:0};D(L,"status",j),R.push(k),w.add($),I++}}I>0&&V("initializeASTStorage merged status-driven targets",{added:I,total:R.length})}let A=[];V("incremental deleted scan start",{projectPath:this.projectPath});for(let w of M.keys())y.has(w)||A.push(w);if(V("incremental deleted scan done",{projectPath:this.projectPath,deleted:A.length}),V("[IndexerDiag] re-index evaluation",{diskCount:b.size,mappingCount:O,staleOrNew:R.length,pendingStatus:E.length,counts:x,sample:v}),A.length>0&&V("[IndexerDiag] deleted candidates",{count:A.length,sample:A.slice(0,Math.max(0,Math.min(F,25)))}),V("\u{1F4CA} Incremental indexing",{staleOrNew:R.length,deleted:A.length}),A.length>0)for(let w of A)_.delete(w);R.length>0?(V("incremental indexFiles start",{count:R.length}),await this.withTransientIndexer(w=>w.indexFiles(R)),V("incremental indexFiles done",{count:R.length}),V("\u2705 Incremental indexing complete.")):(V("incremental no-op",{deleted:A.length}),V("\u2705 Everything up to date. No indexing needed."))}finally{this.disposeTransientIndexer(i,"initializeASTStorage complete")}}async forceSave(){await this.project.save()}getStats(){return{projectPath:this.projectPath,operationCount:this.operationCount,sourceFiles:this.project.getSourceFiles().length,projectStats:Ls.getProjectStats(this.project),useASTStorage:!1}}refresh(){this.project.getSourceFiles().forEach(e=>e.refreshFromFileSystemSync())}async execute(e,t){this.operationCount++;let r=Date.now(),s=c=>{let l=Math.max(0,Date.now()-r),u=c??{success:!1},{success:d=!1,projectRoot:p,...f}=u;return{projectRoot:this.projectPath,success:d,elapsedMs:l,...f}},{signal:i,cleanup:o}=Dk(t?.signal,this.operationResetController.signal);t?.clearTypeCache&&(SC(),be(bC)).TypeInference.clearCache();let a=this.project;try{if(ct(i,"Operation cancelled before execution started"),!this.lspHost)try{let{CodeEngineFactory:u}=(ms(),be(cc)),d=u.getEngineOptions(this.projectPath);(d?.lspHost||d?.languageSupport)&&this.setRuntimeOptions(d)}catch{}let c=new Ap(a,this.projectPath);if(this.lspHost&&c.setLspHost(this.lspHost),!Array.isArray(e)){let u=await this.executeSingle(e,c,i);return u.success&&u.changes?.count&&u.changes.count>0&&await this.project.save(),u}let l=[];for(let u of e){let d=await this.executeSingle(u,c,i);if(!d.success){if(t?.continueOnError){l.push(d);continue}throw new Error(`Operation failed: ${d.error}`)}l.push(d)}if(!t?.dryRun&&l.some(u=>u.success&&u.changes?.count&&u.changes.count>0)){let u=0;for(let d of l)d.success&&d.changes?.count&&(u+=d.changes.count);u>0&&await this.project.save()}return l}catch(c){let l=Mi(c),u=l?c?.message||"Operation cancelled":c.message;return Array.isArray(e)?[s({success:!1,error:u,...l?{error_code:"cancelled"}:{}})]:s({success:!1,error:u,...l?{error_code:"cancelled"}:{}})}finally{o()}}async executeWithContext(e,t,r){if(!Array.isArray(e))return this.executeSingle(e,t,r?.signal);let s=[];for(let i of e){let o=await this.executeSingle(i,t,r?.signal);if(!o.success)throw new Error(`Operation failed: ${o.error}`);s.push(o)}return s}async executeSingle(e,t,r){ct(r);let s=e.op,i=s==="add-code"?"insert":s==="replace-body"?"replace":s,o=new Set(["rename","delete","insert","add-code","replace","replace-body","edit-file-text","change-signature","filter-map-reduce","move-clojure-namespace","rename-clojure-namespace","restore-snapshot","restore-files","snapshot-worktree","repair-history","add-exclude-dir","remove-exclude-dir"]),a=new Set(["get-project-root","read_this_first","list-snapshots","diff-snapshots","get-snapshot-file","get-snapshot-trailers","get-db-schema","query-db"]),c=new Set(["snapshot-worktree","restore-snapshot","restore-files"]),l=new Set(["change-signature","snapshot-worktree","restore-snapshot","restore-files","repair-history"]),u=typeof i=="string"&&o.has(i)||typeof s=="string"&&o.has(s),d=typeof i=="string"&&c.has(i),p=typeof i=="string"&&l.has(i),f=typeof i=="string"&&a.has(i),m=Date.now(),h=P=>{let A=Math.max(0,Date.now()-m),w=P??{success:!1},{success:I=!1,projectRoot:k,...$}=w;return{projectRoot:this.projectPath,success:I,elapsedMs:A,...$}};try{await this.xxHashReady}catch(P){return h({success:!1,error:`xxHash initialization failed: ${P?.message||String(P)}`})}let g=hC(e);if(!g.valid)return h({success:!1,error:g.error,error_code:"validation_failed",details:{operation:i??null,issues:g.issues}});let y=i==="restore-snapshot";if(y&&(await this.supersedePendingProjectSyncForRestore(i),this.installRestoreFastPathMetadata(e,t)),!f)try{await this.awaitPendingProjectSync(i)}catch(P){return h({success:!1,error:`Project refresh failed after prior write: ${P?.message||String(P)}`,details:{reason:"project_refresh_failed",operation:i??null,pendingProjectSyncReason:this.pendingProjectSyncReason??null}})}let b=zs.getInstance(this.projectPath),S=(()=>{try{return(Su(),be(Ef)).FTSStatusTracker.getInstance(this.projectPath)}catch{return null}})(),_=(()=>{try{return(ra(),be(na)).SnapshotStatusTracker.getInstance(this.projectPath)}catch{return null}})(),R=null,T=null,E=!1,x=!0,v="Ready for write operations",F=null;try{let P=this.getIndexingStore();R=P?.getIndexingSession?.()??null,T=Ic(this.projectPath,0);let A=Math.max(0,Math.floor(Number(T?.totalFiles)||0)),w=Math.max(0,Math.floor(Number(T?.filesProcessed)||0)),I=yf({projectRoot:this.projectPath,store:P,sessionData:R,pendingCount:Math.max(0,Number(P.getPendingStats?.()?.count||0)),overviewTotal:A,overviewProcessed:w,indexingIsIndexing:b.isIndexing(),snapshotIsSnapshotting:!!_?.isSnapshotting,snapshotFilesChanged:_?.status?.filesChanged,snapshotFilesDeleted:_?.status?.filesDeleted,logScope:"CodeEngine"});R=I.sessionData,E=I.indexingActive,x=I.writesPermitted,v=I.writeBlockMessage,F=I.writeBlockReason}catch{R=null}let D=!!(S&&S.isBuilding),N=!!(_&&_.isSnapshotting);if(y&&!x&&!N&&!E&&(x=!0,F="ready",v="Restore-snapshot allowed as a recovery operation while metadata indexing is idle."),u&&!x){let P=Ic(this.projectPath,0),A=this.computeIndexingEta()??(P?.estimatedSecondsRemaining!=null?{seconds:Math.max(1,Math.ceil(P.estimatedSecondsRemaining)),basis:"files"}:null),w={reason:F||"background_work_in_progress",operation:i??null},I=[`Operation '${String(i||"unknown")}' is temporarily blocked. ${v}`];if(P&&P.totalFiles!=null&&P.filesProcessed!=null){let $=Number(P.filesProcessed),L=Number(P.totalFiles),j=L>0?L:0,z=j>0?Math.round($/j*100):void 0,U=j>0?Math.max(0,j-$):void 0;w.indexing={isIndexing:!0,filesIndexed:P.filesIndexed??void 0,filesSkipped:P.filesSkipped??void 0,filesFailed:P.filesFailed??void 0,filesProcessed:$,totalFiles:j,filesRemaining:U,percentComplete:z,estSecondsRemaining:P.estimatedSecondsRemaining??(A?A.seconds:void 0),statusMessage:P.message??void 0},I.push(`Progress: ${$}/${j} files${z!=null?` (${z}%)`:""}.`)}else if(R&&R.total_files_estimate!=null&&R.files_processed!=null){let $=Math.max(0,Math.floor(Number(R.files_processed)||0)),L=Math.max(0,Math.floor(Number(R.total_files_estimate)||0)),j=L>0?Math.round($/L*100):void 0,z=L>0?Math.max(0,L-$):void 0;w.indexing={isIndexing:!0,filesProcessed:$,totalFiles:L,filesRemaining:z,percentComplete:j,statusMessage:R.run_state?`run_state=${R.run_state}`:void 0},I.push(`Progress: ${$}/${L} files${j!=null?` (${j}%)`:""}.`)}A?(I.push(`Estimated retry window: ~${A.seconds}s.`),w.retryAfterSeconds=A.seconds,w.retryAfterBasis=A.basis):I.push("Retry shortly."),w.message=I.join(" "),w.indexing&&A?(w.indexing.retryAfterSeconds=A.seconds,w.indexing.retryAfterBasis=A.basis):!w.indexing&&A&&(w.indexing={isIndexing:E,retryAfterSeconds:A.seconds,retryAfterBasis:A.basis}),D&&(w.fts={state:S?.status?.state,snapshotId:S?.status?.snapshotId,blocking:!1}),N&&(w.snapshot={state:"snapshotting"});let k=w.message||"BUSY_RETRY_LATER";return h({success:!1,error:k,hints:["Wait a few seconds and retry the same operation. The indexer is still processing files."],details:w})}if(this.refreshingInProgress&&!f){let P=this.refreshingFiles.length,A=Math.max(1,Math.ceil(P/50));return V("[OperationGate] blocked by refresh",{op:i??null,totalFiles:P,etaSeconds:A,sampleFiles:this.refreshingFiles.slice(0,10)}),h({success:!1,error:`Engine is reconciling in-memory state with disk changes. Refreshing ${P} files, rough ETA ~${A}s. Retry in ~${A} seconds.`,hints:[`Wait ~${A} seconds and retry the same operation.`],details:{reason:"refreshing_in_progress",operation:i??null,message:`Engine is reconciling in-memory state with disk changes. Refreshing ${P} files, progress 0/${P}, rough ETA ~${A}s.`,retryAfterSeconds:A,refresh:{filesProcessed:0,totalFiles:P,estSecondsRemaining:A,sampleFiles:this.refreshingFiles.slice(0,10)}}})}if(u){if(this.modifyingOpActive){V("[OperationGate] blocked by active modifying op",{op:i??null,activeOp:this.modifyingOpName||"unknown",pendingProjectSyncReason:this.pendingProjectSyncReason??null,batchInProgress:this.batchInProgress,batchPhase:this.batchPhase??null,batchPhaseAgeMs:this.batchPhaseStartMs?Date.now()-this.batchPhaseStartMs:null});let P={},A=[`Another modifying operation ('${this.modifyingOpName||"unknown"}') is in progress.`],w=this.computeIndexingEta(),I=b.getStatus?.(),k=null,$=null;try{let z=this.getIndexingStore();$=z?(()=>{let U=z.getThroughput();return{avg_files_per_sec:U.avg_files_per_sec??null,avg_bytes_per_sec:U.avg_bytes_per_sec??null}})():null,k=z?.getIndexerMeta("worker_concurrency_hint")??null}catch(z){try{ee("CodeEngine","busyRetry indexing telemetry failed",{error:z?.message||z})}catch{}}!w&&I?.estimatedSecondsRemaining!=null&&(w={seconds:Math.max(1,Math.ceil(I.estimatedSecondsRemaining)),basis:"files"}),w?(A.push(`Estimated completion in ~${w.seconds}s (${w.basis}).`),P.retryAfterSeconds=w.seconds,P.retryAfterBasis=w.basis):A.push("Please retry shortly.");let L={};if(I&&(I.filesProcessed!=null&&(L.filesProcessed=I.filesProcessed),I.totalFiles!=null&&(L.totalFiles=I.totalFiles),I.estimatedSecondsRemaining!=null&&(L.estSecondsRemaining=I.estimatedSecondsRemaining,P.retryAfterSeconds||(P.retryAfterSeconds=Math.max(1,Math.ceil(I.estimatedSecondsRemaining)),P.retryAfterBasis="files"))),w&&(L.retryAfterSeconds=w.seconds,L.retryAfterBasis=w.basis),$&&($.avg_files_per_sec!=null&&(L.avgFilesPerSecond=$.avg_files_per_sec),$.avg_bytes_per_sec!=null&&(L.avgBytesPerSecond=$.avg_bytes_per_sec)),k){let z=Number(k);L.workerConcurrencyHint=Number.isFinite(z)?z:k}if(Object.keys(L).length>0&&(P.indexing=L),_&&_.isSnapshotting){let z=_.status;if(P.snapshot={state:z.state,startedAt:z.startedAt??void 0,filesChanged:z.filesChanged??void 0,filesDeleted:z.filesDeleted??void 0},!w&&z.startedAt){let U=Math.max(1,Math.floor((Date.now()-z.startedAt)/1e3));P.snapshot.elapsedSeconds=U}}P.message=A.join(" ");let j=P.message||"BUSY_RETRY_LATER";return h({success:!1,error:j,hints:["Wait a few seconds and retry the same operation."],details:P})}this.modifyingOpActive=!0,this.modifyingOpName=i,V("[OperationGate] acquired modifying op lock",{op:i??null,projectPath:this.projectPath})}let C=()=>{u&&(this.modifyingOpActive=!1,this.modifyingOpName=void 0)},O;try{let P=String(i||"").toLowerCase()==="delete"||!!e?.forceMayBreakSyntax;if(u&&!P&&!p){let A=await this.preflightExpectedHashCheck(e,t,i);if(!A.ok)return C(),h({success:!1,error:A.error});let w=this.extractTouchedFiles(e);w.length>0&&(O=await this.collectDiagnostics(t,w))}}catch{O=void 0}let M=P=>{let A=P??{success:!1};if(!u){let w=[],k=(()=>{let $=A?.indexing;if($&&typeof $=="object")return $;let L=A?.data?.indexing;return L&&typeof L=="object"?L:null})()??Ic(this.projectPath,0);if(k.isIndexing){let $=Math.max(0,Math.floor(Number(k.filesProcessed)||0)),L=Math.max(0,Math.floor(Number(k.totalFiles)||0)),j=k.estimatedSecondsRemaining!=null?k.estimatedSecondsRemaining:this.computeIndexingEta()?.seconds??null;(j==null||!Number.isFinite(j))&&this.computeIndexingEta()?.seconds!=null&&(j=this.computeIndexingEta().seconds);let z=L>0?Math.round($/L*100):void 0,U=[k.filesIndexed?`${k.filesIndexed} indexed`:null,k.filesSkipped?`${k.filesSkipped} skipped`:null,k.filesFailed?`${k.filesFailed} failed`:null].filter(Boolean).join(", ");w.push(`Indexing in progress: ${$||"?"} / ${L||"?"} files${z!=null?` (${z}%)`:""}${j!=null?`, est. ${j}s remaining`:""}${U?`; ${U}`:""}. Results may be incomplete.`)}S&&S.isBuilding&&w.push("FTS index building in background; text/FTS queries may be partial until ready."),_&&_.isSnapshotting&&w.push("Snapshotting in progress; results may lag until snapshot completes."),w.length&&(A.warnings=Array.isArray(A.warnings)?[...A.warnings,...w]:w)}return h(A)};try{let P=iC(e),{boundary:A}=P,{requireConfirmation:w,confirmed:I}=P,k=e.path||e.to||e.of||void 0;V("[OperationDispatch] begin",{op:i,rawOpName:s,isModifying:u,projectPath:this.projectPath,targetPath:k||null});let $=require("path"),L=require("fs"),j=k&&typeof k=="string"&&k.includes("#")?k.split("#")[0]:void 0,z=this.projectPath;if(j)z=$.isAbsolute(j)?j:$.join(this.projectPath,j);else if(e.scopeNode||e.scope){let X=e.scope,q=e.scopeNode?String(e.scopeNode):X?.node?.path||X?.files?.[0]||X?.dir||"";q.includes("#")&&(q=q.split("#")[0]);let Z=$.isAbsolute(q)?q:$.join(this.projectPath,q);try{L.existsSync(Z)&&L.statSync(Z).isDirectory()?z=$.join(Z,"__virtual__.ts"):z=Z}catch{z=Z}}let U=Ca(z),K=new Set;e&&e.boundary==null&&!k&&!e.scopeNode&&!e.scope&&(A="workspace");try{L.existsSync(U)||(A="workspace")}catch{A="workspace"}if(A==="project")if(!k&&!e.scopeNode&&!e.scope){let X=mS(this.projectPath);if(X.length>0)for(let q of X)K.add(q);else K.add(U)}else K.add(U);else if(A==="reachable"){let X={maxDepth:e.reachabilityDepth,...e.reachabilityOptions||{}},q=oC(this.projectPath,U,X);for(let Z of q)K.add(Z)}let G=new Fm(this.projectPath,{allowedTsconfigs:K,mode:A},t.ls.getForFile,async X=>{let q=String(X||"").replace(/\\/g,"/");if(!q)return!1;let Z=$.isAbsolute(q)?q:$.join(this.projectPath,q);try{if(!L.existsSync(Z)||!L.statSync(Z).isFile())return!1}catch{return!1}return(await this.withTransientIndexer(ae=>ae.indexFiles([Z],{emitMode:"full"}),"find-nodes full AST JIT")).processed>0});if(t.setQueryLayer(G),String(i||"").toLowerCase()==="rename"&&A!=="project"&&w&&!I)try{if(k){let X=e.expectedHash?`${k}@${e.expectedHash}`:`${k}`,q=Jr(X,this.project,this.projectPath);if(q){let Z=q.getSourceFile().getFilePath(),se=UB(q);if(se!=null){let ae=[],Fe=!!e.includeStrings,he=!!e.includeComments,Ke=G.findRenameLocations(Z,se,Fe,he);ae=Array.from(new Set(Ke.map(Ye=>$.resolve(Ye.fileName))));let Ze=Dm.build("rename",aC(X),this.projectPath,ae,{boundary:A,allowedTsconfigs:Array.from(K),referenceCount:Ke.length,rename:{newName:e.newName,locations:Ke,page:e.page}});return M({success:!1,error:"Cross-project rename requires explicit approval",crossProjectConfirmation:Ze})}}}}catch{}let pe=!!e?.dryRun,Ee=(()=>{try{let{openSnapshotsDb:X}=(hi(),be(mo)),q=X(this.projectPath,{readonly:!0});try{return q.prepare("SELECT snapshot_id FROM snapshots ORDER BY timestamp DESC, rowid DESC LIMIT 1").get()?.snapshot_id}finally{try{q.close()}catch{}}}catch{return}})(),re=X=>X?!!(String(X.op||"").toLowerCase()==="delete"||X.forceMayBreakSyntax||X.forceInsertWillBreakSyntax===!0||X.forceReplaceWillBreakSyntax===!0||X.forceDeleteReferencesMayBreakSyntax===!0):!1,W;switch(i){case"read_this_first":{let q=["Pando is an AST-aware code navigation and editing layer for large repos.","It keeps a light index of supported source files, uses that index to narrow candidate files, then parses exact AST details at query or edit time.","","Use Pando for source-code search, navigation, references, callers, exports, renames, inserts, replacements, and deletes.","Use shell/text tools for builds, tests, generated files, non-code files, and unsupported languages.",".clj-kondo is special: those files are intentionally excluded from semantic Clojure indexing to avoid indexing loops, but Pando exposes edit-file-text for .clj-kondo config and hook text edits.","","Read next:","- workspace-overview: quick inventory of indexed files and symbols.","- find-nodes: search by language, scope, and Datalog; request include.self/topN when you need paths and hashes for edits.","- get-content: read files or node paths returned by search tools.","- list-exports, find-references, and find-callers: follow symbols before changing them.","- Writers: rename, replace, replace-body, insert, delete, and edit-file-text for .clj-kondo config/hook files. Use edit-file-text for supported .clj-kondo text edits even though those files are excluded from the semantic index. Re-run find-nodes first if a path or hash is stale.","","Unnamed nodes can and should still be edited with Pando.","Statements, returns, calls, arguments, branches, literals, and other unnamed syntax are normal AST nodes; find them by starting from a named entity or file, then narrowing by kind, text, role, parent, or child index.","","Examples:","- In one find-nodes call, search for a function by name within the workspace and request include.self/topN to get the exact node path and hash.",'- To edit a statement inside a named function, find the function with include.self, then call find-nodes again with scope.node set to { path, expectedHash } for that function. Use predicates such as :node/kind "ReturnStatement" or :node/text "oldValue", then pass the returned statement path and hash without @ to replace or insert; delete uses expectedHashes.',"- For scripts or top-level code, scope find-nodes to the file path instead of a named node, find the statement by kind/text/role/index, then edit that returned node with a writer.","- Insert code is literal: include the newline and indentation you want when inserting before or after a statement anchor."].join(`
|
|
868
|
-
`);try{let Z=require("fs"),ae=require("path").resolve(__dirname,"..","..","mcp-pando-server","resources","messages.json");if(Z.existsSync(ae)){let he=JSON.parse(Z.readFileSync(ae,"utf8"))?.read_this_first;typeof he=="string"&&he.trim().length>0&&(q=he)}}catch{}W={success:!0,help:{title:"read_this_first",body:q}};break}case"insert":{let{InsertCodeExecutor:X}=await Promise.resolve().then(()=>(Yu(),$P)),q=s==="add-code"?{...e,op:"insert"}:e;W=await X.execute(q,t,this.project);break}case"workspace-overview":W=await Pf.execute(e,t,this.project);break;case"list-exports":W=Cf.execute(e,t,this.project);break;case"analyze-imports":W=If.execute(e,t,this.project);break;case"clojure-namespace-graph":W=Af.execute(e,t,this.project);break;case"clojure-namespace-dependencies":W=_u.executeDependencies(e,t,this.project);break;case"clojure-namespace-dependents":W=_u.executeDependents(e,t,this.project);break;case"plan-clojure-namespace-move":W=wu.executeMove(e,t,this.project);break;case"plan-clojure-namespace-rename":W=wu.executeRename(e,t,this.project);break;case"move-clojure-namespace":W=await vu.executeMove(e,t,this.project);break;case"rename-clojure-namespace":W=await vu.executeRename(e,t,this.project);break;case"get-db-schema":W=Ru.execute(e,t,this.project);break;case"query-db":W=await Nf.execute(e,t,this.project);break;case"delete":W=await yo.execute(e,t,this.project);break;case"find-references":W=await xa.execute(e,t,this.project);break;case"find-callers":W=await Xu.execute(e,t,this.project);break;case"rename":W=await So.execute(e,t,this.project);break;case"filter-map-reduce":{let{FilterMapReduceExecutor:X}=await Promise.resolve().then(()=>(nS(),jP));W=await X.execute(e,t,this.project);break}case"replace":{let X=s==="replace-body"?{...e,op:"replace",scope:"body"}:e;if(X.scope==="body"){let{ReplaceBodyExecutor:q}=await Promise.resolve().then(()=>(nd(),wm));W=await q.execute(X,t,this.project)}else{let{ReplaceNodeExecutor:q}=await Promise.resolve().then(()=>(sd(),vm));W=await q.execute(X,t,this.project)}break}case"edit-file-text":{let{TextFileEditExecutor:X}=await Promise.resolve().then(()=>(RC(),vC));W=await X.execute(e,t);break}case"add-exclude-dir":W=await this.handleAddExcludeDir(e);break;case"remove-exclude-dir":W=await this.handleRemoveExcludeDir(e);break;case"set-enabled-languages":W=await this.handleSetEnabledLanguages(e);break;case"list-snapshots":W=is.listSnapshots(e,t,this.project);break;case"diff-snapshots":W=is.diffSnapshots(e,t,this.project);break;case"get-snapshot-file":W=await is.getSnapshotFile(e,t,this.project);break;case"get-snapshot-trailers":W=is.getSnapshotTrailers(e,t,this.project);break;case"snapshot-worktree":W=await this.handleSnapshotWorktree(e,r);break;case"repair-history":W=await is.repairShadowHistory(e,t,this.project);break;case"restore-snapshot":W=await is.restoreSnapshot(e,t,this.project);break;case"restore-files":W=await is.restoreFiles(e,t,this.project);break;case"change-signature":V("[OperationDispatch] entering ChangeSignatureExecutor",{op:i,targetPath:e?.path??null}),W=await Cm.execute(e,t,this.project);break;case"get-project-root":W=this.handleGetProjectRoot();break;default:try{let{AtomicExecutor:X}=await Promise.resolve().then(()=>(TC(),kC));W=await X.execute(e,t,this.project,this)}catch{W={success:!1,error:`Operation ${e.op} not implemented`}}}V("[OperationDispatch] executor returned",{op:i,success:!!W?.success,error:W?.error??null,errorCode:W?.error_code??null,changedFiles:Array.isArray(W?.details?.changedFiles)?W.details.changedFiles.length:null,allChangedFiles:Array.isArray(W?.details?.allChangedFiles)?W.details.allChangedFiles.length:null});let me=Date.now(),_e={executorMs:Math.max(0,me-m)},Se=String(i||"").toLowerCase()==="delete"||!!e?.forceMayBreakSyntax;if(u&&W&&!W.success&&!pe&&!re(e)){let X=W.error_code;if((X==="would_introduce_syntax_error"||X==="validation_failed"||X==="io_write_failed")&&Ee){let Z=Array.isArray(W.details?.changedFiles)?W.details.changedFiles:[];if(Z.length>0)try{await is.restoreSnapshot({op:"restore-snapshot",snapshotId:Ee,shouldCreateNewSnapshot:!1,restrictToPaths:Z},t,this.project),W.details=W.details||{},W.details.rollbackAttempted=!0,W.details.snapshotBefore=Ee}catch{}}}if(u&&W&&W.success&&!pe&&!d){try{let X=Array.isArray(W.details?.allChangedFiles)?W.details.allChangedFiles:Array.isArray(W.details?.changedFiles)?W.details.changedFiles:[],q=Array.isArray(W.details?.deletedFiles)?W.details.deletedFiles:[];if((!X||X.length===0)&&(!q||q.length===0))return V("[OperationDispatch] skipping snapshot because no files changed",{op:i}),M(W);let Z=W.details?.receipt||{op:i,target:e.path||e.to||e.of,timestamp:Date.now(),changedFilesCount:X.length},{SnapshotService:se}=(vS(),be(wS)),{SnapshotStatusTracker:ae}=(ra(),be(na)),Fe=Date.now();V("[SnapshotService] Starting snapshot",{files:X.length,deleted:q.length});try{ae.getInstance(this.projectPath).start(X.length,q.length)}catch{}let he=W.details&&W.details.trailers?W.details.trailers:void 0,{snapshotId:Ke,parentId:Ze}=await se.takeSnapshotNow(this.projectPath,X,i,Z,he,q,r);_e.snapshotMs=Date.now()-Fe,V("[SnapshotService] Snapshot finished",{durationMs:_e.snapshotMs,snapshotId:Ke});try{ae.getInstance(this.projectPath).complete()}catch{}if(W.snapshotBefore=Ze||"<none>",W.snapshotAfter=Ke,W.details||(W.details={}),W.details.receipt=Z,W.details&&W.details.trailers){let Ye=W.details.trailers,Dt={};for(let ke of Object.keys(Ye)){let rt=String(Ye[ke]??"");Dt[ke]=rt.length>200?rt.slice(0,200):rt}delete W.details.trailers,W.details.trailersPreview=Dt,W.details.trailersNote="Trailers truncated to 200 chars. Use list-snapshots/get-snapshot-trailers to fetch full trailers."}}catch(X){return V("[OperationDispatch] snapshot finalization failed",{op:i,error:X?.message||String(X)}),M({success:!1,error:`Snapshot failure: ${X?.message||X}`})}if(!Se&&!p){let X=Array.isArray(W.details?.allChangedFiles)?W.details.allChangedFiles:Array.isArray(W.details?.changedFiles)?W.details.changedFiles:[];if(X.length>0){let q=Date.now(),Z=await this.validateChangedFiles(t,X,O);if(_e.validationMs=Date.now()-q,Z.skipped&&Z.warning&&(W.warnings=Array.isArray(W.warnings)?[...W.warnings,Z.warning]:[Z.warning]),!Z.ok){let se=W.snapshotBefore,ae=W.snapshotAfter;if(se&&ae&&ae!=="<none>")try{await is.restoreSnapshot({op:"restore-snapshot",snapshotId:se,shouldCreateNewSnapshot:!1,deleteSnapshotId:ae,restrictToPaths:X},t,this.project)}catch{}return M({success:!1,error:Z.error||"Post-operation validation failed; changes rolled back.",details:{validation:Z,snapshotBefore:se,snapshotAfter:ae,rollbackAttempted:!0}})}}}}u&&(W?.success?this.recordRestoreFastPathState(i,W):this.invalidateRestoreFastPathState("modifying-op-failed",{op:i??null,error:W?.error??null}));try{if(u&&W&&!pe){let X=Date.now(),q=require("path"),Z=Array.isArray(W.details?.allChangedFiles)?W.details.allChangedFiles:Array.isArray(W.details?.changedFiles)?W.details.changedFiles:[],se=Array.isArray(W.details?.createdFiles)?W.details.createdFiles:[],ae=Array.isArray(W.details?.deletedFiles)?W.details.deletedFiles:[],Fe=ke=>q.isAbsolute(ke)?ke:q.join(this.projectPath,ke),he=ke=>Array.from(new Set(ke.filter(Boolean))),Ke=he(se.map(Fe)),Ze=new Set(Ke),Ye=he(Z.map(Fe)).filter(ke=>!Ze.has(ke)),Dt=he(ae.map(Fe));(Ye.length>0||Dt.length>0||Ke.length>0)&&this.scheduleProjectSync({created:Ke,modified:Ye,deleted:Dt},`${String(i||s||"unknown")} post-write sync`).catch(ke=>{An("[RefreshFromDisk] post-op refresh failed",ke?.message||ke)}),_e.syncEnqueueMs=Date.now()-X}}catch(X){An("[RefreshFromDisk] post-op refresh failed",X?.message||X)}return V("[OperationDispatch] post-execution complete",{op:i,success:!!W?.success,totalElapsedMs:Math.max(0,Date.now()-m),postExecutionMs:Math.max(0,Date.now()-me),timings:_e,changedFiles:Array.isArray(W?.details?.changedFiles)?W.details.changedFiles.length:null,allChangedFiles:Array.isArray(W?.details?.allChangedFiles)?W.details.allChangedFiles.length:null}),M(W)}finally{V("[OperationGate] releasing modifying op lock",{op:i??null,activeOp:this.modifyingOpName||null}),C()}}async refreshFilesFromDisk(e,t){let r=require("fs"),s=require("path"),i=a=>{try{return s.relative(this.projectPath,a).replace(/\\/g,"/")}catch{return a}};if(e=this.filterExcludedAbsolutePaths(e),!e.length)return;ct(t,"Workspace sync refresh cancelled"),this.refreshingInProgress=!0,this.refreshingFiles=e.map(i);let o=Date.now();try{for(let a of e){ct(t,"Workspace sync refresh cancelled");try{let c=r.existsSync(a),l=this.project.getSourceFile(a);if(!c){l&&this.project.removeSourceFile(l);continue}(l||this.project.addSourceFileAtPath(a)).refreshFromFileSystemSync()}catch(c){An("[RefreshFromDisk] Failed for",a,c?.message||c)}}}finally{let a=Date.now()-o;Nn("code-engine.refreshFilesFromDisk.complete",{projectRoot:this.projectPath,files:e.length,sample:e.slice(0,20).map(i),elapsedMs:a}),V("[RefreshFromDisk] Completed",{files:e.length,ms:a}),this.refreshingInProgress=!1,this.refreshingFiles=[]}}scheduleProjectSync(e,t){let r=`project-sync:${Date.now().toString(36)}:${Math.random().toString(36).slice(2,8)}`,s=Date.now(),i=this.workspaceSyncController.signal;V("[ProjectSync] enqueue",{syncId:r,reason:t,created:e.created.length,modified:e.modified.length,deleted:e.deleted.length,hadPending:!!this.pendingProjectSync,pendingSyncId:this.pendingProjectSyncId??null,pendingReason:this.pendingProjectSyncReason??null});let o=async()=>{let l=Date.now();V("[ProjectSync] begin",{syncId:r,reason:t,queueWaitMs:l-s,created:e.created.length,modified:e.modified.length,deleted:e.deleted.length});try{if(await this.handleBatchFileChanges(e,{signal:i,source:"post-write-sync"}),i.aborted){V("[ProjectSync] superseded",{syncId:r,reason:t,durationMs:Date.now()-l,totalMs:Date.now()-s});return}V("[ProjectSync] complete",{syncId:r,reason:t,durationMs:Date.now()-l,totalMs:Date.now()-s})}catch(u){if(Mi(u)||i.aborted){V("[ProjectSync] superseded",{syncId:r,reason:t,durationMs:Date.now()-l,totalMs:Date.now()-s,message:u?.message||String(u)});return}throw V("[ProjectSync] failed",{syncId:r,reason:t,durationMs:Date.now()-l,totalMs:Date.now()-s,message:u?.message||String(u)}),u}},a=(this.pendingProjectSync??Promise.resolve()).catch(l=>{if(Mi(l)){V("[ProjectSync] previous queued refresh superseded",{syncId:r,reason:t,message:l?.message||String(l)});return}An("[ProjectSync] previous queued refresh failed",l?.message||l)}).then(o),c=Symbol(r);return this.pendingProjectSyncToken=c,this.pendingProjectSyncId=r,this.pendingProjectSyncEnqueuedAt=s,this.pendingProjectSyncReason=t,this.pendingProjectSync=a.finally(()=>{this.clearPendingProjectSyncState(c)}),this.pendingProjectSync}async awaitPendingProjectSync(e){let t=this.pendingProjectSync;if(!t)return;let r=Date.now();V("[ProjectSync] awaiting queued refresh before operation",{syncId:this.pendingProjectSyncId??null,operation:e??null,reason:this.pendingProjectSyncReason??null,queuedForMs:this.pendingProjectSyncEnqueuedAt?r-this.pendingProjectSyncEnqueuedAt:null});let s=setInterval(()=>{V("[ProjectSync] waiting",{syncId:this.pendingProjectSyncId??null,operation:e??null,reason:this.pendingProjectSyncReason??null,queuedForMs:this.pendingProjectSyncEnqueuedAt?Date.now()-this.pendingProjectSyncEnqueuedAt:null,waitedMs:Date.now()-r})},n.PROJECT_SYNC_HEARTBEAT_MS);s.unref?.();try{await t,V("[ProjectSync] awaited queued refresh complete",{syncId:this.pendingProjectSyncId??null,operation:e??null,reason:this.pendingProjectSyncReason??null,waitedMs:Date.now()-r})}finally{clearInterval(s)}}async awaitPostWriteWorkSettled(e="external"){let t=Date.now();V("[PostWriteDrain] begin",{reason:e,pendingProjectSync:!!this.pendingProjectSync,pendingProjectSyncId:this.pendingProjectSyncId??null,batchRunner:!!this.batchRunner,batchInProgress:this.batchInProgress,refreshingInProgress:this.refreshingInProgress});let r=setInterval(()=>{V("[PostWriteDrain] waiting",{reason:e,waitedMs:Date.now()-t,pendingProjectSync:!!this.pendingProjectSync,pendingProjectSyncId:this.pendingProjectSyncId??null,pendingProjectSyncReason:this.pendingProjectSyncReason??null,batchRunner:!!this.batchRunner,batchInProgress:this.batchInProgress,refreshingInProgress:this.refreshingInProgress,queuedBatch:this.describeQueuedBatch()})},n.PROJECT_SYNC_HEARTBEAT_MS);r.unref?.();try{for(;;){let s=this.pendingProjectSync;if(s){await s;continue}let i=this.batchRunner;if(i){await i;continue}if(!this.batchInProgress&&!this.refreshingInProgress&&!this.queuedBatch)break;await new Promise(o=>setTimeout(o,25))}}finally{clearInterval(r),V("[PostWriteDrain] complete",{reason:e,waitedMs:Date.now()-t,pendingProjectSync:!!this.pendingProjectSync,batchRunner:!!this.batchRunner,batchInProgress:this.batchInProgress,refreshingInProgress:this.refreshingInProgress})}}scheduleLspWorkspaceSync(e,t){let r=this.lspHost,s=r?.workspaceFilesChanged?.bind(r),i=e.created.length+e.modified.length+e.deleted.length;if(!s||i===0)return Nn("code-engine.batch.workspaceFilesChanged.skipped",{projectRoot:this.projectPath,created:e.created.length,modified:e.modified.length,deleted:e.deleted.length,reason:s?"empty-batch":"no-lsp-host"}),Promise.resolve();Nn("code-engine.batch.workspaceFilesChanged.scheduled",{projectRoot:this.projectPath,created:e.created.length,modified:e.modified.length,deleted:e.deleted.length,reason:t});let o=async()=>{let c=Date.now();Nn("code-engine.batch.workspaceFilesChanged.start",{projectRoot:this.projectPath,created:e.created.length,modified:e.modified.length,deleted:e.deleted.length,createdSample:e.created.slice(0,20),modifiedSample:e.modified.slice(0,20),deletedSample:e.deleted.slice(0,20),reason:t});try{await s(e),Nn("code-engine.batch.workspaceFilesChanged.complete",{projectRoot:this.projectPath,created:e.created.length,modified:e.modified.length,deleted:e.deleted.length,elapsedMs:Date.now()-c,reason:t})}catch(l){Nn("code-engine.batch.workspaceFilesChanged.failed",{projectRoot:this.projectPath,created:e.created.length,modified:e.modified.length,deleted:e.deleted.length,elapsedMs:Date.now()-c,error:l?.message||String(l),reason:t}),An("[LspWorkspaceSync] workspaceFilesChanged failed",l?.message||l)}},a=(this.pendingLspWorkspaceSync??Promise.resolve()).catch(c=>{An("[LspWorkspaceSync] previous queued sync failed",c?.message||c)}).then(o);return this.pendingLspWorkspaceSync=a.finally(()=>{this.pendingLspWorkspaceSync===a&&(this.pendingLspWorkspaceSync=null)}),this.pendingLspWorkspaceSync}withSnapshotReceipt(e,t,r){return{...r}}async handleBatchFileChanges(e,t){let r=t?.source??"external",s=t?.signal??this.workspaceSyncController.signal;if(V("batch-change event",{created:e.created.length,modified:e.modified.length,deleted:e.deleted.length,source:r,signalAborted:s.aborted}),e.created.length+e.modified.length+e.deleted.length===0)return;if(r!=="post-write-sync"&&this.invalidateRestoreFastPathState("batch-change",{source:r,created:e.created.length,modified:e.modified.length,deleted:e.deleted.length}),s.aborted){V("[BatchQueue] skipped aborted batch",{source:r,created:e.created.length,modified:e.modified.length,deleted:e.deleted.length});return}let o={created:e.created.map(as),modified:e.modified.map(as),deleted:e.deleted.map(as)};Nn("code-engine.batch.enqueue",{projectRoot:this.projectPath,created:o.created.length,modified:o.modified.length,deleted:o.deleted.length,createdSample:o.created.slice(0,20),modifiedSample:o.modified.slice(0,20),deletedSample:o.deleted.slice(0,20)});let a=`${ft(this.projectPath)}/`,c=o.deleted.find(u=>u.startsWith(a)&&u.endsWith(".db"));if(c&&!this.indexingInProgress){V("\u{1F504} Index DB deleted; triggering full reindex...",{file:c}),await this.startIndexing();return}let l=this.mergeQueuedBatch(o,r);V("[BatchQueue] enqueue",{incoming:{created:o.created.length,modified:o.modified.length,deleted:o.deleted.length},source:r,queued:l,indexingInProgress:this.indexingInProgress,batchInProgress:this.batchInProgress,runnerActive:!!this.batchRunner}),!this.indexingInProgress&&await this.ensureBatchRunner()}}});var nc=B(require("path"));ny();ms();It();var cd=class{constructor(e){this.options=e;this.workspaceRoots=new Set;this.explicitProjectRoot=null;this.registeredRoots=new Set}getWorkspaceRoots(){return Array.from(this.workspaceRoots).sort((e,t)=>e.localeCompare(t))}getExplicitProjectRoot(){return this.explicitProjectRoot}getRegisteredRoots(){return Array.from(this.registeredRoots).sort((e,t)=>e.localeCompare(t))}async setWorkspaceRoots(e,t){return this.workspaceRoots=new Set(e.map(r=>this.options.normalizeRoot(r)).filter(r=>!!r)),this.refreshEffectiveRoots(t)}async setProjectRoot(e,t){let r=Date.now();ee("ProjectRootManager","setProjectRoot begin",{rootOrPath:e,currentExplicitRoot:this.explicitProjectRoot,opts:t});let s=this.options.normalizeRoot(e);if(!s)return ee("ProjectRootManager","setProjectRoot normalized to null",{rootOrPath:e,elapsedMs:Date.now()-r}),null;let i=this.options.resolveIndexRoot(s);return i?this.explicitProjectRoot===i?(ee("ProjectRootManager","setProjectRoot no-op",{rootOrPath:e,resolvedInput:s,targetDir:i,elapsedMs:Date.now()-r}),i):(this.explicitProjectRoot=i,await this.refreshEffectiveRoots(t),ee("ProjectRootManager","setProjectRoot complete",{rootOrPath:e,resolvedInput:s,targetDir:i,registeredRoots:this.getRegisteredRoots(),elapsedMs:Date.now()-r}),i):(ee("ProjectRootManager","setProjectRoot resolveIndexRoot returned null",{rootOrPath:e,resolvedInput:s,elapsedMs:Date.now()-r}),null)}async refreshEffectiveRoots(e){let t=Date.now(),r=this.explicitProjectRoot?new Set([this.explicitProjectRoot]):new Set(this.workspaceRoots),s=new Set(this.registeredRoots),i=[];ee("ProjectRootManager","refreshEffectiveRoots begin",{effective:Array.from(r),registeredBefore:Array.from(s),opts:e});for(let o of r){if(this.registeredRoots.has(o))continue;let a=Date.now(),c=await this.options.registerRoot(o);ee("ProjectRootManager","refreshEffectiveRoots registerRoot resolved",{requestedRoot:o,registered:c,elapsedMs:Date.now()-a}),c&&(this.registeredRoots.add(c),i.push(c))}for(let o of s)r.has(o)||(this.options.disposeRoot(o),this.registeredRoots.delete(o));if(e?.indexNewRoots&&this.options.startIndexingForRoot)for(let o of i)ee("ProjectRootManager","refreshEffectiveRoots startIndexingForRoot dispatch",{root:o}),this.options.startIndexingForRoot(o);return ee("ProjectRootManager","refreshEffectiveRoots complete",{newlyRegistered:i,finalRoots:this.getRegisteredRoots(),elapsedMs:Date.now()-t}),{newlyRegistered:i,finalRoots:this.getRegisteredRoots()}}};ms();Wo();zn();uu();Yo();var CS=5e4,KB=1*1024*1024;function jm(n,e){let t=typeof e?.limit=="number"&&Number.isFinite(e.limit)?Math.max(1,Math.trunc(e.limit)):CS,r=e?.languageSupport,s=Hs(n),i=su(r),o=Kr(n,s),a=nk(n,i,{shouldExclude:o,maxFileBytes:KB,limit:t});return{root:n,candidateIndexableFiles:a.count,limit:t,exceeded:a.limitExceeded}}function CC(n){let e=n.exceeded?"at least":"exactly";return new Error(`Refusing to index '${n.root}': candidate_indexable_files is ${e} ${n.candidateIndexableFiles}, above the limit of ${n.limit}. Choose a narrower root or add excludes before retrying.`)}_n();It();var ld=class n{constructor(e,t){this.options=t;this.indexingSuppressedRoots=new Set;this.rootManager=new cd({normalizeRoot:r=>{let s=r.trim();return s?en(s):null},resolveIndexRoot:r=>r,registerRoot:async r=>{let s=Date.now();ee("DirectProjectRootManager","registerRoot begin",{root:r,hasOptions:!!this.options});let i=this.getOptionsForRoot(r);return i&&wn.setEngineOptions(r,i),wn.getEngine(r,i),ee("DirectProjectRootManager","registerRoot complete",{root:r,elapsedMs:Date.now()-s}),r},disposeRoot:r=>{ee("DirectProjectRootManager","disposeRoot",{root:r}),wn.clearEngine(r)},startIndexingForRoot:async r=>{let s=Date.now();if(ee("DirectProjectRootManager","startIndexingForRoot begin",{root:r}),this.indexingSuppressedRoots.has(en(r))){ee("DirectProjectRootManager","startIndexingForRoot skipped (root over indexing limit)",{root:r});return}let i=wn.getEngine(r,this.getOptionsForRoot(r));typeof i?.startIndexing=="function"&&await i.startIndexing(),ee("DirectProjectRootManager","startIndexingForRoot dispatched",{root:r,elapsedMs:Date.now()-s})}}),this.initialRoot=e}static async create(e,t){let r=new n(e,t);return await r.validateProjectRoot(e),await r.rootManager.setWorkspaceRoots([e]),r}getProjectRoot(){let e=this.rootManager.getExplicitProjectRoot();return e||(this.rootManager.getRegisteredRoots()[0]??null)}getEngine(){let e=this.getProjectRoot();if(!e)throw new Error("No project root configured.");return wn.getEngine(e,this.getOptionsForRoot(e))}async validateProjectRoot(e){let t=e.trim();if(!t)return null;let r=en(t),s=jm(r,{languageSupport:this.getOptionsForRoot(r)?.languageSupport,limit:this.indexingLimitOverride});if(s.exceeded){this.indexingSuppressedRoots.add(r);let i=CC(s).message;ee("DirectProjectRootManager","validateProjectRoot indexing suppressed",{root:r,candidateIndexableFiles:s.candidateIndexableFiles,limit:s.limit,reason:i})}else this.indexingSuppressedRoots.delete(r);return r}isIndexingSuppressed(e){return this.indexingSuppressedRoots.has(en(e))}setIndexingLimitOverrideForTesting(e){this.indexingLimitOverride=e}async setProjectRoot(e){let t=Date.now();ee("DirectProjectRootManager","setProjectRoot begin",{root:e}),await this.validateProjectRoot(e);let r=await this.rootManager.setProjectRoot(e,{indexNewRoots:!0});return ee("DirectProjectRootManager","setProjectRoot complete",{root:e,resolved:r,elapsedMs:Date.now()-t}),r}updateRootOptions(e,t){let r=en(e),s=t??this.getOptionsForRoot(r);s&&wn.setEngineOptions(r,s)}getOptionsForRoot(e){let t=en(e),r=this.options?.languageSupport??Ho(t),s=this.options?.lspHost;if(!(!r&&!s))return{...r?{languageSupport:r}:{},...s?{lspHost:s}:{}}}};bi();Mf();Wo();zn();Ws();Js();var ZB=B(require("fs")),GB=B(require("path"));$f();var OC=require("events");Mf();$f();zn();Wo();ms();_n();var MC=require("child_process");ms();ur();It();var IS=require("child_process"),Ma=null,ud=null;async function AC(n){return Ma||ud||(ud=Promise.resolve().then(()=>{let e=IC();if(e.available)return Ma=e,e;let t=VB(),r=e.error;for(let s of t){n?.(`[NodeFileWatcher] watchman missing; trying install via ${s.label}`);let i=JB(s),o=IC();if(o.available)return Ma={available:!0,version:o.version,installAttempted:!0,installSucceeded:!0,installMethod:s.label},Ma;r=i.error??o.error??r}return Ma={available:!1,installAttempted:t.length>0,installSucceeded:!1,error:r},Ma}).finally(()=>{ud=null}),ud)}function IC(){let n=(0,IS.spawnSync)("watchman",["--version"],{encoding:"utf8",stdio:"pipe",shell:process.platform==="win32"});return n.status===0?{available:!0,version:`${n.stdout||n.stderr||""}`.trim()||void 0,installAttempted:!1,installSucceeded:!1}:{available:!1,installAttempted:!1,installSucceeded:!1,error:NC(n.error,n.stderr,n.stdout)}}function JB(n){for(let e of n.steps){let t=(0,IS.spawnSync)(e.cmd,e.args,{encoding:"utf8",stdio:"pipe",shell:process.platform==="win32"});if(t.status!==0)return{ok:!1,error:NC(t.error,t.stderr,t.stdout)}}return{ok:!0}}function VB(){let n=typeof process.getuid=="function"?process.getuid()===0:!1,e=(t,r)=>n?{cmd:t,args:r}:{cmd:"sudo",args:["-n",t,...r]};switch(process.platform){case"darwin":return[{label:"homebrew",steps:[{cmd:"brew",args:["install","watchman"]}]},{label:"macports",steps:[e("port",["install","watchman"])]}];case"linux":return[{label:"homebrew",steps:[{cmd:"brew",args:["install","watchman"]}]},{label:"apt",steps:[e("apt-get",["update"]),e("apt-get",["install","-y","watchman"])]},{label:"dnf",steps:[e("dnf",["install","-y","watchman"])]},{label:"pacman",steps:[e("pacman",["-S","--noconfirm","watchman"])]}];case"win32":return[{label:"chocolatey",steps:[{cmd:"choco",args:["install","watchman","-y"]}]},{label:"winget",steps:[{cmd:"winget",args:["install","--id","Facebook.Watchman","-e"]}]}];default:return[]}}function NC(n,e,t){if(n instanceof Error&&n.message)return n.message;let r=`${e??""}`.trim();return r||`${t??""}`.trim()||void 0}function Mn(n,e){if(!Ht())return;let t=e&&typeof e=="object"&&!Array.isArray(e)?{pid:process.pid,...e}:{pid:process.pid,details:e};ee("WatcherTrace",n,t)}var Lm=class{constructor(e){this.log=e;this.projectRoot=null;this.languageSupport=null;this.watcherChild=null;this.watcherGeneration=0;this.shutdownGraceMs=1e3;this.switchChain=Promise.resolve()}async activate(e,t){this.languageSupport=t,await this.updateProjectRoot(e,t)}async updateProjectRoot(e,t){if(t&&(this.languageSupport=t),!e||!this.languageSupport||e===this.projectRoot&&!t)return;let r=this.languageSupport,s=this.switchChain.catch(()=>{}).then(async()=>{let i=this.projectRoot,o=this.watcherChild,a=this.watcherGeneration+1;this.log(`[NodeFileWatcher] updateProjectRoot begin from=${i??"null"} to=${e}`),Mn("node-watcher.updateProjectRoot.begin",{fromRoot:i,toRoot:e,previousGeneration:o?.generation??null,hasWatcher:!!o}),o&&(Mn("node-watcher.updateProjectRoot.await-previous-exit",{fromRoot:i,toRoot:e,previousGeneration:o.generation,childPid:o.process.pid??null}),await this.shutdownChild(o,"root-switch"));let c=await AC(this.log);Mn("node-watcher.watchman.status",{root:e,generation:a,available:c.available,version:c.version,installAttempted:c.installAttempted,installSucceeded:c.installSucceeded,installMethod:c.installMethod,error:c.error});let l=this.spawnWatcherChild(e,r,a,c);this.projectRoot=e,this.watcherChild=l,this.watcherGeneration=a,Mn("node-watcher.updateProjectRoot.complete",{fromRoot:i,toRoot:e,generation:a,childPid:l.process.pid??null,scriptPath:l.scriptPath})});this.switchChain=s,await s}async dispose(){let e=this.switchChain.catch(()=>{}).then(async()=>{let t=this.watcherChild,r=this.projectRoot,s=this.watcherGeneration;this.projectRoot=null,this.watcherChild=null,t&&(Mn("node-watcher.dispose",{root:r,generation:s,childPid:t.process.pid??null}),await this.shutdownChild(t,"dispose"))});this.switchChain=e,await e}spawnWatcherChild(e,t,r,s){let i=rE();if(!i)throw new Error("Could not resolve watcher child process script");this.log(`[NodeFileWatcher] activate root=${e}`),Mn("node-watcher.spawn.start",{root:e,generation:r,scriptPath:i});let o=(0,MC.fork)(i,[],{cwd:e,env:{...process.env,PANDO_WATCH_ROOT:e,PANDO_WATCH_GENERATION:String(r),PANDO_WATCH_LANGUAGE_SUPPORT_JSON:JSON.stringify(t),PANDO_WATCH_WATCHMAN_AVAILABLE:s.available?"1":"0",PANDO_WATCH_WATCHMAN_INSTALL_ATTEMPTED:s.installAttempted?"1":"0",PANDO_WATCH_WATCHMAN_INSTALL_SUCCEEDED:s.installSucceeded?"1":"0"},stdio:["ignore","inherit","inherit","ipc"]}),a=()=>{},c=new Promise(u=>{a=u}),l={process:o,root:e,generation:r,scriptPath:i,shutdownTimer:null,shuttingDown:!1,exitPromise:c,resolveExit:a};return o.on("message",u=>{this.handleChildMessage(l,u)}),o.on("exit",(u,d)=>{l.shutdownTimer&&(clearTimeout(l.shutdownTimer),l.shutdownTimer=null),Mn("node-watcher.child.exit",{root:l.root,generation:l.generation,childPid:o.pid??null,code:u,signal:d,shuttingDown:l.shuttingDown}),this.watcherChild===l&&(this.watcherChild=null),l.resolveExit()}),o.on("error",u=>{let d=u instanceof Error?u.message:String(u);this.log(`[NodeFileWatcher] watcher child error root=${e} error=${d}`),Mn("node-watcher.child.error",{root:e,generation:r,childPid:o.pid??null,error:d})}),Mn("node-watcher.spawn.complete",{root:e,generation:r,scriptPath:i,childPid:o.pid??null}),l}async handleChildMessage(e,t){if(!(!t||typeof t!="object"))switch(t.type){case"ready":this.handleReadyMessage(e,t);return;case"error":this.handleErrorMessage(e,t);return;case"batch":await this.handleBatchMessage(e,t);return;default:return}}handleReadyMessage(e,t){if(!this.isActiveChild(e)){Mn("node-watcher.ready.stale",{root:t.root,generation:t.generation,activeRoot:this.projectRoot,activeGeneration:this.watcherGeneration});return}this.log(`[NodeFileWatcher] ready root=${t.root} watchRoots=${t.watchRootCount??0} backend=${t.backendPreference??"native"}`),Mn("node-watcher.ready",{root:t.root,generation:t.generation,childPid:e.process.pid??null,watchRootCount:t.watchRootCount,backendPreference:t.backendPreference,watchmanAvailable:t.watchmanAvailable,watchmanInstallAttempted:t.watchmanInstallAttempted,watchmanInstallSucceeded:t.watchmanInstallSucceeded})}handleErrorMessage(e,t){let r=!this.isActiveChild(e);this.log(`[NodeFileWatcher] watch error path=${t.root} error=${t.error}`),Mn(r?"node-watcher.error.stale":"node-watcher.error",{root:t.root,generation:t.generation,childPid:e.process.pid??null,activeRoot:this.projectRoot,activeGeneration:this.watcherGeneration,error:t.error})}async handleBatchMessage(e,t){if(!this.isActiveChild(e)){Mn("node-watcher.batch.stale",{root:t.root,generation:t.generation,batchId:t.batchId,activeRoot:this.projectRoot,activeGeneration:this.watcherGeneration}),this.sendToChild(e,{type:"batch-ack",batchId:t.batchId,ok:!0});return}let r=wn.getExistingEngine(t.root);if(Mn("node-watcher.batch.start",{root:t.root,generation:t.generation,batchId:t.batchId,childPid:e.process.pid??null,created:t.changes.created.length,modified:t.changes.modified.length,deleted:t.changes.deleted.length,hasEngine:!!r,hasBatchHandler:typeof r?.handleBatchFileChanges=="function"}),!r||typeof r.handleBatchFileChanges!="function"){this.sendToChild(e,{type:"batch-ack",batchId:t.batchId,ok:!1,error:`No batch handler available for root ${t.root}`});return}try{await r.handleBatchFileChanges(t.changes),Mn("node-watcher.batch.complete",{root:t.root,generation:t.generation,batchId:t.batchId,childPid:e.process.pid??null}),this.sendToChild(e,{type:"batch-ack",batchId:t.batchId,ok:!0})}catch(s){let i=s instanceof Error?s.message:String(s);Mn("node-watcher.batch.failed",{root:t.root,generation:t.generation,batchId:t.batchId,childPid:e.process.pid??null,error:i}),this.sendToChild(e,{type:"batch-ack",batchId:t.batchId,ok:!1,error:i})}}isActiveChild(e){return this.watcherChild===e&&this.projectRoot===e.root&&this.watcherGeneration===e.generation}sendToChild(e,t){try{e.process.send?.(t)}catch(r){Mn("node-watcher.child.send.failed",{root:e.root,generation:e.generation,childPid:e.process.pid??null,messageType:t.type,error:r instanceof Error?r.message:String(r)})}}async shutdownChild(e,t){if(e.shuttingDown){await e.exitPromise;return}e.shuttingDown=!0,Mn("node-watcher.child.shutdown.begin",{root:e.root,generation:e.generation,childPid:e.process.pid??null,reason:t}),this.sendToChild(e,{type:"shutdown",reason:t}),e.shutdownTimer=setTimeout(()=>{Mn("node-watcher.child.shutdown.force-kill",{root:e.root,generation:e.generation,childPid:e.process.pid??null,reason:t,graceMs:this.shutdownGraceMs});try{e.process.kill("SIGKILL")}catch(r){Mn("node-watcher.child.shutdown.force-kill.failed",{root:e.root,generation:e.generation,childPid:e.process.pid??null,reason:t,error:r instanceof Error?r.message:String(r)})}},this.shutdownGraceMs),await e.exitPromise}};var FC=DC();function DC(){return process.env.PANDO_RUNTIME_HOST==="vscode-extension"||process.env.VSCODE_PID||process.env.VSCODE_IPC_HOOK||process.env.VSCODE_CWD?"vscode-extension":process.env.PANDO_RUNTIME_HOST==="standalone-cli"?"standalone-cli":"unknown"}function AS(n){FC=n,process.env.PANDO_RUNTIME_HOST=n}function NS(){return FC==="vscode-extension"}ur();ms();async function MS(n){let e=wn.getEngine(n),t={root:n,isIndexing:typeof e?.isIndexingInProgress=="function"?!!e.isIndexingInProgress():!1};try{let r=await e.execute({op:"workspace-overview"});if(!r?.success)return t;let s=r.indexing??{};return{root:n,isIndexing:!!(s.isIndexing??t.isIndexing),progress:typeof s.progress=="number"?s.progress:void 0,totalFiles:typeof s.totalFiles=="number"?s.totalFiles:void 0,filesProcessed:typeof s.filesProcessed=="number"?s.filesProcessed:void 0,filesIndexed:typeof s.filesIndexed=="number"?s.filesIndexed:void 0,filesSkipped:typeof s.filesSkipped=="number"?s.filesSkipped:void 0,filesFailed:typeof s.filesFailed=="number"?s.filesFailed:void 0,message:typeof s.message=="string"?s.message:void 0}}catch{return t}}It();var dd=class n extends OC.EventEmitter{constructor(t,r){super();this.rootManager=t;this.options=r;this.watcher=null}static async create(t){gs()||Ko(process.cwd(),t.runtimePaths);let r=await ld.create(t.initialRoot,{languageSupport:t.languageSupport,lspHost:t.lspHost}),s=new n(r,{...t});return s.warnIfIndexingSuppressed(r.getProjectRoot()),await s.configureWatcher(),s}warnIfIndexingSuppressed(t){!t||!this.rootManager.isIndexingSuppressed(t)||this.options.log?.(`indexing is OFF for '${t}': it has too many files to index safely. Pando is running but its code-graph tools will be empty here. Set the project root to a smaller folder (one with a .git/package.json/etc.) and indexing will start automatically.`)}getProjectRoot(){return this.rootManager.getProjectRoot()}getRoots(){let t=this.getProjectRoot();return t?[t]:[]}getEngine(){return this.rootManager.getEngine()}async setProjectRoot(t){let r=this.getProjectRoot(),s=en(t),i=Date.now();if(ee("PandoRuntime","setProjectRoot begin",{requestedRoot:t,currentRoot:r,nextRoot:s}),await this.rootManager.validateProjectRoot(t),this.warnIfIndexingSuppressed(s),r===s)return ee("PandoRuntime","setProjectRoot no-op",{requestedRoot:t,currentRoot:r,nextRoot:s,elapsedMs:Date.now()-i}),r;if(r&&r!==s){let c=wn.getExistingEngine(r),l=`project root switching from ${r} to ${s}`,u=(p,f,m)=>{ee("PandoRuntime",`setProjectRoot phase:${p}`,{requestedRoot:t,currentRoot:r,nextRoot:s,elapsedMs:Date.now()-f,...m})},d=Date.now();try{c?.cancelActiveOperations?.("project root switching")}catch{}u("cancelActiveOperations",d,{hasEngine:!!c}),d=Date.now();try{c?.cancelIndexing?.("project root switching")}catch{}u("cancelIndexing",d),d=Date.now();try{wn.resetEngine(r)}catch{}u("resetEngine",d),d=Date.now(),Of(),u("shutdownActiveStreamingIndexers",d),d=Date.now(),await Us.shutdownAllShared({force:!0,reason:l}).catch(()=>{}),u("shutdownAllShared(force)",d),d=Date.now(),ia(l),u("shutdownSharedWorkers",d)}let o=Date.now(),a=await this.rootManager.setProjectRoot(t);if(ee("PandoRuntime","setProjectRoot rootManager resolved",{requestedRoot:t,currentRoot:r,nextRoot:s,resolved:a,elapsedMs:Date.now()-o}),a){let c=Date.now();ee("PandoRuntime","setProjectRoot watcher.updateProjectRoot begin",{requestedRoot:t,currentRoot:r,nextRoot:s,resolved:a,hasWatcher:!!this.watcher}),await this.watcher?.updateProjectRoot(a,this.resolveLanguageSupport(a)),ee("PandoRuntime","setProjectRoot watcher.updateProjectRoot complete",{requestedRoot:t,currentRoot:r,nextRoot:s,resolved:a,elapsedMs:Date.now()-c});let l=Date.now();ee("PandoRuntime","setProjectRoot emit rootChanged begin",{requestedRoot:t,currentRoot:r,nextRoot:s,resolved:a}),this.emit("rootChanged",a),ee("PandoRuntime","setProjectRoot emit rootChanged complete",{requestedRoot:t,currentRoot:r,nextRoot:s,resolved:a,elapsedMs:Date.now()-l})}return ee("PandoRuntime","setProjectRoot complete",{requestedRoot:t,currentRoot:r,nextRoot:s,resolved:a,elapsedMs:Date.now()-i}),a}async startIndexing(){let t=this.getProjectRoot();if(!t)return;if(this.rootManager.isIndexingSuppressed(t)){ee("PandoRuntime","startIndexing skipped (root over indexing limit)",{root:t}),this.emit("indexing",{root:t,isIndexing:!1});return}let r=this.rootManager.getEngine();this.emit("indexing",{root:t,isIndexing:!0}),r.startIndexing?.()}async getIndexingStatus(){let t=this.getProjectRoot();return t?MS(t):null}async getWorkspaceOverview(){let t=this.getProjectRoot();if(!t)return null;let r=this.rootManager.getEngine();try{let s=await r.execute({op:"workspace-overview"});if(!s?.success)return null;let i=s.nodes??{},o=qr(i.functions),a=qr(i.classes),c=qr(i.interfaces),l=qr(i.types),u=qr(i.enums),d=qr(i.variables),p=[o,a,c,l,u,d].filter(f=>typeof f=="number").reduce((f,m)=>f+m,0);return{root:t,files:{total:qr(s.files?.total),testFiles:qr(s.files?.testFiles)},nodes:{total:p||void 0,functions:o,classes:a,interfaces:c,types:l,enums:u,variables:d},indexing:{root:t,isIndexing:!!s.indexing?.isIndexing,totalFiles:qr(s.indexing?.totalFiles),filesProcessed:qr(s.indexing?.filesProcessed),filesIndexed:qr(s.indexing?.filesIndexed),filesSkipped:qr(s.indexing?.filesSkipped),filesFailed:qr(s.indexing?.filesFailed),progress:qr(s.indexing?.progress),message:typeof s.indexing?.message=="string"?s.indexing.message:void 0},writes:{ready:!!s.writes?.ready,blocked:!!(s.writes?.blocked??!s.writes?.ready),reason:typeof s.writes?.reason=="string"?s.writes.reason:void 0,message:typeof s.writes?.message=="string"?s.writes.message:void 0,gates:{metadataIndexingComplete:!!s.writes?.gates?.metadataIndexingComplete,snapshotComplete:!!s.writes?.gates?.snapshotComplete,ftsRequired:!1}},lsp:s.lsp&&typeof s.lsp=="object"?s.lsp:void 0}}catch{return null}}async stop(){let t=this.getProjectRoot();await this.watcher?.dispose(),this.watcher=null;let r=t?en(t):null,s=r?wn.getExistingEngine(r):null;try{s?.cancelActiveOperations?.("runtime stopped")}catch{}try{s?.cancelIndexing?.("runtime stopped")}catch{}if(Of(),await Us.shutdownAllShared({force:!0,reason:"runtime stopped"}).catch(()=>{}),ia("runtime stopped"),Fy(),!!r){try{s?.dispose?.()}catch{}wn.clearEngine(r)}}reloadLanguageSupport(t){let r=en(t),s=this.resolveLanguageSupport(r);this.rootManager.updateRootOptions(r,{languageSupport:s,lspHost:this.options.lspHost}),this.getProjectRoot()===r&&this.watcher?.updateProjectRoot(r,s)}async configureWatcher(){if(this.options.enableFileWatching===!1||NS())return;let t=this.getProjectRoot();t&&(this.watcher=new Lm(r=>this.options.log?.(r)??void 0),await this.watcher.activate(t,this.resolveLanguageSupport(t)))}resolveLanguageSupport(t){return this.options.languageSupport??Ho(t)}};function qr(n){return typeof n=="number"?n:void 0}ur();async function zm(n,e={}){return e.hostKind&&AS(e.hostKind),e.runtimePaths&&Ko(e.runtimePaths.runtimeRoot??n,e.runtimePaths),dd.create({initialRoot:n,languageSupport:e.languageSupport,lspHost:e.lspHost,transportMode:e.transportMode,enableFileWatching:e.enableFileWatching,log:e.log,runtimePaths:e.runtimePaths})}ur();var hd=B(require("path"));ms();_n();var XB="Compared against a smart non-pando workflow that would only send targeted declaration/reference snippets and minimal surrounding context, not full files.";var Fa={language:null,charsPerLine:40,charsPerToken:4,searchLines:6,confidence:"heuristic"},QB={c:{language:"c",charsPerLine:40.09,charsPerToken:3.98,searchLines:5.91,confidence:"trace-high"},cpp:{language:"cpp",charsPerLine:42.56,charsPerToken:3.99,searchLines:6.89,confidence:"trace-high"},csharp:{language:"csharp",charsPerLine:38.55,charsPerToken:3.99,searchLines:3.76,confidence:"trace-low"},js:{language:"js",charsPerLine:39.75,charsPerToken:3.98,searchLines:6.02,confidence:"trace-high"},ts:{language:"ts",charsPerLine:37.3,charsPerToken:3.99,searchLines:7.67,confidence:"trace-high"},java:{language:"java",charsPerLine:40,charsPerToken:4,searchLines:6,confidence:"trace-sparse"},clojure:{language:"clojure",charsPerLine:40,charsPerToken:4,searchLines:6,confidence:"modeled-only"},dart:{language:"dart",charsPerLine:40,charsPerToken:4,searchLines:6,confidence:"modeled-only"}};function Wi(n){return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.floor(n))}function md(n){return Math.max(0,Math.floor(n))}function BC(n,e=Fa){return md(Math.round(n*e.charsPerLine))}function qm(n,e=Fa){return n<=0?0:md(Math.ceil(n/e.charsPerToken))}function YB(n){return Buffer.byteLength(n,"utf8")}function e1(n){let e=n[n.length-1],t=n[n.length-2],r=n[n.length-3];return e?e==="content"&&t==="body"||e==="content"&&t==="code"&&r==="self"||e==="content"&&t==="code"?!0:e==="source"||e==="sourceText"||e==="sourceCode"||e==="rawSource"||e==="excerpt"||e==="snippet"||e==="oldString"||e==="old_string"||e==="originalFile"||e==="gitDiff"||e==="diff"||e==="patch":!1}function qC(n){let e=new Set,t=(r,s)=>{if(typeof r=="string")return e1(s)?YB(r):0;if(!r||typeof r!="object"||e.has(r))return 0;if(e.add(r),Array.isArray(r))return r.reduce((o,a,c)=>o+t(a,[...s,String(c)]),0);let i=0;for(let[o,a]of Object.entries(r))i+=t(a,[...s,o]);return i};return md(t(n,[]))}function $S(n){if(Array.isArray(n))return n.length===1?$S(n[0]):null;if(typeof n!="string")return null;let e=n.trim().toLowerCase();return e?e==="typescript"||e==="tsx"?"ts":e==="javascript"||e==="jsx"?"js":e==="c++"||e==="cc"||e==="cxx"?"cpp":e==="c#"||e==="cs"?"csharp":e==="clj"||e==="cljs"||e==="cljc"?"clojure":e:null}function Wn(n){if(typeof n!="string")return null;let e=n.split("#",1)[0].split("?",1)[0].toLowerCase();return/\.(ts|tsx)$/.test(e)?"ts":/\.(js|jsx|mjs|cjs)$/.test(e)?"js":/\.(cc|cpp|cxx|c\+\+|hpp|hh|hxx)$/.test(e)?"cpp":/\.(c|h)$/.test(e)?"c":/\.cs$/.test(e)?"csharp":/\.java$/.test(e)?"java":/\.(clj|cljs|cljc|edn)$/.test(e)?"clojure":/\.dart$/.test(e)?"dart":null}function Bm(n){let e=$S(n?.lang??n?.language);if(e)return e;let t=Wn(n?.path)??Wn(n?.file)??Wn(n?.file_path)??Wn(n?.newFile)??Wn(n?.oldFile)??Wn(n?.bodyEndOf)??Wn(n?.bodyStartOf)??Wn(n?.before)??Wn(n?.after)??Wn(n?.start)??Wn(n?.end)??Wn(n?.location?.file);return t||null}function t1(n,e){let t=$S(n.lang)??Wn(n.path)??Wn(n.to)??Wn(n.of)??Wn(n.file)??Wn(n.newFile)??Bm(n.to)??Bm(n.scope)??Wn(n.scope?.file)??(Array.isArray(n.scope?.files)?Wn(n.scope.files[0]):null);if(t)return t;for(let r of[e.results,e.items,e.exports])if(Array.isArray(r))for(let s of r){let i=Bm(s);if(i)return i}return Bm(e)}function n1(n,e){let t=t1(n,e);return t?QB[t]??{...Fa,language:t,confidence:"heuristic"}:Fa}function r1(n,e){return e==="trace-high"?n:e==="trace-low"||e==="trace-sparse"||e==="modeled-only"?"low":n==="high"?"medium":n}function FS(n,e){let t=n.savedItems.map(s=>{let i=BC(s.estimatedLinesNotSent,e);return{...s,estimatedCharsNotSent:i,estimatedTokensNotSent:qm(i,e)}}),r=t.reduce((s,i)=>s+i.estimatedCharsNotSent,0);return{...n,confidence:r1(n.confidence,e.confidence),savedItems:t,language:e.language,calibrationConfidence:e.confidence,charsPerLine:e.charsPerLine,charsPerToken:e.charsPerToken,counterfactualTextToolChars:r,estimatedCharsNotSent:r,estimatedTokensNotSent:qm(r,e)}}function $C(n,e){return Math.max(1,Math.round(n.searchLines||e))}function En(n,e,t,r,s){let i=Wi(t),o=Wi(r);if(i<=0||o<=0)return null;let a=i*o,c=BC(a),l=qm(c);return{key:n,label:e,count:i,linesPerUnit:o,estimatedLinesNotSent:a,estimatedCharsNotSent:c,estimatedTokensNotSent:l,note:s}}function jC(){return{version:1,calls:0,successfulCalls:0,callsWithSavings:0,estimatedLinesNotSent:0,counterfactualTextToolChars:0,pandoActualSourceChars:0,estimatedCharsNotSent:0,estimatedTokensNotSent:0,byOperation:{},lastUpdatedAt:null}}function Cr(n,e,t,r,s,i){let o=i.filter(d=>d!==null),a=o.reduce((d,p)=>d+p.estimatedLinesNotSent,0),c=o.reduce((d,p)=>d+p.estimatedCharsNotSent,0),l=c,u=o.reduce((d,p)=>d+p.estimatedTokensNotSent,0);return{version:1,op:n,success:e,method:t,confidence:r,comparisonBaseline:XB,rationale:s,savedItems:o,estimatedLinesNotSent:a,language:null,calibrationConfidence:Fa.confidence,charsPerLine:Fa.charsPerLine,charsPerToken:Fa.charsPerToken,counterfactualTextToolChars:c,pandoActualSourceChars:0,estimatedCharsNotSent:l,estimatedTokensNotSent:u}}function DS(n,e){let t=qC(e);if(!n.success||n.counterfactualTextToolChars<=0)return{...n,pandoActualSourceChars:t};let r=md(n.counterfactualTextToolChars-t);return{...n,pandoActualSourceChars:t,estimatedCharsNotSent:r,estimatedTokensNotSent:qm(r,{language:n.language,charsPerLine:n.charsPerLine,charsPerToken:n.charsPerToken,searchLines:6,confidence:n.calibrationConfidence})}}function pd(n,e,t){return Cr(n,e,"none","low",t,[])}function s1(n){switch(n.key){case"candidate-node-metadata":return"declaration snippets";case"candidate-node-self":return"extra declaration context";case"candidate-node-body":return"residual declaration context";case"reference-sites":return"reference snippets";case"caller-sites":return"caller snippets";case"export-result-contexts":return"export snippets";case"import-file-summaries":case"import-module-summaries":return"import snippets";case"namespace-graph-nodes":return"namespace declaration snippets";case"namespace-graph-edges":return"namespace dependency snippets";case"namespace-plan-edits":return"planned rewrite snippets";case"namespace-plan-declaration-context":return"namespace declaration context";case"reference-edit-contexts":return"reference edit snippets";case"declaration-context":return"declaration context";case"delete-target-context":return"delete target snippets";case"delete-reference-contexts":return"reference deletion snippets";case"signature-declaration-context":return"signature declaration context";case"signature-callsite-contexts":return"call-site rewrite snippets";case"fmr-match-contexts":return"matched code snippets";case"namespace-rewrite-files":return"namespace rewrite snippets";case"namespace-declaration-context":return"namespace declaration context";case"text-file-edit-context":return"text file edit context";default:return n.label.replace(/\bthat did not need to be sent\b/gi,"").replace(/\bdid not need raw import snippets\b/gi,"").replace(/\s+/g," ").trim().replace(/[.;:]$/,"")}}function Hm(n){if(!n||n.estimatedTokensNotSent<=0&&n.pandoActualSourceChars<=0)return;let e=n.savedItems.filter(i=>i.estimatedTokensNotSent>0).map(i=>({label:s1(i),count:i.count,estimatedLines:i.estimatedLinesNotSent,estimatedChars:i.estimatedCharsNotSent,estimatedTokens:i.estimatedTokensNotSent})),t=e.reduce((i,o)=>i+o.count,0),r=t===1?"snippet":"snippets",s=`; Pando returned ${n.pandoActualSourceChars} chars of source`;return{version:1,op:n.op,summary:`Would have sent about ${n.estimatedCharsNotSent} chars / ${n.estimatedTokensNotSent} tokens across ${t} ${r}${s}.`,confidence:n.confidence,language:n.language,calibrationConfidence:n.calibrationConfidence,charsPerLine:n.charsPerLine,charsPerToken:n.charsPerToken,estimatedLines:n.estimatedLinesNotSent,counterfactualTextToolChars:n.counterfactualTextToolChars,pandoActualSourceChars:n.pandoActualSourceChars,estimatedChars:n.estimatedCharsNotSent,estimatedTokens:n.estimatedTokensNotSent,wouldSend:e}}function HC(n){return Array.isArray(n.results)?n.results:Array.isArray(n.items)?n.items:Array.isArray(n.exports)?n.exports:[]}function jS(n){let e=n.details;return typeof e?.changedFileCount=="number"?Wi(e.changedFileCount):Array.isArray(e?.allChangedFiles)?e.allChangedFiles.length:Array.isArray(e?.changedFiles)?e.changedFiles.length:Wi(n.changes?.count??0)}function Da(n){return Array.isArray(n)?n.length:0}function i1(n,e){let t=HC(e),r=0,s=0,i=0;for(let o of t){if(o?.body?.content){i+=1;continue}if(o?.self?.code?.content){s+=1;continue}r+=1}return Cr(n,e.success,"mixed","medium","Structured node discovery avoids sending most candidate snippets; when self/body is requested, the saved amount is reduced rather than treated as zero.",[En("candidate-node-metadata","Candidate node snippets that did not need to be sent",r,4,"Metadata-only results usually avoid sending the declaration line plus minimal surrounding context for each candidate."),En("candidate-node-self","Additional node context avoided even when self was requested",s,2,"Including the node itself still avoids some surrounding context a smart text workflow would usually inspect."),En("candidate-node-body","Residual declaration context avoided when body content was requested",i,1,"Requesting body content removes most of the privacy advantage, so only a minimal declaration-context saving is counted.")])}function LC(n,e,t,r){let s=HC(e).length;return Cr(n,e.success,"exact-counts","high","Structured locations avoid sending per-location code snippets and nearby context.",[En(t,t==="reference-sites"?"Reference-site snippets that did not need to be sent":"Caller-site snippets that did not need to be sent",s,r,"The comparison assumes a smart text workflow would only send a minimal location snippet for each result.")])}function o1(n,e){let t=Da(e.exports);return Cr(n,e.success,"exact-counts","medium","Structured export lookup answers declaration-discovery questions without sending export snippets or nearby code.",[En("export-result-contexts","Export declaration snippets that did not need to be sent",t,2,"Only the returned export entries are counted, which keeps paginated list-exports calls conservative.")])}function a1(n,e){let t=e.imports,r=Da(t?.files),s=Da(t?.external),i=Da(t?.internal);return Cr(n,e.success,"exact-counts","medium","Import analysis returns grouped dependency structure without sending raw import blocks; only visible grouped entries are counted.",[En("import-file-summaries","Per-file import summaries that did not need raw import snippets",r,2,"When grouped by file, the estimate counts one small import-summary snippet per returned file entry."),En("import-module-summaries","Grouped import summaries that did not need raw import snippets",s+i,2,"When grouped by module, the estimate counts only the returned grouped entries rather than every underlying import usage.")])}function zC(n,e,t){let r=Da(e.namespaces),s=Da(e.edges);return Cr(n,e.success,"exact-counts","medium",t,[En("namespace-graph-nodes","Namespace declaration snippets that did not need to be sent",r,1,"Each returned namespace usually corresponds to at least one small ns-form context in a text-based workflow."),En("namespace-graph-edges","Namespace dependency snippets that did not need to be sent",s,2,"Each returned edge usually corresponds to one focused require/refer snippet in a text-based workflow.")])}function c1(n,e){let t=Da(e.namespaceEdits);return Cr(n,e.success,"exact-counts","medium","Namespace planning computes the affected declaration and dependent files without sending each candidate require/ns snippet to the provider.",[En("namespace-plan-edits","Planned namespace rewrite snippets that did not need to be sent",t,4,"The estimate counts one small rewrite-planning snippet per planned file edit."),En("namespace-plan-declaration-context","Namespace declaration context that only needed to be localized once",e.success?1:0,6,"The source namespace still needs one focused declaration context to build the plan.")])}function l1(n,e){let t=Wi(e.details?.referencesRenamed);return Cr(n,e.success,"exact-counts","high","Rename uses exact reference counts already produced by the executor, then applies a conservative per-reference context window.",[En("reference-edit-contexts","Reference edit contexts that did not need to be sent",t,3,"A smart non-pando workflow would still need to send each reference with a small amount of surrounding code before editing or approving it."),En("declaration-context","Declaration context that only needed to be localized once",e.success?1:0,6,"The declaration still has to be identified, but pando does not require the model to receive surrounding code for every downstream edit.")])}function u1(n,e){let t=Wi(e.details?.deletedCount),r=Array.isArray(e.details?.receipt?.appliedReferences)?e.details.receipt.appliedReferences.length:0;return Cr(n,e.success,r>0?"mixed":"heuristic",r>0?"high":"medium","Applied reference counts are exact when the executor exposes them; otherwise only the target-level deletion context is counted.",[En("delete-target-context","Delete target contexts that did not need to be sent",t,6,"Each delete target typically needs declaration-level context in a text-based workflow."),En("delete-reference-contexts","Reference deletion contexts that did not need to be sent",r,4,"When reference edits are applied automatically, pando avoids sending each reference and a small surrounding window.")])}function d1(n,e){let t=Wi(e.details?.callSiteStats?.auto_rewritten??e.changes?.callSitesAutoRewritten??0);return Cr(n,e.success,"exact-counts","high","The executor already reports how many call sites were rewritten automatically, so the privacy estimate can stay count-exact while using conservative context windows.",[En("signature-declaration-context","Function signature context that did not need to be sent repeatedly",e.success?1:0,6,"Only one declaration/signature context is counted for the target function."),En("signature-callsite-contexts","Auto-rewritten call-site contexts that did not need to be sent",t,5,"The estimate only counts call sites pando rewrote automatically; manual-review sites are not claimed as privacy savings.")])}function p1(n,e,t){let r=Wi(t.details?.receipt?.processedCount??t.details?.processedCount??t.details?.succeededCount??0),i=(Array.isArray(e.transforms)?e.transforms.length:0)>0?"filter-map-reduce localizes and rewrites matches without shipping matched code to the provider; the count is based on processed matches, not full-file size.":"filter-map-reduce localizes matches without shipping matched code to the provider.";return Cr(n,t.success,"exact-counts","high",i,[En("fmr-match-contexts","Matched-node contexts that did not need to be sent",r,6,"The baseline assumes a smart text workflow would still need to send a small snippet for every matched location before applying or validating a transform.")])}function OS(n,e,t,r,s){let i=jS(e);return Cr(n,e.success,"heuristic","medium",s,[En(`${n}-target-context`,r,i>0?1:0,t,"The estimate assumes one minimal target/anchor snippet would otherwise need to be sent for a single focused edit.")])}function f1(n,e){let t=jS(e),r=Wi(e.details?.appliedEdits??e.details?.receipt?.appliedEdits??0);return Cr(n,e.success,"heuristic","medium","Text-only edits to intentionally unindexed config/hook files avoid sending the target file or surrounding edit context to the provider; this estimate counts only a small local context window per changed file.",[En("text-file-edit-context","Text-file edit context that did not need to be sent",t>0?Math.max(1,r):0,8,"The baseline assumes a smart text workflow would inspect at least a focused snippet for each applied text edit, not necessarily the whole config file.")])}function m1(n,e){let t=jS(e);return Cr(n,e.success,"mixed","medium","Namespace rewrites typically require touching several import/require sites; the estimate stays conservative and file-based.",[En("namespace-rewrite-files","Namespace/import rewrite snippets that did not need to be sent",t,4,"A smart text workflow would usually send at least one small require/import snippet per changed file."),En("namespace-declaration-context","Namespace declaration context that only needed to be localized once",e.success?1:0,6,"The namespace declaration itself still needs one focused context window.")])}function WC(n,e,t){let r=!!t?.success,s=n1(e,t);if(!n)return DS(FS(pd("unknown",r,"Operation name unavailable; no privacy savings claimed."),s),t);if(!r)return DS(FS(pd(n,!1,"Operation did not succeed, so no privacy savings are claimed."),s),t);let i=(()=>{switch(n){case"find-nodes":return i1(n,t);case"find-references":return LC(n,t,"reference-sites",$C(s,6));case"find-callers":return LC(n,t,"caller-sites",$C(s,6));case"list-exports":return o1(n,t);case"analyze-imports":return a1(n,t);case"clojure-namespace-graph":return zC(n,t,"Namespace graph queries return cross-file dependency structure without sending the underlying ns/require snippets.");case"clojure-namespace-dependencies":case"clojure-namespace-dependents":return zC(n,t,"Namespace traversal returns dependency edges directly, avoiding per-edge code snippets in the provider request.");case"plan-clojure-namespace-move":case"plan-clojure-namespace-rename":return c1(n,t);case"rename":return l1(n,t);case"delete":return u1(n,t);case"change-signature":return d1(n,t);case"filter-map-reduce":return p1(n,e,t);case"replace":return OS(n,t,10,"Target replacement context that did not need to be sent","A focused replace still needs target localization in a text-based workflow; pando avoids sending that local code window.");case"replace-body":return OS(n,t,12,"Body replacement context that did not need to be sent","Body replacement typically requires a slightly larger context window than full-node replacement.");case"edit-file-text":return f1(n,t);case"insert":case"add-code":return e?.createFileIfMissing?pd(n,!0,"Insert created a new file, so no existing code context savings are claimed."):OS(n,t,8,"Insertion anchor context that did not need to be sent","A targeted insert usually needs local anchor context in a text-based workflow; pando keeps that out of the provider request.");case"rename-clojure-namespace":case"move-clojure-namespace":return m1(n,t);default:return pd(n,!0,"Administrative or metadata-only operation; privacy savings are too small or too uncertain to claim conservatively.")}})();return DS(FS(i,s),t)}function LS(n,e){if(e.length===0)return pd(n,!0,"No underlying operation estimates were available.");let t=e.every(u=>u.success),r=e.every(u=>u.method==="exact-counts")?"exact-counts":e.some(u=>u.method==="none")?"mixed":e.every(u=>u.method==="heuristic")?"heuristic":"mixed",s=e.every(u=>u.confidence==="high")?"high":e.some(u=>u.confidence==="low")?"low":"medium",i=new Map;for(let u of e)for(let d of u.savedItems){let p=i.get(d.key);if(!p){i.set(d.key,{...d});continue}p.count+=d.count,p.estimatedLinesNotSent+=d.estimatedLinesNotSent,p.estimatedCharsNotSent+=d.estimatedCharsNotSent,p.estimatedTokensNotSent+=d.estimatedTokensNotSent}let o=Cr(n,t,r,s,"Combined from per-root operation estimates in the current dispatcher session.",Array.from(i.values())),a=e.reduce((u,d)=>u+d.pandoActualSourceChars,0),c=md(o.counterfactualTextToolChars-a),l=e.reduce((u,d)=>u+d.estimatedTokensNotSent,0);return{...o,language:e.every(u=>u.language===e[0]?.language)?e[0]?.language??null:null,calibrationConfidence:e.every(u=>u.calibrationConfidence==="trace-high")?"trace-high":e.some(u=>u.calibrationConfidence==="modeled-only")?"modeled-only":e.some(u=>u.calibrationConfidence==="trace-low")?"trace-low":e.some(u=>u.calibrationConfidence==="trace-sparse")?"trace-sparse":"heuristic",pandoActualSourceChars:a,estimatedCharsNotSent:c,estimatedTokensNotSent:l}}var fd=class{constructor(){this.summary=jC()}record(e,t,r){let s=WC(e,t,r),i=this.summary.byOperation[e]??{calls:0,successfulCalls:0,callsWithSavings:0,estimatedLinesNotSent:0,counterfactualTextToolChars:0,pandoActualSourceChars:0,estimatedCharsNotSent:0,estimatedTokensNotSent:0};return i.calls+=1,s.success&&(i.successfulCalls+=1),s.estimatedTokensNotSent>0&&(i.callsWithSavings+=1),i.estimatedLinesNotSent+=s.estimatedLinesNotSent,i.counterfactualTextToolChars+=s.counterfactualTextToolChars,i.pandoActualSourceChars+=s.pandoActualSourceChars,i.estimatedCharsNotSent+=s.estimatedCharsNotSent,i.estimatedTokensNotSent+=s.estimatedTokensNotSent,this.summary.byOperation[e]=i,this.summary.calls+=1,s.success&&(this.summary.successfulCalls+=1),s.estimatedTokensNotSent>0&&(this.summary.callsWithSavings+=1),this.summary.estimatedLinesNotSent+=s.estimatedLinesNotSent,this.summary.counterfactualTextToolChars+=s.counterfactualTextToolChars,this.summary.pandoActualSourceChars+=s.pandoActualSourceChars,this.summary.estimatedCharsNotSent+=s.estimatedCharsNotSent,this.summary.estimatedTokensNotSent+=s.estimatedTokensNotSent,this.summary.lastUpdatedAt=new Date().toISOString(),{operation:s,session:this.getSessionSummary()}}getSessionSummary(){let e={};for(let[t,r]of Object.entries(this.summary.byOperation))e[t]={...r};return{...this.summary,byOperation:e}}reset(){return this.summary=jC(),this.getSessionSummary()}};It();function Is(n){let e=n.details;return e?typeof e.changedFileCount=="number"?e.changedFileCount:Array.isArray(e.allChangedFiles)?e.allChangedFiles.length:Array.isArray(e.changedFiles)?e.changedFiles.length:n.changes?.count??0:n.changes?.count??0}function Wm(n){return n.page?.totalCount??n.totalCount??(Array.isArray(n.results)?n.results.length:0)}var h1={rename:n=>({primary:Is(n),secondary:n.details?.referencesRenamed??0}),delete:n=>({primary:Is(n),secondary:n.details?.deletedCount??0}),insert:n=>({primary:Is(n),secondary:n.created?1:0}),replace:n=>({primary:Is(n),secondary:0}),"replace-body":n=>({primary:Is(n),secondary:0}),"change-signature":n=>({primary:Is(n),secondary:n.changes?.callSitesAutoRewritten??0}),"filter-map-reduce":n=>({primary:Is(n),secondary:0}),"find-references":n=>({primary:Wm(n),secondary:0}),"find-callers":n=>({primary:Wm(n),secondary:0}),"find-nodes":n=>({primary:Wm(n),secondary:0}),"workspace-overview":()=>({primary:0,secondary:0}),"list-exports":n=>({primary:n.page?.totalCount??(Array.isArray(n.exports)?n.exports.length:0),secondary:0}),"analyze-imports":n=>{let e=n.page;return{primary:e?.files?.totalCount??(e?.external?.totalCount??0)+(e?.internal?.totalCount??0),secondary:0}},"clojure-namespace-graph":n=>({primary:n.details?.namespaceCount??0,secondary:n.details?.edgeCount??0}),"clojure-namespace-dependencies":n=>({primary:n.namespacesPage?.totalCount??(Array.isArray(n.namespaces)?n.namespaces.length:0),secondary:n.edgesPage?.totalCount??(Array.isArray(n.edges)?n.edges.length:0)}),"clojure-namespace-dependents":n=>({primary:n.namespacesPage?.totalCount??(Array.isArray(n.namespaces)?n.namespaces.length:0),secondary:n.edgesPage?.totalCount??(Array.isArray(n.edges)?n.edges.length:0)}),"move-clojure-namespace":n=>({primary:Is(n),secondary:0}),"rename-clojure-namespace":n=>({primary:Is(n),secondary:0}),"snapshot-worktree":()=>({primary:0,secondary:0}),"restore-snapshot":n=>({primary:Is(n),secondary:0}),"restore-files":n=>({primary:Is(n),secondary:0})},g1=n=>({primary:Is(n),secondary:Wm(n)});function y1(n,e){let t=h1[n]??g1;try{return t(e)}catch{return{primary:0,secondary:0}}}var b1=0;function zS(){return`${Date.now()}-${++b1}`}function UC(n,e,t,r){let s=y1(n,e);return{schema_version:1,call_id:r,op:n,success:e.success,duration_ms:Math.max(0,Math.round(t)),error_code:e.error_code??void 0,primary_count:s.primary,secondary_count:s.secondary,timestamp:new Date().toISOString()}}var KC="_privacyOperation";function GC(n){let e=n.trim();if(!e)return null;let t=e;return(e.startsWith("pando_")||e.startsWith("pando-"))&&(t=e.slice(6)),t?t.replace(/_/g,"-"):null}function JC(n,e){let t={...e};return delete t.root,t}var Wc=class{constructor(e){this.config=e;this.privacyCounter=new fd}async dispatch(e,t,r){let s=GC(e);if(!s)return{success:!1,error:`Unknown tool: ${e}`};if(s==="set-project-root"){let p=typeof t.root=="string"?t.root.trim():"";if(!p)return{success:!1,error:"Missing required parameter: root"};if(S1(p))return{success:!1,error:"Filesystem root '/' cannot be used as a project root."};let f=Date.now();ee("PandoToolDispatcher","set-project-root begin",{toolName:e,requestedRoot:p});let m;try{m=await this.config.onProjectRootAdded?.(p)}catch(h){let g=h instanceof Error?h.message:String(h);return ee("PandoToolDispatcher","set-project-root rejected",{toolName:e,requestedRoot:p,error:g,elapsedMs:Date.now()-f}),{success:!1,error:g}}return m?(ee("PandoToolDispatcher","set-project-root complete",{toolName:e,requestedRoot:p,resolvedRoot:m,elapsedMs:Date.now()-f}),{success:!0,data:this.attachPrivacyToData("set-project-root",t,{projectRoot:m},{success:!0})}):(ee("PandoToolDispatcher","set-project-root failed",{toolName:e,requestedRoot:p,elapsedMs:Date.now()-f}),{success:!1,error:`Unable to add project root: ${p}`})}let i=this.resolveToolRoots(t);if(!i.roots.length&&i.error)return{success:!1,error:i.error,data:i.availableRoots?{availableRoots:i.availableRoots}:void 0};let o=i.roots;if(s==="get-project-root")return o.length<=1?{success:!0,data:this.attachPrivacyToData("get-project-root",t,{projectRoot:o[0]??null},{success:!0})}:{success:!0,data:this.attachPrivacyToData("get-project-root",t,{projectRoots:o},{success:!0})};if(!o.length)return{success:!1,error:"No workspace root available."};if(s==="read-this-first")return{success:!0,data:this.attachPrivacyToData("read-this-first",t,{help:this.config.loadReadThisFirstMessage()},{success:!0})};let a=JC(s,t),c={op:s,...a},l=zS(),u=r?.telemetry;if(this.isReadOnlyTool(e,s))return this.dispatchReadOnly(o,c,r?.signal,l,u);if(o.length>1){let p=[];for(let m of o)p.push(await this.executeOne(m,c,r?.signal,l,u));await this.handlePostDispatchEffects(s,p);let f=this.buildAggregatePrivacy(s,p);return{success:!0,data:{perRoot:p,...f?{privacy:f}:{}}}}let d=await this.executeOne(o[0],c,r?.signal,l,u);if(!d.success){let p=d.error??"Operation failed",f=Array.isArray(d.result?.hints)?d.result.hints:void 0;return{success:!1,error:p,...f?{hints:f}:{},data:d.result??{success:!1,error:p}}}return await this.handlePostDispatchEffects(s,[d]),{success:!0,data:d.result}}getPrivacySummary(){return this.privacyCounter.getSessionSummary()}resetPrivacySummary(){return this.privacyCounter.reset()}resolveToolRoots(e){if(this.config.resolveRoots)return this.config.resolveRoots(e);let t=this.config.roots(),r=typeof e.root=="string"?e.root.trim():"";if(!r)return{roots:t};let s=en(hd.default.isAbsolute(r)?r:hd.default.resolve(t[0]??process.cwd(),r)),i=t.map(o=>en(o));return i.includes(s)?{roots:[s]}:{roots:[],error:`Requested root is not registered: ${r}`,availableRoots:i}}async dispatchReadOnly(e,t,r,s,i){if(e.length===1){let d=await this.executeOne(e[0],t,r,s,i);if(!d.success){let p=d.error??"Operation failed",f=Array.isArray(d.result?.hints)?d.result.hints:void 0;return{success:!1,error:p,...f?{hints:f}:{},data:d.result??{success:!1,error:p}}}return{success:!0,data:d.result}}let o=[],a=[],c=0,l=!1;for(let d of e){let p=await this.executeOne(d,t,r,s,i);if(o.push(p),!p.success||!p.result)continue;let f=Array.isArray(p.result.items)?p.result.items:Array.isArray(p.result.results)?p.result.results:null;if(!f)continue;for(let g of f)a.push({...g,root:d});let m=p.result.page,h=typeof m?.totalCount=="number"?m.totalCount:typeof p.result.totalCount=="number"?p.result.totalCount:f.length;c+=h,l=l||!!m?.hasMore||!!p.result.hasMore}let u=this.buildAggregatePrivacy(String(t.op||"unknown"),o);return{success:!0,data:{summary:_1(o,a.length?{shownCount:a.length,totalCount:c,hasMore:l}:void 0),results:a.length?a:void 0,totalCount:a.length?c:void 0,hasMore:a.length?l:void 0,perRoot:o,...u?{privacy:u}:{}}}}async executeOne(e,t,r,s,i){let o=typeof t.op=="string"?t.op:"unknown",a=Date.now();try{let l=await wn.getEngine(e).execute(t,{signal:r}),u=this.attachPrivacyToResult(o,t,l);if(await this.emitTelemetry(o,l,Date.now()-a,e,s,i),!l.success){let d=ZC(l.error||"Operation failed");return{root:e,success:!1,error:d,result:{...u,error:d}}}return{root:e,success:!0,result:u}}catch(c){let l={success:!1,error:c instanceof Error?c.message:String(c)},u=this.attachPrivacyToResult(o,t,l);await this.emitTelemetry(o,l,Date.now()-a,e,s,i);let d=ZC(c instanceof Error?c.message:String(c));return{root:e,success:!1,error:d,result:{...u,error:d}}}}async emitTelemetry(e,t,r,s,i,o){try{let a=this.config.onTelemetry?.(UC(e,t,r,i??zS()),s,o);if(!a)return;let c=Promise.resolve(a);if(!this.config.awaitTelemetry){c.catch(()=>{});return}await x1(c,this.config.telemetryTimeoutMs??1e3)}catch{}}async handlePostDispatchEffects(e,t){if(e==="set-enabled-languages")for(let r of t)r.success&&r.result?.details?.languageSupportChanged===!0&&await this.config.onLanguageSupportChanged?.(r.root)}isReadOnlyTool(e,t){let r=t.replace(/-/g,"_");return this.config.readOnlyTools.has(e)||this.config.readOnlyTools.has(t)||this.config.readOnlyTools.has(r)||this.config.readOnlyTools.has(`pando_${r}`)||this.config.readOnlyTools.has(`pando-${t}`)}attachPrivacyToResult(e,t,r){let s=this.privacyCounter.record(e,t,r),i=Hm(s.operation),o={...r,...i?{privacy:i}:{}};return Object.defineProperty(o,KC,{value:s.operation,enumerable:!1,configurable:!0,writable:!1}),o}attachPrivacyToData(e,t,r,s){let i=Hm(this.privacyCounter.record(e,t,s).operation);return{...r,...i?{privacy:i}:{}}}buildAggregatePrivacy(e,t){let r=t.map(s=>s.result?.[KC]).filter(s=>!!s);return Hm(LS(e,r))}};function S1(n){let e=hd.default.resolve(n);return hd.default.parse(e).root===e}function ZC(n){return n.length<=1e3?n:`${n.slice(0,1e3)}\u2026 [truncated]`}function x1(n,e){let t=Math.max(0,Math.trunc(e));return t===0?n:Promise.race([n,new Promise(r=>{setTimeout(r,t)})])}function _1(n,e){let t=n.length,r=n.filter(o=>o.success).length,s=t-r,i=n.map(o=>o.error??(typeof o.result?.error=="string"?o.result.error:void 0)).find(o=>typeof o=="string"&&o.trim().length>0);return{rootsTotal:t,rootsSucceeded:r,rootsFailed:s,shownCount:e?.shownCount,totalCount:e?.totalCount,hasMore:e?.hasMore,error:i}}var VC=B(require("fs")),w1=["set-project-root","set-enabled-languages","workspace-overview","get-db-schema","query-db","find-nodes","find-references","rename","replace","edit-file-text","insert","delete","filter-map-reduce"];function Uc(n,e){let t=VC.default.readFileSync(n,"utf8"),r=JSON.parse(t),s=Array.isArray(r.tools)?r.tools:[],i=new Map(w1.map((o,a)=>[o,a]));return s.filter(o=>typeof o?.name=="string").filter(o=>o.category!=="orchestrator").filter(o=>!(e?.excludeNames?.has(o.name)??!1)).sort((o,a)=>{let c=i.get(o.name),l=i.get(a.name);return c!=null&&l!=null?c-l:c!=null?-1:l!=null?1:o.name.localeCompare(a.name)})}function BS(n){let e=n.parameters&&n.parameters.type==="object"?{...n.parameters,type:"object",properties:v1(n.parameters.properties)}:{type:"object",properties:{},required:[],additionalProperties:!1};return{name:n.name,description:n.description,inputSchema:e}}function Um(n,e){return n.find(r=>r.name===e)?.description??""}function v1(n){if(!n)return;let e={};for(let[t,r]of Object.entries(n))r&&typeof r=="object"&&(e[t]=r);return e}var vt;(function(n){n.assertEqual=s=>{};function e(s){}n.assertIs=e;function t(s){throw new Error}n.assertNever=t,n.arrayToEnum=s=>{let i={};for(let o of s)i[o]=o;return i},n.getValidEnumValues=s=>{let i=n.objectKeys(s).filter(a=>typeof s[s[a]]!="number"),o={};for(let a of i)o[a]=s[a];return n.objectValues(o)},n.objectValues=s=>n.objectKeys(s).map(function(i){return s[i]}),n.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let i=[];for(let o in s)Object.prototype.hasOwnProperty.call(s,o)&&i.push(o);return i},n.find=(s,i)=>{for(let o of s)if(i(o))return o},n.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function r(s,i=" | "){return s.map(o=>typeof o=="string"?`'${o}'`:o).join(i)}n.joinValues=r,n.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(vt||(vt={}));var XC;(function(n){n.mergeShapes=(e,t)=>({...e,...t})})(XC||(XC={}));var Te=vt.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Ui=n=>{switch(typeof n){case"undefined":return Te.undefined;case"string":return Te.string;case"number":return Number.isNaN(n)?Te.nan:Te.number;case"boolean":return Te.boolean;case"function":return Te.function;case"bigint":return Te.bigint;case"symbol":return Te.symbol;case"object":return Array.isArray(n)?Te.array:n===null?Te.null:n.then&&typeof n.then=="function"&&n.catch&&typeof n.catch=="function"?Te.promise:typeof Map<"u"&&n instanceof Map?Te.map:typeof Set<"u"&&n instanceof Set?Te.set:typeof Date<"u"&&n instanceof Date?Te.date:Te.object;default:return Te.unknown}};var ce=vt.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"]);var cs=class n extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){let t=e||function(i){return i.message},r={_errors:[]},s=i=>{for(let o of i.issues)if(o.code==="invalid_union")o.unionErrors.map(s);else if(o.code==="invalid_return_type")s(o.returnTypeError);else if(o.code==="invalid_arguments")s(o.argumentsError);else if(o.path.length===0)r._errors.push(t(o));else{let a=r,c=0;for(;c<o.path.length;){let l=o.path[c];c===o.path.length-1?(a[l]=a[l]||{_errors:[]},a[l]._errors.push(t(o))):a[l]=a[l]||{_errors:[]},a=a[l],c++}}};return s(this),r}static assert(e){if(!(e instanceof n))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,vt.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){let t={},r=[];for(let s of this.issues)if(s.path.length>0){let i=s.path[0];t[i]=t[i]||[],t[i].push(e(s))}else r.push(e(s));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}};cs.create=n=>new cs(n);var R1=(n,e)=>{let t;switch(n.code){case ce.invalid_type:n.received===Te.undefined?t="Required":t=`Expected ${n.expected}, received ${n.received}`;break;case ce.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(n.expected,vt.jsonStringifyReplacer)}`;break;case ce.unrecognized_keys:t=`Unrecognized key(s) in object: ${vt.joinValues(n.keys,", ")}`;break;case ce.invalid_union:t="Invalid input";break;case ce.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${vt.joinValues(n.options)}`;break;case ce.invalid_enum_value:t=`Invalid enum value. Expected ${vt.joinValues(n.options)}, received '${n.received}'`;break;case ce.invalid_arguments:t="Invalid function arguments";break;case ce.invalid_return_type:t="Invalid function return type";break;case ce.invalid_date:t="Invalid date";break;case ce.invalid_string:typeof n.validation=="object"?"includes"in n.validation?(t=`Invalid input: must include "${n.validation.includes}"`,typeof n.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${n.validation.position}`)):"startsWith"in n.validation?t=`Invalid input: must start with "${n.validation.startsWith}"`:"endsWith"in n.validation?t=`Invalid input: must end with "${n.validation.endsWith}"`:vt.assertNever(n.validation):n.validation!=="regex"?t=`Invalid ${n.validation}`:t="Invalid";break;case ce.too_small:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at least":"more than"} ${n.minimum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at least":"over"} ${n.minimum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="bigint"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(n.minimum))}`:t="Invalid input";break;case ce.too_big:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at most":"less than"} ${n.maximum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at most":"under"} ${n.maximum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="bigint"?t=`BigInt must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly":n.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(n.maximum))}`:t="Invalid input";break;case ce.custom:t="Invalid input";break;case ce.invalid_intersection_types:t="Intersection results could not be merged";break;case ce.not_multiple_of:t=`Number must be a multiple of ${n.multipleOf}`;break;case ce.not_finite:t="Number must be finite";break;default:t=e.defaultError,vt.assertNever(n)}return{message:t}},_o=R1;var E1=_o;function gd(){return E1}var Km=n=>{let{data:e,path:t,errorMaps:r,issueData:s}=n,i=[...t,...s.path||[]],o={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let a="",c=r.filter(l=>!!l).slice().reverse();for(let l of c)a=l(o,{data:e,defaultError:a}).message;return{...s,path:i,message:a}};function Re(n,e){let t=gd(),r=Km({issueData:e,data:n.data,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,t,t===_o?void 0:_o].filter(s=>!!s)});n.common.issues.push(r)}var hr=class n{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){let r=[];for(let s of t){if(s.status==="aborted")return tt;s.status==="dirty"&&e.dirty(),r.push(s.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){let r=[];for(let s of t){let i=await s.key,o=await s.value;r.push({key:i,value:o})}return n.mergeObjectSync(e,r)}static mergeObjectSync(e,t){let r={};for(let s of t){let{key:i,value:o}=s;if(i.status==="aborted"||o.status==="aborted")return tt;i.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof o.value<"u"||s.alwaysSet)&&(r[i.value]=o.value)}return{status:e.value,value:r}}},tt=Object.freeze({status:"aborted"}),Kc=n=>({status:"dirty",value:n}),Ir=n=>({status:"valid",value:n}),qS=n=>n.status==="aborted",HS=n=>n.status==="dirty",Oa=n=>n.status==="valid",yd=n=>typeof Promise<"u"&&n instanceof Promise;var Oe;(function(n){n.errToObj=e=>typeof e=="string"?{message:e}:e||{},n.toString=e=>typeof e=="string"?e:e?.message})(Oe||(Oe={}));var As=class{constructor(e,t,r,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=s}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}},QC=(n,e)=>{if(Oa(e))return{success:!0,data:e.value};if(!n.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new cs(n.common.issues);return this._error=t,this._error}}};function dt(n){if(!n)return{};let{errorMap:e,invalid_type_error:t,required_error:r,description:s}=n;if(e&&(t||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(o,a)=>{let{message:c}=n;return o.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??r??a.defaultError}:o.code!=="invalid_type"?{message:a.defaultError}:{message:c??t??a.defaultError}},description:s}}var bt=class{get description(){return this._def.description}_getType(e){return Ui(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Ui(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new hr,ctx:{common:e.parent.common,data:e.data,parsedType:Ui(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(yd(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){let r={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ui(e)},s=this._parseSync({data:e,path:r.path,parent:r});return QC(r,s)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ui(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:t});return Oa(r)?{value:r.value}:{issues:t.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(r=>Oa(r)?{value:r.value}:{issues:t.common.issues})}async parseAsync(e,t){let r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){let r={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ui(e)},s=this._parse({data:e,path:r.path,parent:r}),i=await(yd(s)?s:Promise.resolve(s));return QC(r,i)}refine(e,t){let r=s=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(s):t;return this._refinement((s,i)=>{let o=e(s),a=()=>i.addIssue({code:ce.custom,...r(s)});return typeof Promise<"u"&&o instanceof Promise?o.then(c=>c?!0:(a(),!1)):o?!0:(a(),!1)})}refinement(e,t){return this._refinement((r,s)=>e(r)?!0:(s.addIssue(typeof t=="function"?t(r,s):t),!1))}_refinement(e){return new ei({schema:this,typeName:ue.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,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:t=>this["~validate"](t)}}optional(){return ls.create(this,this._def)}nullable(){return Gi.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return vo.create(this)}promise(){return $a.create(this,this._def)}or(e){return Xc.create([this,e],this._def)}and(e){return Qc.create(this,e,this._def)}transform(e){return new ei({...dt(this._def),schema:this,typeName:ue.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new rl({...dt(this._def),innerType:this,defaultValue:t,typeName:ue.ZodDefault})}brand(){return new Zm({typeName:ue.ZodBranded,type:this,...dt(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new sl({...dt(this._def),innerType:this,catchValue:t,typeName:ue.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return Gm.create(this,e)}readonly(){return il.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},k1=/^c[^\s-]{8,}$/i,T1=/^[0-9a-z]+$/,P1=/^[0-9A-HJKMNP-TV-Z]{26}$/i,C1=/^[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,I1=/^[a-z0-9_-]{21}$/i,A1=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,N1=/^[-+]?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)?)??$/,M1=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,F1="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",WS,D1=/^(?:(?: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])$/,O1=/^(?:(?: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])$/,$1=/^(([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]))$/,j1=/^(([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])$/,L1=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,z1=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,YC="((\\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])))",B1=new RegExp(`^${YC}$`);function eI(n){let e="[0-5]\\d";n.precision?e=`${e}\\.\\d{${n.precision}}`:n.precision==null&&(e=`${e}(\\.\\d+)?`);let t=n.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function q1(n){return new RegExp(`^${eI(n)}$`)}function H1(n){let e=`${YC}T${eI(n)}`,t=[];return t.push(n.local?"Z?":"Z"),n.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function W1(n,e){return!!((e==="v4"||!e)&&D1.test(n)||(e==="v6"||!e)&&$1.test(n))}function U1(n,e){if(!A1.test(n))return!1;try{let[t]=n.split(".");if(!t)return!1;let r=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),s=JSON.parse(atob(r));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function K1(n,e){return!!((e==="v4"||!e)&&O1.test(n)||(e==="v6"||!e)&&j1.test(n))}var Gc=class n extends bt{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==Te.string){let i=this._getOrReturnCtx(e);return Re(i,{code:ce.invalid_type,expected:Te.string,received:i.parsedType}),tt}let r=new hr,s;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),Re(s,{code:ce.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="max")e.data.length>i.value&&(s=this._getOrReturnCtx(e,s),Re(s,{code:ce.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){let o=e.data.length>i.value,a=e.data.length<i.value;(o||a)&&(s=this._getOrReturnCtx(e,s),o?Re(s,{code:ce.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):a&&Re(s,{code:ce.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")M1.test(e.data)||(s=this._getOrReturnCtx(e,s),Re(s,{validation:"email",code:ce.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")WS||(WS=new RegExp(F1,"u")),WS.test(e.data)||(s=this._getOrReturnCtx(e,s),Re(s,{validation:"emoji",code:ce.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")C1.test(e.data)||(s=this._getOrReturnCtx(e,s),Re(s,{validation:"uuid",code:ce.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")I1.test(e.data)||(s=this._getOrReturnCtx(e,s),Re(s,{validation:"nanoid",code:ce.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")k1.test(e.data)||(s=this._getOrReturnCtx(e,s),Re(s,{validation:"cuid",code:ce.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")T1.test(e.data)||(s=this._getOrReturnCtx(e,s),Re(s,{validation:"cuid2",code:ce.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")P1.test(e.data)||(s=this._getOrReturnCtx(e,s),Re(s,{validation:"ulid",code:ce.invalid_string,message:i.message}),r.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),Re(s,{validation:"url",code:ce.invalid_string,message:i.message}),r.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),Re(s,{validation:"regex",code:ce.invalid_string,message:i.message}),r.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(s=this._getOrReturnCtx(e,s),Re(s,{code:ce.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),r.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(s=this._getOrReturnCtx(e,s),Re(s,{code:ce.invalid_string,validation:{startsWith:i.value},message:i.message}),r.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),Re(s,{code:ce.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?H1(i).test(e.data)||(s=this._getOrReturnCtx(e,s),Re(s,{code:ce.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?B1.test(e.data)||(s=this._getOrReturnCtx(e,s),Re(s,{code:ce.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?q1(i).test(e.data)||(s=this._getOrReturnCtx(e,s),Re(s,{code:ce.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?N1.test(e.data)||(s=this._getOrReturnCtx(e,s),Re(s,{validation:"duration",code:ce.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?W1(e.data,i.version)||(s=this._getOrReturnCtx(e,s),Re(s,{validation:"ip",code:ce.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?U1(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),Re(s,{validation:"jwt",code:ce.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?K1(e.data,i.version)||(s=this._getOrReturnCtx(e,s),Re(s,{validation:"cidr",code:ce.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?L1.test(e.data)||(s=this._getOrReturnCtx(e,s),Re(s,{validation:"base64",code:ce.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?z1.test(e.data)||(s=this._getOrReturnCtx(e,s),Re(s,{validation:"base64url",code:ce.invalid_string,message:i.message}),r.dirty()):vt.assertNever(i);return{status:r.value,value:e.data}}_regex(e,t,r){return this.refinement(s=>e.test(s),{validation:t,code:ce.invalid_string,...Oe.errToObj(r)})}_addCheck(e){return new n({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...Oe.errToObj(e)})}url(e){return this._addCheck({kind:"url",...Oe.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...Oe.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...Oe.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...Oe.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...Oe.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...Oe.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...Oe.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...Oe.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...Oe.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...Oe.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...Oe.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...Oe.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...Oe.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...Oe.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...Oe.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...Oe.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...Oe.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...Oe.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...Oe.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...Oe.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...Oe.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...Oe.errToObj(t)})}nonempty(e){return this.min(1,Oe.errToObj(e))}trim(){return new n({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new n({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new n({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};Gc.create=n=>new Gc({checks:[],typeName:ue.ZodString,coerce:n?.coerce??!1,...dt(n)});function Z1(n,e){let t=(n.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,s=t>r?t:r,i=Number.parseInt(n.toFixed(s).replace(".","")),o=Number.parseInt(e.toFixed(s).replace(".",""));return i%o/10**s}var bd=class n extends bt{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==Te.number){let i=this._getOrReturnCtx(e);return Re(i,{code:ce.invalid_type,expected:Te.number,received:i.parsedType}),tt}let r,s=new hr;for(let i of this._def.checks)i.kind==="int"?vt.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),Re(r,{code:ce.invalid_type,expected:"integer",received:"float",message:i.message}),s.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),Re(r,{code:ce.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),Re(r,{code:ce.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?Z1(e.data,i.value)!==0&&(r=this._getOrReturnCtx(e,r),Re(r,{code:ce.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),Re(r,{code:ce.not_finite,message:i.message}),s.dirty()):vt.assertNever(i);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,Oe.toString(t))}gt(e,t){return this.setLimit("min",e,!1,Oe.toString(t))}lte(e,t){return this.setLimit("max",e,!0,Oe.toString(t))}lt(e,t){return this.setLimit("max",e,!1,Oe.toString(t))}setLimit(e,t,r,s){return new n({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:Oe.toString(s)}]})}_addCheck(e){return new n({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:Oe.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Oe.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Oe.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Oe.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Oe.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:Oe.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:Oe.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Oe.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Oe.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&vt.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(t===null||r.value>t)&&(t=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(t)&&Number.isFinite(e)}};bd.create=n=>new bd({checks:[],typeName:ue.ZodNumber,coerce:n?.coerce||!1,...dt(n)});var Sd=class n extends bt{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==Te.bigint)return this._getInvalidInput(e);let r,s=new hr;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),Re(r,{code:ce.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),Re(r,{code:ce.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),Re(r,{code:ce.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):vt.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return Re(t,{code:ce.invalid_type,expected:Te.bigint,received:t.parsedType}),tt}gte(e,t){return this.setLimit("min",e,!0,Oe.toString(t))}gt(e,t){return this.setLimit("min",e,!1,Oe.toString(t))}lte(e,t){return this.setLimit("max",e,!0,Oe.toString(t))}lt(e,t){return this.setLimit("max",e,!1,Oe.toString(t))}setLimit(e,t,r,s){return new n({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:Oe.toString(s)}]})}_addCheck(e){return new n({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Oe.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Oe.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Oe.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Oe.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:Oe.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};Sd.create=n=>new Sd({checks:[],typeName:ue.ZodBigInt,coerce:n?.coerce??!1,...dt(n)});var xd=class extends bt{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==Te.boolean){let r=this._getOrReturnCtx(e);return Re(r,{code:ce.invalid_type,expected:Te.boolean,received:r.parsedType}),tt}return Ir(e.data)}};xd.create=n=>new xd({typeName:ue.ZodBoolean,coerce:n?.coerce||!1,...dt(n)});var _d=class n extends bt{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==Te.date){let i=this._getOrReturnCtx(e);return Re(i,{code:ce.invalid_type,expected:Te.date,received:i.parsedType}),tt}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return Re(i,{code:ce.invalid_date}),tt}let r=new hr,s;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),Re(s,{code:ce.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),r.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(s=this._getOrReturnCtx(e,s),Re(s,{code:ce.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):vt.assertNever(i);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new n({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:Oe.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:Oe.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}};_d.create=n=>new _d({checks:[],coerce:n?.coerce||!1,typeName:ue.ZodDate,...dt(n)});var wd=class extends bt{_parse(e){if(this._getType(e)!==Te.symbol){let r=this._getOrReturnCtx(e);return Re(r,{code:ce.invalid_type,expected:Te.symbol,received:r.parsedType}),tt}return Ir(e.data)}};wd.create=n=>new wd({typeName:ue.ZodSymbol,...dt(n)});var Jc=class extends bt{_parse(e){if(this._getType(e)!==Te.undefined){let r=this._getOrReturnCtx(e);return Re(r,{code:ce.invalid_type,expected:Te.undefined,received:r.parsedType}),tt}return Ir(e.data)}};Jc.create=n=>new Jc({typeName:ue.ZodUndefined,...dt(n)});var Vc=class extends bt{_parse(e){if(this._getType(e)!==Te.null){let r=this._getOrReturnCtx(e);return Re(r,{code:ce.invalid_type,expected:Te.null,received:r.parsedType}),tt}return Ir(e.data)}};Vc.create=n=>new Vc({typeName:ue.ZodNull,...dt(n)});var vd=class extends bt{constructor(){super(...arguments),this._any=!0}_parse(e){return Ir(e.data)}};vd.create=n=>new vd({typeName:ue.ZodAny,...dt(n)});var wo=class extends bt{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Ir(e.data)}};wo.create=n=>new wo({typeName:ue.ZodUnknown,...dt(n)});var _i=class extends bt{_parse(e){let t=this._getOrReturnCtx(e);return Re(t,{code:ce.invalid_type,expected:Te.never,received:t.parsedType}),tt}};_i.create=n=>new _i({typeName:ue.ZodNever,...dt(n)});var Rd=class extends bt{_parse(e){if(this._getType(e)!==Te.undefined){let r=this._getOrReturnCtx(e);return Re(r,{code:ce.invalid_type,expected:Te.void,received:r.parsedType}),tt}return Ir(e.data)}};Rd.create=n=>new Rd({typeName:ue.ZodVoid,...dt(n)});var vo=class n extends bt{_parse(e){let{ctx:t,status:r}=this._processInputParams(e),s=this._def;if(t.parsedType!==Te.array)return Re(t,{code:ce.invalid_type,expected:Te.array,received:t.parsedType}),tt;if(s.exactLength!==null){let o=t.data.length>s.exactLength.value,a=t.data.length<s.exactLength.value;(o||a)&&(Re(t,{code:o?ce.too_big:ce.too_small,minimum:a?s.exactLength.value:void 0,maximum:o?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),r.dirty())}if(s.minLength!==null&&t.data.length<s.minLength.value&&(Re(t,{code:ce.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),s.maxLength!==null&&t.data.length>s.maxLength.value&&(Re(t,{code:ce.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map((o,a)=>s.type._parseAsync(new As(t,o,t.path,a)))).then(o=>hr.mergeArray(r,o));let i=[...t.data].map((o,a)=>s.type._parseSync(new As(t,o,t.path,a)));return hr.mergeArray(r,i)}get element(){return this._def.type}min(e,t){return new n({...this._def,minLength:{value:e,message:Oe.toString(t)}})}max(e,t){return new n({...this._def,maxLength:{value:e,message:Oe.toString(t)}})}length(e,t){return new n({...this._def,exactLength:{value:e,message:Oe.toString(t)}})}nonempty(e){return this.min(1,e)}};vo.create=(n,e)=>new vo({type:n,minLength:null,maxLength:null,exactLength:null,typeName:ue.ZodArray,...dt(e)});function Zc(n){if(n instanceof us){let e={};for(let t in n.shape){let r=n.shape[t];e[t]=ls.create(Zc(r))}return new us({...n._def,shape:()=>e})}else return n instanceof vo?new vo({...n._def,type:Zc(n.element)}):n instanceof ls?ls.create(Zc(n.unwrap())):n instanceof Gi?Gi.create(Zc(n.unwrap())):n instanceof Zi?Zi.create(n.items.map(e=>Zc(e))):n}var us=class n extends bt{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=vt.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==Te.object){let l=this._getOrReturnCtx(e);return Re(l,{code:ce.invalid_type,expected:Te.object,received:l.parsedType}),tt}let{status:r,ctx:s}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),a=[];if(!(this._def.catchall instanceof _i&&this._def.unknownKeys==="strip"))for(let l in s.data)o.includes(l)||a.push(l);let c=[];for(let l of o){let u=i[l],d=s.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new As(s,d,s.path,l)),alwaysSet:l in s.data})}if(this._def.catchall instanceof _i){let l=this._def.unknownKeys;if(l==="passthrough")for(let u of a)c.push({key:{status:"valid",value:u},value:{status:"valid",value:s.data[u]}});else if(l==="strict")a.length>0&&(Re(s,{code:ce.unrecognized_keys,keys:a}),r.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let u of a){let d=s.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new As(s,d,s.path,u)),alwaysSet:u in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let l=[];for(let u of c){let d=await u.key,p=await u.value;l.push({key:d,value:p,alwaysSet:u.alwaysSet})}return l}).then(l=>hr.mergeObjectSync(r,l)):hr.mergeObjectSync(r,c)}get shape(){return this._def.shape()}strict(e){return Oe.errToObj,new n({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,r)=>{let s=this._def.errorMap?.(t,r).message??r.defaultError;return t.code==="unrecognized_keys"?{message:Oe.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new n({...this._def,unknownKeys:"strip"})}passthrough(){return new n({...this._def,unknownKeys:"passthrough"})}extend(e){return new n({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new n({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:ue.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new n({...this._def,catchall:e})}pick(e){let t={};for(let r of vt.objectKeys(e))e[r]&&this.shape[r]&&(t[r]=this.shape[r]);return new n({...this._def,shape:()=>t})}omit(e){let t={};for(let r of vt.objectKeys(this.shape))e[r]||(t[r]=this.shape[r]);return new n({...this._def,shape:()=>t})}deepPartial(){return Zc(this)}partial(e){let t={};for(let r of vt.objectKeys(this.shape)){let s=this.shape[r];e&&!e[r]?t[r]=s:t[r]=s.optional()}return new n({...this._def,shape:()=>t})}required(e){let t={};for(let r of vt.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof ls;)i=i._def.innerType;t[r]=i}return new n({...this._def,shape:()=>t})}keyof(){return tI(vt.objectKeys(this.shape))}};us.create=(n,e)=>new us({shape:()=>n,unknownKeys:"strip",catchall:_i.create(),typeName:ue.ZodObject,...dt(e)});us.strictCreate=(n,e)=>new us({shape:()=>n,unknownKeys:"strict",catchall:_i.create(),typeName:ue.ZodObject,...dt(e)});us.lazycreate=(n,e)=>new us({shape:n,unknownKeys:"strip",catchall:_i.create(),typeName:ue.ZodObject,...dt(e)});var Xc=class extends bt{_parse(e){let{ctx:t}=this._processInputParams(e),r=this._def.options;function s(i){for(let a of i)if(a.result.status==="valid")return a.result;for(let a of i)if(a.result.status==="dirty")return t.common.issues.push(...a.ctx.common.issues),a.result;let o=i.map(a=>new cs(a.ctx.common.issues));return Re(t,{code:ce.invalid_union,unionErrors:o}),tt}if(t.common.async)return Promise.all(r.map(async i=>{let o={...t,common:{...t.common,issues:[]},parent:null};return{result:await i._parseAsync({data:t.data,path:t.path,parent:o}),ctx:o}})).then(s);{let i,o=[];for(let c of r){let l={...t,common:{...t.common,issues:[]},parent:null},u=c._parseSync({data:t.data,path:t.path,parent:l});if(u.status==="valid")return u;u.status==="dirty"&&!i&&(i={result:u,ctx:l}),l.common.issues.length&&o.push(l.common.issues)}if(i)return t.common.issues.push(...i.ctx.common.issues),i.result;let a=o.map(c=>new cs(c));return Re(t,{code:ce.invalid_union,unionErrors:a}),tt}}get options(){return this._def.options}};Xc.create=(n,e)=>new Xc({options:n,typeName:ue.ZodUnion,...dt(e)});var Ki=n=>n instanceof Yc?Ki(n.schema):n instanceof ei?Ki(n.innerType()):n instanceof el?[n.value]:n instanceof tl?n.options:n instanceof nl?vt.objectValues(n.enum):n instanceof rl?Ki(n._def.innerType):n instanceof Jc?[void 0]:n instanceof Vc?[null]:n instanceof ls?[void 0,...Ki(n.unwrap())]:n instanceof Gi?[null,...Ki(n.unwrap())]:n instanceof Zm||n instanceof il?Ki(n.unwrap()):n instanceof sl?Ki(n._def.innerType):[],US=class n extends bt{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==Te.object)return Re(t,{code:ce.invalid_type,expected:Te.object,received:t.parsedType}),tt;let r=this.discriminator,s=t.data[r],i=this.optionsMap.get(s);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(Re(t,{code:ce.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),tt)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,r){let s=new Map;for(let i of t){let o=Ki(i.shape[e]);if(!o.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of o){if(s.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);s.set(a,i)}}return new n({typeName:ue.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:s,...dt(r)})}};function KS(n,e){let t=Ui(n),r=Ui(e);if(n===e)return{valid:!0,data:n};if(t===Te.object&&r===Te.object){let s=vt.objectKeys(e),i=vt.objectKeys(n).filter(a=>s.indexOf(a)!==-1),o={...n,...e};for(let a of i){let c=KS(n[a],e[a]);if(!c.valid)return{valid:!1};o[a]=c.data}return{valid:!0,data:o}}else if(t===Te.array&&r===Te.array){if(n.length!==e.length)return{valid:!1};let s=[];for(let i=0;i<n.length;i++){let o=n[i],a=e[i],c=KS(o,a);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return t===Te.date&&r===Te.date&&+n==+e?{valid:!0,data:n}:{valid:!1}}var Qc=class extends bt{_parse(e){let{status:t,ctx:r}=this._processInputParams(e),s=(i,o)=>{if(qS(i)||qS(o))return tt;let a=KS(i.value,o.value);return a.valid?((HS(i)||HS(o))&&t.dirty(),{status:t.value,value:a.data}):(Re(r,{code:ce.invalid_intersection_types}),tt)};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(([i,o])=>s(i,o)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};Qc.create=(n,e,t)=>new Qc({left:n,right:e,typeName:ue.ZodIntersection,...dt(t)});var Zi=class n extends bt{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==Te.array)return Re(r,{code:ce.invalid_type,expected:Te.array,received:r.parsedType}),tt;if(r.data.length<this._def.items.length)return Re(r,{code:ce.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),tt;!this._def.rest&&r.data.length>this._def.items.length&&(Re(r,{code:ce.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let i=[...r.data].map((o,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new As(r,o,r.path,a)):null}).filter(o=>!!o);return r.common.async?Promise.all(i).then(o=>hr.mergeArray(t,o)):hr.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new n({...this._def,rest:e})}};Zi.create=(n,e)=>{if(!Array.isArray(n))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Zi({items:n,typeName:ue.ZodTuple,rest:null,...dt(e)})};var ZS=class n extends bt{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==Te.object)return Re(r,{code:ce.invalid_type,expected:Te.object,received:r.parsedType}),tt;let s=[],i=this._def.keyType,o=this._def.valueType;for(let a in r.data)s.push({key:i._parse(new As(r,a,r.path,a)),value:o._parse(new As(r,r.data[a],r.path,a)),alwaysSet:a in r.data});return r.common.async?hr.mergeObjectAsync(t,s):hr.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,r){return t instanceof bt?new n({keyType:e,valueType:t,typeName:ue.ZodRecord,...dt(r)}):new n({keyType:Gc.create(),valueType:e,typeName:ue.ZodRecord,...dt(t)})}},Ed=class extends bt{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==Te.map)return Re(r,{code:ce.invalid_type,expected:Te.map,received:r.parsedType}),tt;let s=this._def.keyType,i=this._def.valueType,o=[...r.data.entries()].map(([a,c],l)=>({key:s._parse(new As(r,a,r.path,[l,"key"])),value:i._parse(new As(r,c,r.path,[l,"value"]))}));if(r.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of o){let l=await c.key,u=await c.value;if(l.status==="aborted"||u.status==="aborted")return tt;(l.status==="dirty"||u.status==="dirty")&&t.dirty(),a.set(l.value,u.value)}return{status:t.value,value:a}})}else{let a=new Map;for(let c of o){let l=c.key,u=c.value;if(l.status==="aborted"||u.status==="aborted")return tt;(l.status==="dirty"||u.status==="dirty")&&t.dirty(),a.set(l.value,u.value)}return{status:t.value,value:a}}}};Ed.create=(n,e,t)=>new Ed({valueType:e,keyType:n,typeName:ue.ZodMap,...dt(t)});var kd=class n extends bt{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==Te.set)return Re(r,{code:ce.invalid_type,expected:Te.set,received:r.parsedType}),tt;let s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&(Re(r,{code:ce.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),s.maxSize!==null&&r.data.size>s.maxSize.value&&(Re(r,{code:ce.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());let i=this._def.valueType;function o(c){let l=new Set;for(let u of c){if(u.status==="aborted")return tt;u.status==="dirty"&&t.dirty(),l.add(u.value)}return{status:t.value,value:l}}let a=[...r.data.values()].map((c,l)=>i._parse(new As(r,c,r.path,l)));return r.common.async?Promise.all(a).then(c=>o(c)):o(a)}min(e,t){return new n({...this._def,minSize:{value:e,message:Oe.toString(t)}})}max(e,t){return new n({...this._def,maxSize:{value:e,message:Oe.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};kd.create=(n,e)=>new kd({valueType:n,minSize:null,maxSize:null,typeName:ue.ZodSet,...dt(e)});var GS=class n extends bt{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==Te.function)return Re(t,{code:ce.invalid_type,expected:Te.function,received:t.parsedType}),tt;function r(a,c){return Km({data:a,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,gd(),_o].filter(l=>!!l),issueData:{code:ce.invalid_arguments,argumentsError:c}})}function s(a,c){return Km({data:a,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,gd(),_o].filter(l=>!!l),issueData:{code:ce.invalid_return_type,returnTypeError:c}})}let i={errorMap:t.common.contextualErrorMap},o=t.data;if(this._def.returns instanceof $a){let a=this;return Ir(async function(...c){let l=new cs([]),u=await a._def.args.parseAsync(c,i).catch(f=>{throw l.addIssue(r(c,f)),l}),d=await Reflect.apply(o,this,u);return await a._def.returns._def.type.parseAsync(d,i).catch(f=>{throw l.addIssue(s(d,f)),l})})}else{let a=this;return Ir(function(...c){let l=a._def.args.safeParse(c,i);if(!l.success)throw new cs([r(c,l.error)]);let u=Reflect.apply(o,this,l.data),d=a._def.returns.safeParse(u,i);if(!d.success)throw new cs([s(u,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new n({...this._def,args:Zi.create(e).rest(wo.create())})}returns(e){return new n({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,r){return new n({args:e||Zi.create([]).rest(wo.create()),returns:t||wo.create(),typeName:ue.ZodFunction,...dt(r)})}},Yc=class extends bt{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};Yc.create=(n,e)=>new Yc({getter:n,typeName:ue.ZodLazy,...dt(e)});var el=class extends bt{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return Re(t,{received:t.data,code:ce.invalid_literal,expected:this._def.value}),tt}return{status:"valid",value:e.data}}get value(){return this._def.value}};el.create=(n,e)=>new el({value:n,typeName:ue.ZodLiteral,...dt(e)});function tI(n,e){return new tl({values:n,typeName:ue.ZodEnum,...dt(e)})}var tl=class n extends bt{_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),r=this._def.values;return Re(t,{expected:vt.joinValues(r),received:t.parsedType,code:ce.invalid_type}),tt}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),r=this._def.values;return Re(t,{received:t.data,code:ce.invalid_enum_value,options:r}),tt}return Ir(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return n.create(e,{...this._def,...t})}exclude(e,t=this._def){return n.create(this.options.filter(r=>!e.includes(r)),{...this._def,...t})}};tl.create=tI;var nl=class extends bt{_parse(e){let t=vt.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==Te.string&&r.parsedType!==Te.number){let s=vt.objectValues(t);return Re(r,{expected:vt.joinValues(s),received:r.parsedType,code:ce.invalid_type}),tt}if(this._cache||(this._cache=new Set(vt.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=vt.objectValues(t);return Re(r,{received:r.data,code:ce.invalid_enum_value,options:s}),tt}return Ir(e.data)}get enum(){return this._def.values}};nl.create=(n,e)=>new nl({values:n,typeName:ue.ZodNativeEnum,...dt(e)});var $a=class extends bt{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==Te.promise&&t.common.async===!1)return Re(t,{code:ce.invalid_type,expected:Te.promise,received:t.parsedType}),tt;let r=t.parsedType===Te.promise?t.data:Promise.resolve(t.data);return Ir(r.then(s=>this._def.type.parseAsync(s,{path:t.path,errorMap:t.common.contextualErrorMap})))}};$a.create=(n,e)=>new $a({type:n,typeName:ue.ZodPromise,...dt(e)});var ei=class extends bt{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ue.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:r}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:o=>{Re(r,o),o.fatal?t.abort():t.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){let o=s.transform(r.data,i);if(r.common.async)return Promise.resolve(o).then(async a=>{if(t.value==="aborted")return tt;let c=await this._def.schema._parseAsync({data:a,path:r.path,parent:r});return c.status==="aborted"?tt:c.status==="dirty"?Kc(c.value):t.value==="dirty"?Kc(c.value):c});{if(t.value==="aborted")return tt;let a=this._def.schema._parseSync({data:o,path:r.path,parent:r});return a.status==="aborted"?tt:a.status==="dirty"?Kc(a.value):t.value==="dirty"?Kc(a.value):a}}if(s.type==="refinement"){let o=a=>{let c=s.refinement(a,i);if(r.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(r.common.async===!1){let a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return a.status==="aborted"?tt:(a.status==="dirty"&&t.dirty(),o(a.value),{status:t.value,value:a.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>a.status==="aborted"?tt:(a.status==="dirty"&&t.dirty(),o(a.value).then(()=>({status:t.value,value:a.value}))))}if(s.type==="transform")if(r.common.async===!1){let o=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Oa(o))return tt;let a=s.transform(o.value,i);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:a}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(o=>Oa(o)?Promise.resolve(s.transform(o.value,i)).then(a=>({status:t.value,value:a})):tt);vt.assertNever(s)}};ei.create=(n,e,t)=>new ei({schema:n,typeName:ue.ZodEffects,effect:e,...dt(t)});ei.createWithPreprocess=(n,e,t)=>new ei({schema:e,effect:{type:"preprocess",transform:n},typeName:ue.ZodEffects,...dt(t)});var ls=class extends bt{_parse(e){return this._getType(e)===Te.undefined?Ir(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ls.create=(n,e)=>new ls({innerType:n,typeName:ue.ZodOptional,...dt(e)});var Gi=class extends bt{_parse(e){return this._getType(e)===Te.null?Ir(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Gi.create=(n,e)=>new Gi({innerType:n,typeName:ue.ZodNullable,...dt(e)});var rl=class extends bt{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return t.parsedType===Te.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};rl.create=(n,e)=>new rl({innerType:n,typeName:ue.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...dt(e)});var sl=class extends bt{_parse(e){let{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return yd(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new cs(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new cs(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};sl.create=(n,e)=>new sl({innerType:n,typeName:ue.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...dt(e)});var Td=class extends bt{_parse(e){if(this._getType(e)!==Te.nan){let r=this._getOrReturnCtx(e);return Re(r,{code:ce.invalid_type,expected:Te.nan,received:r.parsedType}),tt}return{status:"valid",value:e.data}}};Td.create=n=>new Td({typeName:ue.ZodNaN,...dt(n)});var Zm=class extends bt{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}},Gm=class n extends bt{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?tt:i.status==="dirty"?(t.dirty(),Kc(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{let s=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?tt:s.status==="dirty"?(t.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(e,t){return new n({in:e,out:t,typeName:ue.ZodPipeline})}},il=class extends bt{_parse(e){let t=this._def.innerType._parse(e),r=s=>(Oa(s)&&(s.value=Object.freeze(s.value)),s);return yd(t)?t.then(s=>r(s)):r(t)}unwrap(){return this._def.innerType}};il.create=(n,e)=>new il({innerType:n,typeName:ue.ZodReadonly,...dt(e)});var Q7={object:us.lazycreate},ue;(function(n){n.ZodString="ZodString",n.ZodNumber="ZodNumber",n.ZodNaN="ZodNaN",n.ZodBigInt="ZodBigInt",n.ZodBoolean="ZodBoolean",n.ZodDate="ZodDate",n.ZodSymbol="ZodSymbol",n.ZodUndefined="ZodUndefined",n.ZodNull="ZodNull",n.ZodAny="ZodAny",n.ZodUnknown="ZodUnknown",n.ZodNever="ZodNever",n.ZodVoid="ZodVoid",n.ZodArray="ZodArray",n.ZodObject="ZodObject",n.ZodUnion="ZodUnion",n.ZodDiscriminatedUnion="ZodDiscriminatedUnion",n.ZodIntersection="ZodIntersection",n.ZodTuple="ZodTuple",n.ZodRecord="ZodRecord",n.ZodMap="ZodMap",n.ZodSet="ZodSet",n.ZodFunction="ZodFunction",n.ZodLazy="ZodLazy",n.ZodLiteral="ZodLiteral",n.ZodEnum="ZodEnum",n.ZodEffects="ZodEffects",n.ZodNativeEnum="ZodNativeEnum",n.ZodOptional="ZodOptional",n.ZodNullable="ZodNullable",n.ZodDefault="ZodDefault",n.ZodCatch="ZodCatch",n.ZodPromise="ZodPromise",n.ZodBranded="ZodBranded",n.ZodPipeline="ZodPipeline",n.ZodReadonly="ZodReadonly"})(ue||(ue={}));var Y7=Gc.create,eee=bd.create,tee=Td.create,nee=Sd.create,ree=xd.create,see=_d.create,iee=wd.create,oee=Jc.create,aee=Vc.create,cee=vd.create,lee=wo.create,uee=_i.create,dee=Rd.create,pee=vo.create,nI=us.create,fee=us.strictCreate,mee=Xc.create,hee=US.create,gee=Qc.create,yee=Zi.create,bee=ZS.create,See=Ed.create,xee=kd.create,_ee=GS.create,wee=Yc.create,vee=el.create,Ree=tl.create,Eee=nl.create,kee=$a.create,Tee=ei.create,Pee=ls.create,Cee=Gi.create,Iee=ei.createWithPreprocess,Aee=Gm.create;var G1=Object.freeze({status:"aborted"});function Y(n,e,t){function r(a,c){var l;Object.defineProperty(a,"_zod",{value:a._zod??{},enumerable:!1}),(l=a._zod).traits??(l.traits=new Set),a._zod.traits.add(n),e(a,c);for(let u in o.prototype)u in a||Object.defineProperty(a,u,{value:o.prototype[u].bind(a)});a._zod.constr=o,a._zod.def=c}let s=t?.Parent??Object;class i extends s{}Object.defineProperty(i,"name",{value:n});function o(a){var c;let l=t?.Parent?new i:this;r(l,a),(c=l._zod).deferred??(c.deferred=[]);for(let u of l._zod.deferred)u();return l}return Object.defineProperty(o,"init",{value:r}),Object.defineProperty(o,Symbol.hasInstance,{value:a=>t?.Parent&&a instanceof t.Parent?!0:a?._zod?.traits?.has(n)}),Object.defineProperty(o,"name",{value:n}),o}var Ji=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Jm={};function ds(n){return n&&Object.assign(Jm,n),Jm}var Rt={};Lt(Rt,{BIGINT_FORMAT_RANGES:()=>sI,Class:()=>VS,NUMBER_FORMAT_RANGES:()=>rx,aborted:()=>La,allowsEval:()=>ex,assert:()=>Y1,assertEqual:()=>J1,assertIs:()=>X1,assertNever:()=>Q1,assertNotEqual:()=>V1,assignProp:()=>YS,cached:()=>Id,captureStackTrace:()=>Xm,cleanEnum:()=>pq,cleanRegex:()=>Nd,clone:()=>ps,createTransparentProxy:()=>iq,defineLazy:()=>Xt,esc:()=>ja,escapeRegex:()=>Ro,extend:()=>cq,finalizeIssue:()=>ti,floatSafeRemainder:()=>QS,getElementAtPath:()=>eq,getEnumValues:()=>Cd,getLengthableOrigin:()=>Md,getParsedType:()=>sq,getSizableOrigin:()=>iI,isObject:()=>ol,isPlainObject:()=>al,issue:()=>sx,joinValues:()=>Vm,jsonStringifyReplacer:()=>XS,merge:()=>lq,normalizeParams:()=>Qe,nullish:()=>Ad,numKeys:()=>rq,omit:()=>aq,optionalKeys:()=>nx,partial:()=>uq,pick:()=>oq,prefixIssues:()=>wi,primitiveTypes:()=>rI,promiseAllObject:()=>tq,propertyKeyTypes:()=>tx,randomString:()=>nq,required:()=>dq,stringifyPrimitive:()=>Qm,unwrapMessage:()=>Pd});function J1(n){return n}function V1(n){return n}function X1(n){}function Q1(n){throw new Error}function Y1(n){}function Cd(n){let e=Object.values(n).filter(r=>typeof r=="number");return Object.entries(n).filter(([r,s])=>e.indexOf(+r)===-1).map(([r,s])=>s)}function Vm(n,e="|"){return n.map(t=>Qm(t)).join(e)}function XS(n,e){return typeof e=="bigint"?e.toString():e}function Id(n){return{get value(){{let t=n();return Object.defineProperty(this,"value",{value:t}),t}throw new Error("cached value already set")}}}function Ad(n){return n==null}function Nd(n){let e=n.startsWith("^")?1:0,t=n.endsWith("$")?n.length-1:n.length;return n.slice(e,t)}function QS(n,e){let t=(n.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,s=t>r?t:r,i=Number.parseInt(n.toFixed(s).replace(".","")),o=Number.parseInt(e.toFixed(s).replace(".",""));return i%o/10**s}function Xt(n,e,t){Object.defineProperty(n,e,{get(){{let s=t();return n[e]=s,s}throw new Error("cached value already set")},set(s){Object.defineProperty(n,e,{value:s})},configurable:!0})}function YS(n,e,t){Object.defineProperty(n,e,{value:t,writable:!0,enumerable:!0,configurable:!0})}function eq(n,e){return e?e.reduce((t,r)=>t?.[r],n):n}function tq(n){let e=Object.keys(n),t=e.map(r=>n[r]);return Promise.all(t).then(r=>{let s={};for(let i=0;i<e.length;i++)s[e[i]]=r[i];return s})}function nq(n=10){let e="abcdefghijklmnopqrstuvwxyz",t="";for(let r=0;r<n;r++)t+=e[Math.floor(Math.random()*e.length)];return t}function ja(n){return JSON.stringify(n)}var Xm=Error.captureStackTrace?Error.captureStackTrace:(...n)=>{};function ol(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}var ex=Id(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let n=Function;return new n(""),!0}catch{return!1}});function al(n){if(ol(n)===!1)return!1;let e=n.constructor;if(e===void 0)return!0;let t=e.prototype;return!(ol(t)===!1||Object.prototype.hasOwnProperty.call(t,"isPrototypeOf")===!1)}function rq(n){let e=0;for(let t in n)Object.prototype.hasOwnProperty.call(n,t)&&e++;return e}var sq=n=>{let e=typeof n;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(n)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(n)?"array":n===null?"null":n.then&&typeof n.then=="function"&&n.catch&&typeof n.catch=="function"?"promise":typeof Map<"u"&&n instanceof Map?"map":typeof Set<"u"&&n instanceof Set?"set":typeof Date<"u"&&n instanceof Date?"date":typeof File<"u"&&n instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},tx=new Set(["string","number","symbol"]),rI=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Ro(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ps(n,e,t){let r=new n._zod.constr(e??n._zod.def);return(!e||t?.parent)&&(r._zod.parent=n),r}function Qe(n){let e=n;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function iq(n){let e;return new Proxy({},{get(t,r,s){return e??(e=n()),Reflect.get(e,r,s)},set(t,r,s,i){return e??(e=n()),Reflect.set(e,r,s,i)},has(t,r){return e??(e=n()),Reflect.has(e,r)},deleteProperty(t,r){return e??(e=n()),Reflect.deleteProperty(e,r)},ownKeys(t){return e??(e=n()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(t,r){return e??(e=n()),Reflect.getOwnPropertyDescriptor(e,r)},defineProperty(t,r,s){return e??(e=n()),Reflect.defineProperty(e,r,s)}})}function Qm(n){return typeof n=="bigint"?n.toString()+"n":typeof n=="string"?`"${n}"`:`${n}`}function nx(n){return Object.keys(n).filter(e=>n[e]._zod.optin==="optional"&&n[e]._zod.optout==="optional")}var rx={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},sI={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function oq(n,e){let t={},r=n._zod.def;for(let s in e){if(!(s in r.shape))throw new Error(`Unrecognized key: "${s}"`);e[s]&&(t[s]=r.shape[s])}return ps(n,{...n._zod.def,shape:t,checks:[]})}function aq(n,e){let t={...n._zod.def.shape},r=n._zod.def;for(let s in e){if(!(s in r.shape))throw new Error(`Unrecognized key: "${s}"`);e[s]&&delete t[s]}return ps(n,{...n._zod.def,shape:t,checks:[]})}function cq(n,e){if(!al(e))throw new Error("Invalid input to extend: expected a plain object");let t={...n._zod.def,get shape(){let r={...n._zod.def.shape,...e};return YS(this,"shape",r),r},checks:[]};return ps(n,t)}function lq(n,e){return ps(n,{...n._zod.def,get shape(){let t={...n._zod.def.shape,...e._zod.def.shape};return YS(this,"shape",t),t},catchall:e._zod.def.catchall,checks:[]})}function uq(n,e,t){let r=e._zod.def.shape,s={...r};if(t)for(let i in t){if(!(i in r))throw new Error(`Unrecognized key: "${i}"`);t[i]&&(s[i]=n?new n({type:"optional",innerType:r[i]}):r[i])}else for(let i in r)s[i]=n?new n({type:"optional",innerType:r[i]}):r[i];return ps(e,{...e._zod.def,shape:s,checks:[]})}function dq(n,e,t){let r=e._zod.def.shape,s={...r};if(t)for(let i in t){if(!(i in s))throw new Error(`Unrecognized key: "${i}"`);t[i]&&(s[i]=new n({type:"nonoptional",innerType:r[i]}))}else for(let i in r)s[i]=new n({type:"nonoptional",innerType:r[i]});return ps(e,{...e._zod.def,shape:s,checks:[]})}function La(n,e=0){for(let t=e;t<n.issues.length;t++)if(n.issues[t]?.continue!==!0)return!0;return!1}function wi(n,e){return e.map(t=>{var r;return(r=t).path??(r.path=[]),t.path.unshift(n),t})}function Pd(n){return typeof n=="string"?n:n?.message}function ti(n,e,t){let r={...n,path:n.path??[]};if(!n.message){let s=Pd(n.inst?._zod.def?.error?.(n))??Pd(e?.error?.(n))??Pd(t.customError?.(n))??Pd(t.localeError?.(n))??"Invalid input";r.message=s}return delete r.inst,delete r.continue,e?.reportInput||delete r.input,r}function iI(n){return n instanceof Set?"set":n instanceof Map?"map":n instanceof File?"file":"unknown"}function Md(n){return Array.isArray(n)?"array":typeof n=="string"?"string":"unknown"}function sx(...n){let[e,t,r]=n;return typeof e=="string"?{message:e,code:"custom",input:t,inst:r}:{...e}}function pq(n){return Object.entries(n).filter(([e,t])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var VS=class{constructor(...e){}};var oI=(n,e)=>{n.name="$ZodError",Object.defineProperty(n,"_zod",{value:n._zod,enumerable:!1}),Object.defineProperty(n,"issues",{value:e,enumerable:!1}),Object.defineProperty(n,"message",{get(){return JSON.stringify(e,XS,2)},enumerable:!0}),Object.defineProperty(n,"toString",{value:()=>n.message,enumerable:!1})},Ym=Y("$ZodError",oI),Fd=Y("$ZodError",oI,{Parent:Error});function ix(n,e=t=>t.message){let t={},r=[];for(let s of n.issues)s.path.length>0?(t[s.path[0]]=t[s.path[0]]||[],t[s.path[0]].push(e(s))):r.push(e(s));return{formErrors:r,fieldErrors:t}}function ox(n,e){let t=e||function(i){return i.message},r={_errors:[]},s=i=>{for(let o of i.issues)if(o.code==="invalid_union"&&o.errors.length)o.errors.map(a=>s({issues:a}));else if(o.code==="invalid_key")s({issues:o.issues});else if(o.code==="invalid_element")s({issues:o.issues});else if(o.path.length===0)r._errors.push(t(o));else{let a=r,c=0;for(;c<o.path.length;){let l=o.path[c];c===o.path.length-1?(a[l]=a[l]||{_errors:[]},a[l]._errors.push(t(o))):a[l]=a[l]||{_errors:[]},a=a[l],c++}}};return s(n),r}var ax=n=>(e,t,r,s)=>{let i=r?Object.assign(r,{async:!1}):{async:!1},o=e._zod.run({value:t,issues:[]},i);if(o instanceof Promise)throw new Ji;if(o.issues.length){let a=new(s?.Err??n)(o.issues.map(c=>ti(c,i,ds())));throw Xm(a,s?.callee),a}return o.value},cx=ax(Fd),lx=n=>async(e,t,r,s)=>{let i=r?Object.assign(r,{async:!0}):{async:!0},o=e._zod.run({value:t,issues:[]},i);if(o instanceof Promise&&(o=await o),o.issues.length){let a=new(s?.Err??n)(o.issues.map(c=>ti(c,i,ds())));throw Xm(a,s?.callee),a}return o.value},ux=lx(Fd),dx=n=>(e,t,r)=>{let s=r?{...r,async:!1}:{async:!1},i=e._zod.run({value:t,issues:[]},s);if(i instanceof Promise)throw new Ji;return i.issues.length?{success:!1,error:new(n??Ym)(i.issues.map(o=>ti(o,s,ds())))}:{success:!0,data:i.value}},za=dx(Fd),px=n=>async(e,t,r)=>{let s=r?Object.assign(r,{async:!0}):{async:!0},i=e._zod.run({value:t,issues:[]},s);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new n(i.issues.map(o=>ti(o,s,ds())))}:{success:!0,data:i.value}},Ba=px(Fd);var aI=/^[cC][^\s-]{8,}$/,cI=/^[0-9a-z]+$/,lI=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,uI=/^[0-9a-vA-V]{20}$/,dI=/^[A-Za-z0-9]{27}$/,pI=/^[a-zA-Z0-9_-]{21}$/,fI=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var mI=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,fx=n=>n?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${n}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/;var hI=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var mq="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function gI(){return new RegExp(mq,"u")}var yI=/^(?:(?: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])$/,bI=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,SI=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,xI=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,_I=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,mx=/^[A-Za-z0-9_-]*$/,wI=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;var vI=/^\+(?:[0-9]){6,14}[0-9]$/,RI="(?:(?:\\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])))",EI=new RegExp(`^${RI}$`);function kI(n){let e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof n.precision=="number"?n.precision===-1?`${e}`:n.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${n.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function TI(n){return new RegExp(`^${kI(n)}$`)}function PI(n){let e=kI({precision:n.precision}),t=["Z"];n.local&&t.push(""),n.offset&&t.push("([+-]\\d{2}:\\d{2})");let r=`${e}(?:${t.join("|")})`;return new RegExp(`^${RI}T(?:${r})$`)}var CI=n=>{let e=n?`[\\s\\S]{${n?.minimum??0},${n?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)};var II=/^\d+$/,AI=/^-?\d+(?:\.\d+)?/i,NI=/true|false/i,MI=/null/i;var FI=/^[^A-Z]*$/,DI=/^[^a-z]*$/;var sr=Y("$ZodCheck",(n,e)=>{var t;n._zod??(n._zod={}),n._zod.def=e,(t=n._zod).onattach??(t.onattach=[])}),OI={number:"number",bigint:"bigint",object:"date"},hx=Y("$ZodCheckLessThan",(n,e)=>{sr.init(n,e);let t=OI[typeof e.value];n._zod.onattach.push(r=>{let s=r._zod.bag,i=(e.inclusive?s.maximum:s.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<i&&(e.inclusive?s.maximum=e.value:s.exclusiveMaximum=e.value)}),n._zod.check=r=>{(e.inclusive?r.value<=e.value:r.value<e.value)||r.issues.push({origin:t,code:"too_big",maximum:e.value,input:r.value,inclusive:e.inclusive,inst:n,continue:!e.abort})}}),gx=Y("$ZodCheckGreaterThan",(n,e)=>{sr.init(n,e);let t=OI[typeof e.value];n._zod.onattach.push(r=>{let s=r._zod.bag,i=(e.inclusive?s.minimum:s.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>i&&(e.inclusive?s.minimum=e.value:s.exclusiveMinimum=e.value)}),n._zod.check=r=>{(e.inclusive?r.value>=e.value:r.value>e.value)||r.issues.push({origin:t,code:"too_small",minimum:e.value,input:r.value,inclusive:e.inclusive,inst:n,continue:!e.abort})}}),$I=Y("$ZodCheckMultipleOf",(n,e)=>{sr.init(n,e),n._zod.onattach.push(t=>{var r;(r=t._zod.bag).multipleOf??(r.multipleOf=e.value)}),n._zod.check=t=>{if(typeof t.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof t.value=="bigint"?t.value%e.value===BigInt(0):QS(t.value,e.value)===0)||t.issues.push({origin:typeof t.value,code:"not_multiple_of",divisor:e.value,input:t.value,inst:n,continue:!e.abort})}}),jI=Y("$ZodCheckNumberFormat",(n,e)=>{sr.init(n,e),e.format=e.format||"float64";let t=e.format?.includes("int"),r=t?"int":"number",[s,i]=rx[e.format];n._zod.onattach.push(o=>{let a=o._zod.bag;a.format=e.format,a.minimum=s,a.maximum=i,t&&(a.pattern=II)}),n._zod.check=o=>{let a=o.value;if(t){if(!Number.isInteger(a)){o.issues.push({expected:r,format:e.format,code:"invalid_type",input:a,inst:n});return}if(!Number.isSafeInteger(a)){a>0?o.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:n,origin:r,continue:!e.abort}):o.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:n,origin:r,continue:!e.abort});return}}a<s&&o.issues.push({origin:"number",input:a,code:"too_small",minimum:s,inclusive:!0,inst:n,continue:!e.abort}),a>i&&o.issues.push({origin:"number",input:a,code:"too_big",maximum:i,inst:n})}});var LI=Y("$ZodCheckMaxLength",(n,e)=>{var t;sr.init(n,e),(t=n._zod.def).when??(t.when=r=>{let s=r.value;return!Ad(s)&&s.length!==void 0}),n._zod.onattach.push(r=>{let s=r._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<s&&(r._zod.bag.maximum=e.maximum)}),n._zod.check=r=>{let s=r.value;if(s.length<=e.maximum)return;let o=Md(s);r.issues.push({origin:o,code:"too_big",maximum:e.maximum,inclusive:!0,input:s,inst:n,continue:!e.abort})}}),zI=Y("$ZodCheckMinLength",(n,e)=>{var t;sr.init(n,e),(t=n._zod.def).when??(t.when=r=>{let s=r.value;return!Ad(s)&&s.length!==void 0}),n._zod.onattach.push(r=>{let s=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>s&&(r._zod.bag.minimum=e.minimum)}),n._zod.check=r=>{let s=r.value;if(s.length>=e.minimum)return;let o=Md(s);r.issues.push({origin:o,code:"too_small",minimum:e.minimum,inclusive:!0,input:s,inst:n,continue:!e.abort})}}),BI=Y("$ZodCheckLengthEquals",(n,e)=>{var t;sr.init(n,e),(t=n._zod.def).when??(t.when=r=>{let s=r.value;return!Ad(s)&&s.length!==void 0}),n._zod.onattach.push(r=>{let s=r._zod.bag;s.minimum=e.length,s.maximum=e.length,s.length=e.length}),n._zod.check=r=>{let s=r.value,i=s.length;if(i===e.length)return;let o=Md(s),a=i>e.length;r.issues.push({origin:o,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:r.value,inst:n,continue:!e.abort})}}),Dd=Y("$ZodCheckStringFormat",(n,e)=>{var t,r;sr.init(n,e),n._zod.onattach.push(s=>{let i=s._zod.bag;i.format=e.format,e.pattern&&(i.patterns??(i.patterns=new Set),i.patterns.add(e.pattern))}),e.pattern?(t=n._zod).check??(t.check=s=>{e.pattern.lastIndex=0,!e.pattern.test(s.value)&&s.issues.push({origin:"string",code:"invalid_format",format:e.format,input:s.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:n,continue:!e.abort})}):(r=n._zod).check??(r.check=()=>{})}),qI=Y("$ZodCheckRegex",(n,e)=>{Dd.init(n,e),n._zod.check=t=>{e.pattern.lastIndex=0,!e.pattern.test(t.value)&&t.issues.push({origin:"string",code:"invalid_format",format:"regex",input:t.value,pattern:e.pattern.toString(),inst:n,continue:!e.abort})}}),HI=Y("$ZodCheckLowerCase",(n,e)=>{e.pattern??(e.pattern=FI),Dd.init(n,e)}),WI=Y("$ZodCheckUpperCase",(n,e)=>{e.pattern??(e.pattern=DI),Dd.init(n,e)}),UI=Y("$ZodCheckIncludes",(n,e)=>{sr.init(n,e);let t=Ro(e.includes),r=new RegExp(typeof e.position=="number"?`^.{${e.position}}${t}`:t);e.pattern=r,n._zod.onattach.push(s=>{let i=s._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(r)}),n._zod.check=s=>{s.value.includes(e.includes,e.position)||s.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:s.value,inst:n,continue:!e.abort})}}),KI=Y("$ZodCheckStartsWith",(n,e)=>{sr.init(n,e);let t=new RegExp(`^${Ro(e.prefix)}.*`);e.pattern??(e.pattern=t),n._zod.onattach.push(r=>{let s=r._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(t)}),n._zod.check=r=>{r.value.startsWith(e.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:r.value,inst:n,continue:!e.abort})}}),ZI=Y("$ZodCheckEndsWith",(n,e)=>{sr.init(n,e);let t=new RegExp(`.*${Ro(e.suffix)}$`);e.pattern??(e.pattern=t),n._zod.onattach.push(r=>{let s=r._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(t)}),n._zod.check=r=>{r.value.endsWith(e.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:r.value,inst:n,continue:!e.abort})}});var GI=Y("$ZodCheckOverwrite",(n,e)=>{sr.init(n,e),n._zod.check=t=>{t.value=e.tx(t.value)}});var th=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let r=e.split(`
|
|
868
|
+
`);try{let Z=require("fs"),ae=require("path").resolve(__dirname,"..","..","mcp-pando-server","resources","messages.json");if(Z.existsSync(ae)){let he=JSON.parse(Z.readFileSync(ae,"utf8"))?.read_this_first;typeof he=="string"&&he.trim().length>0&&(q=he)}}catch{}W={success:!0,help:{title:"read_this_first",body:q}};break}case"insert":{let{InsertCodeExecutor:X}=await Promise.resolve().then(()=>(Yu(),$P)),q=s==="add-code"?{...e,op:"insert"}:e;W=await X.execute(q,t,this.project);break}case"workspace-overview":W=await Pf.execute(e,t,this.project);break;case"list-exports":W=Cf.execute(e,t,this.project);break;case"analyze-imports":W=If.execute(e,t,this.project);break;case"clojure-namespace-graph":W=Af.execute(e,t,this.project);break;case"clojure-namespace-dependencies":W=_u.executeDependencies(e,t,this.project);break;case"clojure-namespace-dependents":W=_u.executeDependents(e,t,this.project);break;case"plan-clojure-namespace-move":W=wu.executeMove(e,t,this.project);break;case"plan-clojure-namespace-rename":W=wu.executeRename(e,t,this.project);break;case"move-clojure-namespace":W=await vu.executeMove(e,t,this.project);break;case"rename-clojure-namespace":W=await vu.executeRename(e,t,this.project);break;case"get-db-schema":W=Ru.execute(e,t,this.project);break;case"query-db":W=await Nf.execute(e,t,this.project);break;case"delete":W=await yo.execute(e,t,this.project);break;case"find-references":W=await xa.execute(e,t,this.project);break;case"find-callers":W=await Xu.execute(e,t,this.project);break;case"rename":W=await So.execute(e,t,this.project);break;case"filter-map-reduce":{let{FilterMapReduceExecutor:X}=await Promise.resolve().then(()=>(nS(),jP));W=await X.execute(e,t,this.project);break}case"replace":{let X=s==="replace-body"?{...e,op:"replace",scope:"body"}:e;if(X.scope==="body"){let{ReplaceBodyExecutor:q}=await Promise.resolve().then(()=>(nd(),wm));W=await q.execute(X,t,this.project)}else{let{ReplaceNodeExecutor:q}=await Promise.resolve().then(()=>(sd(),vm));W=await q.execute(X,t,this.project)}break}case"edit-file-text":{let{TextFileEditExecutor:X}=await Promise.resolve().then(()=>(RC(),vC));W=await X.execute(e,t);break}case"add-exclude-dir":W=await this.handleAddExcludeDir(e);break;case"remove-exclude-dir":W=await this.handleRemoveExcludeDir(e);break;case"set-enabled-languages":W=await this.handleSetEnabledLanguages(e);break;case"list-snapshots":W=is.listSnapshots(e,t,this.project);break;case"diff-snapshots":W=is.diffSnapshots(e,t,this.project);break;case"get-snapshot-file":W=await is.getSnapshotFile(e,t,this.project);break;case"get-snapshot-trailers":W=is.getSnapshotTrailers(e,t,this.project);break;case"snapshot-worktree":W=await this.handleSnapshotWorktree(e,r);break;case"repair-history":W=await is.repairShadowHistory(e,t,this.project);break;case"restore-snapshot":W=await is.restoreSnapshot(e,t,this.project);break;case"restore-files":W=await is.restoreFiles(e,t,this.project);break;case"change-signature":V("[OperationDispatch] entering ChangeSignatureExecutor",{op:i,targetPath:e?.path??null}),W=await Cm.execute(e,t,this.project);break;case"get-project-root":W=this.handleGetProjectRoot();break;default:try{let{AtomicExecutor:X}=await Promise.resolve().then(()=>(TC(),kC));W=await X.execute(e,t,this.project,this)}catch{W={success:!1,error:`Operation ${e.op} not implemented`}}}V("[OperationDispatch] executor returned",{op:i,success:!!W?.success,error:W?.error??null,errorCode:W?.error_code??null,changedFiles:Array.isArray(W?.details?.changedFiles)?W.details.changedFiles.length:null,allChangedFiles:Array.isArray(W?.details?.allChangedFiles)?W.details.allChangedFiles.length:null});let me=Date.now(),_e={executorMs:Math.max(0,me-m)},Se=String(i||"").toLowerCase()==="delete"||!!e?.forceMayBreakSyntax;if(u&&W&&!W.success&&!pe&&!re(e)){let X=W.error_code;if((X==="would_introduce_syntax_error"||X==="validation_failed"||X==="io_write_failed")&&Ee){let Z=Array.isArray(W.details?.changedFiles)?W.details.changedFiles:[];if(Z.length>0)try{await is.restoreSnapshot({op:"restore-snapshot",snapshotId:Ee,shouldCreateNewSnapshot:!1,restrictToPaths:Z},t,this.project),W.details=W.details||{},W.details.rollbackAttempted=!0,W.details.snapshotBefore=Ee}catch{}}}if(u&&W&&W.success&&!pe&&!d){try{let X=Array.isArray(W.details?.allChangedFiles)?W.details.allChangedFiles:Array.isArray(W.details?.changedFiles)?W.details.changedFiles:[],q=Array.isArray(W.details?.deletedFiles)?W.details.deletedFiles:[];if((!X||X.length===0)&&(!q||q.length===0))return V("[OperationDispatch] skipping snapshot because no files changed",{op:i}),M(W);let Z=W.details?.receipt||{op:i,target:e.path||e.to||e.of,timestamp:Date.now(),changedFilesCount:X.length},{SnapshotService:se}=(vS(),be(wS)),{SnapshotStatusTracker:ae}=(ra(),be(na)),Fe=Date.now();V("[SnapshotService] Starting snapshot",{files:X.length,deleted:q.length});try{ae.getInstance(this.projectPath).start(X.length,q.length)}catch{}let he=W.details&&W.details.trailers?W.details.trailers:void 0,{snapshotId:Ke,parentId:Ze}=await se.takeSnapshotNow(this.projectPath,X,i,Z,he,q,r);_e.snapshotMs=Date.now()-Fe,V("[SnapshotService] Snapshot finished",{durationMs:_e.snapshotMs,snapshotId:Ke});try{ae.getInstance(this.projectPath).complete()}catch{}if(W.snapshotBefore=Ze||"<none>",W.snapshotAfter=Ke,W.details||(W.details={}),W.details.receipt=Z,W.details&&W.details.trailers){let Ye=W.details.trailers,Dt={};for(let ke of Object.keys(Ye)){let rt=String(Ye[ke]??"");Dt[ke]=rt.length>200?rt.slice(0,200):rt}delete W.details.trailers,W.details.trailersPreview=Dt,W.details.trailersNote="Trailers truncated to 200 chars. Use list-snapshots/get-snapshot-trailers to fetch full trailers."}}catch(X){return V("[OperationDispatch] snapshot finalization failed",{op:i,error:X?.message||String(X)}),M({success:!1,error:`Snapshot failure: ${X?.message||X}`})}if(!Se&&!p){let X=Array.isArray(W.details?.allChangedFiles)?W.details.allChangedFiles:Array.isArray(W.details?.changedFiles)?W.details.changedFiles:[];if(X.length>0){let q=Date.now(),Z=await this.validateChangedFiles(t,X,O);if(_e.validationMs=Date.now()-q,Z.skipped&&Z.warning&&(W.warnings=Array.isArray(W.warnings)?[...W.warnings,Z.warning]:[Z.warning]),!Z.ok){let se=W.snapshotBefore,ae=W.snapshotAfter;if(se&&ae&&ae!=="<none>")try{await is.restoreSnapshot({op:"restore-snapshot",snapshotId:se,shouldCreateNewSnapshot:!1,deleteSnapshotId:ae,restrictToPaths:X},t,this.project)}catch{}return M({success:!1,error:Z.error||"Post-operation validation failed; changes rolled back.",details:{validation:Z,snapshotBefore:se,snapshotAfter:ae,rollbackAttempted:!0}})}}}}u&&(W?.success?this.recordRestoreFastPathState(i,W):this.invalidateRestoreFastPathState("modifying-op-failed",{op:i??null,error:W?.error??null}));try{if(u&&W&&!pe){let X=Date.now(),q=require("path"),Z=Array.isArray(W.details?.allChangedFiles)?W.details.allChangedFiles:Array.isArray(W.details?.changedFiles)?W.details.changedFiles:[],se=Array.isArray(W.details?.createdFiles)?W.details.createdFiles:[],ae=Array.isArray(W.details?.deletedFiles)?W.details.deletedFiles:[],Fe=ke=>q.isAbsolute(ke)?ke:q.join(this.projectPath,ke),he=ke=>Array.from(new Set(ke.filter(Boolean))),Ke=he(se.map(Fe)),Ze=new Set(Ke),Ye=he(Z.map(Fe)).filter(ke=>!Ze.has(ke)),Dt=he(ae.map(Fe));(Ye.length>0||Dt.length>0||Ke.length>0)&&this.scheduleProjectSync({created:Ke,modified:Ye,deleted:Dt},`${String(i||s||"unknown")} post-write sync`).catch(ke=>{An("[RefreshFromDisk] post-op refresh failed",ke?.message||ke)}),_e.syncEnqueueMs=Date.now()-X}}catch(X){An("[RefreshFromDisk] post-op refresh failed",X?.message||X)}return V("[OperationDispatch] post-execution complete",{op:i,success:!!W?.success,totalElapsedMs:Math.max(0,Date.now()-m),postExecutionMs:Math.max(0,Date.now()-me),timings:_e,changedFiles:Array.isArray(W?.details?.changedFiles)?W.details.changedFiles.length:null,allChangedFiles:Array.isArray(W?.details?.allChangedFiles)?W.details.allChangedFiles.length:null}),M(W)}finally{V("[OperationGate] releasing modifying op lock",{op:i??null,activeOp:this.modifyingOpName||null}),C()}}async refreshFilesFromDisk(e,t){let r=require("fs"),s=require("path"),i=a=>{try{return s.relative(this.projectPath,a).replace(/\\/g,"/")}catch{return a}};if(e=this.filterExcludedAbsolutePaths(e),!e.length)return;ct(t,"Workspace sync refresh cancelled"),this.refreshingInProgress=!0,this.refreshingFiles=e.map(i);let o=Date.now();try{for(let a of e){ct(t,"Workspace sync refresh cancelled");try{let c=r.existsSync(a),l=this.project.getSourceFile(a);if(!c){l&&this.project.removeSourceFile(l);continue}(l||this.project.addSourceFileAtPath(a)).refreshFromFileSystemSync()}catch(c){An("[RefreshFromDisk] Failed for",a,c?.message||c)}}}finally{let a=Date.now()-o;Nn("code-engine.refreshFilesFromDisk.complete",{projectRoot:this.projectPath,files:e.length,sample:e.slice(0,20).map(i),elapsedMs:a}),V("[RefreshFromDisk] Completed",{files:e.length,ms:a}),this.refreshingInProgress=!1,this.refreshingFiles=[]}}scheduleProjectSync(e,t){let r=`project-sync:${Date.now().toString(36)}:${Math.random().toString(36).slice(2,8)}`,s=Date.now(),i=this.workspaceSyncController.signal;V("[ProjectSync] enqueue",{syncId:r,reason:t,created:e.created.length,modified:e.modified.length,deleted:e.deleted.length,hadPending:!!this.pendingProjectSync,pendingSyncId:this.pendingProjectSyncId??null,pendingReason:this.pendingProjectSyncReason??null});let o=async()=>{let l=Date.now();V("[ProjectSync] begin",{syncId:r,reason:t,queueWaitMs:l-s,created:e.created.length,modified:e.modified.length,deleted:e.deleted.length});try{if(await this.handleBatchFileChanges(e,{signal:i,source:"post-write-sync"}),i.aborted){V("[ProjectSync] superseded",{syncId:r,reason:t,durationMs:Date.now()-l,totalMs:Date.now()-s});return}V("[ProjectSync] complete",{syncId:r,reason:t,durationMs:Date.now()-l,totalMs:Date.now()-s})}catch(u){if(Mi(u)||i.aborted){V("[ProjectSync] superseded",{syncId:r,reason:t,durationMs:Date.now()-l,totalMs:Date.now()-s,message:u?.message||String(u)});return}throw V("[ProjectSync] failed",{syncId:r,reason:t,durationMs:Date.now()-l,totalMs:Date.now()-s,message:u?.message||String(u)}),u}},a=(this.pendingProjectSync??Promise.resolve()).catch(l=>{if(Mi(l)){V("[ProjectSync] previous queued refresh superseded",{syncId:r,reason:t,message:l?.message||String(l)});return}An("[ProjectSync] previous queued refresh failed",l?.message||l)}).then(o),c=Symbol(r);return this.pendingProjectSyncToken=c,this.pendingProjectSyncId=r,this.pendingProjectSyncEnqueuedAt=s,this.pendingProjectSyncReason=t,this.pendingProjectSync=a.finally(()=>{this.clearPendingProjectSyncState(c)}),this.pendingProjectSync}async awaitPendingProjectSync(e){let t=this.pendingProjectSync;if(!t)return;let r=Date.now();V("[ProjectSync] awaiting queued refresh before operation",{syncId:this.pendingProjectSyncId??null,operation:e??null,reason:this.pendingProjectSyncReason??null,queuedForMs:this.pendingProjectSyncEnqueuedAt?r-this.pendingProjectSyncEnqueuedAt:null});let s=setInterval(()=>{V("[ProjectSync] waiting",{syncId:this.pendingProjectSyncId??null,operation:e??null,reason:this.pendingProjectSyncReason??null,queuedForMs:this.pendingProjectSyncEnqueuedAt?Date.now()-this.pendingProjectSyncEnqueuedAt:null,waitedMs:Date.now()-r})},n.PROJECT_SYNC_HEARTBEAT_MS);s.unref?.();try{await t,V("[ProjectSync] awaited queued refresh complete",{syncId:this.pendingProjectSyncId??null,operation:e??null,reason:this.pendingProjectSyncReason??null,waitedMs:Date.now()-r})}finally{clearInterval(s)}}async awaitPostWriteWorkSettled(e="external"){let t=Date.now();V("[PostWriteDrain] begin",{reason:e,pendingProjectSync:!!this.pendingProjectSync,pendingProjectSyncId:this.pendingProjectSyncId??null,batchRunner:!!this.batchRunner,batchInProgress:this.batchInProgress,refreshingInProgress:this.refreshingInProgress});let r=setInterval(()=>{V("[PostWriteDrain] waiting",{reason:e,waitedMs:Date.now()-t,pendingProjectSync:!!this.pendingProjectSync,pendingProjectSyncId:this.pendingProjectSyncId??null,pendingProjectSyncReason:this.pendingProjectSyncReason??null,batchRunner:!!this.batchRunner,batchInProgress:this.batchInProgress,refreshingInProgress:this.refreshingInProgress,queuedBatch:this.describeQueuedBatch()})},n.PROJECT_SYNC_HEARTBEAT_MS);r.unref?.();try{for(;;){let s=this.pendingProjectSync;if(s){await s;continue}let i=this.batchRunner;if(i){await i;continue}if(!this.batchInProgress&&!this.refreshingInProgress&&!this.queuedBatch)break;await new Promise(o=>setTimeout(o,25))}}finally{clearInterval(r),V("[PostWriteDrain] complete",{reason:e,waitedMs:Date.now()-t,pendingProjectSync:!!this.pendingProjectSync,batchRunner:!!this.batchRunner,batchInProgress:this.batchInProgress,refreshingInProgress:this.refreshingInProgress})}}scheduleLspWorkspaceSync(e,t){let r=this.lspHost,s=r?.workspaceFilesChanged?.bind(r),i=e.created.length+e.modified.length+e.deleted.length;if(!s||i===0)return Nn("code-engine.batch.workspaceFilesChanged.skipped",{projectRoot:this.projectPath,created:e.created.length,modified:e.modified.length,deleted:e.deleted.length,reason:s?"empty-batch":"no-lsp-host"}),Promise.resolve();Nn("code-engine.batch.workspaceFilesChanged.scheduled",{projectRoot:this.projectPath,created:e.created.length,modified:e.modified.length,deleted:e.deleted.length,reason:t});let o=async()=>{let c=Date.now();Nn("code-engine.batch.workspaceFilesChanged.start",{projectRoot:this.projectPath,created:e.created.length,modified:e.modified.length,deleted:e.deleted.length,createdSample:e.created.slice(0,20),modifiedSample:e.modified.slice(0,20),deletedSample:e.deleted.slice(0,20),reason:t});try{await s(e),Nn("code-engine.batch.workspaceFilesChanged.complete",{projectRoot:this.projectPath,created:e.created.length,modified:e.modified.length,deleted:e.deleted.length,elapsedMs:Date.now()-c,reason:t})}catch(l){Nn("code-engine.batch.workspaceFilesChanged.failed",{projectRoot:this.projectPath,created:e.created.length,modified:e.modified.length,deleted:e.deleted.length,elapsedMs:Date.now()-c,error:l?.message||String(l),reason:t}),An("[LspWorkspaceSync] workspaceFilesChanged failed",l?.message||l)}},a=(this.pendingLspWorkspaceSync??Promise.resolve()).catch(c=>{An("[LspWorkspaceSync] previous queued sync failed",c?.message||c)}).then(o);return this.pendingLspWorkspaceSync=a.finally(()=>{this.pendingLspWorkspaceSync===a&&(this.pendingLspWorkspaceSync=null)}),this.pendingLspWorkspaceSync}withSnapshotReceipt(e,t,r){return{...r}}async handleBatchFileChanges(e,t){let r=t?.source??"external",s=t?.signal??this.workspaceSyncController.signal;if(V("batch-change event",{created:e.created.length,modified:e.modified.length,deleted:e.deleted.length,source:r,signalAborted:s.aborted}),e.created.length+e.modified.length+e.deleted.length===0)return;if(r!=="post-write-sync"&&this.invalidateRestoreFastPathState("batch-change",{source:r,created:e.created.length,modified:e.modified.length,deleted:e.deleted.length}),s.aborted){V("[BatchQueue] skipped aborted batch",{source:r,created:e.created.length,modified:e.modified.length,deleted:e.deleted.length});return}let o={created:e.created.map(as),modified:e.modified.map(as),deleted:e.deleted.map(as)};Nn("code-engine.batch.enqueue",{projectRoot:this.projectPath,created:o.created.length,modified:o.modified.length,deleted:o.deleted.length,createdSample:o.created.slice(0,20),modifiedSample:o.modified.slice(0,20),deletedSample:o.deleted.slice(0,20)});let a=`${ft(this.projectPath)}/`,c=o.deleted.find(u=>u.startsWith(a)&&u.endsWith(".db"));if(c&&!this.indexingInProgress){V("\u{1F504} Index DB deleted; triggering full reindex...",{file:c}),await this.startIndexing();return}let l=this.mergeQueuedBatch(o,r);V("[BatchQueue] enqueue",{incoming:{created:o.created.length,modified:o.modified.length,deleted:o.deleted.length},source:r,queued:l,indexingInProgress:this.indexingInProgress,batchInProgress:this.batchInProgress,runnerActive:!!this.batchRunner}),!this.indexingInProgress&&await this.ensureBatchRunner()}}});var nc=B(require("path"));ny();ms();It();var cd=class{constructor(e){this.options=e;this.workspaceRoots=new Set;this.explicitProjectRoot=null;this.registeredRoots=new Set}getWorkspaceRoots(){return Array.from(this.workspaceRoots).sort((e,t)=>e.localeCompare(t))}getExplicitProjectRoot(){return this.explicitProjectRoot}getRegisteredRoots(){return Array.from(this.registeredRoots).sort((e,t)=>e.localeCompare(t))}async setWorkspaceRoots(e,t){return this.workspaceRoots=new Set(e.map(r=>this.options.normalizeRoot(r)).filter(r=>!!r)),this.refreshEffectiveRoots(t)}async setProjectRoot(e,t){let r=Date.now();ee("ProjectRootManager","setProjectRoot begin",{rootOrPath:e,currentExplicitRoot:this.explicitProjectRoot,opts:t});let s=this.options.normalizeRoot(e);if(!s)return ee("ProjectRootManager","setProjectRoot normalized to null",{rootOrPath:e,elapsedMs:Date.now()-r}),null;let i=this.options.resolveIndexRoot(s);return i?this.explicitProjectRoot===i?(ee("ProjectRootManager","setProjectRoot no-op",{rootOrPath:e,resolvedInput:s,targetDir:i,elapsedMs:Date.now()-r}),i):(this.explicitProjectRoot=i,await this.refreshEffectiveRoots(t),ee("ProjectRootManager","setProjectRoot complete",{rootOrPath:e,resolvedInput:s,targetDir:i,registeredRoots:this.getRegisteredRoots(),elapsedMs:Date.now()-r}),i):(ee("ProjectRootManager","setProjectRoot resolveIndexRoot returned null",{rootOrPath:e,resolvedInput:s,elapsedMs:Date.now()-r}),null)}async refreshEffectiveRoots(e){let t=Date.now(),r=this.explicitProjectRoot?new Set([this.explicitProjectRoot]):new Set(this.workspaceRoots),s=new Set(this.registeredRoots),i=[];ee("ProjectRootManager","refreshEffectiveRoots begin",{effective:Array.from(r),registeredBefore:Array.from(s),opts:e});for(let o of r){if(this.registeredRoots.has(o))continue;let a=Date.now(),c=await this.options.registerRoot(o);ee("ProjectRootManager","refreshEffectiveRoots registerRoot resolved",{requestedRoot:o,registered:c,elapsedMs:Date.now()-a}),c&&(this.registeredRoots.add(c),i.push(c))}for(let o of s)r.has(o)||(this.options.disposeRoot(o),this.registeredRoots.delete(o));if(e?.indexNewRoots&&this.options.startIndexingForRoot)for(let o of i)ee("ProjectRootManager","refreshEffectiveRoots startIndexingForRoot dispatch",{root:o}),this.options.startIndexingForRoot(o);return ee("ProjectRootManager","refreshEffectiveRoots complete",{newlyRegistered:i,finalRoots:this.getRegisteredRoots(),elapsedMs:Date.now()-t}),{newlyRegistered:i,finalRoots:this.getRegisteredRoots()}}};ms();Wo();zn();uu();Yo();var CS=5e4,KB=1*1024*1024;function jm(n,e){let t=typeof e?.limit=="number"&&Number.isFinite(e.limit)?Math.max(1,Math.trunc(e.limit)):CS,r=e?.languageSupport,s=Hs(n),i=su(r),o=Kr(n,s),a=nk(n,i,{shouldExclude:o,maxFileBytes:KB,limit:t});return{root:n,candidateIndexableFiles:a.count,limit:t,exceeded:a.limitExceeded}}function CC(n){let e=n.exceeded?"at least":"exactly";return new Error(`Refusing to index '${n.root}': candidate_indexable_files is ${e} ${n.candidateIndexableFiles}, above the limit of ${n.limit}. Choose a narrower root or add excludes before retrying.`)}_n();It();var ld=class n{constructor(e,t){this.options=t;this.indexingSuppressedRoots=new Set;this.rootManager=new cd({normalizeRoot:r=>{let s=r.trim();return s?en(s):null},resolveIndexRoot:r=>r,registerRoot:async r=>{let s=Date.now();ee("DirectProjectRootManager","registerRoot begin",{root:r,hasOptions:!!this.options});let i=this.getOptionsForRoot(r);return i&&wn.setEngineOptions(r,i),wn.getEngine(r,i),ee("DirectProjectRootManager","registerRoot complete",{root:r,elapsedMs:Date.now()-s}),r},disposeRoot:r=>{ee("DirectProjectRootManager","disposeRoot",{root:r}),wn.clearEngine(r)},startIndexingForRoot:async r=>{let s=Date.now();if(ee("DirectProjectRootManager","startIndexingForRoot begin",{root:r}),this.indexingSuppressedRoots.has(en(r))){ee("DirectProjectRootManager","startIndexingForRoot skipped (root over indexing limit)",{root:r});return}let i=wn.getEngine(r,this.getOptionsForRoot(r));typeof i?.startIndexing=="function"&&await i.startIndexing(),ee("DirectProjectRootManager","startIndexingForRoot dispatched",{root:r,elapsedMs:Date.now()-s})}}),this.initialRoot=e}static async create(e,t){let r=new n(e,t);return await r.validateProjectRoot(e),await r.rootManager.setWorkspaceRoots([e]),r}getProjectRoot(){let e=this.rootManager.getExplicitProjectRoot();return e||(this.rootManager.getRegisteredRoots()[0]??null)}getEngine(){let e=this.getProjectRoot();if(!e)throw new Error("No project root configured.");return wn.getEngine(e,this.getOptionsForRoot(e))}async validateProjectRoot(e){let t=e.trim();if(!t)return null;let r=en(t),s=jm(r,{languageSupport:this.getOptionsForRoot(r)?.languageSupport,limit:this.indexingLimitOverride});if(s.exceeded){this.indexingSuppressedRoots.add(r);let i=CC(s).message;ee("DirectProjectRootManager","validateProjectRoot indexing suppressed",{root:r,candidateIndexableFiles:s.candidateIndexableFiles,limit:s.limit,reason:i})}else this.indexingSuppressedRoots.delete(r);return r}isIndexingSuppressed(e){return this.indexingSuppressedRoots.has(en(e))}setIndexingLimitOverrideForTesting(e){this.indexingLimitOverride=e}async setProjectRoot(e){let t=Date.now();ee("DirectProjectRootManager","setProjectRoot begin",{root:e}),await this.validateProjectRoot(e);let r=await this.rootManager.setProjectRoot(e,{indexNewRoots:!0});return ee("DirectProjectRootManager","setProjectRoot complete",{root:e,resolved:r,elapsedMs:Date.now()-t}),r}updateRootOptions(e,t){let r=en(e),s=t??this.getOptionsForRoot(r);s&&wn.setEngineOptions(r,s)}getOptionsForRoot(e){let t=en(e),r=this.options?.languageSupport??Ho(t),s=this.options?.lspHost;if(!(!r&&!s))return{...r?{languageSupport:r}:{},...s?{lspHost:s}:{}}}};bi();Mf();Wo();zn();Ws();Js();var ZB=B(require("fs")),GB=B(require("path"));$f();var OC=require("events");Mf();$f();zn();Wo();ms();_n();var MC=require("child_process");ms();ur();It();var IS=require("child_process"),Ma=null,ud=null;async function AC(n){return Ma||ud||(ud=Promise.resolve().then(()=>{let e=IC();if(e.available)return Ma=e,e;let t=VB(),r=e.error;for(let s of t){n?.(`[NodeFileWatcher] watchman missing; trying install via ${s.label}`);let i=JB(s),o=IC();if(o.available)return Ma={available:!0,version:o.version,installAttempted:!0,installSucceeded:!0,installMethod:s.label},Ma;r=i.error??o.error??r}return Ma={available:!1,installAttempted:t.length>0,installSucceeded:!1,error:r},Ma}).finally(()=>{ud=null}),ud)}function IC(){let n=(0,IS.spawnSync)("watchman",["--version"],{encoding:"utf8",stdio:"pipe",shell:process.platform==="win32"});return n.status===0?{available:!0,version:`${n.stdout||n.stderr||""}`.trim()||void 0,installAttempted:!1,installSucceeded:!1}:{available:!1,installAttempted:!1,installSucceeded:!1,error:NC(n.error,n.stderr,n.stdout)}}function JB(n){for(let e of n.steps){let t=(0,IS.spawnSync)(e.cmd,e.args,{encoding:"utf8",stdio:"pipe",shell:process.platform==="win32"});if(t.status!==0)return{ok:!1,error:NC(t.error,t.stderr,t.stdout)}}return{ok:!0}}function VB(){let n=typeof process.getuid=="function"?process.getuid()===0:!1,e=(t,r)=>n?{cmd:t,args:r}:{cmd:"sudo",args:["-n",t,...r]};switch(process.platform){case"darwin":return[{label:"homebrew",steps:[{cmd:"brew",args:["install","watchman"]}]},{label:"macports",steps:[e("port",["install","watchman"])]}];case"linux":return[{label:"homebrew",steps:[{cmd:"brew",args:["install","watchman"]}]},{label:"apt",steps:[e("apt-get",["update"]),e("apt-get",["install","-y","watchman"])]},{label:"dnf",steps:[e("dnf",["install","-y","watchman"])]},{label:"pacman",steps:[e("pacman",["-S","--noconfirm","watchman"])]}];case"win32":return[{label:"chocolatey",steps:[{cmd:"choco",args:["install","watchman","-y"]}]},{label:"winget",steps:[{cmd:"winget",args:["install","--id","Facebook.Watchman","-e"]}]}];default:return[]}}function NC(n,e,t){if(n instanceof Error&&n.message)return n.message;let r=`${e??""}`.trim();return r||`${t??""}`.trim()||void 0}function Mn(n,e){if(!Ht())return;let t=e&&typeof e=="object"&&!Array.isArray(e)?{pid:process.pid,...e}:{pid:process.pid,details:e};ee("WatcherTrace",n,t)}var Lm=class{constructor(e){this.log=e;this.projectRoot=null;this.languageSupport=null;this.watcherChild=null;this.watcherGeneration=0;this.shutdownGraceMs=1e3;this.switchChain=Promise.resolve()}async activate(e,t){this.languageSupport=t,await this.updateProjectRoot(e,t)}async updateProjectRoot(e,t){if(t&&(this.languageSupport=t),!e||!this.languageSupport||e===this.projectRoot&&!t)return;let r=this.languageSupport,s=this.switchChain.catch(()=>{}).then(async()=>{let i=this.projectRoot,o=this.watcherChild,a=this.watcherGeneration+1;this.log(`[NodeFileWatcher] updateProjectRoot begin from=${i??"null"} to=${e}`),Mn("node-watcher.updateProjectRoot.begin",{fromRoot:i,toRoot:e,previousGeneration:o?.generation??null,hasWatcher:!!o}),o&&(Mn("node-watcher.updateProjectRoot.await-previous-exit",{fromRoot:i,toRoot:e,previousGeneration:o.generation,childPid:o.process.pid??null}),await this.shutdownChild(o,"root-switch"));let c=await AC(this.log);Mn("node-watcher.watchman.status",{root:e,generation:a,available:c.available,version:c.version,installAttempted:c.installAttempted,installSucceeded:c.installSucceeded,installMethod:c.installMethod,error:c.error});let l=this.spawnWatcherChild(e,r,a,c);this.projectRoot=e,this.watcherChild=l,this.watcherGeneration=a,Mn("node-watcher.updateProjectRoot.complete",{fromRoot:i,toRoot:e,generation:a,childPid:l.process.pid??null,scriptPath:l.scriptPath})});this.switchChain=s,await s}async dispose(){let e=this.switchChain.catch(()=>{}).then(async()=>{let t=this.watcherChild,r=this.projectRoot,s=this.watcherGeneration;this.projectRoot=null,this.watcherChild=null,t&&(Mn("node-watcher.dispose",{root:r,generation:s,childPid:t.process.pid??null}),await this.shutdownChild(t,"dispose"))});this.switchChain=e,await e}spawnWatcherChild(e,t,r,s){let i=rE();if(!i)throw new Error("Could not resolve watcher child process script");this.log(`[NodeFileWatcher] activate root=${e}`),Mn("node-watcher.spawn.start",{root:e,generation:r,scriptPath:i});let o=(0,MC.fork)(i,[],{cwd:e,env:{...process.env,PANDO_WATCH_ROOT:e,PANDO_WATCH_GENERATION:String(r),PANDO_WATCH_LANGUAGE_SUPPORT_JSON:JSON.stringify(t),PANDO_WATCH_WATCHMAN_AVAILABLE:s.available?"1":"0",PANDO_WATCH_WATCHMAN_INSTALL_ATTEMPTED:s.installAttempted?"1":"0",PANDO_WATCH_WATCHMAN_INSTALL_SUCCEEDED:s.installSucceeded?"1":"0"},stdio:["ignore","inherit","inherit","ipc"]}),a=()=>{},c=new Promise(u=>{a=u}),l={process:o,root:e,generation:r,scriptPath:i,shutdownTimer:null,shuttingDown:!1,exitPromise:c,resolveExit:a};return o.on("message",u=>{this.handleChildMessage(l,u)}),o.on("exit",(u,d)=>{l.shutdownTimer&&(clearTimeout(l.shutdownTimer),l.shutdownTimer=null),Mn("node-watcher.child.exit",{root:l.root,generation:l.generation,childPid:o.pid??null,code:u,signal:d,shuttingDown:l.shuttingDown}),this.watcherChild===l&&(this.watcherChild=null),l.resolveExit()}),o.on("error",u=>{let d=u instanceof Error?u.message:String(u);this.log(`[NodeFileWatcher] watcher child error root=${e} error=${d}`),Mn("node-watcher.child.error",{root:e,generation:r,childPid:o.pid??null,error:d})}),Mn("node-watcher.spawn.complete",{root:e,generation:r,scriptPath:i,childPid:o.pid??null}),l}async handleChildMessage(e,t){if(!(!t||typeof t!="object"))switch(t.type){case"ready":this.handleReadyMessage(e,t);return;case"error":this.handleErrorMessage(e,t);return;case"batch":await this.handleBatchMessage(e,t);return;default:return}}handleReadyMessage(e,t){if(!this.isActiveChild(e)){Mn("node-watcher.ready.stale",{root:t.root,generation:t.generation,activeRoot:this.projectRoot,activeGeneration:this.watcherGeneration});return}this.log(`[NodeFileWatcher] ready root=${t.root} watchRoots=${t.watchRootCount??0} backend=${t.backendPreference??"native"}`),Mn("node-watcher.ready",{root:t.root,generation:t.generation,childPid:e.process.pid??null,watchRootCount:t.watchRootCount,backendPreference:t.backendPreference,watchmanAvailable:t.watchmanAvailable,watchmanInstallAttempted:t.watchmanInstallAttempted,watchmanInstallSucceeded:t.watchmanInstallSucceeded})}handleErrorMessage(e,t){let r=!this.isActiveChild(e);this.log(`[NodeFileWatcher] watch error path=${t.root} error=${t.error}`),Mn(r?"node-watcher.error.stale":"node-watcher.error",{root:t.root,generation:t.generation,childPid:e.process.pid??null,activeRoot:this.projectRoot,activeGeneration:this.watcherGeneration,error:t.error})}async handleBatchMessage(e,t){if(!this.isActiveChild(e)){Mn("node-watcher.batch.stale",{root:t.root,generation:t.generation,batchId:t.batchId,activeRoot:this.projectRoot,activeGeneration:this.watcherGeneration}),this.sendToChild(e,{type:"batch-ack",batchId:t.batchId,ok:!0});return}let r=wn.getExistingEngine(t.root);if(Mn("node-watcher.batch.start",{root:t.root,generation:t.generation,batchId:t.batchId,childPid:e.process.pid??null,created:t.changes.created.length,modified:t.changes.modified.length,deleted:t.changes.deleted.length,hasEngine:!!r,hasBatchHandler:typeof r?.handleBatchFileChanges=="function"}),!r||typeof r.handleBatchFileChanges!="function"){this.sendToChild(e,{type:"batch-ack",batchId:t.batchId,ok:!1,error:`No batch handler available for root ${t.root}`});return}try{await r.handleBatchFileChanges(t.changes),Mn("node-watcher.batch.complete",{root:t.root,generation:t.generation,batchId:t.batchId,childPid:e.process.pid??null}),this.sendToChild(e,{type:"batch-ack",batchId:t.batchId,ok:!0})}catch(s){let i=s instanceof Error?s.message:String(s);Mn("node-watcher.batch.failed",{root:t.root,generation:t.generation,batchId:t.batchId,childPid:e.process.pid??null,error:i}),this.sendToChild(e,{type:"batch-ack",batchId:t.batchId,ok:!1,error:i})}}isActiveChild(e){return this.watcherChild===e&&this.projectRoot===e.root&&this.watcherGeneration===e.generation}sendToChild(e,t){try{e.process.send?.(t)}catch(r){Mn("node-watcher.child.send.failed",{root:e.root,generation:e.generation,childPid:e.process.pid??null,messageType:t.type,error:r instanceof Error?r.message:String(r)})}}async shutdownChild(e,t){if(e.shuttingDown){await e.exitPromise;return}e.shuttingDown=!0,Mn("node-watcher.child.shutdown.begin",{root:e.root,generation:e.generation,childPid:e.process.pid??null,reason:t}),this.sendToChild(e,{type:"shutdown",reason:t}),e.shutdownTimer=setTimeout(()=>{Mn("node-watcher.child.shutdown.force-kill",{root:e.root,generation:e.generation,childPid:e.process.pid??null,reason:t,graceMs:this.shutdownGraceMs});try{e.process.kill("SIGKILL")}catch(r){Mn("node-watcher.child.shutdown.force-kill.failed",{root:e.root,generation:e.generation,childPid:e.process.pid??null,reason:t,error:r instanceof Error?r.message:String(r)})}},this.shutdownGraceMs),await e.exitPromise}};var FC=DC();function DC(){return process.env.PANDO_RUNTIME_HOST==="vscode-extension"||process.env.VSCODE_PID||process.env.VSCODE_IPC_HOOK||process.env.VSCODE_CWD?"vscode-extension":process.env.PANDO_RUNTIME_HOST==="standalone-cli"?"standalone-cli":"unknown"}function AS(n){FC=n,process.env.PANDO_RUNTIME_HOST=n}function NS(){return FC==="vscode-extension"}ur();ms();async function MS(n){let e=wn.getEngine(n),t={root:n,isIndexing:typeof e?.isIndexingInProgress=="function"?!!e.isIndexingInProgress():!1};try{let r=await e.execute({op:"workspace-overview"});if(!r?.success)return t;let s=r.indexing??{};return{root:n,isIndexing:!!(s.isIndexing??t.isIndexing),progress:typeof s.progress=="number"?s.progress:void 0,totalFiles:typeof s.totalFiles=="number"?s.totalFiles:void 0,filesProcessed:typeof s.filesProcessed=="number"?s.filesProcessed:void 0,filesIndexed:typeof s.filesIndexed=="number"?s.filesIndexed:void 0,filesSkipped:typeof s.filesSkipped=="number"?s.filesSkipped:void 0,filesFailed:typeof s.filesFailed=="number"?s.filesFailed:void 0,message:typeof s.message=="string"?s.message:void 0}}catch{return t}}It();var dd=class n extends OC.EventEmitter{constructor(t,r){super();this.rootManager=t;this.options=r;this.watcher=null}static async create(t){gs()||Ko(process.cwd(),t.runtimePaths);let r=await ld.create(t.initialRoot,{languageSupport:t.languageSupport,lspHost:t.lspHost}),s=new n(r,{...t});return s.warnIfIndexingSuppressed(r.getProjectRoot()),await s.configureWatcher(),s}warnIfIndexingSuppressed(t){!t||!this.rootManager.isIndexingSuppressed(t)||this.options.log?.(`indexing is OFF for '${t}': it has too many files to index safely. Pando is running but its code-graph tools will be empty here. Set the project root to a smaller folder (one with a .git/package.json/etc.) and indexing will start automatically.`)}getProjectRoot(){return this.rootManager.getProjectRoot()}getRoots(){let t=this.getProjectRoot();return t?[t]:[]}getEngine(){return this.rootManager.getEngine()}async setProjectRoot(t){let r=this.getProjectRoot(),s=en(t),i=Date.now();if(ee("PandoRuntime","setProjectRoot begin",{requestedRoot:t,currentRoot:r,nextRoot:s}),await this.rootManager.validateProjectRoot(t),this.warnIfIndexingSuppressed(s),r===s)return ee("PandoRuntime","setProjectRoot no-op",{requestedRoot:t,currentRoot:r,nextRoot:s,elapsedMs:Date.now()-i}),r;if(r&&r!==s){let c=wn.getExistingEngine(r),l=`project root switching from ${r} to ${s}`,u=(p,f,m)=>{ee("PandoRuntime",`setProjectRoot phase:${p}`,{requestedRoot:t,currentRoot:r,nextRoot:s,elapsedMs:Date.now()-f,...m})},d=Date.now();try{c?.cancelActiveOperations?.("project root switching")}catch{}u("cancelActiveOperations",d,{hasEngine:!!c}),d=Date.now();try{c?.cancelIndexing?.("project root switching")}catch{}u("cancelIndexing",d),d=Date.now();try{wn.resetEngine(r)}catch{}u("resetEngine",d),d=Date.now(),Of(),u("shutdownActiveStreamingIndexers",d),d=Date.now(),await Us.shutdownAllShared({force:!0,reason:l}).catch(()=>{}),u("shutdownAllShared(force)",d),d=Date.now(),ia(l),u("shutdownSharedWorkers",d)}let o=Date.now(),a=await this.rootManager.setProjectRoot(t);if(ee("PandoRuntime","setProjectRoot rootManager resolved",{requestedRoot:t,currentRoot:r,nextRoot:s,resolved:a,elapsedMs:Date.now()-o}),a){let c=Date.now();ee("PandoRuntime","setProjectRoot watcher.updateProjectRoot begin",{requestedRoot:t,currentRoot:r,nextRoot:s,resolved:a,hasWatcher:!!this.watcher}),this.rootManager.isIndexingSuppressed(a)?ee("PandoRuntime","setProjectRoot watcher skipped (root over indexing limit)",{requestedRoot:t,resolved:a}):await this.watcher?.updateProjectRoot(a,this.resolveLanguageSupport(a)),ee("PandoRuntime","setProjectRoot watcher.updateProjectRoot complete",{requestedRoot:t,currentRoot:r,nextRoot:s,resolved:a,elapsedMs:Date.now()-c});let l=Date.now();ee("PandoRuntime","setProjectRoot emit rootChanged begin",{requestedRoot:t,currentRoot:r,nextRoot:s,resolved:a}),this.emit("rootChanged",a),ee("PandoRuntime","setProjectRoot emit rootChanged complete",{requestedRoot:t,currentRoot:r,nextRoot:s,resolved:a,elapsedMs:Date.now()-l})}return ee("PandoRuntime","setProjectRoot complete",{requestedRoot:t,currentRoot:r,nextRoot:s,resolved:a,elapsedMs:Date.now()-i}),a}async startIndexing(){let t=this.getProjectRoot();if(!t)return;if(this.rootManager.isIndexingSuppressed(t)){ee("PandoRuntime","startIndexing skipped (root over indexing limit)",{root:t}),this.emit("indexing",{root:t,isIndexing:!1});return}let r=this.rootManager.getEngine();this.emit("indexing",{root:t,isIndexing:!0}),r.startIndexing?.()}async getIndexingStatus(){let t=this.getProjectRoot();return t?MS(t):null}async getWorkspaceOverview(){let t=this.getProjectRoot();if(!t)return null;let r=this.rootManager.getEngine();try{let s=await r.execute({op:"workspace-overview"});if(!s?.success)return null;let i=s.nodes??{},o=qr(i.functions),a=qr(i.classes),c=qr(i.interfaces),l=qr(i.types),u=qr(i.enums),d=qr(i.variables),p=[o,a,c,l,u,d].filter(f=>typeof f=="number").reduce((f,m)=>f+m,0);return{root:t,files:{total:qr(s.files?.total),testFiles:qr(s.files?.testFiles)},nodes:{total:p||void 0,functions:o,classes:a,interfaces:c,types:l,enums:u,variables:d},indexing:{root:t,isIndexing:!!s.indexing?.isIndexing,totalFiles:qr(s.indexing?.totalFiles),filesProcessed:qr(s.indexing?.filesProcessed),filesIndexed:qr(s.indexing?.filesIndexed),filesSkipped:qr(s.indexing?.filesSkipped),filesFailed:qr(s.indexing?.filesFailed),progress:qr(s.indexing?.progress),message:typeof s.indexing?.message=="string"?s.indexing.message:void 0},writes:{ready:!!s.writes?.ready,blocked:!!(s.writes?.blocked??!s.writes?.ready),reason:typeof s.writes?.reason=="string"?s.writes.reason:void 0,message:typeof s.writes?.message=="string"?s.writes.message:void 0,gates:{metadataIndexingComplete:!!s.writes?.gates?.metadataIndexingComplete,snapshotComplete:!!s.writes?.gates?.snapshotComplete,ftsRequired:!1}},lsp:s.lsp&&typeof s.lsp=="object"?s.lsp:void 0}}catch{return null}}async stop(){let t=this.getProjectRoot();await this.watcher?.dispose(),this.watcher=null;let r=t?en(t):null,s=r?wn.getExistingEngine(r):null;try{s?.cancelActiveOperations?.("runtime stopped")}catch{}try{s?.cancelIndexing?.("runtime stopped")}catch{}if(Of(),await Us.shutdownAllShared({force:!0,reason:"runtime stopped"}).catch(()=>{}),ia("runtime stopped"),Fy(),!!r){try{s?.dispose?.()}catch{}wn.clearEngine(r)}}reloadLanguageSupport(t){let r=en(t),s=this.resolveLanguageSupport(r);this.rootManager.updateRootOptions(r,{languageSupport:s,lspHost:this.options.lspHost}),this.getProjectRoot()===r&&this.watcher?.updateProjectRoot(r,s)}async configureWatcher(){if(this.options.enableFileWatching===!1||NS())return;let t=this.getProjectRoot();if(t){if(this.rootManager.isIndexingSuppressed(t)){ee("PandoRuntime","configureWatcher skipped (root over indexing limit)",{root:t});return}this.watcher=new Lm(r=>this.options.log?.(r)??void 0),await this.watcher.activate(t,this.resolveLanguageSupport(t))}}resolveLanguageSupport(t){return this.options.languageSupport??Ho(t)}};function qr(n){return typeof n=="number"?n:void 0}ur();async function zm(n,e={}){return e.hostKind&&AS(e.hostKind),e.runtimePaths&&Ko(e.runtimePaths.runtimeRoot??n,e.runtimePaths),dd.create({initialRoot:n,languageSupport:e.languageSupport,lspHost:e.lspHost,transportMode:e.transportMode,enableFileWatching:e.enableFileWatching,log:e.log,runtimePaths:e.runtimePaths})}ur();var hd=B(require("path"));ms();_n();var XB="Compared against a smart non-pando workflow that would only send targeted declaration/reference snippets and minimal surrounding context, not full files.";var Fa={language:null,charsPerLine:40,charsPerToken:4,searchLines:6,confidence:"heuristic"},QB={c:{language:"c",charsPerLine:40.09,charsPerToken:3.98,searchLines:5.91,confidence:"trace-high"},cpp:{language:"cpp",charsPerLine:42.56,charsPerToken:3.99,searchLines:6.89,confidence:"trace-high"},csharp:{language:"csharp",charsPerLine:38.55,charsPerToken:3.99,searchLines:3.76,confidence:"trace-low"},js:{language:"js",charsPerLine:39.75,charsPerToken:3.98,searchLines:6.02,confidence:"trace-high"},ts:{language:"ts",charsPerLine:37.3,charsPerToken:3.99,searchLines:7.67,confidence:"trace-high"},java:{language:"java",charsPerLine:40,charsPerToken:4,searchLines:6,confidence:"trace-sparse"},clojure:{language:"clojure",charsPerLine:40,charsPerToken:4,searchLines:6,confidence:"modeled-only"},dart:{language:"dart",charsPerLine:40,charsPerToken:4,searchLines:6,confidence:"modeled-only"}};function Wi(n){return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.floor(n))}function md(n){return Math.max(0,Math.floor(n))}function BC(n,e=Fa){return md(Math.round(n*e.charsPerLine))}function qm(n,e=Fa){return n<=0?0:md(Math.ceil(n/e.charsPerToken))}function YB(n){return Buffer.byteLength(n,"utf8")}function e1(n){let e=n[n.length-1],t=n[n.length-2],r=n[n.length-3];return e?e==="content"&&t==="body"||e==="content"&&t==="code"&&r==="self"||e==="content"&&t==="code"?!0:e==="source"||e==="sourceText"||e==="sourceCode"||e==="rawSource"||e==="excerpt"||e==="snippet"||e==="oldString"||e==="old_string"||e==="originalFile"||e==="gitDiff"||e==="diff"||e==="patch":!1}function qC(n){let e=new Set,t=(r,s)=>{if(typeof r=="string")return e1(s)?YB(r):0;if(!r||typeof r!="object"||e.has(r))return 0;if(e.add(r),Array.isArray(r))return r.reduce((o,a,c)=>o+t(a,[...s,String(c)]),0);let i=0;for(let[o,a]of Object.entries(r))i+=t(a,[...s,o]);return i};return md(t(n,[]))}function $S(n){if(Array.isArray(n))return n.length===1?$S(n[0]):null;if(typeof n!="string")return null;let e=n.trim().toLowerCase();return e?e==="typescript"||e==="tsx"?"ts":e==="javascript"||e==="jsx"?"js":e==="c++"||e==="cc"||e==="cxx"?"cpp":e==="c#"||e==="cs"?"csharp":e==="clj"||e==="cljs"||e==="cljc"?"clojure":e:null}function Wn(n){if(typeof n!="string")return null;let e=n.split("#",1)[0].split("?",1)[0].toLowerCase();return/\.(ts|tsx)$/.test(e)?"ts":/\.(js|jsx|mjs|cjs)$/.test(e)?"js":/\.(cc|cpp|cxx|c\+\+|hpp|hh|hxx)$/.test(e)?"cpp":/\.(c|h)$/.test(e)?"c":/\.cs$/.test(e)?"csharp":/\.java$/.test(e)?"java":/\.(clj|cljs|cljc|edn)$/.test(e)?"clojure":/\.dart$/.test(e)?"dart":null}function Bm(n){let e=$S(n?.lang??n?.language);if(e)return e;let t=Wn(n?.path)??Wn(n?.file)??Wn(n?.file_path)??Wn(n?.newFile)??Wn(n?.oldFile)??Wn(n?.bodyEndOf)??Wn(n?.bodyStartOf)??Wn(n?.before)??Wn(n?.after)??Wn(n?.start)??Wn(n?.end)??Wn(n?.location?.file);return t||null}function t1(n,e){let t=$S(n.lang)??Wn(n.path)??Wn(n.to)??Wn(n.of)??Wn(n.file)??Wn(n.newFile)??Bm(n.to)??Bm(n.scope)??Wn(n.scope?.file)??(Array.isArray(n.scope?.files)?Wn(n.scope.files[0]):null);if(t)return t;for(let r of[e.results,e.items,e.exports])if(Array.isArray(r))for(let s of r){let i=Bm(s);if(i)return i}return Bm(e)}function n1(n,e){let t=t1(n,e);return t?QB[t]??{...Fa,language:t,confidence:"heuristic"}:Fa}function r1(n,e){return e==="trace-high"?n:e==="trace-low"||e==="trace-sparse"||e==="modeled-only"?"low":n==="high"?"medium":n}function FS(n,e){let t=n.savedItems.map(s=>{let i=BC(s.estimatedLinesNotSent,e);return{...s,estimatedCharsNotSent:i,estimatedTokensNotSent:qm(i,e)}}),r=t.reduce((s,i)=>s+i.estimatedCharsNotSent,0);return{...n,confidence:r1(n.confidence,e.confidence),savedItems:t,language:e.language,calibrationConfidence:e.confidence,charsPerLine:e.charsPerLine,charsPerToken:e.charsPerToken,counterfactualTextToolChars:r,estimatedCharsNotSent:r,estimatedTokensNotSent:qm(r,e)}}function $C(n,e){return Math.max(1,Math.round(n.searchLines||e))}function En(n,e,t,r,s){let i=Wi(t),o=Wi(r);if(i<=0||o<=0)return null;let a=i*o,c=BC(a),l=qm(c);return{key:n,label:e,count:i,linesPerUnit:o,estimatedLinesNotSent:a,estimatedCharsNotSent:c,estimatedTokensNotSent:l,note:s}}function jC(){return{version:1,calls:0,successfulCalls:0,callsWithSavings:0,estimatedLinesNotSent:0,counterfactualTextToolChars:0,pandoActualSourceChars:0,estimatedCharsNotSent:0,estimatedTokensNotSent:0,byOperation:{},lastUpdatedAt:null}}function Cr(n,e,t,r,s,i){let o=i.filter(d=>d!==null),a=o.reduce((d,p)=>d+p.estimatedLinesNotSent,0),c=o.reduce((d,p)=>d+p.estimatedCharsNotSent,0),l=c,u=o.reduce((d,p)=>d+p.estimatedTokensNotSent,0);return{version:1,op:n,success:e,method:t,confidence:r,comparisonBaseline:XB,rationale:s,savedItems:o,estimatedLinesNotSent:a,language:null,calibrationConfidence:Fa.confidence,charsPerLine:Fa.charsPerLine,charsPerToken:Fa.charsPerToken,counterfactualTextToolChars:c,pandoActualSourceChars:0,estimatedCharsNotSent:l,estimatedTokensNotSent:u}}function DS(n,e){let t=qC(e);if(!n.success||n.counterfactualTextToolChars<=0)return{...n,pandoActualSourceChars:t};let r=md(n.counterfactualTextToolChars-t);return{...n,pandoActualSourceChars:t,estimatedCharsNotSent:r,estimatedTokensNotSent:qm(r,{language:n.language,charsPerLine:n.charsPerLine,charsPerToken:n.charsPerToken,searchLines:6,confidence:n.calibrationConfidence})}}function pd(n,e,t){return Cr(n,e,"none","low",t,[])}function s1(n){switch(n.key){case"candidate-node-metadata":return"declaration snippets";case"candidate-node-self":return"extra declaration context";case"candidate-node-body":return"residual declaration context";case"reference-sites":return"reference snippets";case"caller-sites":return"caller snippets";case"export-result-contexts":return"export snippets";case"import-file-summaries":case"import-module-summaries":return"import snippets";case"namespace-graph-nodes":return"namespace declaration snippets";case"namespace-graph-edges":return"namespace dependency snippets";case"namespace-plan-edits":return"planned rewrite snippets";case"namespace-plan-declaration-context":return"namespace declaration context";case"reference-edit-contexts":return"reference edit snippets";case"declaration-context":return"declaration context";case"delete-target-context":return"delete target snippets";case"delete-reference-contexts":return"reference deletion snippets";case"signature-declaration-context":return"signature declaration context";case"signature-callsite-contexts":return"call-site rewrite snippets";case"fmr-match-contexts":return"matched code snippets";case"namespace-rewrite-files":return"namespace rewrite snippets";case"namespace-declaration-context":return"namespace declaration context";case"text-file-edit-context":return"text file edit context";default:return n.label.replace(/\bthat did not need to be sent\b/gi,"").replace(/\bdid not need raw import snippets\b/gi,"").replace(/\s+/g," ").trim().replace(/[.;:]$/,"")}}function Hm(n){if(!n||n.estimatedTokensNotSent<=0&&n.pandoActualSourceChars<=0)return;let e=n.savedItems.filter(i=>i.estimatedTokensNotSent>0).map(i=>({label:s1(i),count:i.count,estimatedLines:i.estimatedLinesNotSent,estimatedChars:i.estimatedCharsNotSent,estimatedTokens:i.estimatedTokensNotSent})),t=e.reduce((i,o)=>i+o.count,0),r=t===1?"snippet":"snippets",s=`; Pando returned ${n.pandoActualSourceChars} chars of source`;return{version:1,op:n.op,summary:`Would have sent about ${n.estimatedCharsNotSent} chars / ${n.estimatedTokensNotSent} tokens across ${t} ${r}${s}.`,confidence:n.confidence,language:n.language,calibrationConfidence:n.calibrationConfidence,charsPerLine:n.charsPerLine,charsPerToken:n.charsPerToken,estimatedLines:n.estimatedLinesNotSent,counterfactualTextToolChars:n.counterfactualTextToolChars,pandoActualSourceChars:n.pandoActualSourceChars,estimatedChars:n.estimatedCharsNotSent,estimatedTokens:n.estimatedTokensNotSent,wouldSend:e}}function HC(n){return Array.isArray(n.results)?n.results:Array.isArray(n.items)?n.items:Array.isArray(n.exports)?n.exports:[]}function jS(n){let e=n.details;return typeof e?.changedFileCount=="number"?Wi(e.changedFileCount):Array.isArray(e?.allChangedFiles)?e.allChangedFiles.length:Array.isArray(e?.changedFiles)?e.changedFiles.length:Wi(n.changes?.count??0)}function Da(n){return Array.isArray(n)?n.length:0}function i1(n,e){let t=HC(e),r=0,s=0,i=0;for(let o of t){if(o?.body?.content){i+=1;continue}if(o?.self?.code?.content){s+=1;continue}r+=1}return Cr(n,e.success,"mixed","medium","Structured node discovery avoids sending most candidate snippets; when self/body is requested, the saved amount is reduced rather than treated as zero.",[En("candidate-node-metadata","Candidate node snippets that did not need to be sent",r,4,"Metadata-only results usually avoid sending the declaration line plus minimal surrounding context for each candidate."),En("candidate-node-self","Additional node context avoided even when self was requested",s,2,"Including the node itself still avoids some surrounding context a smart text workflow would usually inspect."),En("candidate-node-body","Residual declaration context avoided when body content was requested",i,1,"Requesting body content removes most of the privacy advantage, so only a minimal declaration-context saving is counted.")])}function LC(n,e,t,r){let s=HC(e).length;return Cr(n,e.success,"exact-counts","high","Structured locations avoid sending per-location code snippets and nearby context.",[En(t,t==="reference-sites"?"Reference-site snippets that did not need to be sent":"Caller-site snippets that did not need to be sent",s,r,"The comparison assumes a smart text workflow would only send a minimal location snippet for each result.")])}function o1(n,e){let t=Da(e.exports);return Cr(n,e.success,"exact-counts","medium","Structured export lookup answers declaration-discovery questions without sending export snippets or nearby code.",[En("export-result-contexts","Export declaration snippets that did not need to be sent",t,2,"Only the returned export entries are counted, which keeps paginated list-exports calls conservative.")])}function a1(n,e){let t=e.imports,r=Da(t?.files),s=Da(t?.external),i=Da(t?.internal);return Cr(n,e.success,"exact-counts","medium","Import analysis returns grouped dependency structure without sending raw import blocks; only visible grouped entries are counted.",[En("import-file-summaries","Per-file import summaries that did not need raw import snippets",r,2,"When grouped by file, the estimate counts one small import-summary snippet per returned file entry."),En("import-module-summaries","Grouped import summaries that did not need raw import snippets",s+i,2,"When grouped by module, the estimate counts only the returned grouped entries rather than every underlying import usage.")])}function zC(n,e,t){let r=Da(e.namespaces),s=Da(e.edges);return Cr(n,e.success,"exact-counts","medium",t,[En("namespace-graph-nodes","Namespace declaration snippets that did not need to be sent",r,1,"Each returned namespace usually corresponds to at least one small ns-form context in a text-based workflow."),En("namespace-graph-edges","Namespace dependency snippets that did not need to be sent",s,2,"Each returned edge usually corresponds to one focused require/refer snippet in a text-based workflow.")])}function c1(n,e){let t=Da(e.namespaceEdits);return Cr(n,e.success,"exact-counts","medium","Namespace planning computes the affected declaration and dependent files without sending each candidate require/ns snippet to the provider.",[En("namespace-plan-edits","Planned namespace rewrite snippets that did not need to be sent",t,4,"The estimate counts one small rewrite-planning snippet per planned file edit."),En("namespace-plan-declaration-context","Namespace declaration context that only needed to be localized once",e.success?1:0,6,"The source namespace still needs one focused declaration context to build the plan.")])}function l1(n,e){let t=Wi(e.details?.referencesRenamed);return Cr(n,e.success,"exact-counts","high","Rename uses exact reference counts already produced by the executor, then applies a conservative per-reference context window.",[En("reference-edit-contexts","Reference edit contexts that did not need to be sent",t,3,"A smart non-pando workflow would still need to send each reference with a small amount of surrounding code before editing or approving it."),En("declaration-context","Declaration context that only needed to be localized once",e.success?1:0,6,"The declaration still has to be identified, but pando does not require the model to receive surrounding code for every downstream edit.")])}function u1(n,e){let t=Wi(e.details?.deletedCount),r=Array.isArray(e.details?.receipt?.appliedReferences)?e.details.receipt.appliedReferences.length:0;return Cr(n,e.success,r>0?"mixed":"heuristic",r>0?"high":"medium","Applied reference counts are exact when the executor exposes them; otherwise only the target-level deletion context is counted.",[En("delete-target-context","Delete target contexts that did not need to be sent",t,6,"Each delete target typically needs declaration-level context in a text-based workflow."),En("delete-reference-contexts","Reference deletion contexts that did not need to be sent",r,4,"When reference edits are applied automatically, pando avoids sending each reference and a small surrounding window.")])}function d1(n,e){let t=Wi(e.details?.callSiteStats?.auto_rewritten??e.changes?.callSitesAutoRewritten??0);return Cr(n,e.success,"exact-counts","high","The executor already reports how many call sites were rewritten automatically, so the privacy estimate can stay count-exact while using conservative context windows.",[En("signature-declaration-context","Function signature context that did not need to be sent repeatedly",e.success?1:0,6,"Only one declaration/signature context is counted for the target function."),En("signature-callsite-contexts","Auto-rewritten call-site contexts that did not need to be sent",t,5,"The estimate only counts call sites pando rewrote automatically; manual-review sites are not claimed as privacy savings.")])}function p1(n,e,t){let r=Wi(t.details?.receipt?.processedCount??t.details?.processedCount??t.details?.succeededCount??0),i=(Array.isArray(e.transforms)?e.transforms.length:0)>0?"filter-map-reduce localizes and rewrites matches without shipping matched code to the provider; the count is based on processed matches, not full-file size.":"filter-map-reduce localizes matches without shipping matched code to the provider.";return Cr(n,t.success,"exact-counts","high",i,[En("fmr-match-contexts","Matched-node contexts that did not need to be sent",r,6,"The baseline assumes a smart text workflow would still need to send a small snippet for every matched location before applying or validating a transform.")])}function OS(n,e,t,r,s){let i=jS(e);return Cr(n,e.success,"heuristic","medium",s,[En(`${n}-target-context`,r,i>0?1:0,t,"The estimate assumes one minimal target/anchor snippet would otherwise need to be sent for a single focused edit.")])}function f1(n,e){let t=jS(e),r=Wi(e.details?.appliedEdits??e.details?.receipt?.appliedEdits??0);return Cr(n,e.success,"heuristic","medium","Text-only edits to intentionally unindexed config/hook files avoid sending the target file or surrounding edit context to the provider; this estimate counts only a small local context window per changed file.",[En("text-file-edit-context","Text-file edit context that did not need to be sent",t>0?Math.max(1,r):0,8,"The baseline assumes a smart text workflow would inspect at least a focused snippet for each applied text edit, not necessarily the whole config file.")])}function m1(n,e){let t=jS(e);return Cr(n,e.success,"mixed","medium","Namespace rewrites typically require touching several import/require sites; the estimate stays conservative and file-based.",[En("namespace-rewrite-files","Namespace/import rewrite snippets that did not need to be sent",t,4,"A smart text workflow would usually send at least one small require/import snippet per changed file."),En("namespace-declaration-context","Namespace declaration context that only needed to be localized once",e.success?1:0,6,"The namespace declaration itself still needs one focused context window.")])}function WC(n,e,t){let r=!!t?.success,s=n1(e,t);if(!n)return DS(FS(pd("unknown",r,"Operation name unavailable; no privacy savings claimed."),s),t);if(!r)return DS(FS(pd(n,!1,"Operation did not succeed, so no privacy savings are claimed."),s),t);let i=(()=>{switch(n){case"find-nodes":return i1(n,t);case"find-references":return LC(n,t,"reference-sites",$C(s,6));case"find-callers":return LC(n,t,"caller-sites",$C(s,6));case"list-exports":return o1(n,t);case"analyze-imports":return a1(n,t);case"clojure-namespace-graph":return zC(n,t,"Namespace graph queries return cross-file dependency structure without sending the underlying ns/require snippets.");case"clojure-namespace-dependencies":case"clojure-namespace-dependents":return zC(n,t,"Namespace traversal returns dependency edges directly, avoiding per-edge code snippets in the provider request.");case"plan-clojure-namespace-move":case"plan-clojure-namespace-rename":return c1(n,t);case"rename":return l1(n,t);case"delete":return u1(n,t);case"change-signature":return d1(n,t);case"filter-map-reduce":return p1(n,e,t);case"replace":return OS(n,t,10,"Target replacement context that did not need to be sent","A focused replace still needs target localization in a text-based workflow; pando avoids sending that local code window.");case"replace-body":return OS(n,t,12,"Body replacement context that did not need to be sent","Body replacement typically requires a slightly larger context window than full-node replacement.");case"edit-file-text":return f1(n,t);case"insert":case"add-code":return e?.createFileIfMissing?pd(n,!0,"Insert created a new file, so no existing code context savings are claimed."):OS(n,t,8,"Insertion anchor context that did not need to be sent","A targeted insert usually needs local anchor context in a text-based workflow; pando keeps that out of the provider request.");case"rename-clojure-namespace":case"move-clojure-namespace":return m1(n,t);default:return pd(n,!0,"Administrative or metadata-only operation; privacy savings are too small or too uncertain to claim conservatively.")}})();return DS(FS(i,s),t)}function LS(n,e){if(e.length===0)return pd(n,!0,"No underlying operation estimates were available.");let t=e.every(u=>u.success),r=e.every(u=>u.method==="exact-counts")?"exact-counts":e.some(u=>u.method==="none")?"mixed":e.every(u=>u.method==="heuristic")?"heuristic":"mixed",s=e.every(u=>u.confidence==="high")?"high":e.some(u=>u.confidence==="low")?"low":"medium",i=new Map;for(let u of e)for(let d of u.savedItems){let p=i.get(d.key);if(!p){i.set(d.key,{...d});continue}p.count+=d.count,p.estimatedLinesNotSent+=d.estimatedLinesNotSent,p.estimatedCharsNotSent+=d.estimatedCharsNotSent,p.estimatedTokensNotSent+=d.estimatedTokensNotSent}let o=Cr(n,t,r,s,"Combined from per-root operation estimates in the current dispatcher session.",Array.from(i.values())),a=e.reduce((u,d)=>u+d.pandoActualSourceChars,0),c=md(o.counterfactualTextToolChars-a),l=e.reduce((u,d)=>u+d.estimatedTokensNotSent,0);return{...o,language:e.every(u=>u.language===e[0]?.language)?e[0]?.language??null:null,calibrationConfidence:e.every(u=>u.calibrationConfidence==="trace-high")?"trace-high":e.some(u=>u.calibrationConfidence==="modeled-only")?"modeled-only":e.some(u=>u.calibrationConfidence==="trace-low")?"trace-low":e.some(u=>u.calibrationConfidence==="trace-sparse")?"trace-sparse":"heuristic",pandoActualSourceChars:a,estimatedCharsNotSent:c,estimatedTokensNotSent:l}}var fd=class{constructor(){this.summary=jC()}record(e,t,r){let s=WC(e,t,r),i=this.summary.byOperation[e]??{calls:0,successfulCalls:0,callsWithSavings:0,estimatedLinesNotSent:0,counterfactualTextToolChars:0,pandoActualSourceChars:0,estimatedCharsNotSent:0,estimatedTokensNotSent:0};return i.calls+=1,s.success&&(i.successfulCalls+=1),s.estimatedTokensNotSent>0&&(i.callsWithSavings+=1),i.estimatedLinesNotSent+=s.estimatedLinesNotSent,i.counterfactualTextToolChars+=s.counterfactualTextToolChars,i.pandoActualSourceChars+=s.pandoActualSourceChars,i.estimatedCharsNotSent+=s.estimatedCharsNotSent,i.estimatedTokensNotSent+=s.estimatedTokensNotSent,this.summary.byOperation[e]=i,this.summary.calls+=1,s.success&&(this.summary.successfulCalls+=1),s.estimatedTokensNotSent>0&&(this.summary.callsWithSavings+=1),this.summary.estimatedLinesNotSent+=s.estimatedLinesNotSent,this.summary.counterfactualTextToolChars+=s.counterfactualTextToolChars,this.summary.pandoActualSourceChars+=s.pandoActualSourceChars,this.summary.estimatedCharsNotSent+=s.estimatedCharsNotSent,this.summary.estimatedTokensNotSent+=s.estimatedTokensNotSent,this.summary.lastUpdatedAt=new Date().toISOString(),{operation:s,session:this.getSessionSummary()}}getSessionSummary(){let e={};for(let[t,r]of Object.entries(this.summary.byOperation))e[t]={...r};return{...this.summary,byOperation:e}}reset(){return this.summary=jC(),this.getSessionSummary()}};It();function Is(n){let e=n.details;return e?typeof e.changedFileCount=="number"?e.changedFileCount:Array.isArray(e.allChangedFiles)?e.allChangedFiles.length:Array.isArray(e.changedFiles)?e.changedFiles.length:n.changes?.count??0:n.changes?.count??0}function Wm(n){return n.page?.totalCount??n.totalCount??(Array.isArray(n.results)?n.results.length:0)}var h1={rename:n=>({primary:Is(n),secondary:n.details?.referencesRenamed??0}),delete:n=>({primary:Is(n),secondary:n.details?.deletedCount??0}),insert:n=>({primary:Is(n),secondary:n.created?1:0}),replace:n=>({primary:Is(n),secondary:0}),"replace-body":n=>({primary:Is(n),secondary:0}),"change-signature":n=>({primary:Is(n),secondary:n.changes?.callSitesAutoRewritten??0}),"filter-map-reduce":n=>({primary:Is(n),secondary:0}),"find-references":n=>({primary:Wm(n),secondary:0}),"find-callers":n=>({primary:Wm(n),secondary:0}),"find-nodes":n=>({primary:Wm(n),secondary:0}),"workspace-overview":()=>({primary:0,secondary:0}),"list-exports":n=>({primary:n.page?.totalCount??(Array.isArray(n.exports)?n.exports.length:0),secondary:0}),"analyze-imports":n=>{let e=n.page;return{primary:e?.files?.totalCount??(e?.external?.totalCount??0)+(e?.internal?.totalCount??0),secondary:0}},"clojure-namespace-graph":n=>({primary:n.details?.namespaceCount??0,secondary:n.details?.edgeCount??0}),"clojure-namespace-dependencies":n=>({primary:n.namespacesPage?.totalCount??(Array.isArray(n.namespaces)?n.namespaces.length:0),secondary:n.edgesPage?.totalCount??(Array.isArray(n.edges)?n.edges.length:0)}),"clojure-namespace-dependents":n=>({primary:n.namespacesPage?.totalCount??(Array.isArray(n.namespaces)?n.namespaces.length:0),secondary:n.edgesPage?.totalCount??(Array.isArray(n.edges)?n.edges.length:0)}),"move-clojure-namespace":n=>({primary:Is(n),secondary:0}),"rename-clojure-namespace":n=>({primary:Is(n),secondary:0}),"snapshot-worktree":()=>({primary:0,secondary:0}),"restore-snapshot":n=>({primary:Is(n),secondary:0}),"restore-files":n=>({primary:Is(n),secondary:0})},g1=n=>({primary:Is(n),secondary:Wm(n)});function y1(n,e){let t=h1[n]??g1;try{return t(e)}catch{return{primary:0,secondary:0}}}var b1=0;function zS(){return`${Date.now()}-${++b1}`}function UC(n,e,t,r){let s=y1(n,e);return{schema_version:1,call_id:r,op:n,success:e.success,duration_ms:Math.max(0,Math.round(t)),error_code:e.error_code??void 0,primary_count:s.primary,secondary_count:s.secondary,timestamp:new Date().toISOString()}}var KC="_privacyOperation";function GC(n){let e=n.trim();if(!e)return null;let t=e;return(e.startsWith("pando_")||e.startsWith("pando-"))&&(t=e.slice(6)),t?t.replace(/_/g,"-"):null}function JC(n,e){let t={...e};return delete t.root,t}var Wc=class{constructor(e){this.config=e;this.privacyCounter=new fd}async dispatch(e,t,r){let s=GC(e);if(!s)return{success:!1,error:`Unknown tool: ${e}`};if(s==="set-project-root"){let p=typeof t.root=="string"?t.root.trim():"";if(!p)return{success:!1,error:"Missing required parameter: root"};if(S1(p))return{success:!1,error:"Filesystem root '/' cannot be used as a project root."};let f=Date.now();ee("PandoToolDispatcher","set-project-root begin",{toolName:e,requestedRoot:p});let m;try{m=await this.config.onProjectRootAdded?.(p)}catch(h){let g=h instanceof Error?h.message:String(h);return ee("PandoToolDispatcher","set-project-root rejected",{toolName:e,requestedRoot:p,error:g,elapsedMs:Date.now()-f}),{success:!1,error:g}}return m?(ee("PandoToolDispatcher","set-project-root complete",{toolName:e,requestedRoot:p,resolvedRoot:m,elapsedMs:Date.now()-f}),{success:!0,data:this.attachPrivacyToData("set-project-root",t,{projectRoot:m},{success:!0})}):(ee("PandoToolDispatcher","set-project-root failed",{toolName:e,requestedRoot:p,elapsedMs:Date.now()-f}),{success:!1,error:`Unable to add project root: ${p}`})}let i=this.resolveToolRoots(t);if(!i.roots.length&&i.error)return{success:!1,error:i.error,data:i.availableRoots?{availableRoots:i.availableRoots}:void 0};let o=i.roots;if(s==="get-project-root")return o.length<=1?{success:!0,data:this.attachPrivacyToData("get-project-root",t,{projectRoot:o[0]??null},{success:!0})}:{success:!0,data:this.attachPrivacyToData("get-project-root",t,{projectRoots:o},{success:!0})};if(!o.length)return{success:!1,error:"No workspace root available."};if(s==="read-this-first")return{success:!0,data:this.attachPrivacyToData("read-this-first",t,{help:this.config.loadReadThisFirstMessage()},{success:!0})};let a=JC(s,t),c={op:s,...a},l=zS(),u=r?.telemetry;if(this.isReadOnlyTool(e,s))return this.dispatchReadOnly(o,c,r?.signal,l,u);if(o.length>1){let p=[];for(let m of o)p.push(await this.executeOne(m,c,r?.signal,l,u));await this.handlePostDispatchEffects(s,p);let f=this.buildAggregatePrivacy(s,p);return{success:!0,data:{perRoot:p,...f?{privacy:f}:{}}}}let d=await this.executeOne(o[0],c,r?.signal,l,u);if(!d.success){let p=d.error??"Operation failed",f=Array.isArray(d.result?.hints)?d.result.hints:void 0;return{success:!1,error:p,...f?{hints:f}:{},data:d.result??{success:!1,error:p}}}return await this.handlePostDispatchEffects(s,[d]),{success:!0,data:d.result}}getPrivacySummary(){return this.privacyCounter.getSessionSummary()}resetPrivacySummary(){return this.privacyCounter.reset()}resolveToolRoots(e){if(this.config.resolveRoots)return this.config.resolveRoots(e);let t=this.config.roots(),r=typeof e.root=="string"?e.root.trim():"";if(!r)return{roots:t};let s=en(hd.default.isAbsolute(r)?r:hd.default.resolve(t[0]??process.cwd(),r)),i=t.map(o=>en(o));return i.includes(s)?{roots:[s]}:{roots:[],error:`Requested root is not registered: ${r}`,availableRoots:i}}async dispatchReadOnly(e,t,r,s,i){if(e.length===1){let d=await this.executeOne(e[0],t,r,s,i);if(!d.success){let p=d.error??"Operation failed",f=Array.isArray(d.result?.hints)?d.result.hints:void 0;return{success:!1,error:p,...f?{hints:f}:{},data:d.result??{success:!1,error:p}}}return{success:!0,data:d.result}}let o=[],a=[],c=0,l=!1;for(let d of e){let p=await this.executeOne(d,t,r,s,i);if(o.push(p),!p.success||!p.result)continue;let f=Array.isArray(p.result.items)?p.result.items:Array.isArray(p.result.results)?p.result.results:null;if(!f)continue;for(let g of f)a.push({...g,root:d});let m=p.result.page,h=typeof m?.totalCount=="number"?m.totalCount:typeof p.result.totalCount=="number"?p.result.totalCount:f.length;c+=h,l=l||!!m?.hasMore||!!p.result.hasMore}let u=this.buildAggregatePrivacy(String(t.op||"unknown"),o);return{success:!0,data:{summary:_1(o,a.length?{shownCount:a.length,totalCount:c,hasMore:l}:void 0),results:a.length?a:void 0,totalCount:a.length?c:void 0,hasMore:a.length?l:void 0,perRoot:o,...u?{privacy:u}:{}}}}async executeOne(e,t,r,s,i){let o=typeof t.op=="string"?t.op:"unknown",a=Date.now();try{let l=await wn.getEngine(e).execute(t,{signal:r}),u=this.attachPrivacyToResult(o,t,l);if(await this.emitTelemetry(o,l,Date.now()-a,e,s,i),!l.success){let d=ZC(l.error||"Operation failed");return{root:e,success:!1,error:d,result:{...u,error:d}}}return{root:e,success:!0,result:u}}catch(c){let l={success:!1,error:c instanceof Error?c.message:String(c)},u=this.attachPrivacyToResult(o,t,l);await this.emitTelemetry(o,l,Date.now()-a,e,s,i);let d=ZC(c instanceof Error?c.message:String(c));return{root:e,success:!1,error:d,result:{...u,error:d}}}}async emitTelemetry(e,t,r,s,i,o){try{let a=this.config.onTelemetry?.(UC(e,t,r,i??zS()),s,o);if(!a)return;let c=Promise.resolve(a);if(!this.config.awaitTelemetry){c.catch(()=>{});return}await x1(c,this.config.telemetryTimeoutMs??1e3)}catch{}}async handlePostDispatchEffects(e,t){if(e==="set-enabled-languages")for(let r of t)r.success&&r.result?.details?.languageSupportChanged===!0&&await this.config.onLanguageSupportChanged?.(r.root)}isReadOnlyTool(e,t){let r=t.replace(/-/g,"_");return this.config.readOnlyTools.has(e)||this.config.readOnlyTools.has(t)||this.config.readOnlyTools.has(r)||this.config.readOnlyTools.has(`pando_${r}`)||this.config.readOnlyTools.has(`pando-${t}`)}attachPrivacyToResult(e,t,r){let s=this.privacyCounter.record(e,t,r),i=Hm(s.operation),o={...r,...i?{privacy:i}:{}};return Object.defineProperty(o,KC,{value:s.operation,enumerable:!1,configurable:!0,writable:!1}),o}attachPrivacyToData(e,t,r,s){let i=Hm(this.privacyCounter.record(e,t,s).operation);return{...r,...i?{privacy:i}:{}}}buildAggregatePrivacy(e,t){let r=t.map(s=>s.result?.[KC]).filter(s=>!!s);return Hm(LS(e,r))}};function S1(n){let e=hd.default.resolve(n);return hd.default.parse(e).root===e}function ZC(n){return n.length<=1e3?n:`${n.slice(0,1e3)}\u2026 [truncated]`}function x1(n,e){let t=Math.max(0,Math.trunc(e));return t===0?n:Promise.race([n,new Promise(r=>{setTimeout(r,t)})])}function _1(n,e){let t=n.length,r=n.filter(o=>o.success).length,s=t-r,i=n.map(o=>o.error??(typeof o.result?.error=="string"?o.result.error:void 0)).find(o=>typeof o=="string"&&o.trim().length>0);return{rootsTotal:t,rootsSucceeded:r,rootsFailed:s,shownCount:e?.shownCount,totalCount:e?.totalCount,hasMore:e?.hasMore,error:i}}var VC=B(require("fs")),w1=["set-project-root","set-enabled-languages","workspace-overview","get-db-schema","query-db","find-nodes","find-references","rename","replace","edit-file-text","insert","delete","filter-map-reduce"];function Uc(n,e){let t=VC.default.readFileSync(n,"utf8"),r=JSON.parse(t),s=Array.isArray(r.tools)?r.tools:[],i=new Map(w1.map((o,a)=>[o,a]));return s.filter(o=>typeof o?.name=="string").filter(o=>o.category!=="orchestrator").filter(o=>!(e?.excludeNames?.has(o.name)??!1)).sort((o,a)=>{let c=i.get(o.name),l=i.get(a.name);return c!=null&&l!=null?c-l:c!=null?-1:l!=null?1:o.name.localeCompare(a.name)})}function BS(n){let e=n.parameters&&n.parameters.type==="object"?{...n.parameters,type:"object",properties:v1(n.parameters.properties)}:{type:"object",properties:{},required:[],additionalProperties:!1};return{name:n.name,description:n.description,inputSchema:e}}function Um(n,e){return n.find(r=>r.name===e)?.description??""}function v1(n){if(!n)return;let e={};for(let[t,r]of Object.entries(n))r&&typeof r=="object"&&(e[t]=r);return e}var vt;(function(n){n.assertEqual=s=>{};function e(s){}n.assertIs=e;function t(s){throw new Error}n.assertNever=t,n.arrayToEnum=s=>{let i={};for(let o of s)i[o]=o;return i},n.getValidEnumValues=s=>{let i=n.objectKeys(s).filter(a=>typeof s[s[a]]!="number"),o={};for(let a of i)o[a]=s[a];return n.objectValues(o)},n.objectValues=s=>n.objectKeys(s).map(function(i){return s[i]}),n.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let i=[];for(let o in s)Object.prototype.hasOwnProperty.call(s,o)&&i.push(o);return i},n.find=(s,i)=>{for(let o of s)if(i(o))return o},n.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function r(s,i=" | "){return s.map(o=>typeof o=="string"?`'${o}'`:o).join(i)}n.joinValues=r,n.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(vt||(vt={}));var XC;(function(n){n.mergeShapes=(e,t)=>({...e,...t})})(XC||(XC={}));var Te=vt.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Ui=n=>{switch(typeof n){case"undefined":return Te.undefined;case"string":return Te.string;case"number":return Number.isNaN(n)?Te.nan:Te.number;case"boolean":return Te.boolean;case"function":return Te.function;case"bigint":return Te.bigint;case"symbol":return Te.symbol;case"object":return Array.isArray(n)?Te.array:n===null?Te.null:n.then&&typeof n.then=="function"&&n.catch&&typeof n.catch=="function"?Te.promise:typeof Map<"u"&&n instanceof Map?Te.map:typeof Set<"u"&&n instanceof Set?Te.set:typeof Date<"u"&&n instanceof Date?Te.date:Te.object;default:return Te.unknown}};var ce=vt.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"]);var cs=class n extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){let t=e||function(i){return i.message},r={_errors:[]},s=i=>{for(let o of i.issues)if(o.code==="invalid_union")o.unionErrors.map(s);else if(o.code==="invalid_return_type")s(o.returnTypeError);else if(o.code==="invalid_arguments")s(o.argumentsError);else if(o.path.length===0)r._errors.push(t(o));else{let a=r,c=0;for(;c<o.path.length;){let l=o.path[c];c===o.path.length-1?(a[l]=a[l]||{_errors:[]},a[l]._errors.push(t(o))):a[l]=a[l]||{_errors:[]},a=a[l],c++}}};return s(this),r}static assert(e){if(!(e instanceof n))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,vt.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){let t={},r=[];for(let s of this.issues)if(s.path.length>0){let i=s.path[0];t[i]=t[i]||[],t[i].push(e(s))}else r.push(e(s));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}};cs.create=n=>new cs(n);var R1=(n,e)=>{let t;switch(n.code){case ce.invalid_type:n.received===Te.undefined?t="Required":t=`Expected ${n.expected}, received ${n.received}`;break;case ce.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(n.expected,vt.jsonStringifyReplacer)}`;break;case ce.unrecognized_keys:t=`Unrecognized key(s) in object: ${vt.joinValues(n.keys,", ")}`;break;case ce.invalid_union:t="Invalid input";break;case ce.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${vt.joinValues(n.options)}`;break;case ce.invalid_enum_value:t=`Invalid enum value. Expected ${vt.joinValues(n.options)}, received '${n.received}'`;break;case ce.invalid_arguments:t="Invalid function arguments";break;case ce.invalid_return_type:t="Invalid function return type";break;case ce.invalid_date:t="Invalid date";break;case ce.invalid_string:typeof n.validation=="object"?"includes"in n.validation?(t=`Invalid input: must include "${n.validation.includes}"`,typeof n.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${n.validation.position}`)):"startsWith"in n.validation?t=`Invalid input: must start with "${n.validation.startsWith}"`:"endsWith"in n.validation?t=`Invalid input: must end with "${n.validation.endsWith}"`:vt.assertNever(n.validation):n.validation!=="regex"?t=`Invalid ${n.validation}`:t="Invalid";break;case ce.too_small:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at least":"more than"} ${n.minimum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at least":"over"} ${n.minimum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="bigint"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(n.minimum))}`:t="Invalid input";break;case ce.too_big:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at most":"less than"} ${n.maximum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at most":"under"} ${n.maximum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="bigint"?t=`BigInt must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly":n.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(n.maximum))}`:t="Invalid input";break;case ce.custom:t="Invalid input";break;case ce.invalid_intersection_types:t="Intersection results could not be merged";break;case ce.not_multiple_of:t=`Number must be a multiple of ${n.multipleOf}`;break;case ce.not_finite:t="Number must be finite";break;default:t=e.defaultError,vt.assertNever(n)}return{message:t}},_o=R1;var E1=_o;function gd(){return E1}var Km=n=>{let{data:e,path:t,errorMaps:r,issueData:s}=n,i=[...t,...s.path||[]],o={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let a="",c=r.filter(l=>!!l).slice().reverse();for(let l of c)a=l(o,{data:e,defaultError:a}).message;return{...s,path:i,message:a}};function Re(n,e){let t=gd(),r=Km({issueData:e,data:n.data,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,t,t===_o?void 0:_o].filter(s=>!!s)});n.common.issues.push(r)}var hr=class n{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){let r=[];for(let s of t){if(s.status==="aborted")return tt;s.status==="dirty"&&e.dirty(),r.push(s.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){let r=[];for(let s of t){let i=await s.key,o=await s.value;r.push({key:i,value:o})}return n.mergeObjectSync(e,r)}static mergeObjectSync(e,t){let r={};for(let s of t){let{key:i,value:o}=s;if(i.status==="aborted"||o.status==="aborted")return tt;i.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof o.value<"u"||s.alwaysSet)&&(r[i.value]=o.value)}return{status:e.value,value:r}}},tt=Object.freeze({status:"aborted"}),Kc=n=>({status:"dirty",value:n}),Ir=n=>({status:"valid",value:n}),qS=n=>n.status==="aborted",HS=n=>n.status==="dirty",Oa=n=>n.status==="valid",yd=n=>typeof Promise<"u"&&n instanceof Promise;var Oe;(function(n){n.errToObj=e=>typeof e=="string"?{message:e}:e||{},n.toString=e=>typeof e=="string"?e:e?.message})(Oe||(Oe={}));var As=class{constructor(e,t,r,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=s}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}},QC=(n,e)=>{if(Oa(e))return{success:!0,data:e.value};if(!n.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new cs(n.common.issues);return this._error=t,this._error}}};function dt(n){if(!n)return{};let{errorMap:e,invalid_type_error:t,required_error:r,description:s}=n;if(e&&(t||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(o,a)=>{let{message:c}=n;return o.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??r??a.defaultError}:o.code!=="invalid_type"?{message:a.defaultError}:{message:c??t??a.defaultError}},description:s}}var bt=class{get description(){return this._def.description}_getType(e){return Ui(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Ui(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new hr,ctx:{common:e.parent.common,data:e.data,parsedType:Ui(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(yd(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){let r={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ui(e)},s=this._parseSync({data:e,path:r.path,parent:r});return QC(r,s)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ui(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:t});return Oa(r)?{value:r.value}:{issues:t.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(r=>Oa(r)?{value:r.value}:{issues:t.common.issues})}async parseAsync(e,t){let r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){let r={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ui(e)},s=this._parse({data:e,path:r.path,parent:r}),i=await(yd(s)?s:Promise.resolve(s));return QC(r,i)}refine(e,t){let r=s=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(s):t;return this._refinement((s,i)=>{let o=e(s),a=()=>i.addIssue({code:ce.custom,...r(s)});return typeof Promise<"u"&&o instanceof Promise?o.then(c=>c?!0:(a(),!1)):o?!0:(a(),!1)})}refinement(e,t){return this._refinement((r,s)=>e(r)?!0:(s.addIssue(typeof t=="function"?t(r,s):t),!1))}_refinement(e){return new ei({schema:this,typeName:ue.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,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:t=>this["~validate"](t)}}optional(){return ls.create(this,this._def)}nullable(){return Gi.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return vo.create(this)}promise(){return $a.create(this,this._def)}or(e){return Xc.create([this,e],this._def)}and(e){return Qc.create(this,e,this._def)}transform(e){return new ei({...dt(this._def),schema:this,typeName:ue.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new rl({...dt(this._def),innerType:this,defaultValue:t,typeName:ue.ZodDefault})}brand(){return new Zm({typeName:ue.ZodBranded,type:this,...dt(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new sl({...dt(this._def),innerType:this,catchValue:t,typeName:ue.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return Gm.create(this,e)}readonly(){return il.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},k1=/^c[^\s-]{8,}$/i,T1=/^[0-9a-z]+$/,P1=/^[0-9A-HJKMNP-TV-Z]{26}$/i,C1=/^[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,I1=/^[a-z0-9_-]{21}$/i,A1=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,N1=/^[-+]?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)?)??$/,M1=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,F1="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",WS,D1=/^(?:(?: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])$/,O1=/^(?:(?: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])$/,$1=/^(([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]))$/,j1=/^(([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])$/,L1=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,z1=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,YC="((\\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])))",B1=new RegExp(`^${YC}$`);function eI(n){let e="[0-5]\\d";n.precision?e=`${e}\\.\\d{${n.precision}}`:n.precision==null&&(e=`${e}(\\.\\d+)?`);let t=n.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function q1(n){return new RegExp(`^${eI(n)}$`)}function H1(n){let e=`${YC}T${eI(n)}`,t=[];return t.push(n.local?"Z?":"Z"),n.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function W1(n,e){return!!((e==="v4"||!e)&&D1.test(n)||(e==="v6"||!e)&&$1.test(n))}function U1(n,e){if(!A1.test(n))return!1;try{let[t]=n.split(".");if(!t)return!1;let r=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),s=JSON.parse(atob(r));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function K1(n,e){return!!((e==="v4"||!e)&&O1.test(n)||(e==="v6"||!e)&&j1.test(n))}var Gc=class n extends bt{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==Te.string){let i=this._getOrReturnCtx(e);return Re(i,{code:ce.invalid_type,expected:Te.string,received:i.parsedType}),tt}let r=new hr,s;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),Re(s,{code:ce.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="max")e.data.length>i.value&&(s=this._getOrReturnCtx(e,s),Re(s,{code:ce.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){let o=e.data.length>i.value,a=e.data.length<i.value;(o||a)&&(s=this._getOrReturnCtx(e,s),o?Re(s,{code:ce.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):a&&Re(s,{code:ce.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")M1.test(e.data)||(s=this._getOrReturnCtx(e,s),Re(s,{validation:"email",code:ce.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")WS||(WS=new RegExp(F1,"u")),WS.test(e.data)||(s=this._getOrReturnCtx(e,s),Re(s,{validation:"emoji",code:ce.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")C1.test(e.data)||(s=this._getOrReturnCtx(e,s),Re(s,{validation:"uuid",code:ce.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")I1.test(e.data)||(s=this._getOrReturnCtx(e,s),Re(s,{validation:"nanoid",code:ce.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")k1.test(e.data)||(s=this._getOrReturnCtx(e,s),Re(s,{validation:"cuid",code:ce.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")T1.test(e.data)||(s=this._getOrReturnCtx(e,s),Re(s,{validation:"cuid2",code:ce.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")P1.test(e.data)||(s=this._getOrReturnCtx(e,s),Re(s,{validation:"ulid",code:ce.invalid_string,message:i.message}),r.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),Re(s,{validation:"url",code:ce.invalid_string,message:i.message}),r.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),Re(s,{validation:"regex",code:ce.invalid_string,message:i.message}),r.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(s=this._getOrReturnCtx(e,s),Re(s,{code:ce.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),r.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(s=this._getOrReturnCtx(e,s),Re(s,{code:ce.invalid_string,validation:{startsWith:i.value},message:i.message}),r.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),Re(s,{code:ce.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?H1(i).test(e.data)||(s=this._getOrReturnCtx(e,s),Re(s,{code:ce.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?B1.test(e.data)||(s=this._getOrReturnCtx(e,s),Re(s,{code:ce.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?q1(i).test(e.data)||(s=this._getOrReturnCtx(e,s),Re(s,{code:ce.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?N1.test(e.data)||(s=this._getOrReturnCtx(e,s),Re(s,{validation:"duration",code:ce.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?W1(e.data,i.version)||(s=this._getOrReturnCtx(e,s),Re(s,{validation:"ip",code:ce.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?U1(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),Re(s,{validation:"jwt",code:ce.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?K1(e.data,i.version)||(s=this._getOrReturnCtx(e,s),Re(s,{validation:"cidr",code:ce.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?L1.test(e.data)||(s=this._getOrReturnCtx(e,s),Re(s,{validation:"base64",code:ce.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?z1.test(e.data)||(s=this._getOrReturnCtx(e,s),Re(s,{validation:"base64url",code:ce.invalid_string,message:i.message}),r.dirty()):vt.assertNever(i);return{status:r.value,value:e.data}}_regex(e,t,r){return this.refinement(s=>e.test(s),{validation:t,code:ce.invalid_string,...Oe.errToObj(r)})}_addCheck(e){return new n({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...Oe.errToObj(e)})}url(e){return this._addCheck({kind:"url",...Oe.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...Oe.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...Oe.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...Oe.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...Oe.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...Oe.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...Oe.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...Oe.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...Oe.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...Oe.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...Oe.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...Oe.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...Oe.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...Oe.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...Oe.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...Oe.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...Oe.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...Oe.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...Oe.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...Oe.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...Oe.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...Oe.errToObj(t)})}nonempty(e){return this.min(1,Oe.errToObj(e))}trim(){return new n({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new n({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new n({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};Gc.create=n=>new Gc({checks:[],typeName:ue.ZodString,coerce:n?.coerce??!1,...dt(n)});function Z1(n,e){let t=(n.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,s=t>r?t:r,i=Number.parseInt(n.toFixed(s).replace(".","")),o=Number.parseInt(e.toFixed(s).replace(".",""));return i%o/10**s}var bd=class n extends bt{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==Te.number){let i=this._getOrReturnCtx(e);return Re(i,{code:ce.invalid_type,expected:Te.number,received:i.parsedType}),tt}let r,s=new hr;for(let i of this._def.checks)i.kind==="int"?vt.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),Re(r,{code:ce.invalid_type,expected:"integer",received:"float",message:i.message}),s.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),Re(r,{code:ce.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),Re(r,{code:ce.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?Z1(e.data,i.value)!==0&&(r=this._getOrReturnCtx(e,r),Re(r,{code:ce.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),Re(r,{code:ce.not_finite,message:i.message}),s.dirty()):vt.assertNever(i);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,Oe.toString(t))}gt(e,t){return this.setLimit("min",e,!1,Oe.toString(t))}lte(e,t){return this.setLimit("max",e,!0,Oe.toString(t))}lt(e,t){return this.setLimit("max",e,!1,Oe.toString(t))}setLimit(e,t,r,s){return new n({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:Oe.toString(s)}]})}_addCheck(e){return new n({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:Oe.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Oe.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Oe.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Oe.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Oe.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:Oe.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:Oe.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Oe.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Oe.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&vt.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(t===null||r.value>t)&&(t=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(t)&&Number.isFinite(e)}};bd.create=n=>new bd({checks:[],typeName:ue.ZodNumber,coerce:n?.coerce||!1,...dt(n)});var Sd=class n extends bt{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==Te.bigint)return this._getInvalidInput(e);let r,s=new hr;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),Re(r,{code:ce.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),Re(r,{code:ce.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),Re(r,{code:ce.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):vt.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return Re(t,{code:ce.invalid_type,expected:Te.bigint,received:t.parsedType}),tt}gte(e,t){return this.setLimit("min",e,!0,Oe.toString(t))}gt(e,t){return this.setLimit("min",e,!1,Oe.toString(t))}lte(e,t){return this.setLimit("max",e,!0,Oe.toString(t))}lt(e,t){return this.setLimit("max",e,!1,Oe.toString(t))}setLimit(e,t,r,s){return new n({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:Oe.toString(s)}]})}_addCheck(e){return new n({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Oe.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Oe.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Oe.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Oe.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:Oe.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};Sd.create=n=>new Sd({checks:[],typeName:ue.ZodBigInt,coerce:n?.coerce??!1,...dt(n)});var xd=class extends bt{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==Te.boolean){let r=this._getOrReturnCtx(e);return Re(r,{code:ce.invalid_type,expected:Te.boolean,received:r.parsedType}),tt}return Ir(e.data)}};xd.create=n=>new xd({typeName:ue.ZodBoolean,coerce:n?.coerce||!1,...dt(n)});var _d=class n extends bt{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==Te.date){let i=this._getOrReturnCtx(e);return Re(i,{code:ce.invalid_type,expected:Te.date,received:i.parsedType}),tt}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return Re(i,{code:ce.invalid_date}),tt}let r=new hr,s;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),Re(s,{code:ce.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),r.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(s=this._getOrReturnCtx(e,s),Re(s,{code:ce.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):vt.assertNever(i);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new n({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:Oe.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:Oe.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}};_d.create=n=>new _d({checks:[],coerce:n?.coerce||!1,typeName:ue.ZodDate,...dt(n)});var wd=class extends bt{_parse(e){if(this._getType(e)!==Te.symbol){let r=this._getOrReturnCtx(e);return Re(r,{code:ce.invalid_type,expected:Te.symbol,received:r.parsedType}),tt}return Ir(e.data)}};wd.create=n=>new wd({typeName:ue.ZodSymbol,...dt(n)});var Jc=class extends bt{_parse(e){if(this._getType(e)!==Te.undefined){let r=this._getOrReturnCtx(e);return Re(r,{code:ce.invalid_type,expected:Te.undefined,received:r.parsedType}),tt}return Ir(e.data)}};Jc.create=n=>new Jc({typeName:ue.ZodUndefined,...dt(n)});var Vc=class extends bt{_parse(e){if(this._getType(e)!==Te.null){let r=this._getOrReturnCtx(e);return Re(r,{code:ce.invalid_type,expected:Te.null,received:r.parsedType}),tt}return Ir(e.data)}};Vc.create=n=>new Vc({typeName:ue.ZodNull,...dt(n)});var vd=class extends bt{constructor(){super(...arguments),this._any=!0}_parse(e){return Ir(e.data)}};vd.create=n=>new vd({typeName:ue.ZodAny,...dt(n)});var wo=class extends bt{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Ir(e.data)}};wo.create=n=>new wo({typeName:ue.ZodUnknown,...dt(n)});var _i=class extends bt{_parse(e){let t=this._getOrReturnCtx(e);return Re(t,{code:ce.invalid_type,expected:Te.never,received:t.parsedType}),tt}};_i.create=n=>new _i({typeName:ue.ZodNever,...dt(n)});var Rd=class extends bt{_parse(e){if(this._getType(e)!==Te.undefined){let r=this._getOrReturnCtx(e);return Re(r,{code:ce.invalid_type,expected:Te.void,received:r.parsedType}),tt}return Ir(e.data)}};Rd.create=n=>new Rd({typeName:ue.ZodVoid,...dt(n)});var vo=class n extends bt{_parse(e){let{ctx:t,status:r}=this._processInputParams(e),s=this._def;if(t.parsedType!==Te.array)return Re(t,{code:ce.invalid_type,expected:Te.array,received:t.parsedType}),tt;if(s.exactLength!==null){let o=t.data.length>s.exactLength.value,a=t.data.length<s.exactLength.value;(o||a)&&(Re(t,{code:o?ce.too_big:ce.too_small,minimum:a?s.exactLength.value:void 0,maximum:o?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),r.dirty())}if(s.minLength!==null&&t.data.length<s.minLength.value&&(Re(t,{code:ce.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),s.maxLength!==null&&t.data.length>s.maxLength.value&&(Re(t,{code:ce.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map((o,a)=>s.type._parseAsync(new As(t,o,t.path,a)))).then(o=>hr.mergeArray(r,o));let i=[...t.data].map((o,a)=>s.type._parseSync(new As(t,o,t.path,a)));return hr.mergeArray(r,i)}get element(){return this._def.type}min(e,t){return new n({...this._def,minLength:{value:e,message:Oe.toString(t)}})}max(e,t){return new n({...this._def,maxLength:{value:e,message:Oe.toString(t)}})}length(e,t){return new n({...this._def,exactLength:{value:e,message:Oe.toString(t)}})}nonempty(e){return this.min(1,e)}};vo.create=(n,e)=>new vo({type:n,minLength:null,maxLength:null,exactLength:null,typeName:ue.ZodArray,...dt(e)});function Zc(n){if(n instanceof us){let e={};for(let t in n.shape){let r=n.shape[t];e[t]=ls.create(Zc(r))}return new us({...n._def,shape:()=>e})}else return n instanceof vo?new vo({...n._def,type:Zc(n.element)}):n instanceof ls?ls.create(Zc(n.unwrap())):n instanceof Gi?Gi.create(Zc(n.unwrap())):n instanceof Zi?Zi.create(n.items.map(e=>Zc(e))):n}var us=class n extends bt{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=vt.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==Te.object){let l=this._getOrReturnCtx(e);return Re(l,{code:ce.invalid_type,expected:Te.object,received:l.parsedType}),tt}let{status:r,ctx:s}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),a=[];if(!(this._def.catchall instanceof _i&&this._def.unknownKeys==="strip"))for(let l in s.data)o.includes(l)||a.push(l);let c=[];for(let l of o){let u=i[l],d=s.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new As(s,d,s.path,l)),alwaysSet:l in s.data})}if(this._def.catchall instanceof _i){let l=this._def.unknownKeys;if(l==="passthrough")for(let u of a)c.push({key:{status:"valid",value:u},value:{status:"valid",value:s.data[u]}});else if(l==="strict")a.length>0&&(Re(s,{code:ce.unrecognized_keys,keys:a}),r.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let u of a){let d=s.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new As(s,d,s.path,u)),alwaysSet:u in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let l=[];for(let u of c){let d=await u.key,p=await u.value;l.push({key:d,value:p,alwaysSet:u.alwaysSet})}return l}).then(l=>hr.mergeObjectSync(r,l)):hr.mergeObjectSync(r,c)}get shape(){return this._def.shape()}strict(e){return Oe.errToObj,new n({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,r)=>{let s=this._def.errorMap?.(t,r).message??r.defaultError;return t.code==="unrecognized_keys"?{message:Oe.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new n({...this._def,unknownKeys:"strip"})}passthrough(){return new n({...this._def,unknownKeys:"passthrough"})}extend(e){return new n({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new n({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:ue.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new n({...this._def,catchall:e})}pick(e){let t={};for(let r of vt.objectKeys(e))e[r]&&this.shape[r]&&(t[r]=this.shape[r]);return new n({...this._def,shape:()=>t})}omit(e){let t={};for(let r of vt.objectKeys(this.shape))e[r]||(t[r]=this.shape[r]);return new n({...this._def,shape:()=>t})}deepPartial(){return Zc(this)}partial(e){let t={};for(let r of vt.objectKeys(this.shape)){let s=this.shape[r];e&&!e[r]?t[r]=s:t[r]=s.optional()}return new n({...this._def,shape:()=>t})}required(e){let t={};for(let r of vt.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof ls;)i=i._def.innerType;t[r]=i}return new n({...this._def,shape:()=>t})}keyof(){return tI(vt.objectKeys(this.shape))}};us.create=(n,e)=>new us({shape:()=>n,unknownKeys:"strip",catchall:_i.create(),typeName:ue.ZodObject,...dt(e)});us.strictCreate=(n,e)=>new us({shape:()=>n,unknownKeys:"strict",catchall:_i.create(),typeName:ue.ZodObject,...dt(e)});us.lazycreate=(n,e)=>new us({shape:n,unknownKeys:"strip",catchall:_i.create(),typeName:ue.ZodObject,...dt(e)});var Xc=class extends bt{_parse(e){let{ctx:t}=this._processInputParams(e),r=this._def.options;function s(i){for(let a of i)if(a.result.status==="valid")return a.result;for(let a of i)if(a.result.status==="dirty")return t.common.issues.push(...a.ctx.common.issues),a.result;let o=i.map(a=>new cs(a.ctx.common.issues));return Re(t,{code:ce.invalid_union,unionErrors:o}),tt}if(t.common.async)return Promise.all(r.map(async i=>{let o={...t,common:{...t.common,issues:[]},parent:null};return{result:await i._parseAsync({data:t.data,path:t.path,parent:o}),ctx:o}})).then(s);{let i,o=[];for(let c of r){let l={...t,common:{...t.common,issues:[]},parent:null},u=c._parseSync({data:t.data,path:t.path,parent:l});if(u.status==="valid")return u;u.status==="dirty"&&!i&&(i={result:u,ctx:l}),l.common.issues.length&&o.push(l.common.issues)}if(i)return t.common.issues.push(...i.ctx.common.issues),i.result;let a=o.map(c=>new cs(c));return Re(t,{code:ce.invalid_union,unionErrors:a}),tt}}get options(){return this._def.options}};Xc.create=(n,e)=>new Xc({options:n,typeName:ue.ZodUnion,...dt(e)});var Ki=n=>n instanceof Yc?Ki(n.schema):n instanceof ei?Ki(n.innerType()):n instanceof el?[n.value]:n instanceof tl?n.options:n instanceof nl?vt.objectValues(n.enum):n instanceof rl?Ki(n._def.innerType):n instanceof Jc?[void 0]:n instanceof Vc?[null]:n instanceof ls?[void 0,...Ki(n.unwrap())]:n instanceof Gi?[null,...Ki(n.unwrap())]:n instanceof Zm||n instanceof il?Ki(n.unwrap()):n instanceof sl?Ki(n._def.innerType):[],US=class n extends bt{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==Te.object)return Re(t,{code:ce.invalid_type,expected:Te.object,received:t.parsedType}),tt;let r=this.discriminator,s=t.data[r],i=this.optionsMap.get(s);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(Re(t,{code:ce.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),tt)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,r){let s=new Map;for(let i of t){let o=Ki(i.shape[e]);if(!o.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of o){if(s.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);s.set(a,i)}}return new n({typeName:ue.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:s,...dt(r)})}};function KS(n,e){let t=Ui(n),r=Ui(e);if(n===e)return{valid:!0,data:n};if(t===Te.object&&r===Te.object){let s=vt.objectKeys(e),i=vt.objectKeys(n).filter(a=>s.indexOf(a)!==-1),o={...n,...e};for(let a of i){let c=KS(n[a],e[a]);if(!c.valid)return{valid:!1};o[a]=c.data}return{valid:!0,data:o}}else if(t===Te.array&&r===Te.array){if(n.length!==e.length)return{valid:!1};let s=[];for(let i=0;i<n.length;i++){let o=n[i],a=e[i],c=KS(o,a);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return t===Te.date&&r===Te.date&&+n==+e?{valid:!0,data:n}:{valid:!1}}var Qc=class extends bt{_parse(e){let{status:t,ctx:r}=this._processInputParams(e),s=(i,o)=>{if(qS(i)||qS(o))return tt;let a=KS(i.value,o.value);return a.valid?((HS(i)||HS(o))&&t.dirty(),{status:t.value,value:a.data}):(Re(r,{code:ce.invalid_intersection_types}),tt)};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(([i,o])=>s(i,o)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};Qc.create=(n,e,t)=>new Qc({left:n,right:e,typeName:ue.ZodIntersection,...dt(t)});var Zi=class n extends bt{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==Te.array)return Re(r,{code:ce.invalid_type,expected:Te.array,received:r.parsedType}),tt;if(r.data.length<this._def.items.length)return Re(r,{code:ce.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),tt;!this._def.rest&&r.data.length>this._def.items.length&&(Re(r,{code:ce.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let i=[...r.data].map((o,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new As(r,o,r.path,a)):null}).filter(o=>!!o);return r.common.async?Promise.all(i).then(o=>hr.mergeArray(t,o)):hr.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new n({...this._def,rest:e})}};Zi.create=(n,e)=>{if(!Array.isArray(n))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Zi({items:n,typeName:ue.ZodTuple,rest:null,...dt(e)})};var ZS=class n extends bt{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==Te.object)return Re(r,{code:ce.invalid_type,expected:Te.object,received:r.parsedType}),tt;let s=[],i=this._def.keyType,o=this._def.valueType;for(let a in r.data)s.push({key:i._parse(new As(r,a,r.path,a)),value:o._parse(new As(r,r.data[a],r.path,a)),alwaysSet:a in r.data});return r.common.async?hr.mergeObjectAsync(t,s):hr.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,r){return t instanceof bt?new n({keyType:e,valueType:t,typeName:ue.ZodRecord,...dt(r)}):new n({keyType:Gc.create(),valueType:e,typeName:ue.ZodRecord,...dt(t)})}},Ed=class extends bt{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==Te.map)return Re(r,{code:ce.invalid_type,expected:Te.map,received:r.parsedType}),tt;let s=this._def.keyType,i=this._def.valueType,o=[...r.data.entries()].map(([a,c],l)=>({key:s._parse(new As(r,a,r.path,[l,"key"])),value:i._parse(new As(r,c,r.path,[l,"value"]))}));if(r.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of o){let l=await c.key,u=await c.value;if(l.status==="aborted"||u.status==="aborted")return tt;(l.status==="dirty"||u.status==="dirty")&&t.dirty(),a.set(l.value,u.value)}return{status:t.value,value:a}})}else{let a=new Map;for(let c of o){let l=c.key,u=c.value;if(l.status==="aborted"||u.status==="aborted")return tt;(l.status==="dirty"||u.status==="dirty")&&t.dirty(),a.set(l.value,u.value)}return{status:t.value,value:a}}}};Ed.create=(n,e,t)=>new Ed({valueType:e,keyType:n,typeName:ue.ZodMap,...dt(t)});var kd=class n extends bt{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==Te.set)return Re(r,{code:ce.invalid_type,expected:Te.set,received:r.parsedType}),tt;let s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&(Re(r,{code:ce.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),s.maxSize!==null&&r.data.size>s.maxSize.value&&(Re(r,{code:ce.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());let i=this._def.valueType;function o(c){let l=new Set;for(let u of c){if(u.status==="aborted")return tt;u.status==="dirty"&&t.dirty(),l.add(u.value)}return{status:t.value,value:l}}let a=[...r.data.values()].map((c,l)=>i._parse(new As(r,c,r.path,l)));return r.common.async?Promise.all(a).then(c=>o(c)):o(a)}min(e,t){return new n({...this._def,minSize:{value:e,message:Oe.toString(t)}})}max(e,t){return new n({...this._def,maxSize:{value:e,message:Oe.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};kd.create=(n,e)=>new kd({valueType:n,minSize:null,maxSize:null,typeName:ue.ZodSet,...dt(e)});var GS=class n extends bt{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==Te.function)return Re(t,{code:ce.invalid_type,expected:Te.function,received:t.parsedType}),tt;function r(a,c){return Km({data:a,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,gd(),_o].filter(l=>!!l),issueData:{code:ce.invalid_arguments,argumentsError:c}})}function s(a,c){return Km({data:a,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,gd(),_o].filter(l=>!!l),issueData:{code:ce.invalid_return_type,returnTypeError:c}})}let i={errorMap:t.common.contextualErrorMap},o=t.data;if(this._def.returns instanceof $a){let a=this;return Ir(async function(...c){let l=new cs([]),u=await a._def.args.parseAsync(c,i).catch(f=>{throw l.addIssue(r(c,f)),l}),d=await Reflect.apply(o,this,u);return await a._def.returns._def.type.parseAsync(d,i).catch(f=>{throw l.addIssue(s(d,f)),l})})}else{let a=this;return Ir(function(...c){let l=a._def.args.safeParse(c,i);if(!l.success)throw new cs([r(c,l.error)]);let u=Reflect.apply(o,this,l.data),d=a._def.returns.safeParse(u,i);if(!d.success)throw new cs([s(u,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new n({...this._def,args:Zi.create(e).rest(wo.create())})}returns(e){return new n({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,r){return new n({args:e||Zi.create([]).rest(wo.create()),returns:t||wo.create(),typeName:ue.ZodFunction,...dt(r)})}},Yc=class extends bt{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};Yc.create=(n,e)=>new Yc({getter:n,typeName:ue.ZodLazy,...dt(e)});var el=class extends bt{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return Re(t,{received:t.data,code:ce.invalid_literal,expected:this._def.value}),tt}return{status:"valid",value:e.data}}get value(){return this._def.value}};el.create=(n,e)=>new el({value:n,typeName:ue.ZodLiteral,...dt(e)});function tI(n,e){return new tl({values:n,typeName:ue.ZodEnum,...dt(e)})}var tl=class n extends bt{_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),r=this._def.values;return Re(t,{expected:vt.joinValues(r),received:t.parsedType,code:ce.invalid_type}),tt}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),r=this._def.values;return Re(t,{received:t.data,code:ce.invalid_enum_value,options:r}),tt}return Ir(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return n.create(e,{...this._def,...t})}exclude(e,t=this._def){return n.create(this.options.filter(r=>!e.includes(r)),{...this._def,...t})}};tl.create=tI;var nl=class extends bt{_parse(e){let t=vt.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==Te.string&&r.parsedType!==Te.number){let s=vt.objectValues(t);return Re(r,{expected:vt.joinValues(s),received:r.parsedType,code:ce.invalid_type}),tt}if(this._cache||(this._cache=new Set(vt.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=vt.objectValues(t);return Re(r,{received:r.data,code:ce.invalid_enum_value,options:s}),tt}return Ir(e.data)}get enum(){return this._def.values}};nl.create=(n,e)=>new nl({values:n,typeName:ue.ZodNativeEnum,...dt(e)});var $a=class extends bt{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==Te.promise&&t.common.async===!1)return Re(t,{code:ce.invalid_type,expected:Te.promise,received:t.parsedType}),tt;let r=t.parsedType===Te.promise?t.data:Promise.resolve(t.data);return Ir(r.then(s=>this._def.type.parseAsync(s,{path:t.path,errorMap:t.common.contextualErrorMap})))}};$a.create=(n,e)=>new $a({type:n,typeName:ue.ZodPromise,...dt(e)});var ei=class extends bt{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ue.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:r}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:o=>{Re(r,o),o.fatal?t.abort():t.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){let o=s.transform(r.data,i);if(r.common.async)return Promise.resolve(o).then(async a=>{if(t.value==="aborted")return tt;let c=await this._def.schema._parseAsync({data:a,path:r.path,parent:r});return c.status==="aborted"?tt:c.status==="dirty"?Kc(c.value):t.value==="dirty"?Kc(c.value):c});{if(t.value==="aborted")return tt;let a=this._def.schema._parseSync({data:o,path:r.path,parent:r});return a.status==="aborted"?tt:a.status==="dirty"?Kc(a.value):t.value==="dirty"?Kc(a.value):a}}if(s.type==="refinement"){let o=a=>{let c=s.refinement(a,i);if(r.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(r.common.async===!1){let a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return a.status==="aborted"?tt:(a.status==="dirty"&&t.dirty(),o(a.value),{status:t.value,value:a.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>a.status==="aborted"?tt:(a.status==="dirty"&&t.dirty(),o(a.value).then(()=>({status:t.value,value:a.value}))))}if(s.type==="transform")if(r.common.async===!1){let o=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Oa(o))return tt;let a=s.transform(o.value,i);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:a}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(o=>Oa(o)?Promise.resolve(s.transform(o.value,i)).then(a=>({status:t.value,value:a})):tt);vt.assertNever(s)}};ei.create=(n,e,t)=>new ei({schema:n,typeName:ue.ZodEffects,effect:e,...dt(t)});ei.createWithPreprocess=(n,e,t)=>new ei({schema:e,effect:{type:"preprocess",transform:n},typeName:ue.ZodEffects,...dt(t)});var ls=class extends bt{_parse(e){return this._getType(e)===Te.undefined?Ir(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ls.create=(n,e)=>new ls({innerType:n,typeName:ue.ZodOptional,...dt(e)});var Gi=class extends bt{_parse(e){return this._getType(e)===Te.null?Ir(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Gi.create=(n,e)=>new Gi({innerType:n,typeName:ue.ZodNullable,...dt(e)});var rl=class extends bt{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return t.parsedType===Te.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};rl.create=(n,e)=>new rl({innerType:n,typeName:ue.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...dt(e)});var sl=class extends bt{_parse(e){let{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return yd(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new cs(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new cs(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};sl.create=(n,e)=>new sl({innerType:n,typeName:ue.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...dt(e)});var Td=class extends bt{_parse(e){if(this._getType(e)!==Te.nan){let r=this._getOrReturnCtx(e);return Re(r,{code:ce.invalid_type,expected:Te.nan,received:r.parsedType}),tt}return{status:"valid",value:e.data}}};Td.create=n=>new Td({typeName:ue.ZodNaN,...dt(n)});var Zm=class extends bt{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}},Gm=class n extends bt{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?tt:i.status==="dirty"?(t.dirty(),Kc(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{let s=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?tt:s.status==="dirty"?(t.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(e,t){return new n({in:e,out:t,typeName:ue.ZodPipeline})}},il=class extends bt{_parse(e){let t=this._def.innerType._parse(e),r=s=>(Oa(s)&&(s.value=Object.freeze(s.value)),s);return yd(t)?t.then(s=>r(s)):r(t)}unwrap(){return this._def.innerType}};il.create=(n,e)=>new il({innerType:n,typeName:ue.ZodReadonly,...dt(e)});var Q7={object:us.lazycreate},ue;(function(n){n.ZodString="ZodString",n.ZodNumber="ZodNumber",n.ZodNaN="ZodNaN",n.ZodBigInt="ZodBigInt",n.ZodBoolean="ZodBoolean",n.ZodDate="ZodDate",n.ZodSymbol="ZodSymbol",n.ZodUndefined="ZodUndefined",n.ZodNull="ZodNull",n.ZodAny="ZodAny",n.ZodUnknown="ZodUnknown",n.ZodNever="ZodNever",n.ZodVoid="ZodVoid",n.ZodArray="ZodArray",n.ZodObject="ZodObject",n.ZodUnion="ZodUnion",n.ZodDiscriminatedUnion="ZodDiscriminatedUnion",n.ZodIntersection="ZodIntersection",n.ZodTuple="ZodTuple",n.ZodRecord="ZodRecord",n.ZodMap="ZodMap",n.ZodSet="ZodSet",n.ZodFunction="ZodFunction",n.ZodLazy="ZodLazy",n.ZodLiteral="ZodLiteral",n.ZodEnum="ZodEnum",n.ZodEffects="ZodEffects",n.ZodNativeEnum="ZodNativeEnum",n.ZodOptional="ZodOptional",n.ZodNullable="ZodNullable",n.ZodDefault="ZodDefault",n.ZodCatch="ZodCatch",n.ZodPromise="ZodPromise",n.ZodBranded="ZodBranded",n.ZodPipeline="ZodPipeline",n.ZodReadonly="ZodReadonly"})(ue||(ue={}));var Y7=Gc.create,eee=bd.create,tee=Td.create,nee=Sd.create,ree=xd.create,see=_d.create,iee=wd.create,oee=Jc.create,aee=Vc.create,cee=vd.create,lee=wo.create,uee=_i.create,dee=Rd.create,pee=vo.create,nI=us.create,fee=us.strictCreate,mee=Xc.create,hee=US.create,gee=Qc.create,yee=Zi.create,bee=ZS.create,See=Ed.create,xee=kd.create,_ee=GS.create,wee=Yc.create,vee=el.create,Ree=tl.create,Eee=nl.create,kee=$a.create,Tee=ei.create,Pee=ls.create,Cee=Gi.create,Iee=ei.createWithPreprocess,Aee=Gm.create;var G1=Object.freeze({status:"aborted"});function Y(n,e,t){function r(a,c){var l;Object.defineProperty(a,"_zod",{value:a._zod??{},enumerable:!1}),(l=a._zod).traits??(l.traits=new Set),a._zod.traits.add(n),e(a,c);for(let u in o.prototype)u in a||Object.defineProperty(a,u,{value:o.prototype[u].bind(a)});a._zod.constr=o,a._zod.def=c}let s=t?.Parent??Object;class i extends s{}Object.defineProperty(i,"name",{value:n});function o(a){var c;let l=t?.Parent?new i:this;r(l,a),(c=l._zod).deferred??(c.deferred=[]);for(let u of l._zod.deferred)u();return l}return Object.defineProperty(o,"init",{value:r}),Object.defineProperty(o,Symbol.hasInstance,{value:a=>t?.Parent&&a instanceof t.Parent?!0:a?._zod?.traits?.has(n)}),Object.defineProperty(o,"name",{value:n}),o}var Ji=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Jm={};function ds(n){return n&&Object.assign(Jm,n),Jm}var Rt={};Lt(Rt,{BIGINT_FORMAT_RANGES:()=>sI,Class:()=>VS,NUMBER_FORMAT_RANGES:()=>rx,aborted:()=>La,allowsEval:()=>ex,assert:()=>Y1,assertEqual:()=>J1,assertIs:()=>X1,assertNever:()=>Q1,assertNotEqual:()=>V1,assignProp:()=>YS,cached:()=>Id,captureStackTrace:()=>Xm,cleanEnum:()=>pq,cleanRegex:()=>Nd,clone:()=>ps,createTransparentProxy:()=>iq,defineLazy:()=>Xt,esc:()=>ja,escapeRegex:()=>Ro,extend:()=>cq,finalizeIssue:()=>ti,floatSafeRemainder:()=>QS,getElementAtPath:()=>eq,getEnumValues:()=>Cd,getLengthableOrigin:()=>Md,getParsedType:()=>sq,getSizableOrigin:()=>iI,isObject:()=>ol,isPlainObject:()=>al,issue:()=>sx,joinValues:()=>Vm,jsonStringifyReplacer:()=>XS,merge:()=>lq,normalizeParams:()=>Qe,nullish:()=>Ad,numKeys:()=>rq,omit:()=>aq,optionalKeys:()=>nx,partial:()=>uq,pick:()=>oq,prefixIssues:()=>wi,primitiveTypes:()=>rI,promiseAllObject:()=>tq,propertyKeyTypes:()=>tx,randomString:()=>nq,required:()=>dq,stringifyPrimitive:()=>Qm,unwrapMessage:()=>Pd});function J1(n){return n}function V1(n){return n}function X1(n){}function Q1(n){throw new Error}function Y1(n){}function Cd(n){let e=Object.values(n).filter(r=>typeof r=="number");return Object.entries(n).filter(([r,s])=>e.indexOf(+r)===-1).map(([r,s])=>s)}function Vm(n,e="|"){return n.map(t=>Qm(t)).join(e)}function XS(n,e){return typeof e=="bigint"?e.toString():e}function Id(n){return{get value(){{let t=n();return Object.defineProperty(this,"value",{value:t}),t}throw new Error("cached value already set")}}}function Ad(n){return n==null}function Nd(n){let e=n.startsWith("^")?1:0,t=n.endsWith("$")?n.length-1:n.length;return n.slice(e,t)}function QS(n,e){let t=(n.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,s=t>r?t:r,i=Number.parseInt(n.toFixed(s).replace(".","")),o=Number.parseInt(e.toFixed(s).replace(".",""));return i%o/10**s}function Xt(n,e,t){Object.defineProperty(n,e,{get(){{let s=t();return n[e]=s,s}throw new Error("cached value already set")},set(s){Object.defineProperty(n,e,{value:s})},configurable:!0})}function YS(n,e,t){Object.defineProperty(n,e,{value:t,writable:!0,enumerable:!0,configurable:!0})}function eq(n,e){return e?e.reduce((t,r)=>t?.[r],n):n}function tq(n){let e=Object.keys(n),t=e.map(r=>n[r]);return Promise.all(t).then(r=>{let s={};for(let i=0;i<e.length;i++)s[e[i]]=r[i];return s})}function nq(n=10){let e="abcdefghijklmnopqrstuvwxyz",t="";for(let r=0;r<n;r++)t+=e[Math.floor(Math.random()*e.length)];return t}function ja(n){return JSON.stringify(n)}var Xm=Error.captureStackTrace?Error.captureStackTrace:(...n)=>{};function ol(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}var ex=Id(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let n=Function;return new n(""),!0}catch{return!1}});function al(n){if(ol(n)===!1)return!1;let e=n.constructor;if(e===void 0)return!0;let t=e.prototype;return!(ol(t)===!1||Object.prototype.hasOwnProperty.call(t,"isPrototypeOf")===!1)}function rq(n){let e=0;for(let t in n)Object.prototype.hasOwnProperty.call(n,t)&&e++;return e}var sq=n=>{let e=typeof n;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(n)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(n)?"array":n===null?"null":n.then&&typeof n.then=="function"&&n.catch&&typeof n.catch=="function"?"promise":typeof Map<"u"&&n instanceof Map?"map":typeof Set<"u"&&n instanceof Set?"set":typeof Date<"u"&&n instanceof Date?"date":typeof File<"u"&&n instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},tx=new Set(["string","number","symbol"]),rI=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Ro(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ps(n,e,t){let r=new n._zod.constr(e??n._zod.def);return(!e||t?.parent)&&(r._zod.parent=n),r}function Qe(n){let e=n;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function iq(n){let e;return new Proxy({},{get(t,r,s){return e??(e=n()),Reflect.get(e,r,s)},set(t,r,s,i){return e??(e=n()),Reflect.set(e,r,s,i)},has(t,r){return e??(e=n()),Reflect.has(e,r)},deleteProperty(t,r){return e??(e=n()),Reflect.deleteProperty(e,r)},ownKeys(t){return e??(e=n()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(t,r){return e??(e=n()),Reflect.getOwnPropertyDescriptor(e,r)},defineProperty(t,r,s){return e??(e=n()),Reflect.defineProperty(e,r,s)}})}function Qm(n){return typeof n=="bigint"?n.toString()+"n":typeof n=="string"?`"${n}"`:`${n}`}function nx(n){return Object.keys(n).filter(e=>n[e]._zod.optin==="optional"&&n[e]._zod.optout==="optional")}var rx={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},sI={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function oq(n,e){let t={},r=n._zod.def;for(let s in e){if(!(s in r.shape))throw new Error(`Unrecognized key: "${s}"`);e[s]&&(t[s]=r.shape[s])}return ps(n,{...n._zod.def,shape:t,checks:[]})}function aq(n,e){let t={...n._zod.def.shape},r=n._zod.def;for(let s in e){if(!(s in r.shape))throw new Error(`Unrecognized key: "${s}"`);e[s]&&delete t[s]}return ps(n,{...n._zod.def,shape:t,checks:[]})}function cq(n,e){if(!al(e))throw new Error("Invalid input to extend: expected a plain object");let t={...n._zod.def,get shape(){let r={...n._zod.def.shape,...e};return YS(this,"shape",r),r},checks:[]};return ps(n,t)}function lq(n,e){return ps(n,{...n._zod.def,get shape(){let t={...n._zod.def.shape,...e._zod.def.shape};return YS(this,"shape",t),t},catchall:e._zod.def.catchall,checks:[]})}function uq(n,e,t){let r=e._zod.def.shape,s={...r};if(t)for(let i in t){if(!(i in r))throw new Error(`Unrecognized key: "${i}"`);t[i]&&(s[i]=n?new n({type:"optional",innerType:r[i]}):r[i])}else for(let i in r)s[i]=n?new n({type:"optional",innerType:r[i]}):r[i];return ps(e,{...e._zod.def,shape:s,checks:[]})}function dq(n,e,t){let r=e._zod.def.shape,s={...r};if(t)for(let i in t){if(!(i in s))throw new Error(`Unrecognized key: "${i}"`);t[i]&&(s[i]=new n({type:"nonoptional",innerType:r[i]}))}else for(let i in r)s[i]=new n({type:"nonoptional",innerType:r[i]});return ps(e,{...e._zod.def,shape:s,checks:[]})}function La(n,e=0){for(let t=e;t<n.issues.length;t++)if(n.issues[t]?.continue!==!0)return!0;return!1}function wi(n,e){return e.map(t=>{var r;return(r=t).path??(r.path=[]),t.path.unshift(n),t})}function Pd(n){return typeof n=="string"?n:n?.message}function ti(n,e,t){let r={...n,path:n.path??[]};if(!n.message){let s=Pd(n.inst?._zod.def?.error?.(n))??Pd(e?.error?.(n))??Pd(t.customError?.(n))??Pd(t.localeError?.(n))??"Invalid input";r.message=s}return delete r.inst,delete r.continue,e?.reportInput||delete r.input,r}function iI(n){return n instanceof Set?"set":n instanceof Map?"map":n instanceof File?"file":"unknown"}function Md(n){return Array.isArray(n)?"array":typeof n=="string"?"string":"unknown"}function sx(...n){let[e,t,r]=n;return typeof e=="string"?{message:e,code:"custom",input:t,inst:r}:{...e}}function pq(n){return Object.entries(n).filter(([e,t])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var VS=class{constructor(...e){}};var oI=(n,e)=>{n.name="$ZodError",Object.defineProperty(n,"_zod",{value:n._zod,enumerable:!1}),Object.defineProperty(n,"issues",{value:e,enumerable:!1}),Object.defineProperty(n,"message",{get(){return JSON.stringify(e,XS,2)},enumerable:!0}),Object.defineProperty(n,"toString",{value:()=>n.message,enumerable:!1})},Ym=Y("$ZodError",oI),Fd=Y("$ZodError",oI,{Parent:Error});function ix(n,e=t=>t.message){let t={},r=[];for(let s of n.issues)s.path.length>0?(t[s.path[0]]=t[s.path[0]]||[],t[s.path[0]].push(e(s))):r.push(e(s));return{formErrors:r,fieldErrors:t}}function ox(n,e){let t=e||function(i){return i.message},r={_errors:[]},s=i=>{for(let o of i.issues)if(o.code==="invalid_union"&&o.errors.length)o.errors.map(a=>s({issues:a}));else if(o.code==="invalid_key")s({issues:o.issues});else if(o.code==="invalid_element")s({issues:o.issues});else if(o.path.length===0)r._errors.push(t(o));else{let a=r,c=0;for(;c<o.path.length;){let l=o.path[c];c===o.path.length-1?(a[l]=a[l]||{_errors:[]},a[l]._errors.push(t(o))):a[l]=a[l]||{_errors:[]},a=a[l],c++}}};return s(n),r}var ax=n=>(e,t,r,s)=>{let i=r?Object.assign(r,{async:!1}):{async:!1},o=e._zod.run({value:t,issues:[]},i);if(o instanceof Promise)throw new Ji;if(o.issues.length){let a=new(s?.Err??n)(o.issues.map(c=>ti(c,i,ds())));throw Xm(a,s?.callee),a}return o.value},cx=ax(Fd),lx=n=>async(e,t,r,s)=>{let i=r?Object.assign(r,{async:!0}):{async:!0},o=e._zod.run({value:t,issues:[]},i);if(o instanceof Promise&&(o=await o),o.issues.length){let a=new(s?.Err??n)(o.issues.map(c=>ti(c,i,ds())));throw Xm(a,s?.callee),a}return o.value},ux=lx(Fd),dx=n=>(e,t,r)=>{let s=r?{...r,async:!1}:{async:!1},i=e._zod.run({value:t,issues:[]},s);if(i instanceof Promise)throw new Ji;return i.issues.length?{success:!1,error:new(n??Ym)(i.issues.map(o=>ti(o,s,ds())))}:{success:!0,data:i.value}},za=dx(Fd),px=n=>async(e,t,r)=>{let s=r?Object.assign(r,{async:!0}):{async:!0},i=e._zod.run({value:t,issues:[]},s);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new n(i.issues.map(o=>ti(o,s,ds())))}:{success:!0,data:i.value}},Ba=px(Fd);var aI=/^[cC][^\s-]{8,}$/,cI=/^[0-9a-z]+$/,lI=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,uI=/^[0-9a-vA-V]{20}$/,dI=/^[A-Za-z0-9]{27}$/,pI=/^[a-zA-Z0-9_-]{21}$/,fI=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var mI=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,fx=n=>n?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${n}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/;var hI=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var mq="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function gI(){return new RegExp(mq,"u")}var yI=/^(?:(?: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])$/,bI=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,SI=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,xI=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,_I=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,mx=/^[A-Za-z0-9_-]*$/,wI=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;var vI=/^\+(?:[0-9]){6,14}[0-9]$/,RI="(?:(?:\\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])))",EI=new RegExp(`^${RI}$`);function kI(n){let e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof n.precision=="number"?n.precision===-1?`${e}`:n.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${n.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function TI(n){return new RegExp(`^${kI(n)}$`)}function PI(n){let e=kI({precision:n.precision}),t=["Z"];n.local&&t.push(""),n.offset&&t.push("([+-]\\d{2}:\\d{2})");let r=`${e}(?:${t.join("|")})`;return new RegExp(`^${RI}T(?:${r})$`)}var CI=n=>{let e=n?`[\\s\\S]{${n?.minimum??0},${n?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)};var II=/^\d+$/,AI=/^-?\d+(?:\.\d+)?/i,NI=/true|false/i,MI=/null/i;var FI=/^[^A-Z]*$/,DI=/^[^a-z]*$/;var sr=Y("$ZodCheck",(n,e)=>{var t;n._zod??(n._zod={}),n._zod.def=e,(t=n._zod).onattach??(t.onattach=[])}),OI={number:"number",bigint:"bigint",object:"date"},hx=Y("$ZodCheckLessThan",(n,e)=>{sr.init(n,e);let t=OI[typeof e.value];n._zod.onattach.push(r=>{let s=r._zod.bag,i=(e.inclusive?s.maximum:s.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<i&&(e.inclusive?s.maximum=e.value:s.exclusiveMaximum=e.value)}),n._zod.check=r=>{(e.inclusive?r.value<=e.value:r.value<e.value)||r.issues.push({origin:t,code:"too_big",maximum:e.value,input:r.value,inclusive:e.inclusive,inst:n,continue:!e.abort})}}),gx=Y("$ZodCheckGreaterThan",(n,e)=>{sr.init(n,e);let t=OI[typeof e.value];n._zod.onattach.push(r=>{let s=r._zod.bag,i=(e.inclusive?s.minimum:s.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>i&&(e.inclusive?s.minimum=e.value:s.exclusiveMinimum=e.value)}),n._zod.check=r=>{(e.inclusive?r.value>=e.value:r.value>e.value)||r.issues.push({origin:t,code:"too_small",minimum:e.value,input:r.value,inclusive:e.inclusive,inst:n,continue:!e.abort})}}),$I=Y("$ZodCheckMultipleOf",(n,e)=>{sr.init(n,e),n._zod.onattach.push(t=>{var r;(r=t._zod.bag).multipleOf??(r.multipleOf=e.value)}),n._zod.check=t=>{if(typeof t.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof t.value=="bigint"?t.value%e.value===BigInt(0):QS(t.value,e.value)===0)||t.issues.push({origin:typeof t.value,code:"not_multiple_of",divisor:e.value,input:t.value,inst:n,continue:!e.abort})}}),jI=Y("$ZodCheckNumberFormat",(n,e)=>{sr.init(n,e),e.format=e.format||"float64";let t=e.format?.includes("int"),r=t?"int":"number",[s,i]=rx[e.format];n._zod.onattach.push(o=>{let a=o._zod.bag;a.format=e.format,a.minimum=s,a.maximum=i,t&&(a.pattern=II)}),n._zod.check=o=>{let a=o.value;if(t){if(!Number.isInteger(a)){o.issues.push({expected:r,format:e.format,code:"invalid_type",input:a,inst:n});return}if(!Number.isSafeInteger(a)){a>0?o.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:n,origin:r,continue:!e.abort}):o.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:n,origin:r,continue:!e.abort});return}}a<s&&o.issues.push({origin:"number",input:a,code:"too_small",minimum:s,inclusive:!0,inst:n,continue:!e.abort}),a>i&&o.issues.push({origin:"number",input:a,code:"too_big",maximum:i,inst:n})}});var LI=Y("$ZodCheckMaxLength",(n,e)=>{var t;sr.init(n,e),(t=n._zod.def).when??(t.when=r=>{let s=r.value;return!Ad(s)&&s.length!==void 0}),n._zod.onattach.push(r=>{let s=r._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<s&&(r._zod.bag.maximum=e.maximum)}),n._zod.check=r=>{let s=r.value;if(s.length<=e.maximum)return;let o=Md(s);r.issues.push({origin:o,code:"too_big",maximum:e.maximum,inclusive:!0,input:s,inst:n,continue:!e.abort})}}),zI=Y("$ZodCheckMinLength",(n,e)=>{var t;sr.init(n,e),(t=n._zod.def).when??(t.when=r=>{let s=r.value;return!Ad(s)&&s.length!==void 0}),n._zod.onattach.push(r=>{let s=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>s&&(r._zod.bag.minimum=e.minimum)}),n._zod.check=r=>{let s=r.value;if(s.length>=e.minimum)return;let o=Md(s);r.issues.push({origin:o,code:"too_small",minimum:e.minimum,inclusive:!0,input:s,inst:n,continue:!e.abort})}}),BI=Y("$ZodCheckLengthEquals",(n,e)=>{var t;sr.init(n,e),(t=n._zod.def).when??(t.when=r=>{let s=r.value;return!Ad(s)&&s.length!==void 0}),n._zod.onattach.push(r=>{let s=r._zod.bag;s.minimum=e.length,s.maximum=e.length,s.length=e.length}),n._zod.check=r=>{let s=r.value,i=s.length;if(i===e.length)return;let o=Md(s),a=i>e.length;r.issues.push({origin:o,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:r.value,inst:n,continue:!e.abort})}}),Dd=Y("$ZodCheckStringFormat",(n,e)=>{var t,r;sr.init(n,e),n._zod.onattach.push(s=>{let i=s._zod.bag;i.format=e.format,e.pattern&&(i.patterns??(i.patterns=new Set),i.patterns.add(e.pattern))}),e.pattern?(t=n._zod).check??(t.check=s=>{e.pattern.lastIndex=0,!e.pattern.test(s.value)&&s.issues.push({origin:"string",code:"invalid_format",format:e.format,input:s.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:n,continue:!e.abort})}):(r=n._zod).check??(r.check=()=>{})}),qI=Y("$ZodCheckRegex",(n,e)=>{Dd.init(n,e),n._zod.check=t=>{e.pattern.lastIndex=0,!e.pattern.test(t.value)&&t.issues.push({origin:"string",code:"invalid_format",format:"regex",input:t.value,pattern:e.pattern.toString(),inst:n,continue:!e.abort})}}),HI=Y("$ZodCheckLowerCase",(n,e)=>{e.pattern??(e.pattern=FI),Dd.init(n,e)}),WI=Y("$ZodCheckUpperCase",(n,e)=>{e.pattern??(e.pattern=DI),Dd.init(n,e)}),UI=Y("$ZodCheckIncludes",(n,e)=>{sr.init(n,e);let t=Ro(e.includes),r=new RegExp(typeof e.position=="number"?`^.{${e.position}}${t}`:t);e.pattern=r,n._zod.onattach.push(s=>{let i=s._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(r)}),n._zod.check=s=>{s.value.includes(e.includes,e.position)||s.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:s.value,inst:n,continue:!e.abort})}}),KI=Y("$ZodCheckStartsWith",(n,e)=>{sr.init(n,e);let t=new RegExp(`^${Ro(e.prefix)}.*`);e.pattern??(e.pattern=t),n._zod.onattach.push(r=>{let s=r._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(t)}),n._zod.check=r=>{r.value.startsWith(e.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:r.value,inst:n,continue:!e.abort})}}),ZI=Y("$ZodCheckEndsWith",(n,e)=>{sr.init(n,e);let t=new RegExp(`.*${Ro(e.suffix)}$`);e.pattern??(e.pattern=t),n._zod.onattach.push(r=>{let s=r._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(t)}),n._zod.check=r=>{r.value.endsWith(e.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:r.value,inst:n,continue:!e.abort})}});var GI=Y("$ZodCheckOverwrite",(n,e)=>{sr.init(n,e),n._zod.check=t=>{t.value=e.tx(t.value)}});var th=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let r=e.split(`
|
|
869
869
|
`).filter(o=>o),s=Math.min(...r.map(o=>o.length-o.trimStart().length)),i=r.map(o=>o.slice(s)).map(o=>" ".repeat(this.indent*2)+o);for(let o of i)this.content.push(o)}compile(){let e=Function,t=this?.args,s=[...(this?.content??[""]).map(i=>` ${i}`)];return new e(...t,s.join(`
|
|
870
870
|
`))}};var VI={major:4,minor:0,patch:0};var qt=Y("$ZodType",(n,e)=>{var t;n??(n={}),n._zod.def=e,n._zod.bag=n._zod.bag||{},n._zod.version=VI;let r=[...n._zod.def.checks??[]];n._zod.traits.has("$ZodCheck")&&r.unshift(n);for(let s of r)for(let i of s._zod.onattach)i(n);if(r.length===0)(t=n._zod).deferred??(t.deferred=[]),n._zod.deferred?.push(()=>{n._zod.run=n._zod.parse});else{let s=(i,o,a)=>{let c=La(i),l;for(let u of o){if(u._zod.def.when){if(!u._zod.def.when(i))continue}else if(c)continue;let d=i.issues.length,p=u._zod.check(i);if(p instanceof Promise&&a?.async===!1)throw new Ji;if(l||p instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await p,i.issues.length!==d&&(c||(c=La(i,d)))});else{if(i.issues.length===d)continue;c||(c=La(i,d))}}return l?l.then(()=>i):i};n._zod.run=(i,o)=>{let a=n._zod.parse(i,o);if(a instanceof Promise){if(o.async===!1)throw new Ji;return a.then(c=>s(c,r,o))}return s(a,r,o)}}n["~standard"]={validate:s=>{try{let i=za(n,s);return i.success?{value:i.data}:{issues:i.error?.issues}}catch{return Ba(n,s).then(o=>o.success?{value:o.data}:{issues:o.error?.issues})}},vendor:"zod",version:1}}),Od=Y("$ZodString",(n,e)=>{qt.init(n,e),n._zod.pattern=[...n?._zod.bag?.patterns??[]].pop()??CI(n._zod.bag),n._zod.parse=(t,r)=>{if(e.coerce)try{t.value=String(t.value)}catch{}return typeof t.value=="string"||t.issues.push({expected:"string",code:"invalid_type",input:t.value,inst:n}),t}}),Qt=Y("$ZodStringFormat",(n,e)=>{Dd.init(n,e),Od.init(n,e)}),bx=Y("$ZodGUID",(n,e)=>{e.pattern??(e.pattern=mI),Qt.init(n,e)}),Sx=Y("$ZodUUID",(n,e)=>{if(e.version){let r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(r===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=fx(r))}else e.pattern??(e.pattern=fx());Qt.init(n,e)}),xx=Y("$ZodEmail",(n,e)=>{e.pattern??(e.pattern=hI),Qt.init(n,e)}),_x=Y("$ZodURL",(n,e)=>{Qt.init(n,e),n._zod.check=t=>{try{let r=t.value,s=new URL(r),i=s.href;e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(s.hostname)||t.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:wI.source,input:t.value,inst:n,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(s.protocol.endsWith(":")?s.protocol.slice(0,-1):s.protocol)||t.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:t.value,inst:n,continue:!e.abort})),!r.endsWith("/")&&i.endsWith("/")?t.value=i.slice(0,-1):t.value=i;return}catch{t.issues.push({code:"invalid_format",format:"url",input:t.value,inst:n,continue:!e.abort})}}}),wx=Y("$ZodEmoji",(n,e)=>{e.pattern??(e.pattern=gI()),Qt.init(n,e)}),vx=Y("$ZodNanoID",(n,e)=>{e.pattern??(e.pattern=pI),Qt.init(n,e)}),Rx=Y("$ZodCUID",(n,e)=>{e.pattern??(e.pattern=aI),Qt.init(n,e)}),Ex=Y("$ZodCUID2",(n,e)=>{e.pattern??(e.pattern=cI),Qt.init(n,e)}),kx=Y("$ZodULID",(n,e)=>{e.pattern??(e.pattern=lI),Qt.init(n,e)}),Tx=Y("$ZodXID",(n,e)=>{e.pattern??(e.pattern=uI),Qt.init(n,e)}),Px=Y("$ZodKSUID",(n,e)=>{e.pattern??(e.pattern=dI),Qt.init(n,e)}),oA=Y("$ZodISODateTime",(n,e)=>{e.pattern??(e.pattern=PI(e)),Qt.init(n,e)}),aA=Y("$ZodISODate",(n,e)=>{e.pattern??(e.pattern=EI),Qt.init(n,e)}),cA=Y("$ZodISOTime",(n,e)=>{e.pattern??(e.pattern=TI(e)),Qt.init(n,e)}),lA=Y("$ZodISODuration",(n,e)=>{e.pattern??(e.pattern=fI),Qt.init(n,e)}),Cx=Y("$ZodIPv4",(n,e)=>{e.pattern??(e.pattern=yI),Qt.init(n,e),n._zod.onattach.push(t=>{let r=t._zod.bag;r.format="ipv4"})}),Ix=Y("$ZodIPv6",(n,e)=>{e.pattern??(e.pattern=bI),Qt.init(n,e),n._zod.onattach.push(t=>{let r=t._zod.bag;r.format="ipv6"}),n._zod.check=t=>{try{new URL(`http://[${t.value}]`)}catch{t.issues.push({code:"invalid_format",format:"ipv6",input:t.value,inst:n,continue:!e.abort})}}}),Ax=Y("$ZodCIDRv4",(n,e)=>{e.pattern??(e.pattern=SI),Qt.init(n,e)}),Nx=Y("$ZodCIDRv6",(n,e)=>{e.pattern??(e.pattern=xI),Qt.init(n,e),n._zod.check=t=>{let[r,s]=t.value.split("/");try{if(!s)throw new Error;let i=Number(s);if(`${i}`!==s)throw new Error;if(i<0||i>128)throw new Error;new URL(`http://[${r}]`)}catch{t.issues.push({code:"invalid_format",format:"cidrv6",input:t.value,inst:n,continue:!e.abort})}}});function uA(n){if(n==="")return!0;if(n.length%4!==0)return!1;try{return atob(n),!0}catch{return!1}}var Mx=Y("$ZodBase64",(n,e)=>{e.pattern??(e.pattern=_I),Qt.init(n,e),n._zod.onattach.push(t=>{t._zod.bag.contentEncoding="base64"}),n._zod.check=t=>{uA(t.value)||t.issues.push({code:"invalid_format",format:"base64",input:t.value,inst:n,continue:!e.abort})}});function hq(n){if(!mx.test(n))return!1;let e=n.replace(/[-_]/g,r=>r==="-"?"+":"/"),t=e.padEnd(Math.ceil(e.length/4)*4,"=");return uA(t)}var Fx=Y("$ZodBase64URL",(n,e)=>{e.pattern??(e.pattern=mx),Qt.init(n,e),n._zod.onattach.push(t=>{t._zod.bag.contentEncoding="base64url"}),n._zod.check=t=>{hq(t.value)||t.issues.push({code:"invalid_format",format:"base64url",input:t.value,inst:n,continue:!e.abort})}}),Dx=Y("$ZodE164",(n,e)=>{e.pattern??(e.pattern=vI),Qt.init(n,e)});function gq(n,e=null){try{let t=n.split(".");if(t.length!==3)return!1;let[r]=t;if(!r)return!1;let s=JSON.parse(atob(r));return!("typ"in s&&s?.typ!=="JWT"||!s.alg||e&&(!("alg"in s)||s.alg!==e))}catch{return!1}}var Ox=Y("$ZodJWT",(n,e)=>{Qt.init(n,e),n._zod.check=t=>{gq(t.value,e.alg)||t.issues.push({code:"invalid_format",format:"jwt",input:t.value,inst:n,continue:!e.abort})}});var rh=Y("$ZodNumber",(n,e)=>{qt.init(n,e),n._zod.pattern=n._zod.bag.pattern??AI,n._zod.parse=(t,r)=>{if(e.coerce)try{t.value=Number(t.value)}catch{}let s=t.value;if(typeof s=="number"&&!Number.isNaN(s)&&Number.isFinite(s))return t;let i=typeof s=="number"?Number.isNaN(s)?"NaN":Number.isFinite(s)?void 0:"Infinity":void 0;return t.issues.push({expected:"number",code:"invalid_type",input:s,inst:n,...i?{received:i}:{}}),t}}),$x=Y("$ZodNumber",(n,e)=>{jI.init(n,e),rh.init(n,e)}),jx=Y("$ZodBoolean",(n,e)=>{qt.init(n,e),n._zod.pattern=NI,n._zod.parse=(t,r)=>{if(e.coerce)try{t.value=!!t.value}catch{}let s=t.value;return typeof s=="boolean"||t.issues.push({expected:"boolean",code:"invalid_type",input:s,inst:n}),t}});var Lx=Y("$ZodNull",(n,e)=>{qt.init(n,e),n._zod.pattern=MI,n._zod.values=new Set([null]),n._zod.parse=(t,r)=>{let s=t.value;return s===null||t.issues.push({expected:"null",code:"invalid_type",input:s,inst:n}),t}});var zx=Y("$ZodUnknown",(n,e)=>{qt.init(n,e),n._zod.parse=t=>t}),Bx=Y("$ZodNever",(n,e)=>{qt.init(n,e),n._zod.parse=(t,r)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:n}),t)});function XI(n,e,t){n.issues.length&&e.issues.push(...wi(t,n.issues)),e.value[t]=n.value}var qx=Y("$ZodArray",(n,e)=>{qt.init(n,e),n._zod.parse=(t,r)=>{let s=t.value;if(!Array.isArray(s))return t.issues.push({expected:"array",code:"invalid_type",input:s,inst:n}),t;t.value=Array(s.length);let i=[];for(let o=0;o<s.length;o++){let a=s[o],c=e.element._zod.run({value:a,issues:[]},r);c instanceof Promise?i.push(c.then(l=>XI(l,t,o))):XI(c,t,o)}return i.length?Promise.all(i).then(()=>t):t}});function nh(n,e,t){n.issues.length&&e.issues.push(...wi(t,n.issues)),e.value[t]=n.value}function QI(n,e,t,r){n.issues.length?r[t]===void 0?t in r?e.value[t]=void 0:e.value[t]=n.value:e.issues.push(...wi(t,n.issues)):n.value===void 0?t in r&&(e.value[t]=void 0):e.value[t]=n.value}var sh=Y("$ZodObject",(n,e)=>{qt.init(n,e);let t=Id(()=>{let d=Object.keys(e.shape);for(let f of d)if(!(e.shape[f]instanceof qt))throw new Error(`Invalid element at key "${f}": expected a Zod schema`);let p=nx(e.shape);return{shape:e.shape,keys:d,keySet:new Set(d),numKeys:d.length,optionalKeys:new Set(p)}});Xt(n._zod,"propValues",()=>{let d=e.shape,p={};for(let f in d){let m=d[f]._zod;if(m.values){p[f]??(p[f]=new Set);for(let h of m.values)p[f].add(h)}}return p});let r=d=>{let p=new th(["shape","payload","ctx"]),f=t.value,m=b=>{let S=ja(b);return`shape[${S}]._zod.run({ value: input[${S}], issues: [] }, ctx)`};p.write("const input = payload.value;");let h=Object.create(null),g=0;for(let b of f.keys)h[b]=`key_${g++}`;p.write("const newResult = {}");for(let b of f.keys)if(f.optionalKeys.has(b)){let S=h[b];p.write(`const ${S} = ${m(b)};`);let _=ja(b);p.write(`
|
|
871
871
|
if (${S}.issues.length) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pando-ai",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.4",
|
|
4
4
|
"description": "AI coding firewall for Codex and Claude Code: supervised launchers, Pando MCP, policy enforcement, Claude hooks, and local provider gateway.",
|
|
5
5
|
"bin": {
|
|
6
6
|
"pando-ai": "bin/pando-ai.js"
|
|
Binary file
|
|
Binary file
|