From c5129ed01611e1a4a5ee8ae3d818a2c53e9622e2 Mon Sep 17 00:00:00 2001 From: Alex Newman Date: Sat, 4 Apr 2026 14:58:05 -0700 Subject: [PATCH] chore: bump version to 10.7.0 Co-Authored-By: Claude Opus 4.6 (1M context) --- .agent/rules/claude-mem-context.md | 7 ++ .claude-plugin/marketplace.json | 2 +- .github/copilot-instructions.md | 7 ++ .windsurf/rules/claude-mem-context.md | 68 ++++++++++++++++++ WARP.md | 7 ++ package.json | 2 +- plugin/.claude-plugin/plugin.json | 2 +- plugin/package.json | 2 +- plugin/scripts/mcp-server.cjs | 2 +- plugin/scripts/worker-service.cjs | 71 ++++++++++--------- plugin/skills/version-bump/SKILL.md | 42 +++++++++++ .../scripts/generate_changelog.js | 37 ++++++++++ 12 files changed, 209 insertions(+), 40 deletions(-) create mode 100644 .agent/rules/claude-mem-context.md create mode 100644 .github/copilot-instructions.md create mode 100644 .windsurf/rules/claude-mem-context.md create mode 100644 WARP.md create mode 100644 plugin/skills/version-bump/SKILL.md create mode 100755 plugin/skills/version-bump/scripts/generate_changelog.js diff --git a/.agent/rules/claude-mem-context.md b/.agent/rules/claude-mem-context.md new file mode 100644 index 00000000..66d02575 --- /dev/null +++ b/.agent/rules/claude-mem-context.md @@ -0,0 +1,7 @@ + +# claude-mem: Cross-Session Memory + +*No context yet. Complete your first session and context will appear here.* + +Use claude-mem's MCP search tools for manual memory queries. + diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index eaad88b2..33c232e8 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -10,7 +10,7 @@ "plugins": [ { "name": "claude-mem", - "version": "10.6.3", + "version": "10.7.0", "source": "./plugin", "description": "Persistent memory system for Claude Code - context compression across sessions" } diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md new file mode 100644 index 00000000..66d02575 --- /dev/null +++ b/.github/copilot-instructions.md @@ -0,0 +1,7 @@ + +# claude-mem: Cross-Session Memory + +*No context yet. Complete your first session and context will appear here.* + +Use claude-mem's MCP search tools for manual memory queries. + diff --git a/.windsurf/rules/claude-mem-context.md b/.windsurf/rules/claude-mem-context.md new file mode 100644 index 00000000..4ad41cd3 --- /dev/null +++ b/.windsurf/rules/claude-mem-context.md @@ -0,0 +1,68 @@ +# Memory Context from Past Sessions + +The following context is from claude-mem, a persistent memory system that tracks your coding sessions. + +# $CMEM claude-mem 2026-04-03 6:48pm PDT + +Legend: 🎯session πŸ”΄bugfix 🟣feature πŸ”„refactor βœ…change πŸ”΅discovery βš–οΈdecision +Format: ID TIME TYPE TITLE +Fetch details: get_observations([IDs]) | Search: mem-search skill + +Stats: 50 obs (18,868t read) | 401,168t work | 95% savings + +### Apr 3, 2026 +62994 1:47p πŸ”΄ Merge Commit Finalized on thedotmack/npx-gemini-cli Branch +62995 1:48p πŸ”΅ Worker Running but Health Endpoint Doesn't Accept POST +62996 " πŸ”΅ Worker Health Endpoint Returns Detailed Status via GET +62997 1:49p πŸ”΅ Worker Service Timeout and Shutdown Behavior in worker-service.ts +62998 " πŸ”΅ claude-mem Hook Architecture Defined in plugin/hooks/hooks.json +62999 " πŸ”΅ Session Idle Timeout Architecture: Two-Tier System in claude-mem +63000 " πŸ”΅ Orphan Reaper Runs Every 30 Seconds; Sessions Orphaned After 6 Hours +63001 1:51p πŸ”΅ POST /api/sessions/complete Removes Sessions from Active Map to Unblock Orphan Reaper +63002 1:52p πŸ”΅ Stop Hook Summarize Flow: Extracts Last Assistant Message from Transcript +63004 " πŸ”΅ POST /api/sessions/summarize: Privacy Check Before Queuing SDK Agent +63005 " πŸ”΅ SessionManager.deleteSession Verifies Subprocess Exit to Prevent Zombies +63007 " πŸ”΅ deleteSession: 4-Step Teardown with Generator and Subprocess Timeouts +63008 1:53p πŸ”΅ Queue Depth Always Read from Database; Generator Restarts Capped at 3 +63009 " πŸ”΄ Fixed Lost Summaries: session-complete Now Waits for Pending Work Before Deleting Session +63010 1:54p πŸ”΄ SessionEnd Hook Timeout Increased to 180s +63014 2:00p πŸ”΅ claude-mem Hook Architecture and Exit Code System +63015 2:01p πŸ”΅ SessionEnd Hook Has a 1.5s Default Timeout Controlled by Environment Variable +63016 2:02p πŸ”΄ Stop Hook Now Owns Full Session Lifecycle: Summarize β†’ Poll β†’ Complete +63017 " πŸ”΅ Missing /api/sessions/status Route β€” Only DB-ID Variant Exists +63018 2:03p πŸ”΄ Added /api/sessions/status Route Registration to SessionRoutes +63020 " 🟣 Added handleStatusByClaudeId Handler for GET /api/sessions/status +63022 " πŸ”„ Removed Pending-Work Polling from /api/sessions/complete β€” Moved to Stop Hook +63024 " πŸ”„ SessionEnd Hook Reverted to Fast Fire-and-Forget (2s Timeout) +63026 2:04p πŸ”΅ claude-mem hooks.json Full Hook Lifecycle Configuration +63027 2:05p βœ… Push to Pull Request +63028 " πŸ”΅ Pre-Push State: claude-mem Repository Changes +63029 " πŸ”΄ Fix Lost Summaries: Move Summary Wait into Stop Hook +63035 2:11p βœ… Testing Plan Created for tmux-cli npx Installation Flows +63036 2:12p πŸ”΅ claude-mem Supports 13 npx Installation Flows Across IDE Integrations +63037 " πŸ”΅ Detailed Integration Strategies for All 13 claude-mem npx Installation Flows +63038 2:13p βœ… NPX Install Flow Test Plan Document Created +63039 " βœ… 12 TODO Tasks Created for npx Install Flow Testing +63040 2:19p 🟣 Comprehensive Test Suite Requested for Claude-Mem CLI +63041 2:20p πŸ”΅ NPX Install Flow Test Plan Exists for 12 IDE Integrations +63042 " 🟣 Phase 2 E2E Runtime Testing Added to NPX Install Test Plan +63043 " βœ… Test Tasks Updated with Phase 2 E2E Runtime Steps for 5 IDE Flows +63044 " βœ… All Remaining Test Tasks (6–12) Updated with Phase 2 E2E Runtime Steps +63079 6:31p βš–οΈ Test Execution via Subagents Using /do Command +63080 6:32p πŸ”΅ IDE Auto-Detection Module in claude-mem +63081 " πŸ”΅ Install Command Architecture with Multi-IDE Dispatch +63082 " πŸ”΅ MCP Integrations Module for 6 IDEs +63083 " πŸ”΅ Cursor, Windsurf, and Gemini CLI Hook-Based Integrations +63084 " πŸ”΅ OpenCode, OpenClaw, and Codex CLI Installers +63085 6:33p πŸ”΅ tmux-cli Available for Automated Testing +63086 " πŸ”΅ NPX Install Flow Test Plan β€” 12 IDE Flows +63087 6:34p 🟣 Detailed Test Execution Plan Created for NPX Install Flows +63103 6:47p πŸ”΅ NPX Install Fails for Windsurf IDE with Missing rxjs Dependency +63104 " πŸ”΅ Windsurf Install Failure Was a Dependency Ordering Race +63105 " 🟣 claude-mem Gemini CLI Integration: 8 Hooks Registered +63106 " 🟣 claude-mem OpenCode Integration: Plugin File + AGENTS.md Context + +Access 401k tokens of past work via get_observations([IDs]) or mem-search skill. + +--- +*Auto-updated by claude-mem after each session. Use MCP search tools for detailed queries.* diff --git a/WARP.md b/WARP.md new file mode 100644 index 00000000..66d02575 --- /dev/null +++ b/WARP.md @@ -0,0 +1,7 @@ + +# claude-mem: Cross-Session Memory + +*No context yet. Complete your first session and context will appear here.* + +Use claude-mem's MCP search tools for manual memory queries. + diff --git a/package.json b/package.json index a8ffc6c2..7be21de3 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "claude-mem", - "version": "10.6.3", + "version": "10.7.0", "description": "Memory compression system for Claude Code - persist context across sessions", "keywords": [ "claude", diff --git a/plugin/.claude-plugin/plugin.json b/plugin/.claude-plugin/plugin.json index dd46118e..8057fa64 100644 --- a/plugin/.claude-plugin/plugin.json +++ b/plugin/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "claude-mem", - "version": "10.6.3", + "version": "10.7.0", "description": "Persistent memory system for Claude Code - seamlessly preserve context across sessions", "author": { "name": "Alex Newman" diff --git a/plugin/package.json b/plugin/package.json index 86f8d58c..f48e1394 100644 --- a/plugin/package.json +++ b/plugin/package.json @@ -1,6 +1,6 @@ { "name": "claude-mem-plugin", - "version": "10.6.3", + "version": "10.7.0", "private": true, "description": "Runtime dependencies for claude-mem bundled hooks", "type": "module", diff --git a/plugin/scripts/mcp-server.cjs b/plugin/scripts/mcp-server.cjs index 41828456..13c94184 100755 --- a/plugin/scripts/mcp-server.cjs +++ b/plugin/scripts/mcp-server.cjs @@ -114,7 +114,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs. ${c}`}var bP=new Set([".js",".jsx",".ts",".tsx",".mjs",".cjs",".py",".pyw",".go",".rs",".rb",".java",".cs",".cpp",".c",".h",".hpp",".swift",".kt",".php",".vue",".svelte"]),xP=new Set(["node_modules",".git","dist","build",".next","__pycache__",".venv","venv","env",".env","target","vendor",".cache",".turbo","coverage",".nyc_output",".claude",".smart-file-read"]),kP=512*1024;async function*n$(e,t,r=20){if(r<=0)return;let n;try{n=await(0,Sn.readdir)(e,{withFileTypes:!0})}catch{return}for(let o of n){if(o.name.startsWith(".")&&o.name!=="."||xP.has(o.name))continue;let i=(0,pi.join)(e,o.name);if(o.isDirectory())yield*n$(i,t,r-1);else if(o.isFile()){let a=o.name.slice(o.name.lastIndexOf("."));bP.has(a)&&(yield i)}}}async function SP(e){try{let t=await(0,Sn.stat)(e);if(t.size>kP||t.size===0)return null;let r=await(0,Sn.readFile)(e,"utf-8");return r.slice(0,1e3).includes("\0")?null:r}catch{return null}}async function o$(e,t,r={}){let n=r.maxResults||20,o=t.toLowerCase(),i=o.split(/[\s_\-./]+/).filter(h=>h.length>0),a=[];for await(let h of n$(e,e)){if(r.filePattern&&!(0,pi.relative)(e,h).toLowerCase().includes(r.filePattern.toLowerCase()))continue;let _=await SP(h);_&&a.push({absolutePath:h,relativePath:(0,pi.relative)(e,h),content:_})}let s=e$(a),c=[],u=[],l=0;for(let[h,_]of s){l+=wP(_);let E=Os(h.toLowerCase(),i)>0,I=[],A=(j,Le)=>{for(let de of j){let Wt=0,Qe="",Kt=Os(de.name.toLowerCase(),i);Kt>0&&(Wt+=Kt*3,Qe="name match"),de.signature.toLowerCase().includes(o)&&(Wt+=2,Qe=Qe?`${Qe} + signature`:"signature match"),de.jsdoc&&de.jsdoc.toLowerCase().includes(o)&&(Wt+=1,Qe=Qe?`${Qe} + jsdoc`:"jsdoc match"),Wt>0&&(E=!0,I.push({filePath:h,symbolName:Le?`${Le}.${de.name}`:de.name,kind:de.kind,signature:de.signature,jsdoc:de.jsdoc,lineStart:de.lineStart,lineEnd:de.lineEnd,matchReason:Qe})),de.children&&A(de.children,de.name)}};A(_.symbols),E&&(c.push(_),u.push(...I))}u.sort((h,_)=>{let b=Os(h.symbolName.toLowerCase(),i);return Os(_.symbolName.toLowerCase(),i)-b});let d=u.slice(0,n),m=new Set(d.map(h=>h.filePath)),p=c.filter(h=>m.has(h.filePath)).slice(0,n),g=p.reduce((h,_)=>h+_.foldedTokenEstimate,0);return{foldedFiles:p,matchingSymbols:d,totalFilesScanned:a.length,totalSymbolsFound:l,tokenEstimate:g}}function Os(e,t){let r=0;for(let n of t)if(e===n)r+=10;else if(e.includes(n))r+=5;else{let o=0,i=0;for(let a of n){let s=e.indexOf(a,o);s!==-1&&(i++,o=s+1)}i===n.length&&(r+=1)}return r}function wP(e){let t=e.symbols.length;for(let r of e.symbols)r.children&&(t+=r.children.length);return t}function i$(e,t){let r=[];if(r.push(`\u{1F50D} Smart Search: "${t}"`),r.push(` Scanned ${e.totalFilesScanned} files, found ${e.totalSymbolsFound} symbols`),r.push(` ${e.matchingSymbols.length} matches across ${e.foldedFiles.length} files (~${e.tokenEstimate} tokens for folded view)`),r.push(""),e.matchingSymbols.length===0)return r.push(" No matching symbols found."),r.join(` `);r.push("\u2500\u2500 Matching Symbols \u2500\u2500"),r.push("");for(let n of e.matchingSymbols){if(r.push(` ${n.kind} ${n.symbolName} (${n.filePath}:${n.lineStart+1})`),r.push(` ${n.signature}`),n.jsdoc){let o=n.jsdoc.split(` `).find(i=>i.replace(/^[\s*/]+/,"").trim().length>0);o&&r.push(` \u{1F4AC} ${o.replace(/^[\s*/]+/,"").trim()}`)}r.push("")}r.push("\u2500\u2500 Folded File Views \u2500\u2500"),r.push("");for(let n of e.foldedFiles)r.push(kn(n)),r.push("");return r.push("\u2500\u2500 Actions \u2500\u2500"),r.push(" To see full implementation: use smart_unfold with file path and symbol name"),r.join(` -`)}var Of=require("node:fs/promises"),js=require("node:path"),zP="10.6.3";console.log=(...e)=>{ve.error("CONSOLE","Intercepted console output (MCP protocol protection)",void 0,{args:e})};var a$={search:"/api/search",timeline:"/api/timeline"};async function s$(e,t){ve.debug("SYSTEM","\u2192 Worker API",void 0,{endpoint:e,params:t});try{let r=new URLSearchParams;for(let[a,s]of Object.entries(t))s!=null&&r.append(a,String(s));let n=`${e}?${r}`,o=await Ts(n);if(!o.ok){let a=await o.text();throw new Error(`Worker API error (${o.status}): ${a}`)}let i=await o.json();return ve.debug("SYSTEM","\u2190 Worker API success",void 0,{endpoint:e}),i}catch(r){return ve.error("SYSTEM","\u2190 Worker API error",{endpoint:e},r),{content:[{type:"text",text:`Error calling Worker API: ${r instanceof Error?r.message:String(r)}`}],isError:!0}}}async function IP(e,t){ve.debug("HTTP","Worker API request (POST)",void 0,{endpoint:e});try{let r=await Ts(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok){let o=await r.text();throw new Error(`Worker API error (${r.status}): ${o}`)}let n=await r.json();return ve.debug("HTTP","Worker API success (POST)",void 0,{endpoint:e}),{content:[{type:"text",text:JSON.stringify(n,null,2)}]}}catch(r){return ve.error("HTTP","Worker API error (POST)",{endpoint:e},r),{content:[{type:"text",text:`Error calling Worker API: ${r instanceof Error?r.message:String(r)}`}],isError:!0}}}async function EP(){try{return(await Ts("/api/health")).ok}catch(e){return ve.debug("SYSTEM","Worker health check failed",{},e),!1}}var c$=[{name:"__IMPORTANT",description:`3-LAYER WORKFLOW (ALWAYS FOLLOW): +`)}var Of=require("node:fs/promises"),js=require("node:path"),zP="10.7.0";console.log=(...e)=>{ve.error("CONSOLE","Intercepted console output (MCP protocol protection)",void 0,{args:e})};var a$={search:"/api/search",timeline:"/api/timeline"};async function s$(e,t){ve.debug("SYSTEM","\u2192 Worker API",void 0,{endpoint:e,params:t});try{let r=new URLSearchParams;for(let[a,s]of Object.entries(t))s!=null&&r.append(a,String(s));let n=`${e}?${r}`,o=await Ts(n);if(!o.ok){let a=await o.text();throw new Error(`Worker API error (${o.status}): ${a}`)}let i=await o.json();return ve.debug("SYSTEM","\u2190 Worker API success",void 0,{endpoint:e}),i}catch(r){return ve.error("SYSTEM","\u2190 Worker API error",{endpoint:e},r),{content:[{type:"text",text:`Error calling Worker API: ${r instanceof Error?r.message:String(r)}`}],isError:!0}}}async function IP(e,t){ve.debug("HTTP","Worker API request (POST)",void 0,{endpoint:e});try{let r=await Ts(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok){let o=await r.text();throw new Error(`Worker API error (${r.status}): ${o}`)}let n=await r.json();return ve.debug("HTTP","Worker API success (POST)",void 0,{endpoint:e}),{content:[{type:"text",text:JSON.stringify(n,null,2)}]}}catch(r){return ve.error("HTTP","Worker API error (POST)",{endpoint:e},r),{content:[{type:"text",text:`Error calling Worker API: ${r instanceof Error?r.message:String(r)}`}],isError:!0}}}async function EP(){try{return(await Ts("/api/health")).ok}catch(e){return ve.debug("SYSTEM","Worker health check failed",{},e),!1}}var c$=[{name:"__IMPORTANT",description:`3-LAYER WORKFLOW (ALWAYS FOLLOW): 1. search(query) \u2192 Get index with IDs (~50-100 tokens/result) 2. timeline(anchor=ID) \u2192 Get context around interesting results 3. get_observations([IDs]) \u2192 Fetch full details ONLY for filtered IDs diff --git a/plugin/scripts/worker-service.cjs b/plugin/scripts/worker-service.cjs index 85b7c2d2..08a0d40a 100755 --- a/plugin/scripts/worker-service.cjs +++ b/plugin/scripts/worker-service.cjs @@ -8,7 +8,7 @@ var __dirname = require("node:path").dirname(__filename); || ${o} === "boolean" || ${i} === null`).assign(a,(0,je._)`[${i}]`)}}}function ZW({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,je._)`${e} !== undefined`,()=>t.assign((0,je._)`${e}[${r}]`,n))}function jw(t,e,r,n=pc.Correct){let i=n===pc.Correct?je.operators.EQ:je.operators.NEQ,s;switch(t){case"null":return(0,je._)`${e} ${i} null`;case"array":s=(0,je._)`Array.isArray(${e})`;break;case"object":s=(0,je._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=o((0,je._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=o();break;default:return(0,je._)`typeof ${e} ${i} ${t}`}return n===pc.Correct?s:(0,je.not)(s);function o(a=je.nil){return(0,je.and)((0,je._)`typeof ${e} == "number"`,a,r?(0,je._)`isFinite(${e})`:je.nil)}}Nr.checkDataType=jw;function zw(t,e,r,n){if(t.length===1)return jw(t[0],e,r,n);let i,s=(0,MC.toHash)(t);if(s.array&&s.object){let o=(0,je._)`typeof ${e} != "object"`;i=s.null?o:(0,je._)`!${e} || ${o}`,delete s.null,delete s.array,delete s.object}else i=je.nil;s.number&&delete s.integer;for(let o in s)i=(0,je.and)(i,jw(o,e,r,n));return i}Nr.checkDataTypes=zw;var BW={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,je._)`{type: ${t}}`:(0,je._)`{type: ${e}}`};function Lw(t){let e=GW(t);(0,LW.reportError)(e,BW)}Nr.reportTypeError=Lw;function GW(t){let{gen:e,data:r,schema:n}=t,i=(0,MC.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:i,schemaValue:i,parentSchema:n,params:{},it:t}}});var LC=$(fh=>{"use strict";Object.defineProperty(fh,"__esModule",{value:!0});fh.assignDefaults=void 0;var fc=Ue(),WW=it();function VW(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let i in r)zC(t,i,r[i].default);else e==="array"&&Array.isArray(n)&&n.forEach((i,s)=>zC(t,s,i.default))}fh.assignDefaults=VW;function zC(t,e,r){let{gen:n,compositeRule:i,data:s,opts:o}=t;if(r===void 0)return;let a=(0,fc._)`${s}${(0,fc.getProperty)(e)}`;if(i){(0,WW.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,fc._)`${a} === undefined`;o.useDefaults==="empty"&&(c=(0,fc._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,fc._)`${a} = ${(0,fc.stringify)(r)}`)}});var Fn=$(gt=>{"use strict";Object.defineProperty(gt,"__esModule",{value:!0});gt.validateUnion=gt.validateArray=gt.usePattern=gt.callValidateCode=gt.schemaProperties=gt.allSchemaProperties=gt.noPropertyInData=gt.propertyInData=gt.isOwnProperty=gt.hasPropFunc=gt.reportMissingProp=gt.checkMissingProp=gt.checkReportMissingProp=void 0;var Ct=Ue(),Uw=it(),eo=gs(),KW=it();function JW(t,e){let{gen:r,data:n,it:i}=t;r.if(qw(r,n,e,i.opts.ownProperties),()=>{t.setParams({missingProperty:(0,Ct._)`${e}`},!0),t.error()})}gt.checkReportMissingProp=JW;function XW({gen:t,data:e,it:{opts:r}},n,i){return(0,Ct.or)(...n.map(s=>(0,Ct.and)(qw(t,e,s,r.ownProperties),(0,Ct._)`${i} = ${s}`)))}gt.checkMissingProp=XW;function YW(t,e){t.setParams({missingProperty:e},!0),t.error()}gt.reportMissingProp=YW;function UC(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,Ct._)`Object.prototype.hasOwnProperty`})}gt.hasPropFunc=UC;function Fw(t,e,r){return(0,Ct._)`${UC(t)}.call(${e}, ${r})`}gt.isOwnProperty=Fw;function QW(t,e,r,n){let i=(0,Ct._)`${e}${(0,Ct.getProperty)(r)} !== undefined`;return n?(0,Ct._)`${i} && ${Fw(t,e,r)}`:i}gt.propertyInData=QW;function qw(t,e,r,n){let i=(0,Ct._)`${e}${(0,Ct.getProperty)(r)} === undefined`;return n?(0,Ct.or)(i,(0,Ct.not)(Fw(t,e,r))):i}gt.noPropertyInData=qw;function FC(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}gt.allSchemaProperties=FC;function eV(t,e){return FC(e).filter(r=>!(0,Uw.alwaysValidSchema)(t,e[r]))}gt.schemaProperties=eV;function tV({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:i,errorPath:s},it:o},a,c,u){let l=u?(0,Ct._)`${t}, ${e}, ${n}${i}`:e,d=[[eo.default.instancePath,(0,Ct.strConcat)(eo.default.instancePath,s)],[eo.default.parentData,o.parentData],[eo.default.parentDataProperty,o.parentDataProperty],[eo.default.rootData,eo.default.rootData]];o.opts.dynamicRef&&d.push([eo.default.dynamicAnchors,eo.default.dynamicAnchors]);let p=(0,Ct._)`${l}, ${r.object(...d)}`;return c!==Ct.nil?(0,Ct._)`${a}.call(${c}, ${p})`:(0,Ct._)`${a}(${p})`}gt.callValidateCode=tV;var rV=(0,Ct._)`new RegExp`;function nV({gen:t,it:{opts:e}},r){let n=e.unicodeRegExp?"u":"",{regExp:i}=e.code,s=i(r,n);return t.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,Ct._)`${i.code==="new RegExp"?rV:(0,KW.useFunc)(t,i)}(${r}, ${n})`})}gt.usePattern=nV;function iV(t){let{gen:e,data:r,keyword:n,it:i}=t,s=e.name("valid");if(i.allErrors){let a=e.let("valid",!0);return o(()=>e.assign(a,!1)),a}return e.var(s,!0),o(()=>e.break()),s;function o(a){let c=e.const("len",(0,Ct._)`${r}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:n,dataProp:u,dataPropType:Uw.Type.Num},s),e.if((0,Ct.not)(s),a)})}}gt.validateArray=iV;function sV(t){let{gen:e,schema:r,keyword:n,it:i}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(c=>(0,Uw.alwaysValidSchema)(i,c))&&!i.opts.unevaluated)return;let o=e.let("valid",!1),a=e.name("_valid");e.block(()=>r.forEach((c,u)=>{let l=t.subschema({keyword:n,schemaProp:u,compositeRule:!0},a);e.assign(o,(0,Ct._)`${o} || ${a}`),t.mergeValidEvaluated(l,a)||e.if((0,Ct.not)(o))})),t.result(o,()=>t.reset(),()=>t.error(!0))}gt.validateUnion=sV});var ZC=$(Ai=>{"use strict";Object.defineProperty(Ai,"__esModule",{value:!0});Ai.validateKeywordUsage=Ai.validSchemaType=Ai.funcKeywordCode=Ai.macroKeywordCode=void 0;var Kr=Ue(),Zo=gs(),oV=Fn(),aV=fd();function cV(t,e){let{gen:r,keyword:n,schema:i,parentSchema:s,it:o}=t,a=e.macro.call(o.self,i,s,o),c=HC(r,n,a);o.opts.validateSchema!==!1&&o.self.validateSchema(a,!0);let u=r.name("valid");t.subschema({schema:a,schemaPath:Kr.nil,errSchemaPath:`${o.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}Ai.macroKeywordCode=cV;function uV(t,e){var r;let{gen:n,keyword:i,schema:s,parentSchema:o,$data:a,it:c}=t;dV(c,e);let u=!a&&e.compile?e.compile.call(c.self,s,o,c):e.validate,l=HC(n,i,u),d=n.let("valid");t.block$data(d,p),t.ok((r=e.valid)!==null&&r!==void 0?r:d);function p(){if(e.errors===!1)h(),e.modifying&&qC(t),g(()=>t.error());else{let v=e.async?f():m();e.modifying&&qC(t),g(()=>lV(t,v))}}function f(){let v=n.let("ruleErrs",null);return n.try(()=>h((0,Kr._)`await `),S=>n.assign(d,!1).if((0,Kr._)`${S} instanceof ${c.ValidationError}`,()=>n.assign(v,(0,Kr._)`${S}.errors`),()=>n.throw(S))),v}function m(){let v=(0,Kr._)`${l}.errors`;return n.assign(v,null),h(Kr.nil),v}function h(v=e.async?(0,Kr._)`await `:Kr.nil){let S=c.opts.passContext?Zo.default.this:Zo.default.self,_=!("compile"in e&&!a||e.schema===!1);n.assign(d,(0,Kr._)`${v}${(0,oV.callValidateCode)(t,l,S,_)}`,e.modifying)}function g(v){var S;n.if((0,Kr.not)((S=e.valid)!==null&&S!==void 0?S:d),v)}}Ai.funcKeywordCode=uV;function qC(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,Kr._)`${n.parentData}[${n.parentDataProperty}]`))}function lV(t,e){let{gen:r}=t;r.if((0,Kr._)`Array.isArray(${e})`,()=>{r.assign(Zo.default.vErrors,(0,Kr._)`${Zo.default.vErrors} === null ? ${e} : ${Zo.default.vErrors}.concat(${e})`).assign(Zo.default.errors,(0,Kr._)`${Zo.default.vErrors}.length`),(0,aV.extendErrors)(t)},()=>t.error())}function dV({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function HC(t,e,r){if(r===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,Kr.stringify)(r)})}function pV(t,e,r=!1){return!e.length||e.some(n=>n==="array"?Array.isArray(t):n==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==n||r&&typeof t>"u")}Ai.validSchemaType=pV;function fV({schema:t,opts:e,self:r,errSchemaPath:n},i,s){if(Array.isArray(i.keyword)?!i.keyword.includes(s):i.keyword!==s)throw new Error("ajv implementation error");let o=i.dependencies;if(o?.some(a=>!Object.prototype.hasOwnProperty.call(t,a)))throw new Error(`parent schema must have dependencies of ${s}: ${o.join(",")}`);if(i.validateSchema&&!i.validateSchema(t[s])){let c=`keyword "${s}" value is invalid at path "${n}": `+r.errorsText(i.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}Ai.validateKeywordUsage=fV});var GC=$(to=>{"use strict";Object.defineProperty(to,"__esModule",{value:!0});to.extendSubschemaMode=to.extendSubschemaData=to.getSubschema=void 0;var Ni=Ue(),BC=it();function mV(t,{keyword:e,schemaProp:r,schema:n,schemaPath:i,errSchemaPath:s,topSchemaRef:o}){if(e!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=t.schema[e];return r===void 0?{schema:a,schemaPath:(0,Ni._)`${t.schemaPath}${(0,Ni.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,Ni._)`${t.schemaPath}${(0,Ni.getProperty)(e)}${(0,Ni.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,BC.escapeFragment)(r)}`}}if(n!==void 0){if(i===void 0||s===void 0||o===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:i,topSchemaRef:o,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}to.getSubschema=mV;function hV(t,e,{dataProp:r,dataPropType:n,data:i,dataTypes:s,propertyName:o}){if(i!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(r!==void 0){let{errorPath:u,dataPathArr:l,opts:d}=e,p=a.let("data",(0,Ni._)`${e.data}${(0,Ni.getProperty)(r)}`,!0);c(p),t.errorPath=(0,Ni.str)`${u}${(0,BC.getErrorPath)(r,n,d.jsPropertySyntax)}`,t.parentDataProperty=(0,Ni._)`${r}`,t.dataPathArr=[...l,t.parentDataProperty]}if(i!==void 0){let u=i instanceof Ni.Name?i:a.let("data",i,!0);c(u),o!==void 0&&(t.propertyName=o)}s&&(t.dataTypes=s);function c(u){t.data=u,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,u]}}to.extendSubschemaData=hV;function gV(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:n,createErrors:i,allErrors:s}){n!==void 0&&(t.compositeRule=n),i!==void 0&&(t.createErrors=i),s!==void 0&&(t.allErrors=s),t.jtdDiscriminator=e,t.jtdMetadata=r}to.extendSubschemaMode=gV});var Hw=$((h1e,WC)=>{"use strict";WC.exports=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var n,i,s;if(Array.isArray(e)){if(n=e.length,n!=r.length)return!1;for(i=n;i--!==0;)if(!t(e[i],r[i]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(s=Object.keys(e),n=s.length,n!==Object.keys(r).length)return!1;for(i=n;i--!==0;)if(!Object.prototype.hasOwnProperty.call(r,s[i]))return!1;for(i=n;i--!==0;){var o=s[i];if(!t(e[o],r[o]))return!1}return!0}return e!==e&&r!==r}});var KC=$((g1e,VC)=>{"use strict";var ro=VC.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var n=typeof r=="function"?r:r.pre||function(){},i=r.post||function(){};mh(e,n,i,t,"",t)};ro.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};ro.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};ro.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};ro.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function mh(t,e,r,n,i,s,o,a,c,u){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,i,s,o,a,c,u);for(var l in n){var d=n[l];if(Array.isArray(d)){if(l in ro.arrayKeywords)for(var p=0;p{"use strict";Object.defineProperty(un,"__esModule",{value:!0});un.getSchemaRefs=un.resolveUrl=un.normalizeId=un._getFullPath=un.getFullPath=un.inlineRef=void 0;var yV=it(),_V=Hw(),bV=KC(),SV=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function xV(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Zw(t):e?JC(t)<=e:!1}un.inlineRef=xV;var wV=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Zw(t){for(let e in t){if(wV.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(Zw)||typeof r=="object"&&Zw(r))return!0}return!1}function JC(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!SV.has(r)&&(typeof t[r]=="object"&&(0,yV.eachItem)(t[r],n=>e+=JC(n)),e===1/0))return 1/0}return e}function XC(t,e="",r){r!==!1&&(e=mc(e));let n=t.parse(e);return YC(t,n)}un.getFullPath=XC;function YC(t,e){return t.serialize(e).split("#")[0]+"#"}un._getFullPath=YC;var EV=/#\/?$/;function mc(t){return t?t.replace(EV,""):""}un.normalizeId=mc;function kV(t,e,r){return r=mc(r),t.resolve(e,r)}un.resolveUrl=kV;var TV=/^[a-z_][-a-z0-9._]*$/i;function $V(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,i=mc(t[r]||e),s={"":i},o=XC(n,i,!1),a={},c=new Set;return bV(t,{allKeys:!0},(d,p,f,m)=>{if(m===void 0)return;let h=o+p,g=s[m];typeof d[r]=="string"&&(g=v.call(this,d[r])),S.call(this,d.$anchor),S.call(this,d.$dynamicAnchor),s[p]=g;function v(_){let y=this.opts.uriResolver.resolve;if(_=mc(g?y(g,_):_),c.has(_))throw l(_);c.add(_);let x=this.refs[_];return typeof x=="string"&&(x=this.refs[x]),typeof x=="object"?u(d,x.schema,_):_!==mc(h)&&(_[0]==="#"?(u(d,a[_],_),a[_]=d):this.refs[_]=h),_}function S(_){if(typeof _=="string"){if(!TV.test(_))throw new Error(`invalid anchor "${_}"`);v.call(this,`#${_}`)}}}),a;function u(d,p,f){if(p!==void 0&&!_V(d,p))throw l(f)}function l(d){return new Error(`reference "${d}" resolves to more than one schema`)}}un.getSchemaRefs=$V});var yd=$(no=>{"use strict";Object.defineProperty(no,"__esModule",{value:!0});no.getData=no.KeywordCxt=no.validateFunctionCode=void 0;var nP=PC(),QC=md(),Gw=Dw(),hh=md(),IV=LC(),vd=ZC(),Bw=GC(),me=Ue(),Re=gs(),RV=hd(),vs=it(),gd=fd();function OV(t){if(oP(t)&&(aP(t),sP(t))){AV(t);return}iP(t,()=>(0,nP.topBoolOrEmptySchema)(t))}no.validateFunctionCode=OV;function iP({gen:t,validateName:e,schema:r,schemaEnv:n,opts:i},s){i.code.es5?t.func(e,(0,me._)`${Re.default.data}, ${Re.default.valCxt}`,n.$async,()=>{t.code((0,me._)`"use strict"; ${eP(r,i)}`),PV(t,i),t.code(s)}):t.func(e,(0,me._)`${Re.default.data}, ${CV(i)}`,n.$async,()=>t.code(eP(r,i)).code(s))}function CV(t){return(0,me._)`{${Re.default.instancePath}="", ${Re.default.parentData}, ${Re.default.parentDataProperty}, ${Re.default.rootData}=${Re.default.data}${t.dynamicRef?(0,me._)`, ${Re.default.dynamicAnchors}={}`:me.nil}}={}`}function PV(t,e){t.if(Re.default.valCxt,()=>{t.var(Re.default.instancePath,(0,me._)`${Re.default.valCxt}.${Re.default.instancePath}`),t.var(Re.default.parentData,(0,me._)`${Re.default.valCxt}.${Re.default.parentData}`),t.var(Re.default.parentDataProperty,(0,me._)`${Re.default.valCxt}.${Re.default.parentDataProperty}`),t.var(Re.default.rootData,(0,me._)`${Re.default.valCxt}.${Re.default.rootData}`),e.dynamicRef&&t.var(Re.default.dynamicAnchors,(0,me._)`${Re.default.valCxt}.${Re.default.dynamicAnchors}`)},()=>{t.var(Re.default.instancePath,(0,me._)`""`),t.var(Re.default.parentData,(0,me._)`undefined`),t.var(Re.default.parentDataProperty,(0,me._)`undefined`),t.var(Re.default.rootData,Re.default.data),e.dynamicRef&&t.var(Re.default.dynamicAnchors,(0,me._)`{}`)})}function AV(t){let{schema:e,opts:r,gen:n}=t;iP(t,()=>{r.$comment&&e.$comment&&uP(t),zV(t),n.let(Re.default.vErrors,null),n.let(Re.default.errors,0),r.unevaluated&&NV(t),cP(t),FV(t)})}function NV(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,me._)`${r}.evaluated`),e.if((0,me._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,me._)`${t.evaluated}.props`,(0,me._)`undefined`)),e.if((0,me._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,me._)`${t.evaluated}.items`,(0,me._)`undefined`))}function eP(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,me._)`/*# sourceURL=${r} */`:me.nil}function MV(t,e){if(oP(t)&&(aP(t),sP(t))){DV(t,e);return}(0,nP.boolOrEmptySchema)(t,e)}function sP({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let r in t)if(e.RULES.all[r])return!0;return!1}function oP(t){return typeof t.schema!="boolean"}function DV(t,e){let{schema:r,gen:n,opts:i}=t;i.$comment&&r.$comment&&uP(t),LV(t),UV(t);let s=n.const("_errs",Re.default.errors);cP(t,s),n.var(e,(0,me._)`${s} === ${Re.default.errors}`)}function aP(t){(0,vs.checkUnknownRules)(t),jV(t)}function cP(t,e){if(t.opts.jtd)return tP(t,[],!1,e);let r=(0,QC.getSchemaTypes)(t.schema),n=(0,QC.coerceAndCheckDataType)(t,r);tP(t,r,!n,e)}function jV(t){let{schema:e,errSchemaPath:r,opts:n,self:i}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,vs.schemaHasRulesButRef)(e,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function zV(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,vs.checkStrictMode)(t,"default is ignored in the schema root")}function LV(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,RV.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function UV(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function uP({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:i}){let s=r.$comment;if(i.$comment===!0)t.code((0,me._)`${Re.default.self}.logger.log(${s})`);else if(typeof i.$comment=="function"){let o=(0,me.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,me._)`${Re.default.self}.opts.$comment(${s}, ${o}, ${a}.schema)`)}}function FV(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:i,opts:s}=t;r.$async?e.if((0,me._)`${Re.default.errors} === 0`,()=>e.return(Re.default.data),()=>e.throw((0,me._)`new ${i}(${Re.default.vErrors})`)):(e.assign((0,me._)`${n}.errors`,Re.default.vErrors),s.unevaluated&&qV(t),e.return((0,me._)`${Re.default.errors} === 0`))}function qV({gen:t,evaluated:e,props:r,items:n}){r instanceof me.Name&&t.assign((0,me._)`${e}.props`,r),n instanceof me.Name&&t.assign((0,me._)`${e}.items`,n)}function tP(t,e,r,n){let{gen:i,schema:s,data:o,allErrors:a,opts:c,self:u}=t,{RULES:l}=u;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,vs.schemaHasRulesButRef)(s,l))){i.block(()=>dP(t,"$ref",l.all.$ref.definition));return}c.jtd||HV(t,e),i.block(()=>{for(let p of l.rules)d(p);d(l.post)});function d(p){(0,Gw.shouldUseGroup)(s,p)&&(p.type?(i.if((0,hh.checkDataType)(p.type,o,c.strictNumbers)),rP(t,p),e.length===1&&e[0]===p.type&&r&&(i.else(),(0,hh.reportTypeError)(t)),i.endIf()):rP(t,p),a||i.if((0,me._)`${Re.default.errors} === ${n||0}`))}}function rP(t,e){let{gen:r,schema:n,opts:{useDefaults:i}}=t;i&&(0,IV.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,Gw.shouldUseRule)(n,s)&&dP(t,s.keyword,s.definition,e.type)})}function HV(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(ZV(t,e),t.opts.allowUnionTypes||BV(t,e),GV(t,t.dataTypes))}function ZV(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{lP(t.dataTypes,r)||Ww(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),VV(t,e)}}function BV(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&Ww(t,"use allowUnionTypes to allow union type keyword")}function GV(t,e){let r=t.self.RULES.all;for(let n in r){let i=r[n];if(typeof i=="object"&&(0,Gw.shouldUseRule)(t.schema,i)){let{type:s}=i.definition;s.length&&!s.some(o=>WV(e,o))&&Ww(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function WV(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function lP(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function VV(t,e){let r=[];for(let n of t.dataTypes)lP(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function Ww(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,vs.checkStrictMode)(t,e,t.opts.strictTypes)}var gh=class{constructor(e,r,n){if((0,vd.validateKeywordUsage)(e,r,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=r.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,vs.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=r,this.$data)this.schemaCode=e.gen.const("vSchema",pP(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,vd.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=e.gen.const("_errs",Re.default.errors))}result(e,r,n){this.failResult((0,me.not)(e),r,n)}failResult(e,r,n){this.gen.if(e),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,r){this.failResult((0,me.not)(e),void 0,r)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:r}=this;this.fail((0,me._)`${r} !== undefined && (${(0,me.or)(this.invalid$data(),e)})`)}error(e,r,n){if(r){this.setParams(r),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,r){(e?gd.reportExtraError:gd.reportError)(this,this.def.error,r)}$dataError(){(0,gd.reportError)(this,this.def.$dataError||gd.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,gd.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,r){r?Object.assign(this.params,e):this.params=e}block$data(e,r,n=me.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=me.nil,r=me.nil){if(!this.$data)return;let{gen:n,schemaCode:i,schemaType:s,def:o}=this;n.if((0,me.or)((0,me._)`${i} === undefined`,r)),e!==me.nil&&n.assign(e,!0),(s.length||o.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==me.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:i,it:s}=this;return(0,me.or)(o(),a());function o(){if(n.length){if(!(r instanceof me.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,me._)`${(0,hh.checkDataTypes)(c,r,s.opts.strictNumbers,hh.DataType.Wrong)}`}return me.nil}function a(){if(i.validateSchema){let c=e.scopeValue("validate$data",{ref:i.validateSchema});return(0,me._)`!${c}(${r})`}return me.nil}}subschema(e,r){let n=(0,Bw.getSubschema)(this.it,e);(0,Bw.extendSubschemaData)(n,this.it,e),(0,Bw.extendSubschemaMode)(n,e);let i={...this.it,...n,items:void 0,props:void 0};return MV(i,r),i}mergeEvaluated(e,r){let{it:n,gen:i}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=vs.mergeEvaluated.props(i,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=vs.mergeEvaluated.items(i,e.items,n.items,r)))}mergeValidEvaluated(e,r){let{it:n,gen:i}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return i.if(r,()=>this.mergeEvaluated(e,me.Name)),!0}};no.KeywordCxt=gh;function dP(t,e,r,n){let i=new gh(t,r,e);"code"in r?r.code(i,n):i.$data&&r.validate?(0,vd.funcKeywordCode)(i,r):"macro"in r?(0,vd.macroKeywordCode)(i,r):(r.compile||r.validate)&&(0,vd.funcKeywordCode)(i,r)}var KV=/^\/(?:[^~]|~0|~1)*$/,JV=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function pP(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let i,s;if(t==="")return Re.default.rootData;if(t[0]==="/"){if(!KV.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);i=t,s=Re.default.rootData}else{let u=JV.exec(t);if(!u)throw new Error(`Invalid JSON-pointer: ${t}`);let l=+u[1];if(i=u[2],i==="#"){if(l>=e)throw new Error(c("property/index",l));return n[e-l]}if(l>e)throw new Error(c("data",l));if(s=r[e-l],!i)return s}let o=s,a=i.split("/");for(let u of a)u&&(s=(0,me._)`${s}${(0,me.getProperty)((0,vs.unescapeJsonPointer)(u))}`,o=(0,me._)`${o} && ${s}`);return o;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${e}`}}no.getData=pP});var vh=$(Kw=>{"use strict";Object.defineProperty(Kw,"__esModule",{value:!0});var Vw=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};Kw.default=Vw});var _d=$(Yw=>{"use strict";Object.defineProperty(Yw,"__esModule",{value:!0});var Jw=hd(),Xw=class extends Error{constructor(e,r,n,i){super(i||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Jw.resolveUrl)(e,r,n),this.missingSchema=(0,Jw.normalizeId)((0,Jw.getFullPath)(e,this.missingRef))}};Yw.default=Xw});var _h=$(qn=>{"use strict";Object.defineProperty(qn,"__esModule",{value:!0});qn.resolveSchema=qn.getCompilingSchema=qn.resolveRef=qn.compileSchema=qn.SchemaEnv=void 0;var ci=Ue(),XV=vh(),Bo=gs(),ui=hd(),fP=it(),YV=yd(),hc=class{constructor(e){var r;this.refs={},this.dynamicAnchors={};let n;typeof e.schema=="object"&&(n=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(r=e.baseId)!==null&&r!==void 0?r:(0,ui.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};qn.SchemaEnv=hc;function e0(t){let e=mP.call(this,t);if(e)return e;let r=(0,ui.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:i}=this.opts.code,{ownProperties:s}=this.opts,o=new ci.CodeGen(this.scope,{es5:n,lines:i,ownProperties:s}),a;t.$async&&(a=o.scopeValue("Error",{ref:XV.default,code:(0,ci._)`require("ajv/dist/runtime/validation_error").default`}));let c=o.scopeName("validate");t.validateName=c;let u={gen:o,allErrors:this.opts.allErrors,data:Bo.default.data,parentData:Bo.default.parentData,parentDataProperty:Bo.default.parentDataProperty,dataNames:[Bo.default.data],dataPathArr:[ci.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:o.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,ci.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:ci.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,ci._)`""`,opts:this.opts,self:this},l;try{this._compilations.add(t),(0,YV.validateFunctionCode)(u),o.optimize(this.opts.code.optimize);let d=o.toString();l=`${o.scopeRefs(Bo.default.scope)}return ${d}`,this.opts.code.process&&(l=this.opts.code.process(l,t));let f=new Function(`${Bo.default.self}`,`${Bo.default.scope}`,l)(this,this.scope.get());if(this.scope.value(c,{ref:f}),f.errors=null,f.schema=t.schema,f.schemaEnv=t,t.$async&&(f.$async=!0),this.opts.code.source===!0&&(f.source={validateName:c,validateCode:d,scopeValues:o._values}),this.opts.unevaluated){let{props:m,items:h}=u;f.evaluated={props:m instanceof ci.Name?void 0:m,items:h instanceof ci.Name?void 0:h,dynamicProps:m instanceof ci.Name,dynamicItems:h instanceof ci.Name},f.source&&(f.source.evaluated=(0,ci.stringify)(f.evaluated))}return t.validate=f,t}catch(d){throw delete t.validate,delete t.validateName,l&&this.logger.error("Error compiling schema, function code:",l),d}finally{this._compilations.delete(t)}}qn.compileSchema=e0;function QV(t,e,r){var n;r=(0,ui.resolveUrl)(this.opts.uriResolver,e,r);let i=t.refs[r];if(i)return i;let s=r7.call(this,t,r);if(s===void 0){let o=(n=t.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;o&&(s=new hc({schema:o,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=e7.call(this,s)}qn.resolveRef=QV;function e7(t){return(0,ui.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:e0.call(this,t)}function mP(t){for(let e of this._compilations)if(t7(e,t))return e}qn.getCompilingSchema=mP;function t7(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function r7(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||yh.call(this,t,e)}function yh(t,e){let r=this.opts.uriResolver.parse(e),n=(0,ui._getFullPath)(this.opts.uriResolver,r),i=(0,ui.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===i)return Qw.call(this,r,t);let s=(0,ui.normalizeId)(n),o=this.refs[s]||this.schemas[s];if(typeof o=="string"){let a=yh.call(this,t,o);return typeof a?.schema!="object"?void 0:Qw.call(this,r,a)}if(typeof o?.schema=="object"){if(o.validate||e0.call(this,o),s===(0,ui.normalizeId)(e)){let{schema:a}=o,{schemaId:c}=this.opts,u=a[c];return u&&(i=(0,ui.resolveUrl)(this.opts.uriResolver,i,u)),new hc({schema:a,schemaId:c,root:t,baseId:i})}return Qw.call(this,r,o)}}qn.resolveSchema=yh;var n7=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Qw(t,{baseId:e,schema:r,root:n}){var i;if(((i=t.fragment)===null||i===void 0?void 0:i[0])!=="/")return;for(let a of t.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let c=r[(0,fP.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!n7.has(a)&&u&&(e=(0,ui.resolveUrl)(this.opts.uriResolver,e,u))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,fP.schemaHasRulesButRef)(r,this.RULES)){let a=(0,ui.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=yh.call(this,n,a)}let{schemaId:o}=this.opts;if(s=s||new hc({schema:r,schemaId:o,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var hP=$((x1e,i7)=>{i7.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var r0=$((w1e,_P)=>{"use strict";var s7=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),vP=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function t0(t){let e="",r=0,n=0;for(n=0;n=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n];break}for(n+=1;n=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n]}return e}var o7=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function gP(t){return t.length=0,!0}function a7(t,e,r){if(t.length){let n=t0(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function c7(t){let e=0,r={error:!1,address:"",zone:""},n=[],i=[],s=!1,o=!1,a=a7;for(let c=0;c7){r.error=!0;break}c>0&&t[c-1]===":"&&(s=!0),n.push(":");continue}else if(u==="%"){if(!a(i,n,r))break;a=gP}else{i.push(u);continue}}return i.length&&(a===gP?r.zone=i.join(""):o?n.push(i.join("")):n.push(t0(i))),r.address=n.join(""),r}function yP(t){if(u7(t,":")<2)return{host:t,isIPV6:!1};let e=c7(t);if(e.error)return{host:t,isIPV6:!1};{let r=e.address,n=e.address;return e.zone&&(r+="%"+e.zone,n+="%25"+e.zone),{host:r,isIPV6:!0,escapedHost:n}}}function u7(t,e){let r=0;for(let n=0;n{"use strict";var{isUUID:f7}=r0(),m7=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,h7=["http","https","ws","wss","urn","urn:uuid"];function g7(t){return h7.indexOf(t)!==-1}function n0(t){return t.secure===!0?!0:t.secure===!1?!1:t.scheme?t.scheme.length===3&&(t.scheme[0]==="w"||t.scheme[0]==="W")&&(t.scheme[1]==="s"||t.scheme[1]==="S")&&(t.scheme[2]==="s"||t.scheme[2]==="S"):!1}function bP(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function SP(t){let e=String(t.scheme).toLowerCase()==="https";return(t.port===(e?443:80)||t.port==="")&&(t.port=void 0),t.path||(t.path="/"),t}function v7(t){return t.secure=n0(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function y7(t){if((t.port===(n0(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){let[e,r]=t.resourceName.split("?");t.path=e&&e!=="/"?e:void 0,t.query=r,t.resourceName=void 0}return t.fragment=void 0,t}function _7(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(m7);if(r){let n=e.scheme||t.scheme||"urn";t.nid=r[1].toLowerCase(),t.nss=r[2];let i=`${n}:${e.nid||t.nid}`,s=i0(i);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function b7(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=e.scheme||t.scheme||"urn",n=t.nid.toLowerCase(),i=`${r}:${e.nid||n}`,s=i0(i);s&&(t=s.serialize(t,e));let o=t,a=t.nss;return o.path=`${n||e.nid}:${a}`,e.skipEscape=!0,o}function S7(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!f7(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function x7(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var xP={scheme:"http",domainHost:!0,parse:bP,serialize:SP},w7={scheme:"https",domainHost:xP.domainHost,parse:bP,serialize:SP},bh={scheme:"ws",domainHost:!0,parse:v7,serialize:y7},E7={scheme:"wss",domainHost:bh.domainHost,parse:bh.parse,serialize:bh.serialize},k7={scheme:"urn",parse:_7,serialize:b7,skipNormalize:!0},T7={scheme:"urn:uuid",parse:S7,serialize:x7,skipNormalize:!0},Sh={http:xP,https:w7,ws:bh,wss:E7,urn:k7,"urn:uuid":T7};Object.setPrototypeOf(Sh,null);function i0(t){return t&&(Sh[t]||Sh[t.toLowerCase()])||void 0}wP.exports={wsIsSecure:n0,SCHEMES:Sh,isValidSchemeName:g7,getSchemeHandler:i0}});var $P=$((k1e,wh)=>{"use strict";var{normalizeIPv6:$7,removeDotSegments:bd,recomposeAuthority:I7,normalizeComponentEncoding:xh,isIPv4:R7,nonSimpleDomain:O7}=r0(),{SCHEMES:C7,getSchemeHandler:kP}=EP();function P7(t,e){return typeof t=="string"?t=Mi(ys(t,e),e):typeof t=="object"&&(t=ys(Mi(t,e),e)),t}function A7(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},i=TP(ys(t,n),ys(e,n),n,!0);return n.skipEscape=!0,Mi(i,n)}function TP(t,e,r,n){let i={};return n||(t=ys(Mi(t,r),r),e=ys(Mi(e,r),r)),r=r||{},!r.tolerant&&e.scheme?(i.scheme=e.scheme,i.userinfo=e.userinfo,i.host=e.host,i.port=e.port,i.path=bd(e.path||""),i.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(i.userinfo=e.userinfo,i.host=e.host,i.port=e.port,i.path=bd(e.path||""),i.query=e.query):(e.path?(e.path[0]==="/"?i.path=bd(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?i.path="/"+e.path:t.path?i.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:i.path=e.path,i.path=bd(i.path)),i.query=e.query):(i.path=t.path,e.query!==void 0?i.query=e.query:i.query=t.query),i.userinfo=t.userinfo,i.host=t.host,i.port=t.port),i.scheme=t.scheme),i.fragment=e.fragment,i}function N7(t,e,r){return typeof t=="string"?(t=unescape(t),t=Mi(xh(ys(t,r),!0),{...r,skipEscape:!0})):typeof t=="object"&&(t=Mi(xh(t,!0),{...r,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=Mi(xh(ys(e,r),!0),{...r,skipEscape:!0})):typeof e=="object"&&(e=Mi(xh(e,!0),{...r,skipEscape:!0})),t.toLowerCase()===e.toLowerCase()}function Mi(t,e){let r={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},n=Object.assign({},e),i=[],s=kP(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=unescape(r.path):(r.path=escape(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&i.push(r.scheme,":");let o=I7(r);if(o!==void 0&&(n.reference!=="suffix"&&i.push("//"),i.push(o),r.path&&r.path[0]!=="/"&&i.push("/")),r.path!==void 0){let a=r.path;!n.absolutePath&&(!s||!s.absolutePath)&&(a=bd(a)),o===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),i.push(a)}return r.query!==void 0&&i.push("?",r.query),r.fragment!==void 0&&i.push("#",r.fragment),i.join("")}var M7=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function ys(t,e){let r=Object.assign({},e),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},i=!1;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let s=t.match(M7);if(s){if(n.scheme=s[1],n.userinfo=s[3],n.host=s[4],n.port=parseInt(s[5],10),n.path=s[6]||"",n.query=s[7],n.fragment=s[8],isNaN(n.port)&&(n.port=s[5]),n.host)if(R7(n.host)===!1){let c=$7(n.host);n.host=c.host.toLowerCase(),i=c.isIPV6}else i=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let o=kP(r.scheme||n.scheme);if(!r.unicodeSupport&&(!o||!o.unicodeSupport)&&n.host&&(r.domainHost||o&&o.domainHost)&&i===!1&&O7(n.host))try{n.host=URL.domainToASCII(n.host.toLowerCase())}catch(a){n.error=n.error||"Host's domain name can not be converted to ASCII: "+a}(!o||o&&!o.skipNormalize)&&(t.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=unescape(n.host))),n.path&&(n.path=escape(unescape(n.path))),n.fragment&&(n.fragment=encodeURI(decodeURIComponent(n.fragment)))),o&&o.parse&&o.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return n}var s0={SCHEMES:C7,normalize:P7,resolve:A7,resolveComponent:TP,equal:N7,serialize:Mi,parse:ys};wh.exports=s0;wh.exports.default=s0;wh.exports.fastUri=s0});var RP=$(o0=>{"use strict";Object.defineProperty(o0,"__esModule",{value:!0});var IP=$P();IP.code='require("ajv/dist/runtime/uri").default';o0.default=IP});var jP=$(xr=>{"use strict";Object.defineProperty(xr,"__esModule",{value:!0});xr.CodeGen=xr.Name=xr.nil=xr.stringify=xr.str=xr._=xr.KeywordCxt=void 0;var D7=yd();Object.defineProperty(xr,"KeywordCxt",{enumerable:!0,get:function(){return D7.KeywordCxt}});var gc=Ue();Object.defineProperty(xr,"_",{enumerable:!0,get:function(){return gc._}});Object.defineProperty(xr,"str",{enumerable:!0,get:function(){return gc.str}});Object.defineProperty(xr,"stringify",{enumerable:!0,get:function(){return gc.stringify}});Object.defineProperty(xr,"nil",{enumerable:!0,get:function(){return gc.nil}});Object.defineProperty(xr,"Name",{enumerable:!0,get:function(){return gc.Name}});Object.defineProperty(xr,"CodeGen",{enumerable:!0,get:function(){return gc.CodeGen}});var j7=vh(),NP=_d(),z7=Mw(),Sd=_h(),L7=Ue(),xd=hd(),Eh=md(),c0=it(),OP=hP(),U7=RP(),MP=(t,e)=>new RegExp(t,e);MP.code="new RegExp";var F7=["removeAdditional","useDefaults","coerceTypes"],q7=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),H7={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},Z7={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},CP=200;function B7(t){var e,r,n,i,s,o,a,c,u,l,d,p,f,m,h,g,v,S,_,y,x,w,E,T,I;let A=t.strict,N=(e=t.code)===null||e===void 0?void 0:e.optimize,U=N===!0||N===void 0?1:N||0,V=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:MP,j=(i=t.uriResolver)!==null&&i!==void 0?i:U7.default;return{strictSchema:(o=(s=t.strictSchema)!==null&&s!==void 0?s:A)!==null&&o!==void 0?o:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:A)!==null&&c!==void 0?c:!0,strictTypes:(l=(u=t.strictTypes)!==null&&u!==void 0?u:A)!==null&&l!==void 0?l:"log",strictTuples:(p=(d=t.strictTuples)!==null&&d!==void 0?d:A)!==null&&p!==void 0?p:"log",strictRequired:(m=(f=t.strictRequired)!==null&&f!==void 0?f:A)!==null&&m!==void 0?m:!1,code:t.code?{...t.code,optimize:U,regExp:V}:{optimize:U,regExp:V},loopRequired:(h=t.loopRequired)!==null&&h!==void 0?h:CP,loopEnum:(g=t.loopEnum)!==null&&g!==void 0?g:CP,meta:(v=t.meta)!==null&&v!==void 0?v:!0,messages:(S=t.messages)!==null&&S!==void 0?S:!0,inlineRefs:(_=t.inlineRefs)!==null&&_!==void 0?_:!0,schemaId:(y=t.schemaId)!==null&&y!==void 0?y:"$id",addUsedSchema:(x=t.addUsedSchema)!==null&&x!==void 0?x:!0,validateSchema:(w=t.validateSchema)!==null&&w!==void 0?w:!0,validateFormats:(E=t.validateFormats)!==null&&E!==void 0?E:!0,unicodeRegExp:(T=t.unicodeRegExp)!==null&&T!==void 0?T:!0,int32range:(I=t.int32range)!==null&&I!==void 0?I:!0,uriResolver:j}}var wd=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...B7(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new L7.ValueScope({scope:{},prefixes:q7,es5:r,lines:n}),this.logger=X7(e.logger);let i=e.validateFormats;e.validateFormats=!1,this.RULES=(0,z7.getRules)(),PP.call(this,H7,e,"NOT SUPPORTED"),PP.call(this,Z7,e,"DEPRECATED","warn"),this._metaOpts=K7.call(this),e.formats&&W7.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&V7.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),G7.call(this),e.validateFormats=i}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,i=OP;n==="id"&&(i={...OP},i.id=i.$id,delete i.$id),r&&e&&this.addMetaSchema(i,i[n],!1)}defaultMeta(){let{meta:e,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[r]||e:void 0}validate(e,r){let n;if(typeof e=="string"){if(n=this.getSchema(e),!n)throw new Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let i=n(r);return"$async"in n||(this.errors=n.errors),i}compile(e,r){let n=this._addSchema(e,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return i.call(this,e,r);async function i(l,d){await s.call(this,l.$schema);let p=this._addSchema(l,d);return p.validate||o.call(this,p)}async function s(l){l&&!this.getSchema(l)&&await i.call(this,{$ref:l},!0)}async function o(l){try{return this._compileSchemaEnv(l)}catch(d){if(!(d instanceof NP.default))throw d;return a.call(this,d),await c.call(this,d.missingSchema),o.call(this,l)}}function a({missingSchema:l,missingRef:d}){if(this.refs[l])throw new Error(`AnySchema ${l} is loaded but ${d} cannot be resolved`)}async function c(l){let d=await u.call(this,l);this.refs[l]||await s.call(this,d.$schema),this.refs[l]||this.addSchema(d,l,r)}async function u(l){let d=this._loading[l];if(d)return d;try{return await(this._loading[l]=n(l))}finally{delete this._loading[l]}}}addSchema(e,r,n,i=this.opts.validateSchema){if(Array.isArray(e)){for(let o of e)this.addSchema(o,void 0,n,i);return this}let s;if(typeof e=="object"){let{schemaId:o}=this.opts;if(s=e[o],s!==void 0&&typeof s!="string")throw new Error(`schema ${o} must be string`)}return r=(0,xd.normalizeId)(r||s),this._checkUnique(r),this.schemas[r]=this._addSchema(e,n,r,i,!0),this}addMetaSchema(e,r,n=this.opts.validateSchema){return this.addSchema(e,r,!0,n),this}validateSchema(e,r){if(typeof e=="boolean")return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let i=this.validate(n,e);if(!i&&r){let s="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(s);else throw new Error(s)}return i}getSchema(e){let r;for(;typeof(r=AP.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,i=new Sd.SchemaEnv({schema:{},schemaId:n});if(r=Sd.resolveSchema.call(this,i,e),!r)return;this.refs[e]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=AP.call(this,e);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let r=e;this._cache.delete(r);let n=e[this.opts.schemaId];return n&&(n=(0,xd.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let r of e)this.addKeyword(r);return this}addKeyword(e,r){let n;if(typeof e=="string")n=e,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof e=="object"&&r===void 0){if(r=e,n=r.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(Q7.call(this,n,r),!r)return(0,c0.eachItem)(n,s=>a0.call(this,s)),this;tK.call(this,r);let i={...r,type:(0,Eh.getJSONTypes)(r.type),schemaType:(0,Eh.getJSONTypes)(r.schemaType)};return(0,c0.eachItem)(n,i.type.length===0?s=>a0.call(this,s,i):s=>i.type.forEach(o=>a0.call(this,s,i,o))),this}getKeyword(e){let r=this.RULES.all[e];return typeof r=="object"?r.definition:!!r}removeKeyword(e){let{RULES:r}=this;delete r.keywords[e],delete r.all[e];for(let n of r.rules){let i=n.rules.findIndex(s=>s.keyword===e);i>=0&&n.rules.splice(i,1)}return this}addFormat(e,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[e]=r,this}errorsText(e=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!e||e.length===0?"No errors":e.map(i=>`${n}${i.instancePath} ${i.message}`).reduce((i,s)=>i+r+s)}$dataMetaSchema(e,r){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let i of r){let s=i.split("/").slice(1),o=e;for(let a of s)o=o[a];for(let a in n){let c=n[a];if(typeof c!="object")continue;let{$data:u}=c.definition,l=o[a];u&&l&&(o[a]=DP(l))}}return e}_removeAllSchemas(e,r){for(let n in e){let i=e[n];(!r||r.test(n))&&(typeof i=="string"?delete e[n]:i&&!i.meta&&(this._cache.delete(i.schema),delete e[n]))}}_addSchema(e,r,n,i=this.opts.validateSchema,s=this.opts.addUsedSchema){let o,{schemaId:a}=this.opts;if(typeof e=="object")o=e[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(e);if(c!==void 0)return c;n=(0,xd.normalizeId)(o||n);let u=xd.getSchemaRefs.call(this,e,n);return c=new Sd.SchemaEnv({schema:e,schemaId:a,meta:r,baseId:n,localRefs:u}),this._cache.set(c.schema,c),s&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=c),i&&this.validateSchema(e,!0),c}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):Sd.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let r=this.opts;this.opts=this._metaOpts;try{Sd.compileSchema.call(this,e)}finally{this.opts=r}}};wd.ValidationError=j7.default;wd.MissingRefError=NP.default;xr.default=wd;function PP(t,e,r,n="error"){for(let i in t){let s=i;s in e&&this.logger[n](`${r}: option ${i}. ${t[s]}`)}}function AP(t){return t=(0,xd.normalizeId)(t),this.schemas[t]||this.refs[t]}function G7(){let t=this.opts.schemas;if(t)if(Array.isArray(t))this.addSchema(t);else for(let e in t)this.addSchema(t[e],e)}function W7(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function V7(t){if(Array.isArray(t)){this.addVocabulary(t);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in t){let r=t[e];r.keyword||(r.keyword=e),this.addKeyword(r)}}function K7(){let t={...this.opts};for(let e of F7)delete t[e];return t}var J7={log(){},warn(){},error(){}};function X7(t){if(t===!1)return J7;if(t===void 0)return console;if(t.log&&t.warn&&t.error)return t;throw new Error("logger must implement log, warn and error methods")}var Y7=/^[a-z_$][a-z0-9_$:-]*$/i;function Q7(t,e){let{RULES:r}=this;if((0,c0.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!Y7.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function a0(t,e,r){var n;let i=e?.post;if(r&&i)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:s}=this,o=i?s.post:s.rules.find(({type:c})=>c===r);if(o||(o={type:r,rules:[]},s.rules.push(o)),s.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,Eh.getJSONTypes)(e.type),schemaType:(0,Eh.getJSONTypes)(e.schemaType)}};e.before?eK.call(this,o,a,e.before):o.rules.push(a),s.all[t]=a,(n=e.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function eK(t,e,r){let n=t.rules.findIndex(i=>i.keyword===r);n>=0?t.rules.splice(n,0,e):(t.rules.push(e),this.logger.warn(`rule ${r} is not defined`))}function tK(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=DP(e)),t.validateSchema=this.compile(e,!0))}var rK={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function DP(t){return{anyOf:[t,rK]}}});var zP=$(u0=>{"use strict";Object.defineProperty(u0,"__esModule",{value:!0});var nK={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};u0.default=nK});var qP=$(Go=>{"use strict";Object.defineProperty(Go,"__esModule",{value:!0});Go.callRef=Go.getValidate=void 0;var iK=_d(),LP=Fn(),ln=Ue(),vc=gs(),UP=_h(),kh=it(),sK={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:r,it:n}=t,{baseId:i,schemaEnv:s,validateName:o,opts:a,self:c}=n,{root:u}=s;if((r==="#"||r==="#/")&&i===u.baseId)return d();let l=UP.resolveRef.call(c,u,i,r);if(l===void 0)throw new iK.default(n.opts.uriResolver,i,r);if(l instanceof UP.SchemaEnv)return p(l);return f(l);function d(){if(s===u)return Th(t,o,s,s.$async);let m=e.scopeValue("root",{ref:u});return Th(t,(0,ln._)`${m}.validate`,u,u.$async)}function p(m){let h=FP(t,m);Th(t,h,m,m.$async)}function f(m){let h=e.scopeValue("schema",a.code.source===!0?{ref:m,code:(0,ln.stringify)(m)}:{ref:m}),g=e.name("valid"),v=t.subschema({schema:m,dataTypes:[],schemaPath:ln.nil,topSchemaRef:h,errSchemaPath:r},g);t.mergeEvaluated(v),t.ok(g)}}};function FP(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,ln._)`${r.scopeValue("wrapper",{ref:e})}.validate`}Go.getValidate=FP;function Th(t,e,r,n){let{gen:i,it:s}=t,{allErrors:o,schemaEnv:a,opts:c}=s,u=c.passContext?vc.default.this:ln.nil;n?l():d();function l(){if(!a.$async)throw new Error("async schema referenced by sync schema");let m=i.let("valid");i.try(()=>{i.code((0,ln._)`await ${(0,LP.callValidateCode)(t,e,u)}`),f(e),o||i.assign(m,!0)},h=>{i.if((0,ln._)`!(${h} instanceof ${s.ValidationError})`,()=>i.throw(h)),p(h),o||i.assign(m,!1)}),t.ok(m)}function d(){t.result((0,LP.callValidateCode)(t,e,u),()=>f(e),()=>p(e))}function p(m){let h=(0,ln._)`${m}.errors`;i.assign(vc.default.vErrors,(0,ln._)`${vc.default.vErrors} === null ? ${h} : ${vc.default.vErrors}.concat(${h})`),i.assign(vc.default.errors,(0,ln._)`${vc.default.vErrors}.length`)}function f(m){var h;if(!s.opts.unevaluated)return;let g=(h=r?.validate)===null||h===void 0?void 0:h.evaluated;if(s.props!==!0)if(g&&!g.dynamicProps)g.props!==void 0&&(s.props=kh.mergeEvaluated.props(i,g.props,s.props));else{let v=i.var("props",(0,ln._)`${m}.evaluated.props`);s.props=kh.mergeEvaluated.props(i,v,s.props,ln.Name)}if(s.items!==!0)if(g&&!g.dynamicItems)g.items!==void 0&&(s.items=kh.mergeEvaluated.items(i,g.items,s.items));else{let v=i.var("items",(0,ln._)`${m}.evaluated.items`);s.items=kh.mergeEvaluated.items(i,v,s.items,ln.Name)}}}Go.callRef=Th;Go.default=sK});var HP=$(l0=>{"use strict";Object.defineProperty(l0,"__esModule",{value:!0});var oK=zP(),aK=qP(),cK=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",oK.default,aK.default];l0.default=cK});var ZP=$(d0=>{"use strict";Object.defineProperty(d0,"__esModule",{value:!0});var $h=Ue(),io=$h.operators,Ih={maximum:{okStr:"<=",ok:io.LTE,fail:io.GT},minimum:{okStr:">=",ok:io.GTE,fail:io.LT},exclusiveMaximum:{okStr:"<",ok:io.LT,fail:io.GTE},exclusiveMinimum:{okStr:">",ok:io.GT,fail:io.LTE}},uK={message:({keyword:t,schemaCode:e})=>(0,$h.str)`must be ${Ih[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,$h._)`{comparison: ${Ih[t].okStr}, limit: ${e}}`},lK={keyword:Object.keys(Ih),type:"number",schemaType:"number",$data:!0,error:uK,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,$h._)`${r} ${Ih[e].fail} ${n} || isNaN(${r})`)}};d0.default=lK});var BP=$(p0=>{"use strict";Object.defineProperty(p0,"__esModule",{value:!0});var Ed=Ue(),dK={message:({schemaCode:t})=>(0,Ed.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,Ed._)`{multipleOf: ${t}}`},pK={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:dK,code(t){let{gen:e,data:r,schemaCode:n,it:i}=t,s=i.opts.multipleOfPrecision,o=e.let("res"),a=s?(0,Ed._)`Math.abs(Math.round(${o}) - ${o}) > 1e-${s}`:(0,Ed._)`${o} !== parseInt(${o})`;t.fail$data((0,Ed._)`(${n} === 0 || (${o} = ${r}/${n}, ${a}))`)}};p0.default=pK});var WP=$(f0=>{"use strict";Object.defineProperty(f0,"__esModule",{value:!0});function GP(t){let e=t.length,r=0,n=0,i;for(;n=55296&&i<=56319&&n{"use strict";Object.defineProperty(m0,"__esModule",{value:!0});var Wo=Ue(),fK=it(),mK=WP(),hK={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,Wo.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,Wo._)`{limit: ${t}}`},gK={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:hK,code(t){let{keyword:e,data:r,schemaCode:n,it:i}=t,s=e==="maxLength"?Wo.operators.GT:Wo.operators.LT,o=i.opts.unicode===!1?(0,Wo._)`${r}.length`:(0,Wo._)`${(0,fK.useFunc)(t.gen,mK.default)}(${r})`;t.fail$data((0,Wo._)`${o} ${s} ${n}`)}};m0.default=gK});var KP=$(h0=>{"use strict";Object.defineProperty(h0,"__esModule",{value:!0});var vK=Fn(),Rh=Ue(),yK={message:({schemaCode:t})=>(0,Rh.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Rh._)`{pattern: ${t}}`},_K={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:yK,code(t){let{data:e,$data:r,schema:n,schemaCode:i,it:s}=t,o=s.opts.unicodeRegExp?"u":"",a=r?(0,Rh._)`(new RegExp(${i}, ${o}))`:(0,vK.usePattern)(t,n);t.fail$data((0,Rh._)`!${a}.test(${e})`)}};h0.default=_K});var JP=$(g0=>{"use strict";Object.defineProperty(g0,"__esModule",{value:!0});var kd=Ue(),bK={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,kd.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,kd._)`{limit: ${t}}`},SK={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:bK,code(t){let{keyword:e,data:r,schemaCode:n}=t,i=e==="maxProperties"?kd.operators.GT:kd.operators.LT;t.fail$data((0,kd._)`Object.keys(${r}).length ${i} ${n}`)}};g0.default=SK});var XP=$(v0=>{"use strict";Object.defineProperty(v0,"__esModule",{value:!0});var Td=Fn(),$d=Ue(),xK=it(),wK={message:({params:{missingProperty:t}})=>(0,$d.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,$d._)`{missingProperty: ${t}}`},EK={keyword:"required",type:"object",schemaType:"array",$data:!0,error:wK,code(t){let{gen:e,schema:r,schemaCode:n,data:i,$data:s,it:o}=t,{opts:a}=o;if(!s&&r.length===0)return;let c=r.length>=a.loopRequired;if(o.allErrors?u():l(),a.strictRequired){let f=t.parentSchema.properties,{definedProperties:m}=t.it;for(let h of r)if(f?.[h]===void 0&&!m.has(h)){let g=o.schemaEnv.baseId+o.errSchemaPath,v=`required property "${h}" is not defined at "${g}" (strictRequired)`;(0,xK.checkStrictMode)(o,v,o.opts.strictRequired)}}function u(){if(c||s)t.block$data($d.nil,d);else for(let f of r)(0,Td.checkReportMissingProp)(t,f)}function l(){let f=e.let("missing");if(c||s){let m=e.let("valid",!0);t.block$data(m,()=>p(f,m)),t.ok(m)}else e.if((0,Td.checkMissingProp)(t,r,f)),(0,Td.reportMissingProp)(t,f),e.else()}function d(){e.forOf("prop",n,f=>{t.setParams({missingProperty:f}),e.if((0,Td.noPropertyInData)(e,i,f,a.ownProperties),()=>t.error())})}function p(f,m){t.setParams({missingProperty:f}),e.forOf(f,n,()=>{e.assign(m,(0,Td.propertyInData)(e,i,f,a.ownProperties)),e.if((0,$d.not)(m),()=>{t.error(),e.break()})},$d.nil)}}};v0.default=EK});var YP=$(y0=>{"use strict";Object.defineProperty(y0,"__esModule",{value:!0});var Id=Ue(),kK={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,Id.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,Id._)`{limit: ${t}}`},TK={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:kK,code(t){let{keyword:e,data:r,schemaCode:n}=t,i=e==="maxItems"?Id.operators.GT:Id.operators.LT;t.fail$data((0,Id._)`${r}.length ${i} ${n}`)}};y0.default=TK});var Oh=$(_0=>{"use strict";Object.defineProperty(_0,"__esModule",{value:!0});var QP=Hw();QP.code='require("ajv/dist/runtime/equal").default';_0.default=QP});var eA=$(S0=>{"use strict";Object.defineProperty(S0,"__esModule",{value:!0});var b0=md(),wr=Ue(),$K=it(),IK=Oh(),RK={message:({params:{i:t,j:e}})=>(0,wr.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,wr._)`{i: ${t}, j: ${e}}`},OK={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:RK,code(t){let{gen:e,data:r,$data:n,schema:i,parentSchema:s,schemaCode:o,it:a}=t;if(!n&&!i)return;let c=e.let("valid"),u=s.items?(0,b0.getSchemaTypes)(s.items):[];t.block$data(c,l,(0,wr._)`${o} === false`),t.ok(c);function l(){let m=e.let("i",(0,wr._)`${r}.length`),h=e.let("j");t.setParams({i:m,j:h}),e.assign(c,!0),e.if((0,wr._)`${m} > 1`,()=>(d()?p:f)(m,h))}function d(){return u.length>0&&!u.some(m=>m==="object"||m==="array")}function p(m,h){let g=e.name("item"),v=(0,b0.checkDataTypes)(u,g,a.opts.strictNumbers,b0.DataType.Wrong),S=e.const("indices",(0,wr._)`{}`);e.for((0,wr._)`;${m}--;`,()=>{e.let(g,(0,wr._)`${r}[${m}]`),e.if(v,(0,wr._)`continue`),u.length>1&&e.if((0,wr._)`typeof ${g} == "string"`,(0,wr._)`${g} += "_"`),e.if((0,wr._)`typeof ${S}[${g}] == "number"`,()=>{e.assign(h,(0,wr._)`${S}[${g}]`),t.error(),e.assign(c,!1).break()}).code((0,wr._)`${S}[${g}] = ${m}`)})}function f(m,h){let g=(0,$K.useFunc)(e,IK.default),v=e.name("outer");e.label(v).for((0,wr._)`;${m}--;`,()=>e.for((0,wr._)`${h} = ${m}; ${h}--;`,()=>e.if((0,wr._)`${g}(${r}[${m}], ${r}[${h}])`,()=>{t.error(),e.assign(c,!1).break(v)})))}}};S0.default=OK});var tA=$(w0=>{"use strict";Object.defineProperty(w0,"__esModule",{value:!0});var x0=Ue(),CK=it(),PK=Oh(),AK={message:"must be equal to constant",params:({schemaCode:t})=>(0,x0._)`{allowedValue: ${t}}`},NK={keyword:"const",$data:!0,error:AK,code(t){let{gen:e,data:r,$data:n,schemaCode:i,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,x0._)`!${(0,CK.useFunc)(e,PK.default)}(${r}, ${i})`):t.fail((0,x0._)`${s} !== ${r}`)}};w0.default=NK});var rA=$(E0=>{"use strict";Object.defineProperty(E0,"__esModule",{value:!0});var Rd=Ue(),MK=it(),DK=Oh(),jK={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Rd._)`{allowedValues: ${t}}`},zK={keyword:"enum",schemaType:"array",$data:!0,error:jK,code(t){let{gen:e,data:r,$data:n,schema:i,schemaCode:s,it:o}=t;if(!n&&i.length===0)throw new Error("enum must have non-empty array");let a=i.length>=o.opts.loopEnum,c,u=()=>c??(c=(0,MK.useFunc)(e,DK.default)),l;if(a||n)l=e.let("valid"),t.block$data(l,d);else{if(!Array.isArray(i))throw new Error("ajv implementation error");let f=e.const("vSchema",s);l=(0,Rd.or)(...i.map((m,h)=>p(f,h)))}t.pass(l);function d(){e.assign(l,!1),e.forOf("v",s,f=>e.if((0,Rd._)`${u()}(${r}, ${f})`,()=>e.assign(l,!0).break()))}function p(f,m){let h=i[m];return typeof h=="object"&&h!==null?(0,Rd._)`${u()}(${r}, ${f}[${m}])`:(0,Rd._)`${r} === ${h}`}}};E0.default=zK});var nA=$(k0=>{"use strict";Object.defineProperty(k0,"__esModule",{value:!0});var LK=ZP(),UK=BP(),FK=VP(),qK=KP(),HK=JP(),ZK=XP(),BK=YP(),GK=eA(),WK=tA(),VK=rA(),KK=[LK.default,UK.default,FK.default,qK.default,HK.default,ZK.default,BK.default,GK.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},WK.default,VK.default];k0.default=KK});var $0=$(Od=>{"use strict";Object.defineProperty(Od,"__esModule",{value:!0});Od.validateAdditionalItems=void 0;var Vo=Ue(),T0=it(),JK={message:({params:{len:t}})=>(0,Vo.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Vo._)`{limit: ${t}}`},XK={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:JK,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,T0.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}iA(t,n)}};function iA(t,e){let{gen:r,schema:n,data:i,keyword:s,it:o}=t;o.items=!0;let a=r.const("len",(0,Vo._)`${i}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,Vo._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,T0.alwaysValidSchema)(o,n)){let u=r.var("valid",(0,Vo._)`${a} <= ${e.length}`);r.if((0,Vo.not)(u),()=>c(u)),t.ok(u)}function c(u){r.forRange("i",e.length,a,l=>{t.subschema({keyword:s,dataProp:l,dataPropType:T0.Type.Num},u),o.allErrors||r.if((0,Vo.not)(u),()=>r.break())})}}Od.validateAdditionalItems=iA;Od.default=XK});var I0=$(Cd=>{"use strict";Object.defineProperty(Cd,"__esModule",{value:!0});Cd.validateTuple=void 0;var sA=Ue(),Ch=it(),YK=Fn(),QK={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return oA(t,"additionalItems",e);r.items=!0,!(0,Ch.alwaysValidSchema)(r,e)&&t.ok((0,YK.validateArray)(t))}};function oA(t,e,r=t.schema){let{gen:n,parentSchema:i,data:s,keyword:o,it:a}=t;l(i),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=Ch.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),u=n.const("len",(0,sA._)`${s}.length`);r.forEach((d,p)=>{(0,Ch.alwaysValidSchema)(a,d)||(n.if((0,sA._)`${u} > ${p}`,()=>t.subschema({keyword:o,schemaProp:p,dataProp:p},c)),t.ok(c))});function l(d){let{opts:p,errSchemaPath:f}=a,m=r.length,h=m===d.minItems&&(m===d.maxItems||d[e]===!1);if(p.strictTuples&&!h){let g=`"${o}" is ${m}-tuple, but minItems or maxItems/${e} are not specified or different at path "${f}"`;(0,Ch.checkStrictMode)(a,g,p.strictTuples)}}}Cd.validateTuple=oA;Cd.default=QK});var aA=$(R0=>{"use strict";Object.defineProperty(R0,"__esModule",{value:!0});var eJ=I0(),tJ={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,eJ.validateTuple)(t,"items")};R0.default=tJ});var uA=$(O0=>{"use strict";Object.defineProperty(O0,"__esModule",{value:!0});var cA=Ue(),rJ=it(),nJ=Fn(),iJ=$0(),sJ={message:({params:{len:t}})=>(0,cA.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,cA._)`{limit: ${t}}`},oJ={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:sJ,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:i}=r;n.items=!0,!(0,rJ.alwaysValidSchema)(n,e)&&(i?(0,iJ.validateAdditionalItems)(t,i):t.ok((0,nJ.validateArray)(t)))}};O0.default=oJ});var lA=$(C0=>{"use strict";Object.defineProperty(C0,"__esModule",{value:!0});var Hn=Ue(),Ph=it(),aJ={message:({params:{min:t,max:e}})=>e===void 0?(0,Hn.str)`must contain at least ${t} valid item(s)`:(0,Hn.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,Hn._)`{minContains: ${t}}`:(0,Hn._)`{minContains: ${t}, maxContains: ${e}}`},cJ={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:aJ,code(t){let{gen:e,schema:r,parentSchema:n,data:i,it:s}=t,o,a,{minContains:c,maxContains:u}=n;s.opts.next?(o=c===void 0?1:c,a=u):o=1;let l=e.const("len",(0,Hn._)`${i}.length`);if(t.setParams({min:o,max:a}),a===void 0&&o===0){(0,Ph.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&o>a){(0,Ph.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,Ph.alwaysValidSchema)(s,r)){let h=(0,Hn._)`${l} >= ${o}`;a!==void 0&&(h=(0,Hn._)`${h} && ${l} <= ${a}`),t.pass(h);return}s.items=!0;let d=e.name("valid");a===void 0&&o===1?f(d,()=>e.if(d,()=>e.break())):o===0?(e.let(d,!0),a!==void 0&&e.if((0,Hn._)`${i}.length > 0`,p)):(e.let(d,!1),p()),t.result(d,()=>t.reset());function p(){let h=e.name("_valid"),g=e.let("count",0);f(h,()=>e.if(h,()=>m(g)))}function f(h,g){e.forRange("i",0,l,v=>{t.subschema({keyword:"contains",dataProp:v,dataPropType:Ph.Type.Num,compositeRule:!0},h),g()})}function m(h){e.code((0,Hn._)`${h}++`),a===void 0?e.if((0,Hn._)`${h} >= ${o}`,()=>e.assign(d,!0).break()):(e.if((0,Hn._)`${h} > ${a}`,()=>e.assign(d,!1).break()),o===1?e.assign(d,!0):e.if((0,Hn._)`${h} >= ${o}`,()=>e.assign(d,!0)))}}};C0.default=cJ});var fA=$(Di=>{"use strict";Object.defineProperty(Di,"__esModule",{value:!0});Di.validateSchemaDeps=Di.validatePropertyDeps=Di.error=void 0;var P0=Ue(),uJ=it(),Pd=Fn();Di.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,P0.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,P0._)`{property: ${t}, missingProperty: ${n}, depsCount: ${e}, - deps: ${r}}`};var lJ={keyword:"dependencies",type:"object",schemaType:"object",error:Di.error,code(t){let[e,r]=dJ(t);dA(t,e),pA(t,r)}};function dJ({schema:t}){let e={},r={};for(let n in t){if(n==="__proto__")continue;let i=Array.isArray(t[n])?e:r;i[n]=t[n]}return[e,r]}function dA(t,e=t.schema){let{gen:r,data:n,it:i}=t;if(Object.keys(e).length===0)return;let s=r.let("missing");for(let o in e){let a=e[o];if(a.length===0)continue;let c=(0,Pd.propertyInData)(r,n,o,i.opts.ownProperties);t.setParams({property:o,depsCount:a.length,deps:a.join(", ")}),i.allErrors?r.if(c,()=>{for(let u of a)(0,Pd.checkReportMissingProp)(t,u)}):(r.if((0,P0._)`${c} && (${(0,Pd.checkMissingProp)(t,a,s)})`),(0,Pd.reportMissingProp)(t,s),r.else())}}Di.validatePropertyDeps=dA;function pA(t,e=t.schema){let{gen:r,data:n,keyword:i,it:s}=t,o=r.name("valid");for(let a in e)(0,uJ.alwaysValidSchema)(s,e[a])||(r.if((0,Pd.propertyInData)(r,n,a,s.opts.ownProperties),()=>{let c=t.subschema({keyword:i,schemaProp:a},o);t.mergeValidEvaluated(c,o)},()=>r.var(o,!0)),t.ok(o))}Di.validateSchemaDeps=pA;Di.default=lJ});var hA=$(A0=>{"use strict";Object.defineProperty(A0,"__esModule",{value:!0});var mA=Ue(),pJ=it(),fJ={message:"property name must be valid",params:({params:t})=>(0,mA._)`{propertyName: ${t.propertyName}}`},mJ={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:fJ,code(t){let{gen:e,schema:r,data:n,it:i}=t;if((0,pJ.alwaysValidSchema)(i,r))return;let s=e.name("valid");e.forIn("key",n,o=>{t.setParams({propertyName:o}),t.subschema({keyword:"propertyNames",data:o,dataTypes:["string"],propertyName:o,compositeRule:!0},s),e.if((0,mA.not)(s),()=>{t.error(!0),i.allErrors||e.break()})}),t.ok(s)}};A0.default=mJ});var M0=$(N0=>{"use strict";Object.defineProperty(N0,"__esModule",{value:!0});var Ah=Fn(),li=Ue(),hJ=gs(),Nh=it(),gJ={message:"must NOT have additional properties",params:({params:t})=>(0,li._)`{additionalProperty: ${t.additionalProperty}}`},vJ={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:gJ,code(t){let{gen:e,schema:r,parentSchema:n,data:i,errsCount:s,it:o}=t;if(!s)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=o;if(o.props=!0,c.removeAdditional!=="all"&&(0,Nh.alwaysValidSchema)(o,r))return;let u=(0,Ah.allSchemaProperties)(n.properties),l=(0,Ah.allSchemaProperties)(n.patternProperties);d(),t.ok((0,li._)`${s} === ${hJ.default.errors}`);function d(){e.forIn("key",i,g=>{!u.length&&!l.length?m(g):e.if(p(g),()=>m(g))})}function p(g){let v;if(u.length>8){let S=(0,Nh.schemaRefOrVal)(o,n.properties,"properties");v=(0,Ah.isOwnProperty)(e,S,g)}else u.length?v=(0,li.or)(...u.map(S=>(0,li._)`${g} === ${S}`)):v=li.nil;return l.length&&(v=(0,li.or)(v,...l.map(S=>(0,li._)`${(0,Ah.usePattern)(t,S)}.test(${g})`))),(0,li.not)(v)}function f(g){e.code((0,li._)`delete ${i}[${g}]`)}function m(g){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){f(g);return}if(r===!1){t.setParams({additionalProperty:g}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,Nh.alwaysValidSchema)(o,r)){let v=e.name("valid");c.removeAdditional==="failing"?(h(g,v,!1),e.if((0,li.not)(v),()=>{t.reset(),f(g)})):(h(g,v),a||e.if((0,li.not)(v),()=>e.break()))}}function h(g,v,S){let _={keyword:"additionalProperties",dataProp:g,dataPropType:Nh.Type.Str};S===!1&&Object.assign(_,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(_,v)}}};N0.default=vJ});var yA=$(j0=>{"use strict";Object.defineProperty(j0,"__esModule",{value:!0});var yJ=yd(),gA=Fn(),D0=it(),vA=M0(),_J={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:n,data:i,it:s}=t;s.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&vA.default.code(new yJ.KeywordCxt(s,vA.default,"additionalProperties"));let o=(0,gA.allSchemaProperties)(r);for(let d of o)s.definedProperties.add(d);s.opts.unevaluated&&o.length&&s.props!==!0&&(s.props=D0.mergeEvaluated.props(e,(0,D0.toHash)(o),s.props));let a=o.filter(d=>!(0,D0.alwaysValidSchema)(s,r[d]));if(a.length===0)return;let c=e.name("valid");for(let d of a)u(d)?l(d):(e.if((0,gA.propertyInData)(e,i,d,s.opts.ownProperties)),l(d),s.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(d),t.ok(c);function u(d){return s.opts.useDefaults&&!s.compositeRule&&r[d].default!==void 0}function l(d){t.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};j0.default=_J});var xA=$(z0=>{"use strict";Object.defineProperty(z0,"__esModule",{value:!0});var _A=Fn(),Mh=Ue(),bA=it(),SA=it(),bJ={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,data:n,parentSchema:i,it:s}=t,{opts:o}=s,a=(0,_A.allSchemaProperties)(r),c=a.filter(h=>(0,bA.alwaysValidSchema)(s,r[h]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let u=o.strictSchema&&!o.allowMatchingProperties&&i.properties,l=e.name("valid");s.props!==!0&&!(s.props instanceof Mh.Name)&&(s.props=(0,SA.evaluatedPropsToName)(e,s.props));let{props:d}=s;p();function p(){for(let h of a)u&&f(h),s.allErrors?m(h):(e.var(l,!0),m(h),e.if(l))}function f(h){for(let g in u)new RegExp(h).test(g)&&(0,bA.checkStrictMode)(s,`property ${g} matches pattern ${h} (use allowMatchingProperties)`)}function m(h){e.forIn("key",n,g=>{e.if((0,Mh._)`${(0,_A.usePattern)(t,h)}.test(${g})`,()=>{let v=c.includes(h);v||t.subschema({keyword:"patternProperties",schemaProp:h,dataProp:g,dataPropType:SA.Type.Str},l),s.opts.unevaluated&&d!==!0?e.assign((0,Mh._)`${d}[${g}]`,!0):!v&&!s.allErrors&&e.if((0,Mh.not)(l),()=>e.break())})})}}};z0.default=bJ});var wA=$(L0=>{"use strict";Object.defineProperty(L0,"__esModule",{value:!0});var SJ=it(),xJ={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,SJ.alwaysValidSchema)(n,r)){t.fail();return}let i=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},i),t.failResult(i,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};L0.default=xJ});var EA=$(U0=>{"use strict";Object.defineProperty(U0,"__esModule",{value:!0});var wJ=Fn(),EJ={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:wJ.validateUnion,error:{message:"must match a schema in anyOf"}};U0.default=EJ});var kA=$(F0=>{"use strict";Object.defineProperty(F0,"__esModule",{value:!0});var Dh=Ue(),kJ=it(),TJ={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Dh._)`{passingSchemas: ${t.passing}}`},$J={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:TJ,code(t){let{gen:e,schema:r,parentSchema:n,it:i}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(i.opts.discriminator&&n.discriminator)return;let s=r,o=e.let("valid",!1),a=e.let("passing",null),c=e.name("_valid");t.setParams({passing:a}),e.block(u),t.result(o,()=>t.reset(),()=>t.error(!0));function u(){s.forEach((l,d)=>{let p;(0,kJ.alwaysValidSchema)(i,l)?e.var(c,!0):p=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,Dh._)`${c} && ${o}`).assign(o,!1).assign(a,(0,Dh._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(o,!0),e.assign(a,d),p&&t.mergeEvaluated(p,Dh.Name)})})}}};F0.default=$J});var TA=$(q0=>{"use strict";Object.defineProperty(q0,"__esModule",{value:!0});var IJ=it(),RJ={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:r,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");let i=e.name("valid");r.forEach((s,o)=>{if((0,IJ.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:o},i);t.ok(i),t.mergeEvaluated(a)})}};q0.default=RJ});var RA=$(H0=>{"use strict";Object.defineProperty(H0,"__esModule",{value:!0});var jh=Ue(),IA=it(),OJ={message:({params:t})=>(0,jh.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,jh._)`{failingKeyword: ${t.ifClause}}`},CJ={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:OJ,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,IA.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let i=$A(n,"then"),s=$A(n,"else");if(!i&&!s)return;let o=e.let("valid",!0),a=e.name("_valid");if(c(),t.reset(),i&&s){let l=e.let("ifClause");t.setParams({ifClause:l}),e.if(a,u("then",l),u("else",l))}else i?e.if(a,u("then")):e.if((0,jh.not)(a),u("else"));t.pass(o,()=>t.error(!0));function c(){let l=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(l)}function u(l,d){return()=>{let p=t.subschema({keyword:l},a);e.assign(o,a),t.mergeValidEvaluated(p,o),d?e.assign(d,(0,jh._)`${l}`):t.setParams({ifClause:l})}}}};function $A(t,e){let r=t.schema[e];return r!==void 0&&!(0,IA.alwaysValidSchema)(t,r)}H0.default=CJ});var OA=$(Z0=>{"use strict";Object.defineProperty(Z0,"__esModule",{value:!0});var PJ=it(),AJ={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,PJ.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};Z0.default=AJ});var CA=$(B0=>{"use strict";Object.defineProperty(B0,"__esModule",{value:!0});var NJ=$0(),MJ=aA(),DJ=I0(),jJ=uA(),zJ=lA(),LJ=fA(),UJ=hA(),FJ=M0(),qJ=yA(),HJ=xA(),ZJ=wA(),BJ=EA(),GJ=kA(),WJ=TA(),VJ=RA(),KJ=OA();function JJ(t=!1){let e=[ZJ.default,BJ.default,GJ.default,WJ.default,VJ.default,KJ.default,UJ.default,FJ.default,LJ.default,qJ.default,HJ.default];return t?e.push(MJ.default,jJ.default):e.push(NJ.default,DJ.default),e.push(zJ.default),e}B0.default=JJ});var PA=$(G0=>{"use strict";Object.defineProperty(G0,"__esModule",{value:!0});var Jt=Ue(),XJ={message:({schemaCode:t})=>(0,Jt.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Jt._)`{format: ${t}}`},YJ={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:XJ,code(t,e){let{gen:r,data:n,$data:i,schema:s,schemaCode:o,it:a}=t,{opts:c,errSchemaPath:u,schemaEnv:l,self:d}=a;if(!c.validateFormats)return;i?p():f();function p(){let m=r.scopeValue("formats",{ref:d.formats,code:c.code.formats}),h=r.const("fDef",(0,Jt._)`${m}[${o}]`),g=r.let("fType"),v=r.let("format");r.if((0,Jt._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>r.assign(g,(0,Jt._)`${h}.type || "string"`).assign(v,(0,Jt._)`${h}.validate`),()=>r.assign(g,(0,Jt._)`"string"`).assign(v,h)),t.fail$data((0,Jt.or)(S(),_()));function S(){return c.strictSchema===!1?Jt.nil:(0,Jt._)`${o} && !${v}`}function _(){let y=l.$async?(0,Jt._)`(${h}.async ? await ${v}(${n}) : ${v}(${n}))`:(0,Jt._)`${v}(${n})`,x=(0,Jt._)`(typeof ${v} == "function" ? ${y} : ${v}.test(${n}))`;return(0,Jt._)`${v} && ${v} !== true && ${g} === ${e} && !${x}`}}function f(){let m=d.formats[s];if(!m){S();return}if(m===!0)return;let[h,g,v]=_(m);h===e&&t.pass(y());function S(){if(c.strictSchema===!1){d.logger.warn(x());return}throw new Error(x());function x(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function _(x){let w=x instanceof RegExp?(0,Jt.regexpCode)(x):c.code.formats?(0,Jt._)`${c.code.formats}${(0,Jt.getProperty)(s)}`:void 0,E=r.scopeValue("formats",{key:s,ref:x,code:w});return typeof x=="object"&&!(x instanceof RegExp)?[x.type||"string",x.validate,(0,Jt._)`${E}.validate`]:["string",x,E]}function y(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!l.$async)throw new Error("async format in sync schema");return(0,Jt._)`await ${v}(${n})`}return typeof g=="function"?(0,Jt._)`${v}(${n})`:(0,Jt._)`${v}.test(${n})`}}}};G0.default=YJ});var AA=$(W0=>{"use strict";Object.defineProperty(W0,"__esModule",{value:!0});var QJ=PA(),eX=[QJ.default];W0.default=eX});var NA=$(yc=>{"use strict";Object.defineProperty(yc,"__esModule",{value:!0});yc.contentVocabulary=yc.metadataVocabulary=void 0;yc.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];yc.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var DA=$(V0=>{"use strict";Object.defineProperty(V0,"__esModule",{value:!0});var tX=HP(),rX=nA(),nX=CA(),iX=AA(),MA=NA(),sX=[tX.default,rX.default,(0,nX.default)(),iX.default,MA.metadataVocabulary,MA.contentVocabulary];V0.default=sX});var zA=$(zh=>{"use strict";Object.defineProperty(zh,"__esModule",{value:!0});zh.DiscrError=void 0;var jA;(function(t){t.Tag="tag",t.Mapping="mapping"})(jA||(zh.DiscrError=jA={}))});var UA=$(J0=>{"use strict";Object.defineProperty(J0,"__esModule",{value:!0});var _c=Ue(),K0=zA(),LA=_h(),oX=_d(),aX=it(),cX={message:({params:{discrError:t,tagName:e}})=>t===K0.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,_c._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},uX={keyword:"discriminator",type:"object",schemaType:"object",error:cX,code(t){let{gen:e,data:r,schema:n,parentSchema:i,it:s}=t,{oneOf:o}=i;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!o)throw new Error("discriminator: requires oneOf keyword");let c=e.let("valid",!1),u=e.const("tag",(0,_c._)`${r}${(0,_c.getProperty)(a)}`);e.if((0,_c._)`typeof ${u} == "string"`,()=>l(),()=>t.error(!1,{discrError:K0.DiscrError.Tag,tag:u,tagName:a})),t.ok(c);function l(){let f=p();e.if(!1);for(let m in f)e.elseIf((0,_c._)`${u} === ${m}`),e.assign(c,d(f[m]));e.else(),t.error(!1,{discrError:K0.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function d(f){let m=e.name("valid"),h=t.subschema({keyword:"oneOf",schemaProp:f},m);return t.mergeEvaluated(h,_c.Name),m}function p(){var f;let m={},h=v(i),g=!0;for(let y=0;y{lX.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var Y0=$((Pt,X0)=>{"use strict";Object.defineProperty(Pt,"__esModule",{value:!0});Pt.MissingRefError=Pt.ValidationError=Pt.CodeGen=Pt.Name=Pt.nil=Pt.stringify=Pt.str=Pt._=Pt.KeywordCxt=Pt.Ajv=void 0;var dX=jP(),pX=DA(),fX=UA(),qA=FA(),mX=["/properties"],Lh="http://json-schema.org/draft-07/schema",bc=class extends dX.default{_addVocabularies(){super._addVocabularies(),pX.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(fX.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(qA,mX):qA;this.addMetaSchema(e,Lh,!1),this.refs["http://json-schema.org/schema"]=Lh}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Lh)?Lh:void 0)}};Pt.Ajv=bc;X0.exports=Pt=bc;X0.exports.Ajv=bc;Object.defineProperty(Pt,"__esModule",{value:!0});Pt.default=bc;var hX=yd();Object.defineProperty(Pt,"KeywordCxt",{enumerable:!0,get:function(){return hX.KeywordCxt}});var Sc=Ue();Object.defineProperty(Pt,"_",{enumerable:!0,get:function(){return Sc._}});Object.defineProperty(Pt,"str",{enumerable:!0,get:function(){return Sc.str}});Object.defineProperty(Pt,"stringify",{enumerable:!0,get:function(){return Sc.stringify}});Object.defineProperty(Pt,"nil",{enumerable:!0,get:function(){return Sc.nil}});Object.defineProperty(Pt,"Name",{enumerable:!0,get:function(){return Sc.Name}});Object.defineProperty(Pt,"CodeGen",{enumerable:!0,get:function(){return Sc.CodeGen}});var gX=vh();Object.defineProperty(Pt,"ValidationError",{enumerable:!0,get:function(){return gX.default}});var vX=_d();Object.defineProperty(Pt,"MissingRefError",{enumerable:!0,get:function(){return vX.default}})});var JA=$(zi=>{"use strict";Object.defineProperty(zi,"__esModule",{value:!0});zi.formatNames=zi.fastFormats=zi.fullFormats=void 0;function ji(t,e){return{validate:t,compare:e}}zi.fullFormats={date:ji(GA,rE),time:ji(eE(!0),nE),"date-time":ji(HA(!0),VA),"iso-time":ji(eE(),WA),"iso-date-time":ji(HA(),KA),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:wX,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:OX,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:EX,int32:{type:"number",validate:$X},int64:{type:"number",validate:IX},float:{type:"number",validate:BA},double:{type:"number",validate:BA},password:!0,binary:!0};zi.fastFormats={...zi.fullFormats,date:ji(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,rE),time:ji(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,nE),"date-time":ji(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,VA),"iso-time":ji(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,WA),"iso-date-time":ji(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,KA),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};zi.formatNames=Object.keys(zi.fullFormats);function yX(t){return t%4===0&&(t%100!==0||t%400===0)}var _X=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,bX=[0,31,28,31,30,31,30,31,31,30,31,30,31];function GA(t){let e=_X.exec(t);if(!e)return!1;let r=+e[1],n=+e[2],i=+e[3];return n>=1&&n<=12&&i>=1&&i<=(n===2&&yX(r)?29:bX[n])}function rE(t,e){if(t&&e)return t>e?1:t23||l>59||t&&!a)return!1;if(i<=23&&s<=59&&o<60)return!0;let d=s-l*c,p=i-u*c-(d<0?1:0);return(p===23||p===-1)&&(d===59||d===-1)&&o<61}}function nE(t,e){if(!(t&&e))return;let r=new Date("2020-01-01T"+t).valueOf(),n=new Date("2020-01-01T"+e).valueOf();if(r&&n)return r-n}function WA(t,e){if(!(t&&e))return;let r=Q0.exec(t),n=Q0.exec(e);if(r&&n)return t=r[1]+r[2]+r[3],e=n[1]+n[2]+n[3],t>e?1:t=kX}function IX(t){return Number.isInteger(t)}function BA(){return!0}var RX=/[^\\]\\Z/;function OX(t){if(RX.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var XA=$(xc=>{"use strict";Object.defineProperty(xc,"__esModule",{value:!0});xc.formatLimitDefinition=void 0;var CX=Y0(),di=Ue(),so=di.operators,Uh={formatMaximum:{okStr:"<=",ok:so.LTE,fail:so.GT},formatMinimum:{okStr:">=",ok:so.GTE,fail:so.LT},formatExclusiveMaximum:{okStr:"<",ok:so.LT,fail:so.GTE},formatExclusiveMinimum:{okStr:">",ok:so.GT,fail:so.LTE}},PX={message:({keyword:t,schemaCode:e})=>(0,di.str)`should be ${Uh[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,di._)`{comparison: ${Uh[t].okStr}, limit: ${e}}`};xc.formatLimitDefinition={keyword:Object.keys(Uh),type:"string",schemaType:"string",$data:!0,error:PX,code(t){let{gen:e,data:r,schemaCode:n,keyword:i,it:s}=t,{opts:o,self:a}=s;if(!o.validateFormats)return;let c=new CX.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?u():l();function u(){let p=e.scopeValue("formats",{ref:a.formats,code:o.code.formats}),f=e.const("fmt",(0,di._)`${p}[${c.schemaCode}]`);t.fail$data((0,di.or)((0,di._)`typeof ${f} != "object"`,(0,di._)`${f} instanceof RegExp`,(0,di._)`typeof ${f}.compare != "function"`,d(f)))}function l(){let p=c.schema,f=a.formats[p];if(!f||f===!0)return;if(typeof f!="object"||f instanceof RegExp||typeof f.compare!="function")throw new Error(`"${i}": format "${p}" does not define "compare" function`);let m=e.scopeValue("formats",{key:p,ref:f,code:o.code.formats?(0,di._)`${o.code.formats}${(0,di.getProperty)(p)}`:void 0});t.fail$data(d(m))}function d(p){return(0,di._)`${p}.compare(${r}, ${n}) ${Uh[i].fail} 0`}},dependencies:["format"]};var AX=t=>(t.addKeyword(xc.formatLimitDefinition),t);xc.default=AX});var tN=$((Ad,eN)=>{"use strict";Object.defineProperty(Ad,"__esModule",{value:!0});var wc=JA(),NX=XA(),iE=Ue(),YA=new iE.Name("fullFormats"),MX=new iE.Name("fastFormats"),sE=(t,e={keywords:!0})=>{if(Array.isArray(e))return QA(t,e,wc.fullFormats,YA),t;let[r,n]=e.mode==="fast"?[wc.fastFormats,MX]:[wc.fullFormats,YA],i=e.formats||wc.formatNames;return QA(t,i,r,n),e.keywords&&(0,NX.default)(t),t};sE.get=(t,e="full")=>{let n=(e==="fast"?wc.fastFormats:wc.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function QA(t,e,r,n){var i,s;(i=(s=t.opts.code).formats)!==null&&i!==void 0||(s.formats=(0,iE._)`require("ajv-formats/dist/formats").${n}`);for(let o of e)t.addFormat(o,r[o])}eN.exports=Ad=sE;Object.defineProperty(Ad,"__esModule",{value:!0});Ad.default=sE});var lN=$(($Oe,uN)=>{uN.exports=cN;cN.sync=LX;var oN=require("fs");function zX(t,e){var r=e.pathExt!==void 0?e.pathExt:process.env.PATHEXT;if(!r||(r=r.split(";"),r.indexOf("")!==-1))return!0;for(var n=0;n{mN.exports=pN;pN.sync=UX;var dN=require("fs");function pN(t,e,r){dN.stat(t,function(n,i){r(n,n?!1:fN(i,e))})}function UX(t,e){return fN(dN.statSync(t),e)}function fN(t,e){return t.isFile()&&FX(t,e)}function FX(t,e){var r=t.mode,n=t.uid,i=t.gid,s=e.uid!==void 0?e.uid:process.getuid&&process.getuid(),o=e.gid!==void 0?e.gid:process.getgid&&process.getgid(),a=parseInt("100",8),c=parseInt("010",8),u=parseInt("001",8),l=a|c,d=r&u||r&c&&i===o||r&a&&n===s||r&l&&s===0;return d}});var vN=$((OOe,gN)=>{var ROe=require("fs"),Zh;process.platform==="win32"||global.TESTING_WINDOWS?Zh=lN():Zh=hN();gN.exports=oE;oE.sync=qX;function oE(t,e,r){if(typeof e=="function"&&(r=e,e={}),!r){if(typeof Promise!="function")throw new TypeError("callback not provided");return new Promise(function(n,i){oE(t,e||{},function(s,o){s?i(s):n(o)})})}Zh(t,e||{},function(n,i){n&&(n.code==="EACCES"||e&&e.ignoreErrors)&&(n=null,i=!1),r(n,i)})}function qX(t,e){try{return Zh.sync(t,e||{})}catch(r){if(e&&e.ignoreErrors||r.code==="EACCES")return!1;throw r}}});var EN=$((COe,wN)=>{var kc=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",yN=require("path"),HX=kc?";":":",_N=vN(),bN=t=>Object.assign(new Error(`not found: ${t}`),{code:"ENOENT"}),SN=(t,e)=>{let r=e.colon||HX,n=t.match(/\//)||kc&&t.match(/\\/)?[""]:[...kc?[process.cwd()]:[],...(e.path||process.env.PATH||"").split(r)],i=kc?e.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",s=kc?i.split(r):[""];return kc&&t.indexOf(".")!==-1&&s[0]!==""&&s.unshift(""),{pathEnv:n,pathExt:s,pathExtExe:i}},xN=(t,e,r)=>{typeof e=="function"&&(r=e,e={}),e||(e={});let{pathEnv:n,pathExt:i,pathExtExe:s}=SN(t,e),o=[],a=u=>new Promise((l,d)=>{if(u===n.length)return e.all&&o.length?l(o):d(bN(t));let p=n[u],f=/^".*"$/.test(p)?p.slice(1,-1):p,m=yN.join(f,t),h=!f&&/^\.[\\\/]/.test(t)?t.slice(0,2)+m:m;l(c(h,u,0))}),c=(u,l,d)=>new Promise((p,f)=>{if(d===i.length)return p(a(l+1));let m=i[d];_N(u+m,{pathExt:s},(h,g)=>{if(!h&&g)if(e.all)o.push(u+m);else return p(u+m);return p(c(u,l,d+1))})});return r?a(0).then(u=>r(null,u),r):a(0)},ZX=(t,e)=>{e=e||{};let{pathEnv:r,pathExt:n,pathExtExe:i}=SN(t,e),s=[];for(let o=0;o{"use strict";var kN=(t={})=>{let e=t.env||process.env;return(t.platform||process.platform)!=="win32"?"PATH":Object.keys(e).reverse().find(n=>n.toUpperCase()==="PATH")||"Path"};aE.exports=kN;aE.exports.default=kN});var ON=$((AOe,RN)=>{"use strict";var $N=require("path"),BX=EN(),GX=TN();function IN(t,e){let r=t.options.env||process.env,n=process.cwd(),i=t.options.cwd!=null,s=i&&process.chdir!==void 0&&!process.chdir.disabled;if(s)try{process.chdir(t.options.cwd)}catch{}let o;try{o=BX.sync(t.command,{path:r[GX({env:r})],pathExt:e?$N.delimiter:void 0})}catch{}finally{s&&process.chdir(n)}return o&&(o=$N.resolve(i?t.options.cwd:"",o)),o}function WX(t){return IN(t)||IN(t,!0)}RN.exports=WX});var CN=$((NOe,uE)=>{"use strict";var cE=/([()\][%!^"`<>&|;, *?])/g;function VX(t){return t=t.replace(cE,"^$1"),t}function KX(t,e){return t=`${t}`,t=t.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),t=t.replace(/(?=(\\+?)?)\1$/,"$1$1"),t=`"${t}"`,t=t.replace(cE,"^$1"),e&&(t=t.replace(cE,"^$1")),t}uE.exports.command=VX;uE.exports.argument=KX});var AN=$((MOe,PN)=>{"use strict";PN.exports=/^#!(.*)/});var MN=$((DOe,NN)=>{"use strict";var JX=AN();NN.exports=(t="")=>{let e=t.match(JX);if(!e)return null;let[r,n]=e[0].replace(/#! ?/,"").split(" "),i=r.split("/").pop();return i==="env"?n:n?`${i} ${n}`:i}});var jN=$((jOe,DN)=>{"use strict";var lE=require("fs"),XX=MN();function YX(t){let r=Buffer.alloc(150),n;try{n=lE.openSync(t,"r"),lE.readSync(n,r,0,150,0),lE.closeSync(n)}catch{}return XX(r.toString())}DN.exports=YX});var FN=$((zOe,UN)=>{"use strict";var QX=require("path"),zN=ON(),LN=CN(),eY=jN(),tY=process.platform==="win32",rY=/\.(?:com|exe)$/i,nY=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function iY(t){t.file=zN(t);let e=t.file&&eY(t.file);return e?(t.args.unshift(t.file),t.command=e,zN(t)):t.file}function sY(t){if(!tY)return t;let e=iY(t),r=!rY.test(e);if(t.options.forceShell||r){let n=nY.test(e);t.command=QX.normalize(t.command),t.command=LN.command(t.command),t.args=t.args.map(s=>LN.argument(s,n));let i=[t.command].concat(t.args).join(" ");t.args=["/d","/s","/c",`"${i}"`],t.command=process.env.comspec||"cmd.exe",t.options.windowsVerbatimArguments=!0}return t}function oY(t,e,r){e&&!Array.isArray(e)&&(r=e,e=null),e=e?e.slice(0):[],r=Object.assign({},r);let n={command:t,args:e,options:r,file:void 0,original:{command:t,args:e}};return r.shell?n:sY(n)}UN.exports=oY});var ZN=$((LOe,HN)=>{"use strict";var dE=process.platform==="win32";function pE(t,e){return Object.assign(new Error(`${e} ${t.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${e} ${t.command}`,path:t.command,spawnargs:t.args})}function aY(t,e){if(!dE)return;let r=t.emit;t.emit=function(n,i){if(n==="exit"){let s=qN(i,e);if(s)return r.call(t,"error",s)}return r.apply(t,arguments)}}function qN(t,e){return dE&&t===1&&!e.file?pE(e.original,"spawn"):null}function cY(t,e){return dE&&t===1&&!e.file?pE(e.original,"spawnSync"):null}HN.exports={hookChildProcess:aY,verifyENOENT:qN,verifyENOENTSync:cY,notFoundError:pE}});var WN=$((UOe,Tc)=>{"use strict";var BN=require("child_process"),fE=FN(),mE=ZN();function GN(t,e,r){let n=fE(t,e,r),i=BN.spawn(n.command,n.args,n.options);return mE.hookChildProcess(i,n),i}function uY(t,e,r){let n=fE(t,e,r),i=BN.spawnSync(n.command,n.args,n.options);return i.error=i.error||mE.verifyENOENTSync(i.status,n),i}Tc.exports=GN;Tc.exports.spawn=GN;Tc.exports.sync=uY;Tc.exports._parse=fE;Tc.exports._enoent=mE});var _s,Md,YN,hE,XN,gE,b,ne=Oe(()=>{"use strict";_s=require("fs"),Md=require("path"),YN=require("os"),hE=(s=>(s[s.DEBUG=0]="DEBUG",s[s.INFO=1]="INFO",s[s.WARN=2]="WARN",s[s.ERROR=3]="ERROR",s[s.SILENT=4]="SILENT",s))(hE||{}),XN=(0,Md.join)((0,YN.homedir)(),".claude-mem"),gE=class{level=null;useColor;logFilePath=null;logFileInitialized=!1;constructor(){this.useColor=process.stdout.isTTY??!1}ensureLogFileInitialized(){if(!this.logFileInitialized){this.logFileInitialized=!0;try{let e=(0,Md.join)(XN,"logs");(0,_s.existsSync)(e)||(0,_s.mkdirSync)(e,{recursive:!0});let r=new Date().toISOString().split("T")[0];this.logFilePath=(0,Md.join)(e,`claude-mem-${r}.log`)}catch(e){console.error("[LOGGER] Failed to initialize log file:",e),this.logFilePath=null}}}getLevel(){if(this.level===null)try{let e=(0,Md.join)(XN,"settings.json");if((0,_s.existsSync)(e)){let r=(0,_s.readFileSync)(e,"utf-8"),i=(JSON.parse(r).CLAUDE_MEM_LOG_LEVEL||"INFO").toUpperCase();this.level=hE[i]??1}else this.level=1}catch{this.level=1}return this.level}correlationId(e,r){return`obs-${e}-${r}`}sessionId(e){return`session-${e}`}formatData(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return e.toString();if(typeof e=="object"){if(e instanceof Error)return this.getLevel()===0?`${e.message} + deps: ${r}}`};var lJ={keyword:"dependencies",type:"object",schemaType:"object",error:Di.error,code(t){let[e,r]=dJ(t);dA(t,e),pA(t,r)}};function dJ({schema:t}){let e={},r={};for(let n in t){if(n==="__proto__")continue;let i=Array.isArray(t[n])?e:r;i[n]=t[n]}return[e,r]}function dA(t,e=t.schema){let{gen:r,data:n,it:i}=t;if(Object.keys(e).length===0)return;let s=r.let("missing");for(let o in e){let a=e[o];if(a.length===0)continue;let c=(0,Pd.propertyInData)(r,n,o,i.opts.ownProperties);t.setParams({property:o,depsCount:a.length,deps:a.join(", ")}),i.allErrors?r.if(c,()=>{for(let u of a)(0,Pd.checkReportMissingProp)(t,u)}):(r.if((0,P0._)`${c} && (${(0,Pd.checkMissingProp)(t,a,s)})`),(0,Pd.reportMissingProp)(t,s),r.else())}}Di.validatePropertyDeps=dA;function pA(t,e=t.schema){let{gen:r,data:n,keyword:i,it:s}=t,o=r.name("valid");for(let a in e)(0,uJ.alwaysValidSchema)(s,e[a])||(r.if((0,Pd.propertyInData)(r,n,a,s.opts.ownProperties),()=>{let c=t.subschema({keyword:i,schemaProp:a},o);t.mergeValidEvaluated(c,o)},()=>r.var(o,!0)),t.ok(o))}Di.validateSchemaDeps=pA;Di.default=lJ});var hA=$(A0=>{"use strict";Object.defineProperty(A0,"__esModule",{value:!0});var mA=Ue(),pJ=it(),fJ={message:"property name must be valid",params:({params:t})=>(0,mA._)`{propertyName: ${t.propertyName}}`},mJ={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:fJ,code(t){let{gen:e,schema:r,data:n,it:i}=t;if((0,pJ.alwaysValidSchema)(i,r))return;let s=e.name("valid");e.forIn("key",n,o=>{t.setParams({propertyName:o}),t.subschema({keyword:"propertyNames",data:o,dataTypes:["string"],propertyName:o,compositeRule:!0},s),e.if((0,mA.not)(s),()=>{t.error(!0),i.allErrors||e.break()})}),t.ok(s)}};A0.default=mJ});var M0=$(N0=>{"use strict";Object.defineProperty(N0,"__esModule",{value:!0});var Ah=Fn(),li=Ue(),hJ=gs(),Nh=it(),gJ={message:"must NOT have additional properties",params:({params:t})=>(0,li._)`{additionalProperty: ${t.additionalProperty}}`},vJ={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:gJ,code(t){let{gen:e,schema:r,parentSchema:n,data:i,errsCount:s,it:o}=t;if(!s)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=o;if(o.props=!0,c.removeAdditional!=="all"&&(0,Nh.alwaysValidSchema)(o,r))return;let u=(0,Ah.allSchemaProperties)(n.properties),l=(0,Ah.allSchemaProperties)(n.patternProperties);d(),t.ok((0,li._)`${s} === ${hJ.default.errors}`);function d(){e.forIn("key",i,g=>{!u.length&&!l.length?m(g):e.if(p(g),()=>m(g))})}function p(g){let v;if(u.length>8){let S=(0,Nh.schemaRefOrVal)(o,n.properties,"properties");v=(0,Ah.isOwnProperty)(e,S,g)}else u.length?v=(0,li.or)(...u.map(S=>(0,li._)`${g} === ${S}`)):v=li.nil;return l.length&&(v=(0,li.or)(v,...l.map(S=>(0,li._)`${(0,Ah.usePattern)(t,S)}.test(${g})`))),(0,li.not)(v)}function f(g){e.code((0,li._)`delete ${i}[${g}]`)}function m(g){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){f(g);return}if(r===!1){t.setParams({additionalProperty:g}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,Nh.alwaysValidSchema)(o,r)){let v=e.name("valid");c.removeAdditional==="failing"?(h(g,v,!1),e.if((0,li.not)(v),()=>{t.reset(),f(g)})):(h(g,v),a||e.if((0,li.not)(v),()=>e.break()))}}function h(g,v,S){let _={keyword:"additionalProperties",dataProp:g,dataPropType:Nh.Type.Str};S===!1&&Object.assign(_,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(_,v)}}};N0.default=vJ});var yA=$(j0=>{"use strict";Object.defineProperty(j0,"__esModule",{value:!0});var yJ=yd(),gA=Fn(),D0=it(),vA=M0(),_J={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:n,data:i,it:s}=t;s.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&vA.default.code(new yJ.KeywordCxt(s,vA.default,"additionalProperties"));let o=(0,gA.allSchemaProperties)(r);for(let d of o)s.definedProperties.add(d);s.opts.unevaluated&&o.length&&s.props!==!0&&(s.props=D0.mergeEvaluated.props(e,(0,D0.toHash)(o),s.props));let a=o.filter(d=>!(0,D0.alwaysValidSchema)(s,r[d]));if(a.length===0)return;let c=e.name("valid");for(let d of a)u(d)?l(d):(e.if((0,gA.propertyInData)(e,i,d,s.opts.ownProperties)),l(d),s.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(d),t.ok(c);function u(d){return s.opts.useDefaults&&!s.compositeRule&&r[d].default!==void 0}function l(d){t.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};j0.default=_J});var xA=$(z0=>{"use strict";Object.defineProperty(z0,"__esModule",{value:!0});var _A=Fn(),Mh=Ue(),bA=it(),SA=it(),bJ={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,data:n,parentSchema:i,it:s}=t,{opts:o}=s,a=(0,_A.allSchemaProperties)(r),c=a.filter(h=>(0,bA.alwaysValidSchema)(s,r[h]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let u=o.strictSchema&&!o.allowMatchingProperties&&i.properties,l=e.name("valid");s.props!==!0&&!(s.props instanceof Mh.Name)&&(s.props=(0,SA.evaluatedPropsToName)(e,s.props));let{props:d}=s;p();function p(){for(let h of a)u&&f(h),s.allErrors?m(h):(e.var(l,!0),m(h),e.if(l))}function f(h){for(let g in u)new RegExp(h).test(g)&&(0,bA.checkStrictMode)(s,`property ${g} matches pattern ${h} (use allowMatchingProperties)`)}function m(h){e.forIn("key",n,g=>{e.if((0,Mh._)`${(0,_A.usePattern)(t,h)}.test(${g})`,()=>{let v=c.includes(h);v||t.subschema({keyword:"patternProperties",schemaProp:h,dataProp:g,dataPropType:SA.Type.Str},l),s.opts.unevaluated&&d!==!0?e.assign((0,Mh._)`${d}[${g}]`,!0):!v&&!s.allErrors&&e.if((0,Mh.not)(l),()=>e.break())})})}}};z0.default=bJ});var wA=$(L0=>{"use strict";Object.defineProperty(L0,"__esModule",{value:!0});var SJ=it(),xJ={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,SJ.alwaysValidSchema)(n,r)){t.fail();return}let i=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},i),t.failResult(i,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};L0.default=xJ});var EA=$(U0=>{"use strict";Object.defineProperty(U0,"__esModule",{value:!0});var wJ=Fn(),EJ={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:wJ.validateUnion,error:{message:"must match a schema in anyOf"}};U0.default=EJ});var kA=$(F0=>{"use strict";Object.defineProperty(F0,"__esModule",{value:!0});var Dh=Ue(),kJ=it(),TJ={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Dh._)`{passingSchemas: ${t.passing}}`},$J={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:TJ,code(t){let{gen:e,schema:r,parentSchema:n,it:i}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(i.opts.discriminator&&n.discriminator)return;let s=r,o=e.let("valid",!1),a=e.let("passing",null),c=e.name("_valid");t.setParams({passing:a}),e.block(u),t.result(o,()=>t.reset(),()=>t.error(!0));function u(){s.forEach((l,d)=>{let p;(0,kJ.alwaysValidSchema)(i,l)?e.var(c,!0):p=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,Dh._)`${c} && ${o}`).assign(o,!1).assign(a,(0,Dh._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(o,!0),e.assign(a,d),p&&t.mergeEvaluated(p,Dh.Name)})})}}};F0.default=$J});var TA=$(q0=>{"use strict";Object.defineProperty(q0,"__esModule",{value:!0});var IJ=it(),RJ={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:r,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");let i=e.name("valid");r.forEach((s,o)=>{if((0,IJ.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:o},i);t.ok(i),t.mergeEvaluated(a)})}};q0.default=RJ});var RA=$(H0=>{"use strict";Object.defineProperty(H0,"__esModule",{value:!0});var jh=Ue(),IA=it(),OJ={message:({params:t})=>(0,jh.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,jh._)`{failingKeyword: ${t.ifClause}}`},CJ={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:OJ,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,IA.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let i=$A(n,"then"),s=$A(n,"else");if(!i&&!s)return;let o=e.let("valid",!0),a=e.name("_valid");if(c(),t.reset(),i&&s){let l=e.let("ifClause");t.setParams({ifClause:l}),e.if(a,u("then",l),u("else",l))}else i?e.if(a,u("then")):e.if((0,jh.not)(a),u("else"));t.pass(o,()=>t.error(!0));function c(){let l=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(l)}function u(l,d){return()=>{let p=t.subschema({keyword:l},a);e.assign(o,a),t.mergeValidEvaluated(p,o),d?e.assign(d,(0,jh._)`${l}`):t.setParams({ifClause:l})}}}};function $A(t,e){let r=t.schema[e];return r!==void 0&&!(0,IA.alwaysValidSchema)(t,r)}H0.default=CJ});var OA=$(Z0=>{"use strict";Object.defineProperty(Z0,"__esModule",{value:!0});var PJ=it(),AJ={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,PJ.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};Z0.default=AJ});var CA=$(B0=>{"use strict";Object.defineProperty(B0,"__esModule",{value:!0});var NJ=$0(),MJ=aA(),DJ=I0(),jJ=uA(),zJ=lA(),LJ=fA(),UJ=hA(),FJ=M0(),qJ=yA(),HJ=xA(),ZJ=wA(),BJ=EA(),GJ=kA(),WJ=TA(),VJ=RA(),KJ=OA();function JJ(t=!1){let e=[ZJ.default,BJ.default,GJ.default,WJ.default,VJ.default,KJ.default,UJ.default,FJ.default,LJ.default,qJ.default,HJ.default];return t?e.push(MJ.default,jJ.default):e.push(NJ.default,DJ.default),e.push(zJ.default),e}B0.default=JJ});var PA=$(G0=>{"use strict";Object.defineProperty(G0,"__esModule",{value:!0});var Jt=Ue(),XJ={message:({schemaCode:t})=>(0,Jt.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Jt._)`{format: ${t}}`},YJ={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:XJ,code(t,e){let{gen:r,data:n,$data:i,schema:s,schemaCode:o,it:a}=t,{opts:c,errSchemaPath:u,schemaEnv:l,self:d}=a;if(!c.validateFormats)return;i?p():f();function p(){let m=r.scopeValue("formats",{ref:d.formats,code:c.code.formats}),h=r.const("fDef",(0,Jt._)`${m}[${o}]`),g=r.let("fType"),v=r.let("format");r.if((0,Jt._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>r.assign(g,(0,Jt._)`${h}.type || "string"`).assign(v,(0,Jt._)`${h}.validate`),()=>r.assign(g,(0,Jt._)`"string"`).assign(v,h)),t.fail$data((0,Jt.or)(S(),_()));function S(){return c.strictSchema===!1?Jt.nil:(0,Jt._)`${o} && !${v}`}function _(){let y=l.$async?(0,Jt._)`(${h}.async ? await ${v}(${n}) : ${v}(${n}))`:(0,Jt._)`${v}(${n})`,x=(0,Jt._)`(typeof ${v} == "function" ? ${y} : ${v}.test(${n}))`;return(0,Jt._)`${v} && ${v} !== true && ${g} === ${e} && !${x}`}}function f(){let m=d.formats[s];if(!m){S();return}if(m===!0)return;let[h,g,v]=_(m);h===e&&t.pass(y());function S(){if(c.strictSchema===!1){d.logger.warn(x());return}throw new Error(x());function x(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function _(x){let w=x instanceof RegExp?(0,Jt.regexpCode)(x):c.code.formats?(0,Jt._)`${c.code.formats}${(0,Jt.getProperty)(s)}`:void 0,E=r.scopeValue("formats",{key:s,ref:x,code:w});return typeof x=="object"&&!(x instanceof RegExp)?[x.type||"string",x.validate,(0,Jt._)`${E}.validate`]:["string",x,E]}function y(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!l.$async)throw new Error("async format in sync schema");return(0,Jt._)`await ${v}(${n})`}return typeof g=="function"?(0,Jt._)`${v}(${n})`:(0,Jt._)`${v}.test(${n})`}}}};G0.default=YJ});var AA=$(W0=>{"use strict";Object.defineProperty(W0,"__esModule",{value:!0});var QJ=PA(),eX=[QJ.default];W0.default=eX});var NA=$(yc=>{"use strict";Object.defineProperty(yc,"__esModule",{value:!0});yc.contentVocabulary=yc.metadataVocabulary=void 0;yc.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];yc.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var DA=$(V0=>{"use strict";Object.defineProperty(V0,"__esModule",{value:!0});var tX=HP(),rX=nA(),nX=CA(),iX=AA(),MA=NA(),sX=[tX.default,rX.default,(0,nX.default)(),iX.default,MA.metadataVocabulary,MA.contentVocabulary];V0.default=sX});var zA=$(zh=>{"use strict";Object.defineProperty(zh,"__esModule",{value:!0});zh.DiscrError=void 0;var jA;(function(t){t.Tag="tag",t.Mapping="mapping"})(jA||(zh.DiscrError=jA={}))});var UA=$(J0=>{"use strict";Object.defineProperty(J0,"__esModule",{value:!0});var _c=Ue(),K0=zA(),LA=_h(),oX=_d(),aX=it(),cX={message:({params:{discrError:t,tagName:e}})=>t===K0.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,_c._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},uX={keyword:"discriminator",type:"object",schemaType:"object",error:cX,code(t){let{gen:e,data:r,schema:n,parentSchema:i,it:s}=t,{oneOf:o}=i;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!o)throw new Error("discriminator: requires oneOf keyword");let c=e.let("valid",!1),u=e.const("tag",(0,_c._)`${r}${(0,_c.getProperty)(a)}`);e.if((0,_c._)`typeof ${u} == "string"`,()=>l(),()=>t.error(!1,{discrError:K0.DiscrError.Tag,tag:u,tagName:a})),t.ok(c);function l(){let f=p();e.if(!1);for(let m in f)e.elseIf((0,_c._)`${u} === ${m}`),e.assign(c,d(f[m]));e.else(),t.error(!1,{discrError:K0.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function d(f){let m=e.name("valid"),h=t.subschema({keyword:"oneOf",schemaProp:f},m);return t.mergeEvaluated(h,_c.Name),m}function p(){var f;let m={},h=v(i),g=!0;for(let y=0;y{lX.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var Y0=$((Pt,X0)=>{"use strict";Object.defineProperty(Pt,"__esModule",{value:!0});Pt.MissingRefError=Pt.ValidationError=Pt.CodeGen=Pt.Name=Pt.nil=Pt.stringify=Pt.str=Pt._=Pt.KeywordCxt=Pt.Ajv=void 0;var dX=jP(),pX=DA(),fX=UA(),qA=FA(),mX=["/properties"],Lh="http://json-schema.org/draft-07/schema",bc=class extends dX.default{_addVocabularies(){super._addVocabularies(),pX.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(fX.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(qA,mX):qA;this.addMetaSchema(e,Lh,!1),this.refs["http://json-schema.org/schema"]=Lh}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Lh)?Lh:void 0)}};Pt.Ajv=bc;X0.exports=Pt=bc;X0.exports.Ajv=bc;Object.defineProperty(Pt,"__esModule",{value:!0});Pt.default=bc;var hX=yd();Object.defineProperty(Pt,"KeywordCxt",{enumerable:!0,get:function(){return hX.KeywordCxt}});var Sc=Ue();Object.defineProperty(Pt,"_",{enumerable:!0,get:function(){return Sc._}});Object.defineProperty(Pt,"str",{enumerable:!0,get:function(){return Sc.str}});Object.defineProperty(Pt,"stringify",{enumerable:!0,get:function(){return Sc.stringify}});Object.defineProperty(Pt,"nil",{enumerable:!0,get:function(){return Sc.nil}});Object.defineProperty(Pt,"Name",{enumerable:!0,get:function(){return Sc.Name}});Object.defineProperty(Pt,"CodeGen",{enumerable:!0,get:function(){return Sc.CodeGen}});var gX=vh();Object.defineProperty(Pt,"ValidationError",{enumerable:!0,get:function(){return gX.default}});var vX=_d();Object.defineProperty(Pt,"MissingRefError",{enumerable:!0,get:function(){return vX.default}})});var JA=$(zi=>{"use strict";Object.defineProperty(zi,"__esModule",{value:!0});zi.formatNames=zi.fastFormats=zi.fullFormats=void 0;function ji(t,e){return{validate:t,compare:e}}zi.fullFormats={date:ji(GA,rE),time:ji(eE(!0),nE),"date-time":ji(HA(!0),VA),"iso-time":ji(eE(),WA),"iso-date-time":ji(HA(),KA),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:wX,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:OX,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:EX,int32:{type:"number",validate:$X},int64:{type:"number",validate:IX},float:{type:"number",validate:BA},double:{type:"number",validate:BA},password:!0,binary:!0};zi.fastFormats={...zi.fullFormats,date:ji(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,rE),time:ji(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,nE),"date-time":ji(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,VA),"iso-time":ji(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,WA),"iso-date-time":ji(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,KA),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};zi.formatNames=Object.keys(zi.fullFormats);function yX(t){return t%4===0&&(t%100!==0||t%400===0)}var _X=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,bX=[0,31,28,31,30,31,30,31,31,30,31,30,31];function GA(t){let e=_X.exec(t);if(!e)return!1;let r=+e[1],n=+e[2],i=+e[3];return n>=1&&n<=12&&i>=1&&i<=(n===2&&yX(r)?29:bX[n])}function rE(t,e){if(t&&e)return t>e?1:t23||l>59||t&&!a)return!1;if(i<=23&&s<=59&&o<60)return!0;let d=s-l*c,p=i-u*c-(d<0?1:0);return(p===23||p===-1)&&(d===59||d===-1)&&o<61}}function nE(t,e){if(!(t&&e))return;let r=new Date("2020-01-01T"+t).valueOf(),n=new Date("2020-01-01T"+e).valueOf();if(r&&n)return r-n}function WA(t,e){if(!(t&&e))return;let r=Q0.exec(t),n=Q0.exec(e);if(r&&n)return t=r[1]+r[2]+r[3],e=n[1]+n[2]+n[3],t>e?1:t=kX}function IX(t){return Number.isInteger(t)}function BA(){return!0}var RX=/[^\\]\\Z/;function OX(t){if(RX.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var XA=$(xc=>{"use strict";Object.defineProperty(xc,"__esModule",{value:!0});xc.formatLimitDefinition=void 0;var CX=Y0(),di=Ue(),so=di.operators,Uh={formatMaximum:{okStr:"<=",ok:so.LTE,fail:so.GT},formatMinimum:{okStr:">=",ok:so.GTE,fail:so.LT},formatExclusiveMaximum:{okStr:"<",ok:so.LT,fail:so.GTE},formatExclusiveMinimum:{okStr:">",ok:so.GT,fail:so.LTE}},PX={message:({keyword:t,schemaCode:e})=>(0,di.str)`should be ${Uh[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,di._)`{comparison: ${Uh[t].okStr}, limit: ${e}}`};xc.formatLimitDefinition={keyword:Object.keys(Uh),type:"string",schemaType:"string",$data:!0,error:PX,code(t){let{gen:e,data:r,schemaCode:n,keyword:i,it:s}=t,{opts:o,self:a}=s;if(!o.validateFormats)return;let c=new CX.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?u():l();function u(){let p=e.scopeValue("formats",{ref:a.formats,code:o.code.formats}),f=e.const("fmt",(0,di._)`${p}[${c.schemaCode}]`);t.fail$data((0,di.or)((0,di._)`typeof ${f} != "object"`,(0,di._)`${f} instanceof RegExp`,(0,di._)`typeof ${f}.compare != "function"`,d(f)))}function l(){let p=c.schema,f=a.formats[p];if(!f||f===!0)return;if(typeof f!="object"||f instanceof RegExp||typeof f.compare!="function")throw new Error(`"${i}": format "${p}" does not define "compare" function`);let m=e.scopeValue("formats",{key:p,ref:f,code:o.code.formats?(0,di._)`${o.code.formats}${(0,di.getProperty)(p)}`:void 0});t.fail$data(d(m))}function d(p){return(0,di._)`${p}.compare(${r}, ${n}) ${Uh[i].fail} 0`}},dependencies:["format"]};var AX=t=>(t.addKeyword(xc.formatLimitDefinition),t);xc.default=AX});var tN=$((Ad,eN)=>{"use strict";Object.defineProperty(Ad,"__esModule",{value:!0});var wc=JA(),NX=XA(),iE=Ue(),YA=new iE.Name("fullFormats"),MX=new iE.Name("fastFormats"),sE=(t,e={keywords:!0})=>{if(Array.isArray(e))return QA(t,e,wc.fullFormats,YA),t;let[r,n]=e.mode==="fast"?[wc.fastFormats,MX]:[wc.fullFormats,YA],i=e.formats||wc.formatNames;return QA(t,i,r,n),e.keywords&&(0,NX.default)(t),t};sE.get=(t,e="full")=>{let n=(e==="fast"?wc.fastFormats:wc.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function QA(t,e,r,n){var i,s;(i=(s=t.opts.code).formats)!==null&&i!==void 0||(s.formats=(0,iE._)`require("ajv-formats/dist/formats").${n}`);for(let o of e)t.addFormat(o,r[o])}eN.exports=Ad=sE;Object.defineProperty(Ad,"__esModule",{value:!0});Ad.default=sE});var lN=$(($Oe,uN)=>{uN.exports=cN;cN.sync=LX;var oN=require("fs");function zX(t,e){var r=e.pathExt!==void 0?e.pathExt:process.env.PATHEXT;if(!r||(r=r.split(";"),r.indexOf("")!==-1))return!0;for(var n=0;n{mN.exports=pN;pN.sync=UX;var dN=require("fs");function pN(t,e,r){dN.stat(t,function(n,i){r(n,n?!1:fN(i,e))})}function UX(t,e){return fN(dN.statSync(t),e)}function fN(t,e){return t.isFile()&&FX(t,e)}function FX(t,e){var r=t.mode,n=t.uid,i=t.gid,s=e.uid!==void 0?e.uid:process.getuid&&process.getuid(),o=e.gid!==void 0?e.gid:process.getgid&&process.getgid(),a=parseInt("100",8),c=parseInt("010",8),u=parseInt("001",8),l=a|c,d=r&u||r&c&&i===o||r&a&&n===s||r&l&&s===0;return d}});var vN=$((OOe,gN)=>{var ROe=require("fs"),Zh;process.platform==="win32"||global.TESTING_WINDOWS?Zh=lN():Zh=hN();gN.exports=oE;oE.sync=qX;function oE(t,e,r){if(typeof e=="function"&&(r=e,e={}),!r){if(typeof Promise!="function")throw new TypeError("callback not provided");return new Promise(function(n,i){oE(t,e||{},function(s,o){s?i(s):n(o)})})}Zh(t,e||{},function(n,i){n&&(n.code==="EACCES"||e&&e.ignoreErrors)&&(n=null,i=!1),r(n,i)})}function qX(t,e){try{return Zh.sync(t,e||{})}catch(r){if(e&&e.ignoreErrors||r.code==="EACCES")return!1;throw r}}});var EN=$((COe,wN)=>{var kc=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",yN=require("path"),HX=kc?";":":",_N=vN(),bN=t=>Object.assign(new Error(`not found: ${t}`),{code:"ENOENT"}),SN=(t,e)=>{let r=e.colon||HX,n=t.match(/\//)||kc&&t.match(/\\/)?[""]:[...kc?[process.cwd()]:[],...(e.path||process.env.PATH||"").split(r)],i=kc?e.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",s=kc?i.split(r):[""];return kc&&t.indexOf(".")!==-1&&s[0]!==""&&s.unshift(""),{pathEnv:n,pathExt:s,pathExtExe:i}},xN=(t,e,r)=>{typeof e=="function"&&(r=e,e={}),e||(e={});let{pathEnv:n,pathExt:i,pathExtExe:s}=SN(t,e),o=[],a=u=>new Promise((l,d)=>{if(u===n.length)return e.all&&o.length?l(o):d(bN(t));let p=n[u],f=/^".*"$/.test(p)?p.slice(1,-1):p,m=yN.join(f,t),h=!f&&/^\.[\\\/]/.test(t)?t.slice(0,2)+m:m;l(c(h,u,0))}),c=(u,l,d)=>new Promise((p,f)=>{if(d===i.length)return p(a(l+1));let m=i[d];_N(u+m,{pathExt:s},(h,g)=>{if(!h&&g)if(e.all)o.push(u+m);else return p(u+m);return p(c(u,l,d+1))})});return r?a(0).then(u=>r(null,u),r):a(0)},ZX=(t,e)=>{e=e||{};let{pathEnv:r,pathExt:n,pathExtExe:i}=SN(t,e),s=[];for(let o=0;o{"use strict";var kN=(t={})=>{let e=t.env||process.env;return(t.platform||process.platform)!=="win32"?"PATH":Object.keys(e).reverse().find(n=>n.toUpperCase()==="PATH")||"Path"};aE.exports=kN;aE.exports.default=kN});var ON=$((AOe,RN)=>{"use strict";var $N=require("path"),BX=EN(),GX=TN();function IN(t,e){let r=t.options.env||process.env,n=process.cwd(),i=t.options.cwd!=null,s=i&&process.chdir!==void 0&&!process.chdir.disabled;if(s)try{process.chdir(t.options.cwd)}catch{}let o;try{o=BX.sync(t.command,{path:r[GX({env:r})],pathExt:e?$N.delimiter:void 0})}catch{}finally{s&&process.chdir(n)}return o&&(o=$N.resolve(i?t.options.cwd:"",o)),o}function WX(t){return IN(t)||IN(t,!0)}RN.exports=WX});var CN=$((NOe,uE)=>{"use strict";var cE=/([()\][%!^"`<>&|;, *?])/g;function VX(t){return t=t.replace(cE,"^$1"),t}function KX(t,e){return t=`${t}`,t=t.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),t=t.replace(/(?=(\\+?)?)\1$/,"$1$1"),t=`"${t}"`,t=t.replace(cE,"^$1"),e&&(t=t.replace(cE,"^$1")),t}uE.exports.command=VX;uE.exports.argument=KX});var AN=$((MOe,PN)=>{"use strict";PN.exports=/^#!(.*)/});var MN=$((DOe,NN)=>{"use strict";var JX=AN();NN.exports=(t="")=>{let e=t.match(JX);if(!e)return null;let[r,n]=e[0].replace(/#! ?/,"").split(" "),i=r.split("/").pop();return i==="env"?n:n?`${i} ${n}`:i}});var jN=$((jOe,DN)=>{"use strict";var lE=require("fs"),XX=MN();function YX(t){let r=Buffer.alloc(150),n;try{n=lE.openSync(t,"r"),lE.readSync(n,r,0,150,0),lE.closeSync(n)}catch{}return XX(r.toString())}DN.exports=YX});var FN=$((zOe,UN)=>{"use strict";var QX=require("path"),zN=ON(),LN=CN(),eY=jN(),tY=process.platform==="win32",rY=/\.(?:com|exe)$/i,nY=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function iY(t){t.file=zN(t);let e=t.file&&eY(t.file);return e?(t.args.unshift(t.file),t.command=e,zN(t)):t.file}function sY(t){if(!tY)return t;let e=iY(t),r=!rY.test(e);if(t.options.forceShell||r){let n=nY.test(e);t.command=QX.normalize(t.command),t.command=LN.command(t.command),t.args=t.args.map(s=>LN.argument(s,n));let i=[t.command].concat(t.args).join(" ");t.args=["/d","/s","/c",`"${i}"`],t.command=process.env.comspec||"cmd.exe",t.options.windowsVerbatimArguments=!0}return t}function oY(t,e,r){e&&!Array.isArray(e)&&(r=e,e=null),e=e?e.slice(0):[],r=Object.assign({},r);let n={command:t,args:e,options:r,file:void 0,original:{command:t,args:e}};return r.shell?n:sY(n)}UN.exports=oY});var ZN=$((LOe,HN)=>{"use strict";var dE=process.platform==="win32";function pE(t,e){return Object.assign(new Error(`${e} ${t.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${e} ${t.command}`,path:t.command,spawnargs:t.args})}function aY(t,e){if(!dE)return;let r=t.emit;t.emit=function(n,i){if(n==="exit"){let s=qN(i,e);if(s)return r.call(t,"error",s)}return r.apply(t,arguments)}}function qN(t,e){return dE&&t===1&&!e.file?pE(e.original,"spawn"):null}function cY(t,e){return dE&&t===1&&!e.file?pE(e.original,"spawnSync"):null}HN.exports={hookChildProcess:aY,verifyENOENT:qN,verifyENOENTSync:cY,notFoundError:pE}});var WN=$((UOe,Tc)=>{"use strict";var BN=require("child_process"),fE=FN(),mE=ZN();function GN(t,e,r){let n=fE(t,e,r),i=BN.spawn(n.command,n.args,n.options);return mE.hookChildProcess(i,n),i}function uY(t,e,r){let n=fE(t,e,r),i=BN.spawnSync(n.command,n.args,n.options);return i.error=i.error||mE.verifyENOENTSync(i.status,n),i}Tc.exports=GN;Tc.exports.spawn=GN;Tc.exports.sync=uY;Tc.exports._parse=fE;Tc.exports._enoent=mE});var _s,Md,YN,hE,XN,gE,b,se=Oe(()=>{"use strict";_s=require("fs"),Md=require("path"),YN=require("os"),hE=(s=>(s[s.DEBUG=0]="DEBUG",s[s.INFO=1]="INFO",s[s.WARN=2]="WARN",s[s.ERROR=3]="ERROR",s[s.SILENT=4]="SILENT",s))(hE||{}),XN=(0,Md.join)((0,YN.homedir)(),".claude-mem"),gE=class{level=null;useColor;logFilePath=null;logFileInitialized=!1;constructor(){this.useColor=process.stdout.isTTY??!1}ensureLogFileInitialized(){if(!this.logFileInitialized){this.logFileInitialized=!0;try{let e=(0,Md.join)(XN,"logs");(0,_s.existsSync)(e)||(0,_s.mkdirSync)(e,{recursive:!0});let r=new Date().toISOString().split("T")[0];this.logFilePath=(0,Md.join)(e,`claude-mem-${r}.log`)}catch(e){console.error("[LOGGER] Failed to initialize log file:",e),this.logFilePath=null}}}getLevel(){if(this.level===null)try{let e=(0,Md.join)(XN,"settings.json");if((0,_s.existsSync)(e)){let r=(0,_s.readFileSync)(e,"utf-8"),i=(JSON.parse(r).CLAUDE_MEM_LOG_LEVEL||"INFO").toUpperCase();this.level=hE[i]??1}else this.level=1}catch{this.level=1}return this.level}correlationId(e,r){return`obs-${e}-${r}`}sessionId(e){return`session-${e}`}formatData(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return e.toString();if(typeof e=="object"){if(e instanceof Error)return this.getLevel()===0?`${e.message} ${e.stack}`:e.message;if(Array.isArray(e))return`[${e.length} items]`;let r=Object.keys(e);return r.length===0?"{}":r.length<=3?JSON.stringify(e):`{${r.length} keys: ${r.slice(0,3).join(", ")}...}`}return String(e)}formatTool(e,r){if(!r)return e;let n=r;if(typeof r=="string")try{n=JSON.parse(r)}catch{n=r}if(e==="Bash"&&n.command)return`${e}(${n.command})`;if(n.file_path)return`${e}(${n.file_path})`;if(n.notebook_path)return`${e}(${n.notebook_path})`;if(e==="Glob"&&n.pattern)return`${e}(${n.pattern})`;if(e==="Grep"&&n.pattern)return`${e}(${n.pattern})`;if(n.url)return`${e}(${n.url})`;if(n.query)return`${e}(${n.query})`;if(e==="Task"){if(n.subagent_type)return`${e}(${n.subagent_type})`;if(n.description)return`${e}(${n.description})`}return e==="Skill"&&n.skill?`${e}(${n.skill})`:e==="LSP"&&n.operation?`${e}(${n.operation})`:e}formatTimestamp(e){let r=e.getFullYear(),n=String(e.getMonth()+1).padStart(2,"0"),i=String(e.getDate()).padStart(2,"0"),s=String(e.getHours()).padStart(2,"0"),o=String(e.getMinutes()).padStart(2,"0"),a=String(e.getSeconds()).padStart(2,"0"),c=String(e.getMilliseconds()).padStart(3,"0");return`${r}-${n}-${i} ${s}:${o}:${a}.${c}`}log(e,r,n,i,s){if(e{"use strict";Er={DEFAULT:3e5,HEALTH_CHECK:3e3,POST_SPAWN_WAIT:5e3,READINESS_WAIT:3e4,PORT_IN_USE_WAIT:3e3,WORKER_STARTUP_WAIT:1e3,PRE_RESTART_SETTLE_DELAY:2e3,POWERSHELL_COMMAND:1e4,WINDOWS_MULTIPLIER:1.5},st={SUCCESS:0,FAILURE:1,BLOCKING_ERROR:2,USER_MESSAGE_ONLY:3}});var eM={};_n(eM,{SettingsDefaultsManager:()=>Ee});var Li,Wh,QN,Ee,rr=Oe(()=>{"use strict";Li=require("fs"),Wh=require("path"),QN=require("os"),Ee=class{static DEFAULTS={CLAUDE_MEM_MODEL:"claude-sonnet-4-5",CLAUDE_MEM_CONTEXT_OBSERVATIONS:"50",CLAUDE_MEM_WORKER_PORT:"37777",CLAUDE_MEM_WORKER_HOST:"127.0.0.1",CLAUDE_MEM_SKIP_TOOLS:"ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion",CLAUDE_MEM_PROVIDER:"claude",CLAUDE_MEM_CLAUDE_AUTH_METHOD:"cli",CLAUDE_MEM_GEMINI_API_KEY:"",CLAUDE_MEM_GEMINI_MODEL:"gemini-2.5-flash-lite",CLAUDE_MEM_GEMINI_RATE_LIMITING_ENABLED:"true",CLAUDE_MEM_OPENROUTER_API_KEY:"",CLAUDE_MEM_OPENROUTER_MODEL:"xiaomi/mimo-v2-flash:free",CLAUDE_MEM_OPENROUTER_SITE_URL:"",CLAUDE_MEM_OPENROUTER_APP_NAME:"claude-mem",CLAUDE_MEM_OPENROUTER_MAX_CONTEXT_MESSAGES:"20",CLAUDE_MEM_OPENROUTER_MAX_TOKENS:"100000",CLAUDE_MEM_DATA_DIR:(0,Wh.join)((0,QN.homedir)(),".claude-mem"),CLAUDE_MEM_LOG_LEVEL:"INFO",CLAUDE_MEM_PYTHON_VERSION:"3.13",CLAUDE_CODE_PATH:"",CLAUDE_MEM_MODE:"code",CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT:"true",CLAUDE_MEM_CONTEXT_FULL_COUNT:"0",CLAUDE_MEM_CONTEXT_FULL_FIELD:"narrative",CLAUDE_MEM_CONTEXT_SESSION_COUNT:"10",CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY:"true",CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE:"false",CLAUDE_MEM_CONTEXT_SHOW_TERMINAL_OUTPUT:"true",CLAUDE_MEM_FOLDER_CLAUDEMD_ENABLED:"false",CLAUDE_MEM_MAX_CONCURRENT_AGENTS:"2",CLAUDE_MEM_EXCLUDED_PROJECTS:"",CLAUDE_MEM_FOLDER_MD_EXCLUDE:"[]",CLAUDE_MEM_CHROMA_ENABLED:"true",CLAUDE_MEM_CHROMA_MODE:"local",CLAUDE_MEM_CHROMA_HOST:"127.0.0.1",CLAUDE_MEM_CHROMA_PORT:"8000",CLAUDE_MEM_CHROMA_SSL:"false",CLAUDE_MEM_CHROMA_API_KEY:"",CLAUDE_MEM_CHROMA_TENANT:"default_tenant",CLAUDE_MEM_CHROMA_DATABASE:"default_database"};static getAllDefaults(){return{...this.DEFAULTS}}static get(e){return process.env[e]??this.DEFAULTS[e]}static getInt(e){let r=this.get(e);return parseInt(r,10)}static getBool(e){let r=this.get(e);return r==="true"||r===!0}static applyEnvOverrides(e){let r={...e};for(let n of Object.keys(this.DEFAULTS))process.env[n]!==void 0&&(r[n]=process.env[n]);return r}static loadFromFile(e){try{if(!(0,Li.existsSync)(e)){let o=this.getAllDefaults();try{let a=(0,Wh.dirname)(e);(0,Li.existsSync)(a)||(0,Li.mkdirSync)(a,{recursive:!0}),(0,Li.writeFileSync)(e,JSON.stringify(o,null,2),"utf-8"),console.log("[SETTINGS] Created settings file with defaults:",e)}catch(a){console.warn("[SETTINGS] Failed to create settings file, using in-memory defaults:",e,a)}return this.applyEnvOverrides(o)}let r=(0,Li.readFileSync)(e,"utf-8"),n=JSON.parse(r),i=n;if(n.env&&typeof n.env=="object"){i=n.env;try{(0,Li.writeFileSync)(e,JSON.stringify(i,null,2),"utf-8"),console.log("[SETTINGS] Migrated settings file from nested to flat schema:",e)}catch(o){console.warn("[SETTINGS] Failed to auto-migrate settings file:",e,o)}}let s={...this.DEFAULTS};for(let o of Object.keys(this.DEFAULTS))i[o]!==void 0&&(s[o]=i[o]);return this.applyEnvOverrides(s)}catch(r){return console.warn("[SETTINGS] Failed to load settings, using defaults:",e,r),this.applyEnvOverrides(this.getAllDefaults())}}}});var cM={};_n(cM,{ARCHIVES_DIR:()=>yE,BACKUPS_DIR:()=>sM,CLAUDE_COMMANDS_DIR:()=>oM,CLAUDE_CONFIG_DIR:()=>bs,CLAUDE_MD_PATH:()=>_Y,CLAUDE_SETTINGS_PATH:()=>yY,DATA_DIR:()=>ur,DB_PATH:()=>Dd,LOGS_DIR:()=>nM,MARKETPLACE_ROOT:()=>Ss,MODES_DIR:()=>_E,OBSERVER_SESSIONS_DIR:()=>Kh,TRASH_DIR:()=>iM,USER_SETTINGS_PATH:()=>qt,VECTOR_DB_DIR:()=>vY,createBackupFilename:()=>TY,ensureAllClaudeDirs:()=>EY,ensureAllDataDirs:()=>xY,ensureDir:()=>Mr,ensureModesDir:()=>wY,getCurrentProjectName:()=>aM,getPackageCommandsDir:()=>kY,getPackageRoot:()=>dn,getProjectArchiveDir:()=>bY,getWorkerSocketPath:()=>SY});function mY(){return typeof __dirname<"u"?__dirname:(0,lt.dirname)((0,rM.fileURLToPath)($Y.url))}function gY(){if(process.env.CLAUDE_MEM_DATA_DIR)return process.env.CLAUDE_MEM_DATA_DIR;let t=(0,lt.join)((0,vE.homedir)(),".claude-mem"),e=(0,lt.join)(t,"settings.json");try{if((0,Vh.existsSync)(e)){let{readFileSync:r}=require("fs"),n=JSON.parse(r(e,"utf-8")),i=n.env??n;if(i.CLAUDE_MEM_DATA_DIR)return i.CLAUDE_MEM_DATA_DIR}}catch{}return t}function bY(t){return(0,lt.join)(yE,t)}function SY(t){return(0,lt.join)(ur,`worker-${t}.sock`)}function Mr(t){(0,Vh.mkdirSync)(t,{recursive:!0})}function xY(){Mr(ur),Mr(yE),Mr(nM),Mr(iM),Mr(sM),Mr(_E)}function wY(){Mr(_E)}function EY(){Mr(bs),Mr(oM)}function aM(){try{let t=(0,tM.execSync)("git rev-parse --show-toplevel",{cwd:process.cwd(),encoding:"utf8",stdio:["pipe","pipe","ignore"],windowsHide:!0}).trim();return(0,lt.basename)((0,lt.dirname)(t))+"/"+(0,lt.basename)(t)}catch(t){b.debug("SYSTEM","Git root detection failed, using cwd basename",{cwd:process.cwd()},t);let e=process.cwd();return(0,lt.basename)((0,lt.dirname)(e))+"/"+(0,lt.basename)(e)}}function dn(){return(0,lt.join)(hY,"..")}function kY(){let t=dn();return(0,lt.join)(t,"commands")}function TY(t){let e=new Date().toISOString().replace(/[:.]/g,"-").replace("T","_").slice(0,19);return`${t}.backup.${e}`}var lt,vE,Vh,tM,rM,$Y,hY,ur,bs,Ss,yE,nM,iM,sM,_E,qt,Dd,vY,Kh,yY,oM,_Y,jt=Oe(()=>{"use strict";lt=require("path"),vE=require("os"),Vh=require("fs"),tM=require("child_process"),rM=require("url");ne();$Y={};hY=mY();ur=gY(),bs=process.env.CLAUDE_CONFIG_DIR||(0,lt.join)((0,vE.homedir)(),".claude"),Ss=(0,lt.join)(bs,"plugins","marketplaces","thedotmack"),yE=(0,lt.join)(ur,"archives"),nM=(0,lt.join)(ur,"logs"),iM=(0,lt.join)(ur,"trash"),sM=(0,lt.join)(ur,"backups"),_E=(0,lt.join)(ur,"modes"),qt=(0,lt.join)(ur,"settings.json"),Dd=(0,lt.join)(ur,"claude-mem.db"),vY=(0,lt.join)(ur,"vector-db"),Kh=(0,lt.join)(ur,"observer-sessions"),yY=(0,lt.join)(bs,"settings.json"),oM=(0,lt.join)(bs,"commands"),_Y=(0,lt.join)(bs,"CLAUDE.md")});function IY(t,e={},r){return new Promise((n,i)=>{let s=setTimeout(()=>i(new Error(`Request timed out after ${r}ms`)),r);fetch(t,e).then(o=>{clearTimeout(s),n(o)},o=>{clearTimeout(s),i(o)})})}function Jr(){if(jd!==null)return jd;let t=Jh.default.join(Ee.get("CLAUDE_MEM_DATA_DIR"),"settings.json"),e=Ee.loadFromFile(t);return jd=parseInt(e.CLAUDE_MEM_WORKER_PORT,10),jd}function SE(){if(zd!==null)return zd;let t=Jh.default.join(Ee.get("CLAUDE_MEM_DATA_DIR"),"settings.json");return zd=Ee.loadFromFile(t).CLAUDE_MEM_WORKER_HOST,zd}function lM(){jd=null,zd=null}function RY(t){return`http://${SE()}:${Jr()}${t}`}function ft(t,e={}){let r=e.method??"GET",n=e.timeoutMs??bE,i=RY(t),s={method:r};return e.headers&&(s.headers=e.headers),e.body&&(s.body=e.body),n>0?IY(i,s,n):fetch(i,s)}async function OY(){return(await ft("/api/health",{timeoutMs:bE})).ok}function CY(){try{let t=Jh.default.join(Ss,"package.json");return JSON.parse((0,uM.readFileSync)(t,"utf-8")).version}catch(t){let e=t.code;if(e==="ENOENT"||e==="EBUSY")return b.debug("SYSTEM","Could not read plugin version (shutdown race)",{code:e}),"unknown";throw t}}async function PY(){let t=await ft("/api/version",{timeoutMs:bE});if(!t.ok)throw new Error(`Failed to get worker version: ${t.status}`);return(await t.json()).version}async function AY(){try{let t=CY();if(t==="unknown")return;let e=await PY();if(e==="unknown")return;t!==e&&b.debug("SYSTEM","Version check",{pluginVersion:t,workerVersion:e,note:"Mismatch will be auto-restarted by worker-service start command"})}catch(t){b.debug("SYSTEM","Version check failed",{error:t instanceof Error?t.message:String(t)})}}async function kr(){try{if(await OY())return await AY(),!0}catch(t){b.debug("SYSTEM","Worker health check failed",{error:t instanceof Error?t.message:String(t)})}return b.warn("SYSTEM","Worker not healthy, hook will proceed gracefully"),!1}var Jh,uM,bE,jd,zd,Dr=Oe(()=>{"use strict";Jh=Me(require("path"),1),uM=require("fs");ne();Tn();rr();jt();bE=(()=>{let t=process.env.CLAUDE_MEM_HEALTH_TIMEOUT_MS;if(t){let e=parseInt(t,10);if(Number.isFinite(e)&&e>=500&&e<=3e5)return e;b.warn("SYSTEM","Invalid CLAUDE_MEM_HEALTH_TIMEOUT_MS, using default",{value:t,min:500,max:3e5})}return Gh(Er.HEALTH_CHECK)})();jd=null,zd=null});function tg(t,e,r){return(0,OM.createHash)("sha256").update((t||"")+(e||"")+(r||"")).digest("hex").slice(0,16)}function rg(t,e,r){let n=r-QY;return t.prepare("SELECT id, created_at_epoch FROM observations WHERE content_hash = ? AND created_at_epoch > ?").get(e,n)}var OM,QY,CM=Oe(()=>{"use strict";OM=require("crypto");ne();jt();QY=3e4});var PM,Es,ng=Oe(()=>{"use strict";PM=require("bun:sqlite");jt();ne();CM();Es=class{db;constructor(e=Dd){e!==":memory:"&&Mr(ur),this.db=new PM.Database(e),this.db.run("PRAGMA journal_mode = WAL"),this.db.run("PRAGMA synchronous = NORMAL"),this.db.run("PRAGMA foreign_keys = ON"),this.initializeSchema(),this.ensureWorkerPortColumn(),this.ensurePromptTrackingColumns(),this.removeSessionSummariesUniqueConstraint(),this.addObservationHierarchicalFields(),this.makeObservationsTextNullable(),this.createUserPromptsTable(),this.ensureDiscoveryTokensColumn(),this.createPendingMessagesTable(),this.renameSessionIdColumns(),this.repairSessionIdColumnRename(),this.addFailedAtEpochColumn(),this.addOnUpdateCascadeToForeignKeys(),this.addObservationContentHashColumn(),this.addSessionCustomTitleColumn()}initializeSchema(){this.db.run(` +`)[2]||"").match(/at\s+(?:.*\s+)?\(?([^:]+):(\d+):(\d+)\)?/),l=u?`${u[1].split("/").pop()}:${u[2]}`:"unknown",d={...n,location:l};return this.warn(e,`[HAPPY-PATH] ${r}`,d,i),s}},b=new gE});function Gh(t){return process.platform==="win32"?Math.round(t*Er.WINDOWS_MULTIPLIER):t}var Er,st,Tn=Oe(()=>{"use strict";Er={DEFAULT:3e5,HEALTH_CHECK:3e3,POST_SPAWN_WAIT:5e3,READINESS_WAIT:3e4,PORT_IN_USE_WAIT:3e3,WORKER_STARTUP_WAIT:1e3,PRE_RESTART_SETTLE_DELAY:2e3,POWERSHELL_COMMAND:1e4,WINDOWS_MULTIPLIER:1.5},st={SUCCESS:0,FAILURE:1,BLOCKING_ERROR:2,USER_MESSAGE_ONLY:3}});var eM={};_n(eM,{SettingsDefaultsManager:()=>Ee});var Li,Wh,QN,Ee,rr=Oe(()=>{"use strict";Li=require("fs"),Wh=require("path"),QN=require("os"),Ee=class{static DEFAULTS={CLAUDE_MEM_MODEL:"claude-sonnet-4-5",CLAUDE_MEM_CONTEXT_OBSERVATIONS:"50",CLAUDE_MEM_WORKER_PORT:"37777",CLAUDE_MEM_WORKER_HOST:"127.0.0.1",CLAUDE_MEM_SKIP_TOOLS:"ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion",CLAUDE_MEM_PROVIDER:"claude",CLAUDE_MEM_CLAUDE_AUTH_METHOD:"cli",CLAUDE_MEM_GEMINI_API_KEY:"",CLAUDE_MEM_GEMINI_MODEL:"gemini-2.5-flash-lite",CLAUDE_MEM_GEMINI_RATE_LIMITING_ENABLED:"true",CLAUDE_MEM_OPENROUTER_API_KEY:"",CLAUDE_MEM_OPENROUTER_MODEL:"xiaomi/mimo-v2-flash:free",CLAUDE_MEM_OPENROUTER_SITE_URL:"",CLAUDE_MEM_OPENROUTER_APP_NAME:"claude-mem",CLAUDE_MEM_OPENROUTER_MAX_CONTEXT_MESSAGES:"20",CLAUDE_MEM_OPENROUTER_MAX_TOKENS:"100000",CLAUDE_MEM_DATA_DIR:(0,Wh.join)((0,QN.homedir)(),".claude-mem"),CLAUDE_MEM_LOG_LEVEL:"INFO",CLAUDE_MEM_PYTHON_VERSION:"3.13",CLAUDE_CODE_PATH:"",CLAUDE_MEM_MODE:"code",CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT:"true",CLAUDE_MEM_CONTEXT_FULL_COUNT:"0",CLAUDE_MEM_CONTEXT_FULL_FIELD:"narrative",CLAUDE_MEM_CONTEXT_SESSION_COUNT:"10",CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY:"true",CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE:"false",CLAUDE_MEM_CONTEXT_SHOW_TERMINAL_OUTPUT:"true",CLAUDE_MEM_FOLDER_CLAUDEMD_ENABLED:"false",CLAUDE_MEM_MAX_CONCURRENT_AGENTS:"2",CLAUDE_MEM_EXCLUDED_PROJECTS:"",CLAUDE_MEM_FOLDER_MD_EXCLUDE:"[]",CLAUDE_MEM_CHROMA_ENABLED:"true",CLAUDE_MEM_CHROMA_MODE:"local",CLAUDE_MEM_CHROMA_HOST:"127.0.0.1",CLAUDE_MEM_CHROMA_PORT:"8000",CLAUDE_MEM_CHROMA_SSL:"false",CLAUDE_MEM_CHROMA_API_KEY:"",CLAUDE_MEM_CHROMA_TENANT:"default_tenant",CLAUDE_MEM_CHROMA_DATABASE:"default_database"};static getAllDefaults(){return{...this.DEFAULTS}}static get(e){return process.env[e]??this.DEFAULTS[e]}static getInt(e){let r=this.get(e);return parseInt(r,10)}static getBool(e){let r=this.get(e);return r==="true"||r===!0}static applyEnvOverrides(e){let r={...e};for(let n of Object.keys(this.DEFAULTS))process.env[n]!==void 0&&(r[n]=process.env[n]);return r}static loadFromFile(e){try{if(!(0,Li.existsSync)(e)){let o=this.getAllDefaults();try{let a=(0,Wh.dirname)(e);(0,Li.existsSync)(a)||(0,Li.mkdirSync)(a,{recursive:!0}),(0,Li.writeFileSync)(e,JSON.stringify(o,null,2),"utf-8"),console.log("[SETTINGS] Created settings file with defaults:",e)}catch(a){console.warn("[SETTINGS] Failed to create settings file, using in-memory defaults:",e,a)}return this.applyEnvOverrides(o)}let r=(0,Li.readFileSync)(e,"utf-8"),n=JSON.parse(r),i=n;if(n.env&&typeof n.env=="object"){i=n.env;try{(0,Li.writeFileSync)(e,JSON.stringify(i,null,2),"utf-8"),console.log("[SETTINGS] Migrated settings file from nested to flat schema:",e)}catch(o){console.warn("[SETTINGS] Failed to auto-migrate settings file:",e,o)}}let s={...this.DEFAULTS};for(let o of Object.keys(this.DEFAULTS))i[o]!==void 0&&(s[o]=i[o]);return this.applyEnvOverrides(s)}catch(r){return console.warn("[SETTINGS] Failed to load settings, using defaults:",e,r),this.applyEnvOverrides(this.getAllDefaults())}}}});var cM={};_n(cM,{ARCHIVES_DIR:()=>yE,BACKUPS_DIR:()=>sM,CLAUDE_COMMANDS_DIR:()=>oM,CLAUDE_CONFIG_DIR:()=>bs,CLAUDE_MD_PATH:()=>_Y,CLAUDE_SETTINGS_PATH:()=>yY,DATA_DIR:()=>ur,DB_PATH:()=>Dd,LOGS_DIR:()=>nM,MARKETPLACE_ROOT:()=>Ss,MODES_DIR:()=>_E,OBSERVER_SESSIONS_DIR:()=>Kh,TRASH_DIR:()=>iM,USER_SETTINGS_PATH:()=>qt,VECTOR_DB_DIR:()=>vY,createBackupFilename:()=>TY,ensureAllClaudeDirs:()=>EY,ensureAllDataDirs:()=>xY,ensureDir:()=>Mr,ensureModesDir:()=>wY,getCurrentProjectName:()=>aM,getPackageCommandsDir:()=>kY,getPackageRoot:()=>dn,getProjectArchiveDir:()=>bY,getWorkerSocketPath:()=>SY});function mY(){return typeof __dirname<"u"?__dirname:(0,lt.dirname)((0,rM.fileURLToPath)($Y.url))}function gY(){if(process.env.CLAUDE_MEM_DATA_DIR)return process.env.CLAUDE_MEM_DATA_DIR;let t=(0,lt.join)((0,vE.homedir)(),".claude-mem"),e=(0,lt.join)(t,"settings.json");try{if((0,Vh.existsSync)(e)){let{readFileSync:r}=require("fs"),n=JSON.parse(r(e,"utf-8")),i=n.env??n;if(i.CLAUDE_MEM_DATA_DIR)return i.CLAUDE_MEM_DATA_DIR}}catch{}return t}function bY(t){return(0,lt.join)(yE,t)}function SY(t){return(0,lt.join)(ur,`worker-${t}.sock`)}function Mr(t){(0,Vh.mkdirSync)(t,{recursive:!0})}function xY(){Mr(ur),Mr(yE),Mr(nM),Mr(iM),Mr(sM),Mr(_E)}function wY(){Mr(_E)}function EY(){Mr(bs),Mr(oM)}function aM(){try{let t=(0,tM.execSync)("git rev-parse --show-toplevel",{cwd:process.cwd(),encoding:"utf8",stdio:["pipe","pipe","ignore"],windowsHide:!0}).trim();return(0,lt.basename)((0,lt.dirname)(t))+"/"+(0,lt.basename)(t)}catch(t){b.debug("SYSTEM","Git root detection failed, using cwd basename",{cwd:process.cwd()},t);let e=process.cwd();return(0,lt.basename)((0,lt.dirname)(e))+"/"+(0,lt.basename)(e)}}function dn(){return(0,lt.join)(hY,"..")}function kY(){let t=dn();return(0,lt.join)(t,"commands")}function TY(t){let e=new Date().toISOString().replace(/[:.]/g,"-").replace("T","_").slice(0,19);return`${t}.backup.${e}`}var lt,vE,Vh,tM,rM,$Y,hY,ur,bs,Ss,yE,nM,iM,sM,_E,qt,Dd,vY,Kh,yY,oM,_Y,jt=Oe(()=>{"use strict";lt=require("path"),vE=require("os"),Vh=require("fs"),tM=require("child_process"),rM=require("url");se();$Y={};hY=mY();ur=gY(),bs=process.env.CLAUDE_CONFIG_DIR||(0,lt.join)((0,vE.homedir)(),".claude"),Ss=(0,lt.join)(bs,"plugins","marketplaces","thedotmack"),yE=(0,lt.join)(ur,"archives"),nM=(0,lt.join)(ur,"logs"),iM=(0,lt.join)(ur,"trash"),sM=(0,lt.join)(ur,"backups"),_E=(0,lt.join)(ur,"modes"),qt=(0,lt.join)(ur,"settings.json"),Dd=(0,lt.join)(ur,"claude-mem.db"),vY=(0,lt.join)(ur,"vector-db"),Kh=(0,lt.join)(ur,"observer-sessions"),yY=(0,lt.join)(bs,"settings.json"),oM=(0,lt.join)(bs,"commands"),_Y=(0,lt.join)(bs,"CLAUDE.md")});function IY(t,e={},r){return new Promise((n,i)=>{let s=setTimeout(()=>i(new Error(`Request timed out after ${r}ms`)),r);fetch(t,e).then(o=>{clearTimeout(s),n(o)},o=>{clearTimeout(s),i(o)})})}function Jr(){if(jd!==null)return jd;let t=Jh.default.join(Ee.get("CLAUDE_MEM_DATA_DIR"),"settings.json"),e=Ee.loadFromFile(t);return jd=parseInt(e.CLAUDE_MEM_WORKER_PORT,10),jd}function SE(){if(zd!==null)return zd;let t=Jh.default.join(Ee.get("CLAUDE_MEM_DATA_DIR"),"settings.json");return zd=Ee.loadFromFile(t).CLAUDE_MEM_WORKER_HOST,zd}function lM(){jd=null,zd=null}function RY(t){return`http://${SE()}:${Jr()}${t}`}function ft(t,e={}){let r=e.method??"GET",n=e.timeoutMs??bE,i=RY(t),s={method:r};return e.headers&&(s.headers=e.headers),e.body&&(s.body=e.body),n>0?IY(i,s,n):fetch(i,s)}async function OY(){return(await ft("/api/health",{timeoutMs:bE})).ok}function CY(){try{let t=Jh.default.join(Ss,"package.json");return JSON.parse((0,uM.readFileSync)(t,"utf-8")).version}catch(t){let e=t.code;if(e==="ENOENT"||e==="EBUSY")return b.debug("SYSTEM","Could not read plugin version (shutdown race)",{code:e}),"unknown";throw t}}async function PY(){let t=await ft("/api/version",{timeoutMs:bE});if(!t.ok)throw new Error(`Failed to get worker version: ${t.status}`);return(await t.json()).version}async function AY(){try{let t=CY();if(t==="unknown")return;let e=await PY();if(e==="unknown")return;t!==e&&b.debug("SYSTEM","Version check",{pluginVersion:t,workerVersion:e,note:"Mismatch will be auto-restarted by worker-service start command"})}catch(t){b.debug("SYSTEM","Version check failed",{error:t instanceof Error?t.message:String(t)})}}async function kr(){try{if(await OY())return await AY(),!0}catch(t){b.debug("SYSTEM","Worker health check failed",{error:t instanceof Error?t.message:String(t)})}return b.warn("SYSTEM","Worker not healthy, hook will proceed gracefully"),!1}var Jh,uM,bE,jd,zd,Dr=Oe(()=>{"use strict";Jh=Me(require("path"),1),uM=require("fs");se();Tn();rr();jt();bE=(()=>{let t=process.env.CLAUDE_MEM_HEALTH_TIMEOUT_MS;if(t){let e=parseInt(t,10);if(Number.isFinite(e)&&e>=500&&e<=3e5)return e;b.warn("SYSTEM","Invalid CLAUDE_MEM_HEALTH_TIMEOUT_MS, using default",{value:t,min:500,max:3e5})}return Gh(Er.HEALTH_CHECK)})();jd=null,zd=null});function tg(t,e,r){return(0,OM.createHash)("sha256").update((t||"")+(e||"")+(r||"")).digest("hex").slice(0,16)}function rg(t,e,r){let n=r-QY;return t.prepare("SELECT id, created_at_epoch FROM observations WHERE content_hash = ? AND created_at_epoch > ?").get(e,n)}var OM,QY,CM=Oe(()=>{"use strict";OM=require("crypto");se();jt();QY=3e4});var PM,Es,ng=Oe(()=>{"use strict";PM=require("bun:sqlite");jt();se();CM();Es=class{db;constructor(e=Dd){e!==":memory:"&&Mr(ur),this.db=new PM.Database(e),this.db.run("PRAGMA journal_mode = WAL"),this.db.run("PRAGMA synchronous = NORMAL"),this.db.run("PRAGMA foreign_keys = ON"),this.initializeSchema(),this.ensureWorkerPortColumn(),this.ensurePromptTrackingColumns(),this.removeSessionSummariesUniqueConstraint(),this.addObservationHierarchicalFields(),this.makeObservationsTextNullable(),this.createUserPromptsTable(),this.ensureDiscoveryTokensColumn(),this.createPendingMessagesTable(),this.renameSessionIdColumns(),this.repairSessionIdColumnRename(),this.addFailedAtEpochColumn(),this.addOnUpdateCascadeToForeignKeys(),this.addObservationContentHashColumn(),this.addSessionCustomTitleColumn()}initializeSchema(){this.db.run(` CREATE TABLE IF NOT EXISTS schema_versions ( id INTEGER PRIMARY KEY, version INTEGER UNIQUE NOT NULL, @@ -660,7 +660,7 @@ Please see the 3.x to 4.x migration guide for details on how to update your app.
`+e+`
-`}function Xce(){return function(){this.error(404)}}function Yce(){return function(e){if(this.hasTrailingSlash()){this.error(404);return}var r=HT.original(this.req);r.path=null,r.pathname=Kce(r.pathname+"/");var n=Zce(Wce.format(r)),i=Jce("Redirecting","Redirecting to "+Bce(n));e.statusCode=301,e.setHeader("Content-Type","text/html; charset=UTF-8"),e.setHeader("Content-Length",Buffer.byteLength(i)),e.setHeader("Content-Security-Policy","default-src 'none'"),e.setHeader("X-Content-Type-Options","nosniff"),e.setHeader("Location",n),e.end(i)}}});var V2=$((hn,W2)=>{"use strict";var mv=yL(),Qce=require("events").EventEmitter,H2=bL(),Z2=YU(),eue=fT(),tue=hT(),B2=E2(),G2=U2();hn=W2.exports=rue;function rue(){var t=function(e,r,n){t.handle(e,r,n)};return H2(t,Qce.prototype,!1),H2(t,Z2,!1),t.request=Object.create(B2,{app:{configurable:!0,enumerable:!0,writable:!0,value:t}}),t.response=Object.create(G2,{app:{configurable:!0,enumerable:!0,writable:!0,value:t}}),t.init(),t}hn.application=Z2;hn.request=B2;hn.response=G2;hn.Route=eue;hn.Router=tue;hn.json=mv.json;hn.query=gT();hn.raw=mv.raw;hn.static=q2();hn.text=mv.text;hn.urlencoded=mv.urlencoded;var nue=["bodyParser","compress","cookieSession","session","logger","cookieParser","favicon","responseTime","errorHandler","timeout","methodOverride","vhost","csrf","directory","limit","multipart","staticCache"];nue.forEach(function(t){Object.defineProperty(hn,t,{get:function(){throw new Error("Most middleware (like "+t+") is no longer bundled with Express and must be installed separately. Please see https://github.com/senchalabs/connect#middleware.")},configurable:!0})})});var hv=$((_Ne,K2)=>{"use strict";K2.exports=V2()});var e6=$((SNe,Q2)=>{"use strict";var Y2=Object.getOwnPropertySymbols,iue=Object.prototype.hasOwnProperty,sue=Object.prototype.propertyIsEnumerable;function oue(t){if(t==null)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(t)}function aue(){try{if(!Object.assign)return!1;var t=new String("abc");if(t[5]="de",Object.getOwnPropertyNames(t)[0]==="5")return!1;for(var e={},r=0;r<10;r++)e["_"+String.fromCharCode(r)]=r;var n=Object.getOwnPropertyNames(e).map(function(s){return e[s]});if(n.join("")!=="0123456789")return!1;var i={};return"abcdefghijklmnopqrst".split("").forEach(function(s){i[s]=s}),Object.keys(Object.assign({},i)).join("")==="abcdefghijklmnopqrst"}catch{return!1}}Q2.exports=aue()?Object.assign:function(t,e){for(var r,n=oue(t),i,s=1;s{(function(){"use strict";var t=e6(),e=FT(),r={origin:"*",methods:"GET,HEAD,PUT,PATCH,POST,DELETE",preflightContinue:!1,optionsSuccessStatus:204};function n(m){return typeof m=="string"||m instanceof String}function i(m,h){if(Array.isArray(h)){for(var g=0;g{"use strict"});var ou={};_n(ou,{PendingMessageStore:()=>$p});var xue,$p,ha=Oe(()=>{"use strict";ne();xue=6e4,$p=class{db;maxRetries;constructor(e,r=3){this.db=e,this.maxRetries=r}enqueue(e,r,n){let i=Date.now();return this.db.prepare(` +`}function Xce(){return function(){this.error(404)}}function Yce(){return function(e){if(this.hasTrailingSlash()){this.error(404);return}var r=HT.original(this.req);r.path=null,r.pathname=Kce(r.pathname+"/");var n=Zce(Wce.format(r)),i=Jce("Redirecting","Redirecting to "+Bce(n));e.statusCode=301,e.setHeader("Content-Type","text/html; charset=UTF-8"),e.setHeader("Content-Length",Buffer.byteLength(i)),e.setHeader("Content-Security-Policy","default-src 'none'"),e.setHeader("X-Content-Type-Options","nosniff"),e.setHeader("Location",n),e.end(i)}}});var V2=$((hn,W2)=>{"use strict";var mv=yL(),Qce=require("events").EventEmitter,H2=bL(),Z2=YU(),eue=fT(),tue=hT(),B2=E2(),G2=U2();hn=W2.exports=rue;function rue(){var t=function(e,r,n){t.handle(e,r,n)};return H2(t,Qce.prototype,!1),H2(t,Z2,!1),t.request=Object.create(B2,{app:{configurable:!0,enumerable:!0,writable:!0,value:t}}),t.response=Object.create(G2,{app:{configurable:!0,enumerable:!0,writable:!0,value:t}}),t.init(),t}hn.application=Z2;hn.request=B2;hn.response=G2;hn.Route=eue;hn.Router=tue;hn.json=mv.json;hn.query=gT();hn.raw=mv.raw;hn.static=q2();hn.text=mv.text;hn.urlencoded=mv.urlencoded;var nue=["bodyParser","compress","cookieSession","session","logger","cookieParser","favicon","responseTime","errorHandler","timeout","methodOverride","vhost","csrf","directory","limit","multipart","staticCache"];nue.forEach(function(t){Object.defineProperty(hn,t,{get:function(){throw new Error("Most middleware (like "+t+") is no longer bundled with Express and must be installed separately. Please see https://github.com/senchalabs/connect#middleware.")},configurable:!0})})});var hv=$((_Ne,K2)=>{"use strict";K2.exports=V2()});var e6=$((SNe,Q2)=>{"use strict";var Y2=Object.getOwnPropertySymbols,iue=Object.prototype.hasOwnProperty,sue=Object.prototype.propertyIsEnumerable;function oue(t){if(t==null)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(t)}function aue(){try{if(!Object.assign)return!1;var t=new String("abc");if(t[5]="de",Object.getOwnPropertyNames(t)[0]==="5")return!1;for(var e={},r=0;r<10;r++)e["_"+String.fromCharCode(r)]=r;var n=Object.getOwnPropertyNames(e).map(function(s){return e[s]});if(n.join("")!=="0123456789")return!1;var i={};return"abcdefghijklmnopqrst".split("").forEach(function(s){i[s]=s}),Object.keys(Object.assign({},i)).join("")==="abcdefghijklmnopqrst"}catch{return!1}}Q2.exports=aue()?Object.assign:function(t,e){for(var r,n=oue(t),i,s=1;s{(function(){"use strict";var t=e6(),e=FT(),r={origin:"*",methods:"GET,HEAD,PUT,PATCH,POST,DELETE",preflightContinue:!1,optionsSuccessStatus:204};function n(m){return typeof m=="string"||m instanceof String}function i(m,h){if(Array.isArray(h)){for(var g=0;g{"use strict"});var ou={};_n(ou,{PendingMessageStore:()=>$p});var xue,$p,ha=Oe(()=>{"use strict";se();xue=6e4,$p=class{db;maxRetries;constructor(e,r=3){this.db=e,this.maxRetries=r}enqueue(e,r,n){let i=Date.now();return this.db.prepare(` INSERT INTO pending_messages ( session_db_id, content_session_id, message_type, tool_name, tool_input, tool_response, cwd, @@ -768,7 +768,7 @@ Please see the 3.x to 4.x migration guide for details on how to update your app. `).run().changes}clearAll(){return this.db.prepare(` DELETE FROM pending_messages WHERE status IN ('pending', 'processing', 'failed') - `).run().changes}toPendingMessage(e){return{type:e.message_type,tool_name:e.tool_name||void 0,tool_input:e.tool_input?JSON.parse(e.tool_input):void 0,tool_response:e.tool_response?JSON.parse(e.tool_response):void 0,prompt_number:e.prompt_number||void 0,cwd:e.cwd||void 0,last_assistant_message:e.last_assistant_message||void 0}}}});var A6={};_n(A6,{ModeManager:()=>He});var Op,Tv,He,Qr=Oe(()=>{"use strict";Op=require("fs"),Tv=require("path");ne();jt();He=class t{static instance=null;activeMode=null;modesDir;constructor(){let e=dn(),r=[(0,Tv.join)(e,"modes"),(0,Tv.join)(e,"..","plugin","modes")],n=r.find(i=>(0,Op.existsSync)(i));this.modesDir=n||r[0]}static getInstance(){return t.instance||(t.instance=new t),t.instance}parseInheritance(e){let r=e.split("--");if(r.length===1)return{hasParent:!1,parentId:"",overrideId:""};if(r.length>2)throw new Error(`Invalid mode inheritance: ${e}. Only one level of inheritance supported (parent--override)`);return{hasParent:!0,parentId:r[0],overrideId:e}}isPlainObject(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}deepMerge(e,r){let n={...e};for(let i in r){let s=r[i],o=e[i];this.isPlainObject(s)&&this.isPlainObject(o)?n[i]=this.deepMerge(o,s):n[i]=s}return n}loadModeFile(e){let r=(0,Tv.join)(this.modesDir,`${e}.json`);if(!(0,Op.existsSync)(r))throw new Error(`Mode file not found: ${r}`);let n=(0,Op.readFileSync)(r,"utf-8");return JSON.parse(n)}loadMode(e){let r=this.parseInheritance(e);if(!r.hasParent)try{let c=this.loadModeFile(e);return this.activeMode=c,b.debug("SYSTEM",`Loaded mode: ${c.name} (${e})`,void 0,{types:c.observation_types.map(u=>u.id),concepts:c.observation_concepts.map(u=>u.id)}),c}catch{if(b.warn("SYSTEM",`Mode file not found: ${e}, falling back to 'code'`),e==="code")throw new Error("Critical: code.json mode file missing");return this.loadMode("code")}let{parentId:n,overrideId:i}=r,s;try{s=this.loadMode(n)}catch{b.warn("SYSTEM",`Parent mode '${n}' not found for ${e}, falling back to 'code'`),s=this.loadMode("code")}let o;try{o=this.loadModeFile(i),b.debug("SYSTEM",`Loaded override file: ${i} for parent ${n}`)}catch{return b.warn("SYSTEM",`Override file '${i}' not found, using parent mode '${n}' only`),this.activeMode=s,s}if(!o)return b.warn("SYSTEM",`Invalid override file: ${i}, using parent mode '${n}' only`),this.activeMode=s,s;let a=this.deepMerge(s,o);return this.activeMode=a,b.debug("SYSTEM",`Loaded mode with inheritance: ${a.name} (${e} = ${n} + ${i})`,void 0,{parent:n,override:i,types:a.observation_types.map(c=>c.id),concepts:a.observation_concepts.map(c=>c.id)}),a}getActiveMode(){if(!this.activeMode)throw new Error("No mode loaded. Call loadMode() first.");return this.activeMode}getObservationTypes(){return this.getActiveMode().observation_types}getObservationConcepts(){return this.getActiveMode().observation_concepts}getTypeIcon(e){return this.getObservationTypes().find(n=>n.id===e)?.emoji||"\u{1F4DD}"}getWorkEmoji(e){return this.getObservationTypes().find(n=>n.id===e)?.work_emoji||"\u{1F4DD}"}validateType(e){return this.getObservationTypes().some(r=>r.id===e)}getTypeLabel(e){return this.getObservationTypes().find(n=>n.id===e)?.label||e}}});function Iv(t){if(!t)return[];try{let e=JSON.parse(t);return Array.isArray(e)?e:[]}catch(e){return b.debug("PARSER","Failed to parse JSON array, using empty fallback",{preview:t?.substring(0,50)},e),[]}}function Rn(t){return new Date(t).toLocaleString("en-US",{month:"short",day:"numeric",hour:"numeric",minute:"2-digit",hour12:!0})}function pr(t){return new Date(t).toLocaleString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0})}function Rs(t){return new Date(t).toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric"})}function D6(t,e){return r$.default.isAbsolute(t)?r$.default.relative(e,t):t}function vi(t,e,r){let n=Iv(t);if(n.length>0)return D6(n[0],e);if(r){let i=Iv(r);if(i.length>0)return D6(i[0],e)}return"General"}function du(t){return t?Math.ceil(t.length/4):0}function Os(t,e){let r=new Map;for(let i of t){let s=e(i),o=Rs(s);r.has(o)||r.set(o,[]),r.get(o).push(i)}let n=Array.from(r.entries()).sort((i,s)=>{let o=new Date(i[0]).getTime(),a=new Date(s[0]).getTime();return o-a});return new Map(n)}var r$,ga=Oe(()=>{"use strict";r$=Me(require("path"),1);ne()});function S9(t){let e=by.default.join(t,".git"),r;try{r=(0,Sy.statSync)(e)}catch{return uf}if(!r.isFile())return uf;let n;try{n=(0,Sy.readFileSync)(e,"utf-8").trim()}catch{return uf}let i=n.match(/^gitdir:\s*(.+)$/);if(!i)return uf;let o=i[1].match(/^(.+)[/\\]\.git[/\\]worktrees[/\\]([^/\\]+)$/);if(!o)return uf;let a=o[1],c=by.default.basename(t),u=by.default.basename(a);return{isWorktree:!0,worktreeName:c,parentRepoPath:a,parentProjectName:u}}var Sy,by,uf,x9=Oe(()=>{"use strict";Sy=require("fs"),by=Me(require("path"),1),uf={isWorktree:!1,worktreeName:null,parentRepoPath:null,parentProjectName:null}});function Ta(t){if(!t||t.trim()==="")return b.warn("PROJECT_NAME","Empty cwd provided, using fallback",{cwd:t}),"unknown-project";let e=w9.default.basename(t);if(e===""){if(process.platform==="win32"){let n=t.match(/^([A-Z]):\\/i);if(n){let s=`drive-${n[1].toUpperCase()}`;return b.info("PROJECT_NAME","Drive root detected",{cwd:t,projectName:s}),s}}return b.warn("PROJECT_NAME","Root directory detected, using fallback",{cwd:t}),"unknown-project"}return e}function xy(t){let e=Ta(t);if(!t)return{primary:e,parent:null,isWorktree:!1,allProjects:[e]};let r=S9(t);return r.isWorktree&&r.parentProjectName?{primary:e,parent:r.parentProjectName,isWorktree:!0,allProjects:[r.parentProjectName,e]}:{primary:e,parent:null,isWorktree:!1,allProjects:[e]}}var w9,lf=Oe(()=>{"use strict";w9=Me(require("path"),1);ne();x9()});function eI(){let t=E9.default.join((0,k9.homedir)(),".claude-mem","settings.json"),e=Ee.loadFromFile(t),r=He.getInstance().getActiveMode(),n=new Set(r.observation_types.map(s=>s.id)),i=new Set(r.observation_concepts.map(s=>s.id));return{totalObservationCount:parseInt(e.CLAUDE_MEM_CONTEXT_OBSERVATIONS,10),fullObservationCount:parseInt(e.CLAUDE_MEM_CONTEXT_FULL_COUNT,10),sessionCount:parseInt(e.CLAUDE_MEM_CONTEXT_SESSION_COUNT,10),showReadTokens:e.CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS==="true",showWorkTokens:e.CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS==="true",showSavingsAmount:e.CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT==="true",showSavingsPercent:e.CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT==="true",observationTypes:n,observationConcepts:i,fullObservationField:e.CLAUDE_MEM_CONTEXT_FULL_FIELD,showLastSummary:e.CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY==="true",showLastMessage:e.CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE==="true"}}var E9,k9,tI=Oe(()=>{"use strict";E9=Me(require("path"),1),k9=require("os");rr();Qr()});var Y,T9,rI,df=Oe(()=>{"use strict";Y={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",cyan:"\x1B[36m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",gray:"\x1B[90m",red:"\x1B[31m"},T9=4,rI=1});function nI(t){let e=(t.title?.length||0)+(t.subtitle?.length||0)+(t.narrative?.length||0)+JSON.stringify(t.facts||[]).length;return Math.ceil(e/T9)}function iI(t){let e=t.length,r=t.reduce((o,a)=>o+nI(a),0),n=t.reduce((o,a)=>o+(a.discovery_tokens||0),0),i=n-r,s=n>0?Math.round(i/n*100):0;return{totalObservations:e,totalReadTokens:r,totalDiscoveryTokens:n,savings:i,savingsPercent:s}}function __e(t){return He.getInstance().getWorkEmoji(t)}function pf(t,e){let r=nI(t),n=t.discovery_tokens||0,i=__e(t.type),s=n>0?`${i} ${n.toLocaleString()}`:"-";return{readTokens:r,discoveryTokens:n,discoveryDisplay:s,workEmoji:i}}function wy(t){return t.showReadTokens||t.showWorkTokens||t.showSavingsAmount||t.showSavingsPercent}var $a=Oe(()=>{"use strict";df();Qr()});function sI(t,e,r){let n=Array.from(r.observationTypes),i=n.map(()=>"?").join(","),s=Array.from(r.observationConcepts),o=s.map(()=>"?").join(",");return t.db.prepare(` + `).run().changes}toPendingMessage(e){return{type:e.message_type,tool_name:e.tool_name||void 0,tool_input:e.tool_input?JSON.parse(e.tool_input):void 0,tool_response:e.tool_response?JSON.parse(e.tool_response):void 0,prompt_number:e.prompt_number||void 0,cwd:e.cwd||void 0,last_assistant_message:e.last_assistant_message||void 0}}}});var A6={};_n(A6,{ModeManager:()=>He});var Op,Tv,He,Qr=Oe(()=>{"use strict";Op=require("fs"),Tv=require("path");se();jt();He=class t{static instance=null;activeMode=null;modesDir;constructor(){let e=dn(),r=[(0,Tv.join)(e,"modes"),(0,Tv.join)(e,"..","plugin","modes")],n=r.find(i=>(0,Op.existsSync)(i));this.modesDir=n||r[0]}static getInstance(){return t.instance||(t.instance=new t),t.instance}parseInheritance(e){let r=e.split("--");if(r.length===1)return{hasParent:!1,parentId:"",overrideId:""};if(r.length>2)throw new Error(`Invalid mode inheritance: ${e}. Only one level of inheritance supported (parent--override)`);return{hasParent:!0,parentId:r[0],overrideId:e}}isPlainObject(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}deepMerge(e,r){let n={...e};for(let i in r){let s=r[i],o=e[i];this.isPlainObject(s)&&this.isPlainObject(o)?n[i]=this.deepMerge(o,s):n[i]=s}return n}loadModeFile(e){let r=(0,Tv.join)(this.modesDir,`${e}.json`);if(!(0,Op.existsSync)(r))throw new Error(`Mode file not found: ${r}`);let n=(0,Op.readFileSync)(r,"utf-8");return JSON.parse(n)}loadMode(e){let r=this.parseInheritance(e);if(!r.hasParent)try{let c=this.loadModeFile(e);return this.activeMode=c,b.debug("SYSTEM",`Loaded mode: ${c.name} (${e})`,void 0,{types:c.observation_types.map(u=>u.id),concepts:c.observation_concepts.map(u=>u.id)}),c}catch{if(b.warn("SYSTEM",`Mode file not found: ${e}, falling back to 'code'`),e==="code")throw new Error("Critical: code.json mode file missing");return this.loadMode("code")}let{parentId:n,overrideId:i}=r,s;try{s=this.loadMode(n)}catch{b.warn("SYSTEM",`Parent mode '${n}' not found for ${e}, falling back to 'code'`),s=this.loadMode("code")}let o;try{o=this.loadModeFile(i),b.debug("SYSTEM",`Loaded override file: ${i} for parent ${n}`)}catch{return b.warn("SYSTEM",`Override file '${i}' not found, using parent mode '${n}' only`),this.activeMode=s,s}if(!o)return b.warn("SYSTEM",`Invalid override file: ${i}, using parent mode '${n}' only`),this.activeMode=s,s;let a=this.deepMerge(s,o);return this.activeMode=a,b.debug("SYSTEM",`Loaded mode with inheritance: ${a.name} (${e} = ${n} + ${i})`,void 0,{parent:n,override:i,types:a.observation_types.map(c=>c.id),concepts:a.observation_concepts.map(c=>c.id)}),a}getActiveMode(){if(!this.activeMode)throw new Error("No mode loaded. Call loadMode() first.");return this.activeMode}getObservationTypes(){return this.getActiveMode().observation_types}getObservationConcepts(){return this.getActiveMode().observation_concepts}getTypeIcon(e){return this.getObservationTypes().find(n=>n.id===e)?.emoji||"\u{1F4DD}"}getWorkEmoji(e){return this.getObservationTypes().find(n=>n.id===e)?.work_emoji||"\u{1F4DD}"}validateType(e){return this.getObservationTypes().some(r=>r.id===e)}getTypeLabel(e){return this.getObservationTypes().find(n=>n.id===e)?.label||e}}});function Iv(t){if(!t)return[];try{let e=JSON.parse(t);return Array.isArray(e)?e:[]}catch(e){return b.debug("PARSER","Failed to parse JSON array, using empty fallback",{preview:t?.substring(0,50)},e),[]}}function Rn(t){return new Date(t).toLocaleString("en-US",{month:"short",day:"numeric",hour:"numeric",minute:"2-digit",hour12:!0})}function pr(t){return new Date(t).toLocaleString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0})}function Rs(t){return new Date(t).toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric"})}function D6(t,e){return r$.default.isAbsolute(t)?r$.default.relative(e,t):t}function vi(t,e,r){let n=Iv(t);if(n.length>0)return D6(n[0],e);if(r){let i=Iv(r);if(i.length>0)return D6(i[0],e)}return"General"}function du(t){return t?Math.ceil(t.length/4):0}function Os(t,e){let r=new Map;for(let i of t){let s=e(i),o=Rs(s);r.has(o)||r.set(o,[]),r.get(o).push(i)}let n=Array.from(r.entries()).sort((i,s)=>{let o=new Date(i[0]).getTime(),a=new Date(s[0]).getTime();return o-a});return new Map(n)}var r$,ga=Oe(()=>{"use strict";r$=Me(require("path"),1);se()});function S9(t){let e=by.default.join(t,".git"),r;try{r=(0,Sy.statSync)(e)}catch{return uf}if(!r.isFile())return uf;let n;try{n=(0,Sy.readFileSync)(e,"utf-8").trim()}catch{return uf}let i=n.match(/^gitdir:\s*(.+)$/);if(!i)return uf;let o=i[1].match(/^(.+)[/\\]\.git[/\\]worktrees[/\\]([^/\\]+)$/);if(!o)return uf;let a=o[1],c=by.default.basename(t),u=by.default.basename(a);return{isWorktree:!0,worktreeName:c,parentRepoPath:a,parentProjectName:u}}var Sy,by,uf,x9=Oe(()=>{"use strict";Sy=require("fs"),by=Me(require("path"),1),uf={isWorktree:!1,worktreeName:null,parentRepoPath:null,parentProjectName:null}});function Ta(t){if(!t||t.trim()==="")return b.warn("PROJECT_NAME","Empty cwd provided, using fallback",{cwd:t}),"unknown-project";let e=w9.default.basename(t);if(e===""){if(process.platform==="win32"){let n=t.match(/^([A-Z]):\\/i);if(n){let s=`drive-${n[1].toUpperCase()}`;return b.info("PROJECT_NAME","Drive root detected",{cwd:t,projectName:s}),s}}return b.warn("PROJECT_NAME","Root directory detected, using fallback",{cwd:t}),"unknown-project"}return e}function xy(t){let e=Ta(t);if(!t)return{primary:e,parent:null,isWorktree:!1,allProjects:[e]};let r=S9(t);return r.isWorktree&&r.parentProjectName?{primary:e,parent:r.parentProjectName,isWorktree:!0,allProjects:[r.parentProjectName,e]}:{primary:e,parent:null,isWorktree:!1,allProjects:[e]}}var w9,lf=Oe(()=>{"use strict";w9=Me(require("path"),1);se();x9()});function eI(){let t=E9.default.join((0,k9.homedir)(),".claude-mem","settings.json"),e=Ee.loadFromFile(t),r=He.getInstance().getActiveMode(),n=new Set(r.observation_types.map(s=>s.id)),i=new Set(r.observation_concepts.map(s=>s.id));return{totalObservationCount:parseInt(e.CLAUDE_MEM_CONTEXT_OBSERVATIONS,10),fullObservationCount:parseInt(e.CLAUDE_MEM_CONTEXT_FULL_COUNT,10),sessionCount:parseInt(e.CLAUDE_MEM_CONTEXT_SESSION_COUNT,10),showReadTokens:e.CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS==="true",showWorkTokens:e.CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS==="true",showSavingsAmount:e.CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT==="true",showSavingsPercent:e.CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT==="true",observationTypes:n,observationConcepts:i,fullObservationField:e.CLAUDE_MEM_CONTEXT_FULL_FIELD,showLastSummary:e.CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY==="true",showLastMessage:e.CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE==="true"}}var E9,k9,tI=Oe(()=>{"use strict";E9=Me(require("path"),1),k9=require("os");rr();Qr()});var Y,T9,rI,df=Oe(()=>{"use strict";Y={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",cyan:"\x1B[36m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",gray:"\x1B[90m",red:"\x1B[31m"},T9=4,rI=1});function nI(t){let e=(t.title?.length||0)+(t.subtitle?.length||0)+(t.narrative?.length||0)+JSON.stringify(t.facts||[]).length;return Math.ceil(e/T9)}function iI(t){let e=t.length,r=t.reduce((o,a)=>o+nI(a),0),n=t.reduce((o,a)=>o+(a.discovery_tokens||0),0),i=n-r,s=n>0?Math.round(i/n*100):0;return{totalObservations:e,totalReadTokens:r,totalDiscoveryTokens:n,savings:i,savingsPercent:s}}function __e(t){return He.getInstance().getWorkEmoji(t)}function pf(t,e){let r=nI(t),n=t.discovery_tokens||0,i=__e(t.type),s=n>0?`${i} ${n.toLocaleString()}`:"-";return{readTokens:r,discoveryTokens:n,discoveryDisplay:s,workEmoji:i}}function wy(t){return t.showReadTokens||t.showWorkTokens||t.showSavingsAmount||t.showSavingsPercent}var $a=Oe(()=>{"use strict";df();Qr()});function sI(t,e,r){let n=Array.from(r.observationTypes),i=n.map(()=>"?").join(","),s=Array.from(r.observationConcepts),o=s.map(()=>"?").join(",");return t.db.prepare(` SELECT id, memory_session_id, type, title, subtitle, narrative, facts, concepts, files_read, files_modified, discovery_tokens, @@ -809,7 +809,7 @@ Please see the 3.x to 4.x migration guide for details on how to update your app. ORDER BY created_at_epoch DESC LIMIT ? `).all(...e,r.sessionCount+rI)}function b_e(t){return t.replace(/\//g,"-")}function S_e(t){try{if(!(0,Ey.existsSync)(t))return{userMessage:"",assistantMessage:""};let e=(0,Ey.readFileSync)(t,"utf-8").trim();if(!e)return{userMessage:"",assistantMessage:""};let r=e.split(` -`).filter(i=>i.trim()),n="";for(let i=r.length-1;i>=0;i--)try{let s=r[i];if(!s.includes('"type":"assistant"'))continue;let o=JSON.parse(s);if(o.type==="assistant"&&o.message?.content&&Array.isArray(o.message.content)){let a="";for(let c of o.message.content)c.type==="text"&&(a+=c.text);if(a=a.replace(/[\s\S]*?<\/system-reminder>/g,"").trim(),a){n=a;break}}}catch(s){b.debug("PARSER","Skipping malformed transcript line",{lineIndex:i},s);continue}return{userMessage:"",assistantMessage:n}}catch(e){return b.failure("WORKER","Failed to extract prior messages from transcript",{transcriptPath:t},e),{userMessage:"",assistantMessage:""}}}function aI(t,e,r,n){if(!e.showLastMessage||t.length===0)return{userMessage:"",assistantMessage:""};let i=t.find(c=>c.memory_session_id!==r);if(!i)return{userMessage:"",assistantMessage:""};let s=i.memory_session_id,o=b_e(n),a=$9.default.join(bs,"projects",o,`${s}.jsonl`);return S_e(a)}function O9(t,e){let r=e[0]?.id;return t.map((n,i)=>{let s=i===0?null:e[i+1];return{...n,displayEpoch:s?s.created_at_epoch:n.created_at_epoch,displayTime:s?s.created_at:n.created_at,shouldShowLink:n.id!==r}})}function cI(t,e){let r=[...t.map(n=>({type:"observation",data:n})),...e.map(n=>({type:"summary",data:n}))];return r.sort((n,i)=>{let s=n.type==="observation"?n.data.created_at_epoch:n.data.displayEpoch,o=i.type==="observation"?i.data.created_at_epoch:i.data.displayEpoch;return s-o}),r}function C9(t,e){return new Set(t.slice(0,e).map(r=>r.id))}var $9,Ey,uI=Oe(()=>{"use strict";$9=Me(require("path"),1),Ey=require("fs");ne();jt();df()});function P9(){let t=new Date,e=t.toLocaleDateString("en-CA"),r=t.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}).toLowerCase().replace(" ",""),n=t.toLocaleTimeString("en-US",{timeZoneName:"short"}).split(" ").pop();return`${e} ${r} ${n}`}function A9(t){return[`# $CMEM ${t} ${P9()}`,""]}function N9(){return[`Legend: \u{1F3AF}session ${He.getInstance().getActiveMode().observation_types.map(r=>`${r.emoji}${r.id}`).join(" ")}`,"Format: ID TIME TYPE TITLE","Fetch details: get_observations([IDs]) | Search: mem-search skill",""]}function M9(){return[]}function D9(){return[]}function j9(t,e){let r=[],n=[`${t.totalObservations} obs (${t.totalReadTokens.toLocaleString()}t read)`,`${t.totalDiscoveryTokens.toLocaleString()}t work`];return t.totalDiscoveryTokens>0&&(e.showSavingsAmount||e.showSavingsPercent)&&(e.showSavingsPercent?n.push(`${t.savingsPercent}% savings`):e.showSavingsAmount&&n.push(`${t.savings.toLocaleString()}t saved`)),r.push(`Stats: ${n.join(" | ")}`),r.push(""),r}function z9(t){return[`### ${t}`]}function L9(t){return t.toLowerCase().replace(" am","a").replace(" pm","p")}function U9(t,e,r){let n=t.title||"Untitled",i=He.getInstance().getTypeIcon(t.type),s=e?L9(e):'"';return`${t.id} ${s} ${i} ${n}`}function F9(t,e,r,n){let i=[],s=t.title||"Untitled",o=He.getInstance().getTypeIcon(t.type),a=e?L9(e):'"',{readTokens:c,discoveryDisplay:u}=pf(t,n);i.push(`**${t.id}** ${a} ${o} **${s}**`),r&&i.push(r);let l=[];return n.showReadTokens&&l.push(`~${c}t`),n.showWorkTokens&&l.push(u),l.length>0&&i.push(l.join(" ")),i.push(""),i}function q9(t,e){return[`S${t.id} ${t.request||"Session started"} (${e})`]}function ff(t,e){return e?[`**${t}**: ${e}`,""]:[]}function H9(t){return t.assistantMessage?["","---","","**Previously**","",`A: ${t.assistantMessage}`,""]:[]}function Z9(t,e){return["",`Access ${Math.round(t/1e3)}k tokens of past work via get_observations([IDs]) or mem-search skill.`]}function B9(t){return`# $CMEM ${t} ${P9()} +`).filter(i=>i.trim()),n="";for(let i=r.length-1;i>=0;i--)try{let s=r[i];if(!s.includes('"type":"assistant"'))continue;let o=JSON.parse(s);if(o.type==="assistant"&&o.message?.content&&Array.isArray(o.message.content)){let a="";for(let c of o.message.content)c.type==="text"&&(a+=c.text);if(a=a.replace(/[\s\S]*?<\/system-reminder>/g,"").trim(),a){n=a;break}}}catch(s){b.debug("PARSER","Skipping malformed transcript line",{lineIndex:i},s);continue}return{userMessage:"",assistantMessage:n}}catch(e){return b.failure("WORKER","Failed to extract prior messages from transcript",{transcriptPath:t},e),{userMessage:"",assistantMessage:""}}}function aI(t,e,r,n){if(!e.showLastMessage||t.length===0)return{userMessage:"",assistantMessage:""};let i=t.find(c=>c.memory_session_id!==r);if(!i)return{userMessage:"",assistantMessage:""};let s=i.memory_session_id,o=b_e(n),a=$9.default.join(bs,"projects",o,`${s}.jsonl`);return S_e(a)}function O9(t,e){let r=e[0]?.id;return t.map((n,i)=>{let s=i===0?null:e[i+1];return{...n,displayEpoch:s?s.created_at_epoch:n.created_at_epoch,displayTime:s?s.created_at:n.created_at,shouldShowLink:n.id!==r}})}function cI(t,e){let r=[...t.map(n=>({type:"observation",data:n})),...e.map(n=>({type:"summary",data:n}))];return r.sort((n,i)=>{let s=n.type==="observation"?n.data.created_at_epoch:n.data.displayEpoch,o=i.type==="observation"?i.data.created_at_epoch:i.data.displayEpoch;return s-o}),r}function C9(t,e){return new Set(t.slice(0,e).map(r=>r.id))}var $9,Ey,uI=Oe(()=>{"use strict";$9=Me(require("path"),1),Ey=require("fs");se();jt();df()});function P9(){let t=new Date,e=t.toLocaleDateString("en-CA"),r=t.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}).toLowerCase().replace(" ",""),n=t.toLocaleTimeString("en-US",{timeZoneName:"short"}).split(" ").pop();return`${e} ${r} ${n}`}function A9(t){return[`# $CMEM ${t} ${P9()}`,""]}function N9(){return[`Legend: \u{1F3AF}session ${He.getInstance().getActiveMode().observation_types.map(r=>`${r.emoji}${r.id}`).join(" ")}`,"Format: ID TIME TYPE TITLE","Fetch details: get_observations([IDs]) | Search: mem-search skill",""]}function M9(){return[]}function D9(){return[]}function j9(t,e){let r=[],n=[`${t.totalObservations} obs (${t.totalReadTokens.toLocaleString()}t read)`,`${t.totalDiscoveryTokens.toLocaleString()}t work`];return t.totalDiscoveryTokens>0&&(e.showSavingsAmount||e.showSavingsPercent)&&(e.showSavingsPercent?n.push(`${t.savingsPercent}% savings`):e.showSavingsAmount&&n.push(`${t.savings.toLocaleString()}t saved`)),r.push(`Stats: ${n.join(" | ")}`),r.push(""),r}function z9(t){return[`### ${t}`]}function L9(t){return t.toLowerCase().replace(" am","a").replace(" pm","p")}function U9(t,e,r){let n=t.title||"Untitled",i=He.getInstance().getTypeIcon(t.type),s=e?L9(e):'"';return`${t.id} ${s} ${i} ${n}`}function F9(t,e,r,n){let i=[],s=t.title||"Untitled",o=He.getInstance().getTypeIcon(t.type),a=e?L9(e):'"',{readTokens:c,discoveryDisplay:u}=pf(t,n);i.push(`**${t.id}** ${a} ${o} **${s}**`),r&&i.push(r);let l=[];return n.showReadTokens&&l.push(`~${c}t`),n.showWorkTokens&&l.push(u),l.length>0&&i.push(l.join(" ")),i.push(""),i}function q9(t,e){return[`S${t.id} ${t.request||"Session started"} (${e})`]}function ff(t,e){return e?[`**${t}**: ${e}`,""]:[]}function H9(t){return t.assistantMessage?["","---","","**Previously**","",`A: ${t.assistantMessage}`,""]:[]}function Z9(t,e){return["",`Access ${Math.round(t/1e3)}k tokens of past work via get_observations([IDs]) or mem-search skill.`]}function B9(t){return`# $CMEM ${t} ${P9()} No previous sessions found.`}var zu=Oe(()=>{"use strict";Qr();$a()});function G9(){let t=new Date,e=t.toLocaleDateString("en-CA"),r=t.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}).toLowerCase().replace(" ",""),n=t.toLocaleTimeString("en-US",{timeZoneName:"short"}).split(" ").pop();return`${e} ${r} ${n}`}function W9(t){return["",`${Y.bright}${Y.cyan}[${t}] recent context, ${G9()}${Y.reset}`,`${Y.gray}${"\u2500".repeat(60)}${Y.reset}`,""]}function V9(){let e=He.getInstance().getActiveMode().observation_types.map(r=>`${r.emoji} ${r.id}`).join(" | ");return[`${Y.dim}Legend: session-request | ${e}${Y.reset}`,""]}function K9(){return[`${Y.bright}Column Key${Y.reset}`,`${Y.dim} Read: Tokens to read this observation (cost to learn it now)${Y.reset}`,`${Y.dim} Work: Tokens spent on work that produced this record ( research, building, deciding)${Y.reset}`,""]}function J9(){return[`${Y.dim}Context Index: This semantic index (titles, types, files, tokens) is usually sufficient to understand past work.${Y.reset}`,"",`${Y.dim}When you need implementation details, rationale, or debugging context:${Y.reset}`,`${Y.dim} - Fetch by ID: get_observations([IDs]) for observations visible in this index${Y.reset}`,`${Y.dim} - Search history: Use the mem-search skill for past decisions, bugs, and deeper research${Y.reset}`,`${Y.dim} - Trust this index over re-reading code for past decisions and learnings${Y.reset}`,""]}function X9(t,e){let r=[];if(r.push(`${Y.bright}${Y.cyan}Context Economics${Y.reset}`),r.push(`${Y.dim} Loading: ${t.totalObservations} observations (${t.totalReadTokens.toLocaleString()} tokens to read)${Y.reset}`),r.push(`${Y.dim} Work investment: ${t.totalDiscoveryTokens.toLocaleString()} tokens spent on research, building, and decisions${Y.reset}`),t.totalDiscoveryTokens>0&&(e.showSavingsAmount||e.showSavingsPercent)){let n=" Your savings: ";e.showSavingsAmount&&e.showSavingsPercent?n+=`${t.savings.toLocaleString()} tokens (${t.savingsPercent}% reduction from reuse)`:e.showSavingsAmount?n+=`${t.savings.toLocaleString()} tokens`:n+=`${t.savingsPercent}% reduction from reuse`,r.push(`${Y.green}${n}${Y.reset}`)}return r.push(""),r}function Y9(t){return[`${Y.bright}${Y.cyan}${t}${Y.reset}`,""]}function Q9(t){return[`${Y.dim}${t}${Y.reset}`]}function e8(t,e,r,n){let i=t.title||"Untitled",s=He.getInstance().getTypeIcon(t.type),{readTokens:o,discoveryTokens:a,workEmoji:c}=pf(t,n),u=r?`${Y.dim}${e}${Y.reset}`:" ".repeat(e.length),l=n.showReadTokens&&o>0?`${Y.dim}(~${o}t)${Y.reset}`:"",d=n.showWorkTokens&&a>0?`${Y.dim}(${c} ${a.toLocaleString()}t)${Y.reset}`:"";return` ${Y.dim}#${t.id}${Y.reset} ${u} ${s} ${i} ${l} ${d}`}function t8(t,e,r,n,i){let s=[],o=t.title||"Untitled",a=He.getInstance().getTypeIcon(t.type),{readTokens:c,discoveryTokens:u,workEmoji:l}=pf(t,i),d=r?`${Y.dim}${e}${Y.reset}`:" ".repeat(e.length),p=i.showReadTokens&&c>0?`${Y.dim}(~${c}t)${Y.reset}`:"",f=i.showWorkTokens&&u>0?`${Y.dim}(${l} ${u.toLocaleString()}t)${Y.reset}`:"";return s.push(` ${Y.dim}#${t.id}${Y.reset} ${d} ${a} ${Y.bright}${o}${Y.reset}`),n&&s.push(` ${Y.dim}${n}${Y.reset}`),(p||f)&&s.push(` ${p} ${f}`),s.push(""),s}function r8(t,e){let r=`${t.request||"Session started"} (${e})`;return[`${Y.yellow}#S${t.id}${Y.reset} ${r}`,""]}function mf(t,e,r){return e?[`${r}${t}:${Y.reset} ${e}`,""]:[]}function n8(t){return t.assistantMessage?["","---","",`${Y.bright}${Y.magenta}Previously${Y.reset}`,"",`${Y.dim}A: ${t.assistantMessage}${Y.reset}`,""]:[]}function i8(t,e){let r=Math.round(t/1e3);return["",`${Y.dim}Access ${r}k tokens of past research & decisions for just ${e.toLocaleString()}t. Use the claude-mem skill to access memories by ID.${Y.reset}`]}function s8(t){return` ${Y.bright}${Y.cyan}[${t}] recent context, ${G9()}${Y.reset} @@ -818,13 +818,13 @@ ${Y.gray}${"\u2500".repeat(60)}${Y.reset} ${Y.dim}No previous sessions found for this project yet.${Y.reset} `}var Lu=Oe(()=>{"use strict";df();Qr();$a()});function o8(t,e,r,n){let i=[];return n?i.push(...W9(t)):i.push(...A9(t)),n?i.push(...V9()):i.push(...N9()),n?i.push(...K9()):i.push(...M9()),n?i.push(...J9()):i.push(...D9()),wy(r)&&(n?i.push(...X9(e,r)):i.push(...j9(e,r))),i}var a8=Oe(()=>{"use strict";$a();zu();Lu()});function x_e(t){let e=new Map;for(let n of t){let i=n.type==="observation"?n.data.created_at:n.data.displayTime,s=Rs(i);e.has(s)||e.set(s,[]),e.get(s).push(n)}let r=Array.from(e.entries()).sort((n,i)=>{let s=new Date(n[0]).getTime(),o=new Date(i[0]).getTime();return s-o});return new Map(r)}function c8(t,e){return e.fullObservationField==="narrative"?t.narrative:t.facts?Iv(t.facts).join(` `):null}function w_e(t,e,r,n){let i=[];i.push(...z9(t));let s="";for(let o of e)if(o.type==="summary"){s="";let a=o.data,c=Rn(a.displayTime);i.push(...q9(a,c))}else{let a=o.data,c=pr(a.created_at),l=c!==s?c:"";if(s=c,r.has(a.id)){let p=c8(a,n);i.push(...F9(a,l,p,n))}else i.push(U9(a,l,n))}return i}function E_e(t,e,r,n,i){let s=[];s.push(...Y9(t));let o=null,a="";for(let c of e)if(c.type==="summary"){o=null,a="";let u=c.data,l=Rn(u.displayTime);s.push(...r8(u,l))}else{let u=c.data,l=vi(u.files_modified,i,u.files_read),d=pr(u.created_at),p=d!==a;a=d;let f=r.has(u.id);if(l!==o&&(s.push(...Q9(l)),o=l),f){let m=c8(u,n);s.push(...t8(u,d,p,m,n))}else s.push(e8(u,d,p,n))}return s.push(""),s}function k_e(t,e,r,n,i,s){return s?E_e(t,e,r,n,i):w_e(t,e,r,n)}function u8(t,e,r,n,i){let s=[],o=x_e(t);for(let[a,c]of o)s.push(...k_e(a,c,e,r,n,i));return s}var l8=Oe(()=>{"use strict";ga();zu();Lu()});function d8(t,e,r){return!(!t.showLastSummary||!e||!!!(e.investigated||e.learned||e.completed||e.next_steps)||r&&e.created_at_epoch<=r.created_at_epoch)}function p8(t,e){let r=[];return e?(r.push(...mf("Investigated",t.investigated,Y.blue)),r.push(...mf("Learned",t.learned,Y.yellow)),r.push(...mf("Completed",t.completed,Y.green)),r.push(...mf("Next Steps",t.next_steps,Y.magenta))):(r.push(...ff("Investigated",t.investigated)),r.push(...ff("Learned",t.learned)),r.push(...ff("Completed",t.completed)),r.push(...ff("Next Steps",t.next_steps))),r}var f8=Oe(()=>{"use strict";df();zu();Lu()});function m8(t,e){return e?n8(t):H9(t)}function h8(t,e,r){return!wy(e)||t.totalDiscoveryTokens<=0||t.savings<=0?[]:r?i8(t.totalDiscoveryTokens,t.totalReadTokens):Z9(t.totalDiscoveryTokens,t.totalReadTokens)}var g8=Oe(()=>{"use strict";$a();zu();Lu()});function $_e(){try{return new Es}catch(t){if(t.code==="ERR_DLOPEN_FAILED"){try{(0,_8.unlinkSync)(T_e)}catch(e){b.debug("SYSTEM","Marker file cleanup failed (may not exist)",{},e)}return b.error("SYSTEM","Native module rebuild needed - restart Claude Code to auto-fix"),null}throw t}}function I_e(t,e){return e?s8(t):B9(t)}function R_e(t,e,r,n,i,s,o){let a=[],c=iI(e);a.push(...o8(t,c,n,o));let u=r.slice(0,n.sessionCount),l=O9(u,r),d=cI(e,l),p=C9(e,n.fullObservationCount);a.push(...u8(d,p,n,i,o));let f=r[0],m=e[0];d8(n,f,m)&&a.push(...p8(f,o));let h=aI(e,n,s,i);return a.push(...m8(h,o)),a.push(...h8(c,n,o)),a.join(` -`).trimEnd()}async function lI(t,e=!1){let r=eI(),n=t?.cwd??process.cwd(),i=Ta(n),s=t?.projects||[i];t?.full&&(r.totalObservationCount=999999,r.sessionCount=999999);let o=$_e();if(!o)return"";try{let a=s.length>1?I9(o,s,r):sI(o,i,r),c=s.length>1?R9(o,s,r):oI(o,i,r);return a.length===0&&c.length===0?I_e(i,e):R_e(i,a,c,r,n,t?.session_id,e)}finally{o.close()}}var v8,y8,_8,T_e,b8=Oe(()=>{"use strict";v8=Me(require("path"),1),y8=require("os"),_8=require("fs");ng();ne();lf();tI();$a();uI();a8();l8();f8();g8();zu();Lu();T_e=v8.default.join((0,y8.homedir)(),".claude","plugins","marketplaces","thedotmack","plugin",".install-version")});var S8=Oe(()=>{"use strict";b8();tI();$a();uI()});var dI={};_n(dI,{generateContext:()=>lI});var pI=Oe(()=>{"use strict";S8()});function iSe(t){let e=t.startsWith("~")?(0,S5.homedir)()+t.slice(1):t;e=e.replace(/\\/g,"/");let r=e.replace(/[.+^${}()|[\]\\]/g,"\\$&");return r=r.replace(/\*\*/g,"<<>>").replace(/\*/g,"[^/]*").replace(/\?/g,"[^/]").replace(/<<>>/g,".*"),new RegExp(`^${r}$`)}function t_(t,e){if(!e||!e.trim())return!1;let r=t.replace(/\\/g,"/"),n=e.split(",").map(i=>i.trim()).filter(Boolean);for(let i of n)try{if(iSe(i).test(r))return!0}catch{continue}return!1}var S5,jI=Oe(()=>{"use strict";S5=require("os")});var Af,r_=Oe(()=>{"use strict";Dr();lf();ne();Tn();jI();rr();jt();Af={async execute(t){if(!await kr())return{continue:!0,suppressOutput:!0,exitCode:st.SUCCESS};let{sessionId:r,cwd:n,prompt:i}=t;if(!r)return b.warn("HOOK","session-init: No sessionId provided, skipping (Codex CLI or unknown platform)"),{continue:!0,suppressOutput:!0,exitCode:st.SUCCESS};let s=Ee.loadFromFile(qt);if(n&&t_(n,s.CLAUDE_MEM_EXCLUDED_PROJECTS))return b.info("HOOK","Project excluded from tracking",{cwd:n}),{continue:!0,suppressOutput:!0};let o=!i||!i.trim()?"[media prompt]":i,a=Ta(n);b.debug("HOOK","session-init: Calling /api/sessions/init",{contentSessionId:r,project:a});let c=await ft("/api/sessions/init",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({contentSessionId:r,project:a,prompt:o})});if(!c.ok)return b.failure("HOOK",`Session initialization failed: ${c.status}`,{contentSessionId:r,project:a}),{continue:!0,suppressOutput:!0,exitCode:st.SUCCESS};let u=await c.json(),l=u.sessionDbId,d=u.promptNumber;if(b.debug("HOOK","session-init: Received from /api/sessions/init",{sessionDbId:l,promptNumber:d,skipped:u.skipped,contextInjected:u.contextInjected}),b.debug("HOOK",`[ALIGNMENT] Hook Entry | contentSessionId=${r} | prompt#=${d} | sessionDbId=${l}`),u.skipped&&u.reason==="private")return b.info("HOOK",`INIT_COMPLETE | sessionDbId=${l} | promptNumber=${d} | skipped=true | reason=private`,{sessionId:l}),{continue:!0,suppressOutput:!0};if(u.contextInjected)return b.info("HOOK",`INIT_COMPLETE | sessionDbId=${l} | promptNumber=${d} | skipped_agent_init=true | reason=context_already_injected`,{sessionId:l}),{continue:!0,suppressOutput:!0};if(t.platform!=="cursor"&&l){let p=o.startsWith("/")?o.substring(1):o;b.debug("HOOK","session-init: Calling /sessions/{sessionDbId}/init",{sessionDbId:l,promptNumber:d});let f=await ft(`/sessions/${l}/init`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({userPrompt:p,promptNumber:d})});f.ok||b.failure("HOOK",`SDK agent start failed: ${f.status}`,{sessionDbId:l,promptNumber:d})}else t.platform==="cursor"&&b.debug("HOOK","session-init: Skipping SDK agent init for Cursor platform",{sessionDbId:l,promptNumber:d});return b.info("HOOK",`INIT_COMPLETE | sessionDbId=${l} | promptNumber=${d} | project=${a}`,{sessionId:l}),{continue:!0,suppressOutput:!0}}}});var Nf,n_=Oe(()=>{"use strict";Dr();ne();Tn();jI();rr();jt();Nf={async execute(t){if(!await kr())return{continue:!0,suppressOutput:!0,exitCode:st.SUCCESS};let{sessionId:r,cwd:n,toolName:i,toolInput:s,toolResponse:o}=t;if(!i)return{continue:!0,suppressOutput:!0,exitCode:st.SUCCESS};let a=b.formatTool(i,s);if(b.dataIn("HOOK",`PostToolUse: ${a}`,{}),!n)throw new Error(`Missing cwd in PostToolUse hook input for session ${r}, tool ${i}`);let c=Ee.loadFromFile(qt);if(t_(n,c.CLAUDE_MEM_EXCLUDED_PROJECTS))return b.debug("HOOK","Project excluded from tracking, skipping observation",{cwd:n,toolName:i}),{continue:!0,suppressOutput:!0};try{let u=await ft("/api/sessions/observations",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({contentSessionId:r,tool_name:i,tool_input:s,tool_response:o,cwd:n})});if(!u.ok)return b.warn("HOOK","Observation storage failed, skipping",{status:u.status,toolName:i}),{continue:!0,suppressOutput:!0,exitCode:st.SUCCESS};b.debug("HOOK","Observation sent successfully",{toolName:i})}catch(u){return b.warn("HOOK","Observation fetch error, skipping",{error:u instanceof Error?u.message:String(u)}),{continue:!0,suppressOutput:!0,exitCode:st.SUCCESS}}return{continue:!0,suppressOutput:!0}}}});var Mf,i_=Oe(()=>{"use strict";Dr();ne();Tn();Mf={async execute(t){if(!await kr())return{continue:!0,suppressOutput:!0,exitCode:st.SUCCESS};let{sessionId:r,cwd:n,filePath:i,edits:s}=t;if(!i)throw new Error("fileEditHandler requires filePath");if(b.dataIn("HOOK",`FileEdit: ${i}`,{editCount:s?.length??0}),!n)throw new Error(`Missing cwd in FileEdit hook input for session ${r}, file ${i}`);try{let o=await ft("/api/sessions/observations",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({contentSessionId:r,tool_name:"write_file",tool_input:{filePath:i,edits:s},tool_response:{success:!0},cwd:n})});if(!o.ok)return b.warn("HOOK","File edit observation storage failed, skipping",{status:o.status,filePath:i}),{continue:!0,suppressOutput:!0,exitCode:st.SUCCESS};b.debug("HOOK","File edit observation sent successfully",{filePath:i})}catch(o){return b.warn("HOOK","File edit observation fetch error, skipping",{error:o instanceof Error?o.message:String(o)}),{continue:!0,suppressOutput:!0,exitCode:st.SUCCESS}}return{continue:!0,suppressOutput:!0}}}});var Df,s_=Oe(()=>{"use strict";Dr();ne();Df={async execute(t){if(!await kr())return{continue:!0,suppressOutput:!0};let{sessionId:r}=t;if(!r)return b.warn("HOOK","session-complete: Missing sessionId, skipping"),{continue:!0,suppressOutput:!0};b.info("HOOK","\u2192 session-complete: Removing session from active map",{contentSessionId:r});try{let n=await ft("/api/sessions/complete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({contentSessionId:r})});if(n.ok)b.info("HOOK","Session completed successfully",{contentSessionId:r});else{let i=await n.text();b.warn("HOOK","session-complete: Failed to complete session",{status:n.status,body:i})}}catch(n){b.warn("HOOK","session-complete: Error completing session",{error:n.message})}return{continue:!0,suppressOutput:!0}}}});function oSe(){try{let t=process.stdin;return t.isTTY?!1:(t.readable,!0)}catch{return!1}}function aSe(t){let e=t.trim();if(!e)return{success:!1};try{return{success:!0,value:JSON.parse(e)}}catch{return{success:!1}}}async function I5(){if(oSe())return new Promise((t,e)=>{let r="",n=!1,i=null,s=()=>{try{process.stdin.removeAllListeners("data"),process.stdin.removeAllListeners("end"),process.stdin.removeAllListeners("error")}catch{}},o=l=>{n||(n=!0,i&&clearTimeout(i),clearTimeout(u),s(),t(l))},a=l=>{n||(n=!0,i&&clearTimeout(i),clearTimeout(u),s(),e(l))},c=()=>{let l=aSe(r);return l.success?(o(l.value),!0):!1},u=setTimeout(()=>{n||c()||(r.trim()?a(new Error(`Incomplete JSON after ${$5}ms: ${r.slice(0,100)}...`)):o(void 0))},$5);try{process.stdin.on("data",l=>{r+=l,i&&(clearTimeout(i),i=null),!c()&&(i=setTimeout(()=>{c()},cSe))}),process.stdin.on("end",()=>{n||c()||o((r.trim(),void 0))}),process.stdin.on("error",()=>{n||o(void 0)})}catch{n=!0,clearTimeout(u),s(),t(void 0)}})}var $5,cSe,R5=Oe(()=>{"use strict";$5=3e4,cSe=50});var O5,C5=Oe(()=>{"use strict";O5={normalizeInput(t){let e=t??{};return{sessionId:e.session_id??e.id??e.sessionId,cwd:e.cwd??process.cwd(),prompt:e.prompt,toolName:e.tool_name,toolInput:e.tool_input,toolResponse:e.tool_response,transcriptPath:e.transcript_path}},formatOutput(t){let e=t??{};if(e.hookSpecificOutput){let n={hookSpecificOutput:t.hookSpecificOutput};return e.systemMessage&&(n.systemMessage=e.systemMessage),n}let r={};return e.systemMessage&&(r.systemMessage=e.systemMessage),r}}});var P5,A5=Oe(()=>{"use strict";P5={normalizeInput(t){let e=t??{},r=!!e.command&&!e.tool_name;return{sessionId:e.conversation_id||e.generation_id||e.id,cwd:e.workspace_roots?.[0]??e.cwd??process.cwd(),prompt:e.prompt??e.query??e.input??e.message,toolName:r?"Bash":e.tool_name,toolInput:r?{command:e.command}:e.tool_input,toolResponse:r?{output:e.output}:e.result_json,transcriptPath:void 0,filePath:e.file_path,edits:e.edits}},formatOutput(t){return{continue:t.continue??!0}}}});var N5,M5=Oe(()=>{"use strict";N5={normalizeInput(t){let e=t??{},r=e.cwd??process.env.GEMINI_CWD??process.env.GEMINI_PROJECT_DIR??process.env.CLAUDE_PROJECT_DIR??process.cwd(),n=e.session_id??process.env.GEMINI_SESSION_ID??void 0,i=e.hook_event_name,s=e.tool_name,o=e.tool_input,a=e.tool_response;i==="AfterAgent"&&e.prompt_response&&(s=s??"GeminiAgent",o=o??{prompt:e.prompt},a=a??{response:e.prompt_response}),i==="BeforeTool"&&s&&!a&&(a={_preExecution:!0}),i==="Notification"&&(s=s??"GeminiNotification",o=o??{notification_type:e.notification_type,message:e.message},a=a??{details:e.details});let c={};return e.source&&(c.source=e.source),e.reason&&(c.reason=e.reason),e.trigger&&(c.trigger=e.trigger),e.mcp_context&&(c.mcp_context=e.mcp_context),e.notification_type&&(c.notification_type=e.notification_type),e.stop_hook_active!==void 0&&(c.stop_hook_active=e.stop_hook_active),e.original_request_name&&(c.original_request_name=e.original_request_name),i&&(c.hook_event_name=i),{sessionId:n,cwd:r,prompt:e.prompt,toolName:s,toolInput:o,toolResponse:a,transcriptPath:e.transcript_path,metadata:Object.keys(c).length>0?c:void 0}},formatOutput(t){let e={};if(e.continue=t.continue??!0,t.suppressOutput!==void 0&&(e.suppressOutput=t.suppressOutput),t.systemMessage){let r=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g;e.systemMessage=t.systemMessage.replace(r,"")}return t.hookSpecificOutput&&(e.hookSpecificOutput={additionalContext:t.hookSpecificOutput.additionalContext}),e}}});var UI,D5=Oe(()=>{"use strict";UI={normalizeInput(t){let e=t;return{sessionId:e.sessionId??e.session_id??"unknown",cwd:e.cwd??process.cwd(),prompt:e.prompt,toolName:e.toolName??e.tool_name,toolInput:e.toolInput??e.tool_input,toolResponse:e.toolResponse??e.tool_response,transcriptPath:e.transcriptPath??e.transcript_path,filePath:e.filePath??e.file_path,edits:e.edits}},formatOutput(t){return t}}});var j5,z5=Oe(()=>{"use strict";j5={normalizeInput(t){let e=t??{},r=e.tool_info??{},n=e.agent_action_name??"",i={sessionId:e.trajectory_id??e.execution_id,cwd:r.cwd??process.cwd(),platform:"windsurf"};switch(n){case"pre_user_prompt":return{...i,prompt:r.user_prompt};case"post_write_code":return{...i,toolName:"Write",filePath:r.file_path,edits:r.edits,toolInput:{file_path:r.file_path,edits:r.edits}};case"post_run_command":return{...i,cwd:r.cwd??i.cwd,toolName:"Bash",toolInput:{command:r.command_line}};case"post_mcp_tool_use":return{...i,toolName:r.mcp_tool_name??"mcp_tool",toolInput:r.mcp_tool_arguments,toolResponse:r.mcp_result};case"post_cascade_response":return{...i,toolName:"cascade_response",toolResponse:r.response};default:return i}},formatOutput(t){return{continue:t.continue??!0}}}});function L5(t){switch(t){case"claude-code":return O5;case"cursor":return P5;case"gemini":case"gemini-cli":return N5;case"windsurf":return j5;case"raw":return UI;default:return UI}}var U5=Oe(()=>{"use strict";C5();A5();M5();D5();z5()});var FI,qI=Oe(()=>{"use strict";Dr();lf();Tn();ne();rr();jt();FI={async execute(t){if(!await kr())return{hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:""},exitCode:st.SUCCESS};let r=t.cwd??process.cwd(),n=xy(r),i=Jr(),o=Ee.loadFromFile(qt).CLAUDE_MEM_CONTEXT_SHOW_TERMINAL_OUTPUT==="true",a=n.allProjects.join(","),c=`/api/context/inject?projects=${encodeURIComponent(a)}`,u=t.platform==="claude-code"?`${c}&colors=true`:c;try{let[l,d]=await Promise.all([ft(c),o?ft(u).catch(()=>null):Promise.resolve(null)]);if(!l.ok)return b.warn("HOOK","Context generation failed, returning empty",{status:l.status}),{hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:""},exitCode:st.SUCCESS};let[p,f]=await Promise.all([l.text(),d?.ok?d.text():Promise.resolve("")]),m=p.trim(),h=f.trim(),g=t.platform,v=h||(g==="gemini-cli"||g==="gemini"?m:""),S=o&&v?`${v} +`).trimEnd()}async function lI(t,e=!1){let r=eI(),n=t?.cwd??process.cwd(),i=Ta(n),s=t?.projects||[i];t?.full&&(r.totalObservationCount=999999,r.sessionCount=999999);let o=$_e();if(!o)return"";try{let a=s.length>1?I9(o,s,r):sI(o,i,r),c=s.length>1?R9(o,s,r):oI(o,i,r);return a.length===0&&c.length===0?I_e(i,e):R_e(i,a,c,r,n,t?.session_id,e)}finally{o.close()}}var v8,y8,_8,T_e,b8=Oe(()=>{"use strict";v8=Me(require("path"),1),y8=require("os"),_8=require("fs");ng();se();lf();tI();$a();uI();a8();l8();f8();g8();zu();Lu();T_e=v8.default.join((0,y8.homedir)(),".claude","plugins","marketplaces","thedotmack","plugin",".install-version")});var S8=Oe(()=>{"use strict";b8();tI();$a();uI()});var dI={};_n(dI,{generateContext:()=>lI});var pI=Oe(()=>{"use strict";S8()});function iSe(t){let e=t.startsWith("~")?(0,S5.homedir)()+t.slice(1):t;e=e.replace(/\\/g,"/");let r=e.replace(/[.+^${}()|[\]\\]/g,"\\$&");return r=r.replace(/\*\*/g,"<<>>").replace(/\*/g,"[^/]*").replace(/\?/g,"[^/]").replace(/<<>>/g,".*"),new RegExp(`^${r}$`)}function t_(t,e){if(!e||!e.trim())return!1;let r=t.replace(/\\/g,"/"),n=e.split(",").map(i=>i.trim()).filter(Boolean);for(let i of n)try{if(iSe(i).test(r))return!0}catch{continue}return!1}var S5,jI=Oe(()=>{"use strict";S5=require("os")});var Af,r_=Oe(()=>{"use strict";Dr();lf();se();Tn();jI();rr();jt();Af={async execute(t){if(!await kr())return{continue:!0,suppressOutput:!0,exitCode:st.SUCCESS};let{sessionId:r,cwd:n,prompt:i}=t;if(!r)return b.warn("HOOK","session-init: No sessionId provided, skipping (Codex CLI or unknown platform)"),{continue:!0,suppressOutput:!0,exitCode:st.SUCCESS};let s=Ee.loadFromFile(qt);if(n&&t_(n,s.CLAUDE_MEM_EXCLUDED_PROJECTS))return b.info("HOOK","Project excluded from tracking",{cwd:n}),{continue:!0,suppressOutput:!0};let o=!i||!i.trim()?"[media prompt]":i,a=Ta(n);b.debug("HOOK","session-init: Calling /api/sessions/init",{contentSessionId:r,project:a});let c=await ft("/api/sessions/init",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({contentSessionId:r,project:a,prompt:o})});if(!c.ok)return b.failure("HOOK",`Session initialization failed: ${c.status}`,{contentSessionId:r,project:a}),{continue:!0,suppressOutput:!0,exitCode:st.SUCCESS};let u=await c.json(),l=u.sessionDbId,d=u.promptNumber;if(b.debug("HOOK","session-init: Received from /api/sessions/init",{sessionDbId:l,promptNumber:d,skipped:u.skipped,contextInjected:u.contextInjected}),b.debug("HOOK",`[ALIGNMENT] Hook Entry | contentSessionId=${r} | prompt#=${d} | sessionDbId=${l}`),u.skipped&&u.reason==="private")return b.info("HOOK",`INIT_COMPLETE | sessionDbId=${l} | promptNumber=${d} | skipped=true | reason=private`,{sessionId:l}),{continue:!0,suppressOutput:!0};if(u.contextInjected)return b.info("HOOK",`INIT_COMPLETE | sessionDbId=${l} | promptNumber=${d} | skipped_agent_init=true | reason=context_already_injected`,{sessionId:l}),{continue:!0,suppressOutput:!0};if(t.platform!=="cursor"&&l){let p=o.startsWith("/")?o.substring(1):o;b.debug("HOOK","session-init: Calling /sessions/{sessionDbId}/init",{sessionDbId:l,promptNumber:d});let f=await ft(`/sessions/${l}/init`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({userPrompt:p,promptNumber:d})});f.ok||b.failure("HOOK",`SDK agent start failed: ${f.status}`,{sessionDbId:l,promptNumber:d})}else t.platform==="cursor"&&b.debug("HOOK","session-init: Skipping SDK agent init for Cursor platform",{sessionDbId:l,promptNumber:d});return b.info("HOOK",`INIT_COMPLETE | sessionDbId=${l} | promptNumber=${d} | project=${a}`,{sessionId:l}),{continue:!0,suppressOutput:!0}}}});var Nf,n_=Oe(()=>{"use strict";Dr();se();Tn();jI();rr();jt();Nf={async execute(t){if(!await kr())return{continue:!0,suppressOutput:!0,exitCode:st.SUCCESS};let{sessionId:r,cwd:n,toolName:i,toolInput:s,toolResponse:o}=t;if(!i)return{continue:!0,suppressOutput:!0,exitCode:st.SUCCESS};let a=b.formatTool(i,s);if(b.dataIn("HOOK",`PostToolUse: ${a}`,{}),!n)throw new Error(`Missing cwd in PostToolUse hook input for session ${r}, tool ${i}`);let c=Ee.loadFromFile(qt);if(t_(n,c.CLAUDE_MEM_EXCLUDED_PROJECTS))return b.debug("HOOK","Project excluded from tracking, skipping observation",{cwd:n,toolName:i}),{continue:!0,suppressOutput:!0};try{let u=await ft("/api/sessions/observations",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({contentSessionId:r,tool_name:i,tool_input:s,tool_response:o,cwd:n})});if(!u.ok)return b.warn("HOOK","Observation storage failed, skipping",{status:u.status,toolName:i}),{continue:!0,suppressOutput:!0,exitCode:st.SUCCESS};b.debug("HOOK","Observation sent successfully",{toolName:i})}catch(u){return b.warn("HOOK","Observation fetch error, skipping",{error:u instanceof Error?u.message:String(u)}),{continue:!0,suppressOutput:!0,exitCode:st.SUCCESS}}return{continue:!0,suppressOutput:!0}}}});var Mf,i_=Oe(()=>{"use strict";Dr();se();Tn();Mf={async execute(t){if(!await kr())return{continue:!0,suppressOutput:!0,exitCode:st.SUCCESS};let{sessionId:r,cwd:n,filePath:i,edits:s}=t;if(!i)throw new Error("fileEditHandler requires filePath");if(b.dataIn("HOOK",`FileEdit: ${i}`,{editCount:s?.length??0}),!n)throw new Error(`Missing cwd in FileEdit hook input for session ${r}, file ${i}`);try{let o=await ft("/api/sessions/observations",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({contentSessionId:r,tool_name:"write_file",tool_input:{filePath:i,edits:s},tool_response:{success:!0},cwd:n})});if(!o.ok)return b.warn("HOOK","File edit observation storage failed, skipping",{status:o.status,filePath:i}),{continue:!0,suppressOutput:!0,exitCode:st.SUCCESS};b.debug("HOOK","File edit observation sent successfully",{filePath:i})}catch(o){return b.warn("HOOK","File edit observation fetch error, skipping",{error:o instanceof Error?o.message:String(o)}),{continue:!0,suppressOutput:!0,exitCode:st.SUCCESS}}return{continue:!0,suppressOutput:!0}}}});var Df,s_=Oe(()=>{"use strict";Dr();se();Df={async execute(t){if(!await kr())return{continue:!0,suppressOutput:!0};let{sessionId:r}=t;if(!r)return b.warn("HOOK","session-complete: Missing sessionId, skipping"),{continue:!0,suppressOutput:!0};b.info("HOOK","\u2192 session-complete: Removing session from active map",{contentSessionId:r});try{let n=await ft("/api/sessions/complete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({contentSessionId:r})});if(n.ok)b.info("HOOK","Session completed successfully",{contentSessionId:r});else{let i=await n.text();b.warn("HOOK","session-complete: Failed to complete session",{status:n.status,body:i})}}catch(n){b.warn("HOOK","session-complete: Error completing session",{error:n.message})}return{continue:!0,suppressOutput:!0}}}});function oSe(){try{let t=process.stdin;return t.isTTY?!1:(t.readable,!0)}catch{return!1}}function aSe(t){let e=t.trim();if(!e)return{success:!1};try{return{success:!0,value:JSON.parse(e)}}catch{return{success:!1}}}async function I5(){if(oSe())return new Promise((t,e)=>{let r="",n=!1,i=null,s=()=>{try{process.stdin.removeAllListeners("data"),process.stdin.removeAllListeners("end"),process.stdin.removeAllListeners("error")}catch{}},o=l=>{n||(n=!0,i&&clearTimeout(i),clearTimeout(u),s(),t(l))},a=l=>{n||(n=!0,i&&clearTimeout(i),clearTimeout(u),s(),e(l))},c=()=>{let l=aSe(r);return l.success?(o(l.value),!0):!1},u=setTimeout(()=>{n||c()||(r.trim()?a(new Error(`Incomplete JSON after ${$5}ms: ${r.slice(0,100)}...`)):o(void 0))},$5);try{process.stdin.on("data",l=>{r+=l,i&&(clearTimeout(i),i=null),!c()&&(i=setTimeout(()=>{c()},cSe))}),process.stdin.on("end",()=>{n||c()||o((r.trim(),void 0))}),process.stdin.on("error",()=>{n||o(void 0)})}catch{n=!0,clearTimeout(u),s(),t(void 0)}})}var $5,cSe,R5=Oe(()=>{"use strict";$5=3e4,cSe=50});var O5,C5=Oe(()=>{"use strict";O5={normalizeInput(t){let e=t??{};return{sessionId:e.session_id??e.id??e.sessionId,cwd:e.cwd??process.cwd(),prompt:e.prompt,toolName:e.tool_name,toolInput:e.tool_input,toolResponse:e.tool_response,transcriptPath:e.transcript_path}},formatOutput(t){let e=t??{};if(e.hookSpecificOutput){let n={hookSpecificOutput:t.hookSpecificOutput};return e.systemMessage&&(n.systemMessage=e.systemMessage),n}let r={};return e.systemMessage&&(r.systemMessage=e.systemMessage),r}}});var P5,A5=Oe(()=>{"use strict";P5={normalizeInput(t){let e=t??{},r=!!e.command&&!e.tool_name;return{sessionId:e.conversation_id||e.generation_id||e.id,cwd:e.workspace_roots?.[0]??e.cwd??process.cwd(),prompt:e.prompt??e.query??e.input??e.message,toolName:r?"Bash":e.tool_name,toolInput:r?{command:e.command}:e.tool_input,toolResponse:r?{output:e.output}:e.result_json,transcriptPath:void 0,filePath:e.file_path,edits:e.edits}},formatOutput(t){return{continue:t.continue??!0}}}});var N5,M5=Oe(()=>{"use strict";N5={normalizeInput(t){let e=t??{},r=e.cwd??process.env.GEMINI_CWD??process.env.GEMINI_PROJECT_DIR??process.env.CLAUDE_PROJECT_DIR??process.cwd(),n=e.session_id??process.env.GEMINI_SESSION_ID??void 0,i=e.hook_event_name,s=e.tool_name,o=e.tool_input,a=e.tool_response;i==="AfterAgent"&&e.prompt_response&&(s=s??"GeminiAgent",o=o??{prompt:e.prompt},a=a??{response:e.prompt_response}),i==="BeforeTool"&&s&&!a&&(a={_preExecution:!0}),i==="Notification"&&(s=s??"GeminiNotification",o=o??{notification_type:e.notification_type,message:e.message},a=a??{details:e.details});let c={};return e.source&&(c.source=e.source),e.reason&&(c.reason=e.reason),e.trigger&&(c.trigger=e.trigger),e.mcp_context&&(c.mcp_context=e.mcp_context),e.notification_type&&(c.notification_type=e.notification_type),e.stop_hook_active!==void 0&&(c.stop_hook_active=e.stop_hook_active),e.original_request_name&&(c.original_request_name=e.original_request_name),i&&(c.hook_event_name=i),{sessionId:n,cwd:r,prompt:e.prompt,toolName:s,toolInput:o,toolResponse:a,transcriptPath:e.transcript_path,metadata:Object.keys(c).length>0?c:void 0}},formatOutput(t){let e={};if(e.continue=t.continue??!0,t.suppressOutput!==void 0&&(e.suppressOutput=t.suppressOutput),t.systemMessage){let r=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g;e.systemMessage=t.systemMessage.replace(r,"")}return t.hookSpecificOutput&&(e.hookSpecificOutput={additionalContext:t.hookSpecificOutput.additionalContext}),e}}});var UI,D5=Oe(()=>{"use strict";UI={normalizeInput(t){let e=t;return{sessionId:e.sessionId??e.session_id??"unknown",cwd:e.cwd??process.cwd(),prompt:e.prompt,toolName:e.toolName??e.tool_name,toolInput:e.toolInput??e.tool_input,toolResponse:e.toolResponse??e.tool_response,transcriptPath:e.transcriptPath??e.transcript_path,filePath:e.filePath??e.file_path,edits:e.edits}},formatOutput(t){return t}}});var j5,z5=Oe(()=>{"use strict";j5={normalizeInput(t){let e=t??{},r=e.tool_info??{},n=e.agent_action_name??"",i={sessionId:e.trajectory_id??e.execution_id,cwd:r.cwd??process.cwd(),platform:"windsurf"};switch(n){case"pre_user_prompt":return{...i,prompt:r.user_prompt};case"post_write_code":return{...i,toolName:"Write",filePath:r.file_path,edits:r.edits,toolInput:{file_path:r.file_path,edits:r.edits}};case"post_run_command":return{...i,cwd:r.cwd??i.cwd,toolName:"Bash",toolInput:{command:r.command_line}};case"post_mcp_tool_use":return{...i,toolName:r.mcp_tool_name??"mcp_tool",toolInput:r.mcp_tool_arguments,toolResponse:r.mcp_result};case"post_cascade_response":return{...i,toolName:"cascade_response",toolResponse:r.response};default:return i}},formatOutput(t){return{continue:t.continue??!0}}}});function L5(t){switch(t){case"claude-code":return O5;case"cursor":return P5;case"gemini":case"gemini-cli":return N5;case"windsurf":return j5;case"raw":return UI;default:return UI}}var U5=Oe(()=>{"use strict";C5();A5();M5();D5();z5()});var FI,qI=Oe(()=>{"use strict";Dr();lf();Tn();se();rr();jt();FI={async execute(t){if(!await kr())return{hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:""},exitCode:st.SUCCESS};let r=t.cwd??process.cwd(),n=xy(r),i=Jr(),o=Ee.loadFromFile(qt).CLAUDE_MEM_CONTEXT_SHOW_TERMINAL_OUTPUT==="true",a=n.allProjects.join(","),c=`/api/context/inject?projects=${encodeURIComponent(a)}`,u=t.platform==="claude-code"?`${c}&colors=true`:c;try{let[l,d]=await Promise.all([ft(c),o?ft(u).catch(()=>null):Promise.resolve(null)]);if(!l.ok)return b.warn("HOOK","Context generation failed, returning empty",{status:l.status}),{hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:""},exitCode:st.SUCCESS};let[p,f]=await Promise.all([l.text(),d?.ok?d.text():Promise.resolve("")]),m=p.trim(),h=f.trim(),g=t.platform,v=h||(g==="gemini-cli"||g==="gemini"?m:""),S=o&&v?`${v} View Observations Live @ http://localhost:${i}`:void 0;return{hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:m},systemMessage:S}}catch(l){return b.warn("HOOK","Context fetch error, returning empty",{error:l instanceof Error?l.message:String(l)}),{hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:""},exitCode:st.SUCCESS}}}}});function F5(t,e,r=!1){if(!t||!(0,l_.existsSync)(t))return b.warn("PARSER",`Transcript path missing or file does not exist: ${t}`),"";let n=(0,l_.readFileSync)(t,"utf-8").trim();if(!n)return b.warn("PARSER",`Transcript file exists but is empty: ${t}`),"";let i=n.split(` `),s=!1;for(let o=i.length-1;o>=0;o--){let a=JSON.parse(i[o]);if(a.type===e&&(s=!0,a.message?.content)){let c="",u=a.message.content;if(typeof u=="string")c=u;else if(Array.isArray(u))c=u.filter(l=>l.type==="text").map(l=>l.text).join(` `);else throw new Error(`Unknown message content format in transcript. Type: ${typeof u}`);return r&&(c=c.replace(/[\s\S]*?<\/system-reminder>/g,""),c=c.replace(/\n{3,}/g,` -`).trim()),c}}return""}var l_,q5=Oe(()=>{"use strict";l_=require("fs");ne()});var uSe,lSe,dSe,HI,ZI=Oe(()=>{"use strict";Dr();ne();q5();Tn();uSe=Gh(Er.DEFAULT),lSe=500,dSe=11e4,HI={async execute(t){if(!await kr())return{continue:!0,suppressOutput:!0,exitCode:st.SUCCESS};let{sessionId:r,transcriptPath:n}=t;if(!n)return b.debug("HOOK",`No transcriptPath in Stop hook input for session ${r} - skipping summary`),{continue:!0,suppressOutput:!0,exitCode:st.SUCCESS};let i="";try{i=F5(n,"assistant",!0)}catch(a){return b.warn("HOOK",`Stop hook: failed to extract last assistant message for session ${r}: ${a instanceof Error?a.message:a}`),{continue:!0,suppressOutput:!0,exitCode:st.SUCCESS}}if(b.dataIn("HOOK","Stop: Requesting summary",{hasLastAssistantMessage:!!i}),!(await ft("/api/sessions/summarize",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({contentSessionId:r,last_assistant_message:i}),timeoutMs:uSe})).ok)return{continue:!0,suppressOutput:!0};b.debug("HOOK","Summary request queued, waiting for completion");let o=Date.now();for(;Date.now()-osetTimeout(a,lSe));try{let a=await ft(`/api/sessions/status?contentSessionId=${encodeURIComponent(r)}`,{timeoutMs:5e3});if(a.ok&&((await a.json()).queueLength??0)===0){b.info("HOOK","Summary processing complete",{waitedMs:Date.now()-o});break}}catch{}}try{await ft("/api/sessions/complete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({contentSessionId:r}),timeoutMs:1e4}),b.info("HOOK","Session completed in Stop hook",{contentSessionId:r})}catch(a){b.warn("HOOK",`Stop hook: session-complete failed: ${a instanceof Error?a.message:a}`)}return{continue:!0,suppressOutput:!0}}}});var H5,BI,GI=Oe(()=>{"use strict";H5=require("path");Dr();Tn();BI={async execute(t){if(!await kr())return{exitCode:st.SUCCESS};let r=Jr(),n=(0,H5.basename)(t.cwd??process.cwd()),i=t.platform==="claude-code"?"&colors=true":"";try{let s=await ft(`/api/context/inject?project=${encodeURIComponent(n)}${i}`);if(!s.ok)return{exitCode:st.SUCCESS};let o=await s.text();process.stderr.write(` +`).trim()),c}}return""}var l_,q5=Oe(()=>{"use strict";l_=require("fs");se()});var uSe,lSe,dSe,HI,ZI=Oe(()=>{"use strict";Dr();se();q5();Tn();uSe=Gh(Er.DEFAULT),lSe=500,dSe=11e4,HI={async execute(t){if(!await kr())return{continue:!0,suppressOutput:!0,exitCode:st.SUCCESS};let{sessionId:r,transcriptPath:n}=t;if(!n)return b.debug("HOOK",`No transcriptPath in Stop hook input for session ${r} - skipping summary`),{continue:!0,suppressOutput:!0,exitCode:st.SUCCESS};let i="";try{i=F5(n,"assistant",!0)}catch(a){return b.warn("HOOK",`Stop hook: failed to extract last assistant message for session ${r}: ${a instanceof Error?a.message:a}`),{continue:!0,suppressOutput:!0,exitCode:st.SUCCESS}}if(b.dataIn("HOOK","Stop: Requesting summary",{hasLastAssistantMessage:!!i}),!(await ft("/api/sessions/summarize",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({contentSessionId:r,last_assistant_message:i}),timeoutMs:uSe})).ok)return{continue:!0,suppressOutput:!0};b.debug("HOOK","Summary request queued, waiting for completion");let o=Date.now();for(;Date.now()-osetTimeout(a,lSe));try{let a=await ft(`/api/sessions/status?contentSessionId=${encodeURIComponent(r)}`,{timeoutMs:5e3});if(a.ok&&((await a.json()).queueLength??0)===0){b.info("HOOK","Summary processing complete",{waitedMs:Date.now()-o});break}}catch{}}try{await ft("/api/sessions/complete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({contentSessionId:r}),timeoutMs:1e4}),b.info("HOOK","Session completed in Stop hook",{contentSessionId:r})}catch(a){b.warn("HOOK",`Stop hook: session-complete failed: ${a instanceof Error?a.message:a}`)}return{continue:!0,suppressOutput:!0}}}});var H5,BI,GI=Oe(()=>{"use strict";H5=require("path");Dr();Tn();BI={async execute(t){if(!await kr())return{exitCode:st.SUCCESS};let r=Jr(),n=(0,H5.basename)(t.cwd??process.cwd()),i=t.platform==="claude-code"?"&colors=true":"";try{let s=await ft(`/api/context/inject?project=${encodeURIComponent(n)}${i}`);if(!s.ok)return{exitCode:st.SUCCESS};let o=await s.text();process.stderr.write(` `+String.fromCodePoint(128221)+` Claude-Mem Context Loaded @@ -834,7 +834,7 @@ View Observations Live @ http://localhost:${i}`:void 0;return{hookSpecificOutput `+String.fromCodePoint(128172)+` Community https://discord.gg/J4wttp9vDu `+String.fromCodePoint(128250)+` Watch live in browser http://localhost:${r}/ -`)}catch{}return{exitCode:st.SUCCESS}}}});function Z5(t){let e=pSe[t];return e||(b.warn("HOOK",`Unknown event type: ${t}, returning no-op`),{async execute(){return{continue:!0,suppressOutput:!0,exitCode:st.SUCCESS}}})}var pSe,B5=Oe(()=>{"use strict";Tn();ne();qI();r_();n_();ZI();GI();i_();s_();qI();r_();n_();ZI();GI();i_();s_();pSe={context:FI,"session-init":Af,observation:Nf,summarize:HI,"session-complete":Df,"user-message":BI,"file-edit":Mf}});var W5={};_n(W5,{hookCommand:()=>fSe,isWorkerUnavailableError:()=>G5});function G5(t){let e=t instanceof Error?t.message:String(t),r=e.toLowerCase();return["econnrefused","econnreset","epipe","etimedout","enotfound","econnaborted","enetunreach","ehostunreach","fetch failed","unable to connect","socket hang up"].some(i=>r.includes(i))||r.includes("timed out")||r.includes("timeout")||/failed:\s*5\d{2}/.test(e)||/status[:\s]+5\d{2}/.test(e)||/failed:\s*429/.test(e)||/status[:\s]+429/.test(e)?!0:(/failed:\s*4\d{2}/.test(e)||/status[:\s]+4\d{2}/.test(e)||t instanceof TypeError||t instanceof ReferenceError||t instanceof SyntaxError,!1)}async function fSe(t,e,r={}){let n=process.stderr.write.bind(process.stderr);process.stderr.write=(()=>!0);try{let i=L5(t),s=Z5(e),o=await I5(),a=i.normalizeInput(o);a.platform=t;let c=await s.execute(a),u=i.formatOutput(c);console.log(JSON.stringify(u));let l=c.exitCode??st.SUCCESS;return r.skipExit||process.exit(l),l}catch(i){return G5(i)?(b.warn("HOOK",`Worker unavailable, skipping hook: ${i instanceof Error?i.message:i}`),r.skipExit||process.exit(st.SUCCESS),st.SUCCESS):(b.error("HOOK",`Hook error: ${i instanceof Error?i.message:i}`,{},i instanceof Error?i:void 0),r.skipExit||process.exit(st.BLOCKING_ERROR),st.BLOCKING_ERROR)}finally{process.stderr.write=n}}var V5=Oe(()=>{"use strict";R5();U5();B5();Tn();ne()});var VI={};_n(VI,{cleanClaudeMd:()=>TSe,generateClaudeMd:()=>kSe});function gSe(t){return hSe[t]||"\u{1F4DD}"}function vSe(t){let e=(t.title?.length||0)+(t.subtitle?.length||0)+(t.narrative?.length||0)+(t.facts?.length||0);return Math.ceil(e/4)}function ySe(t){let e=new Set;try{let n=(0,X5.execSync)("git ls-files",{cwd:t,encoding:"utf-8",maxBuffer:52428800}).trim().split(` +`)}catch{}return{exitCode:st.SUCCESS}}}});function Z5(t){let e=pSe[t];return e||(b.warn("HOOK",`Unknown event type: ${t}, returning no-op`),{async execute(){return{continue:!0,suppressOutput:!0,exitCode:st.SUCCESS}}})}var pSe,B5=Oe(()=>{"use strict";Tn();se();qI();r_();n_();ZI();GI();i_();s_();qI();r_();n_();ZI();GI();i_();s_();pSe={context:FI,"session-init":Af,observation:Nf,summarize:HI,"session-complete":Df,"user-message":BI,"file-edit":Mf}});var W5={};_n(W5,{hookCommand:()=>fSe,isWorkerUnavailableError:()=>G5});function G5(t){let e=t instanceof Error?t.message:String(t),r=e.toLowerCase();return["econnrefused","econnreset","epipe","etimedout","enotfound","econnaborted","enetunreach","ehostunreach","fetch failed","unable to connect","socket hang up"].some(i=>r.includes(i))||r.includes("timed out")||r.includes("timeout")||/failed:\s*5\d{2}/.test(e)||/status[:\s]+5\d{2}/.test(e)||/failed:\s*429/.test(e)||/status[:\s]+429/.test(e)?!0:(/failed:\s*4\d{2}/.test(e)||/status[:\s]+4\d{2}/.test(e)||t instanceof TypeError||t instanceof ReferenceError||t instanceof SyntaxError,!1)}async function fSe(t,e,r={}){let n=process.stderr.write.bind(process.stderr);process.stderr.write=(()=>!0);try{let i=L5(t),s=Z5(e),o=await I5(),a=i.normalizeInput(o);a.platform=t;let c=await s.execute(a),u=i.formatOutput(c);console.log(JSON.stringify(u));let l=c.exitCode??st.SUCCESS;return r.skipExit||process.exit(l),l}catch(i){return G5(i)?(b.warn("HOOK",`Worker unavailable, skipping hook: ${i instanceof Error?i.message:i}`),r.skipExit||process.exit(st.SUCCESS),st.SUCCESS):(b.error("HOOK",`Hook error: ${i instanceof Error?i.message:i}`,{},i instanceof Error?i:void 0),r.skipExit||process.exit(st.BLOCKING_ERROR),st.BLOCKING_ERROR)}finally{process.stderr.write=n}}var V5=Oe(()=>{"use strict";R5();U5();B5();Tn();se()});var VI={};_n(VI,{cleanClaudeMd:()=>TSe,generateClaudeMd:()=>kSe});function gSe(t){return hSe[t]||"\u{1F4DD}"}function vSe(t){let e=(t.title?.length||0)+(t.subtitle?.length||0)+(t.narrative?.length||0)+(t.facts?.length||0);return Math.ceil(e/4)}function ySe(t){let e=new Set;try{let n=(0,X5.execSync)("git ls-files",{cwd:t,encoding:"utf-8",maxBuffer:52428800}).trim().split(` `).filter(i=>i);for(let i of n){let s=ar.default.join(t,i),o=ar.default.dirname(s);for(;o.length>t.length&&o.startsWith(t);)e.add(o),o=ar.default.dirname(o)}}catch(r){b.warn("CLAUDE_MD","git ls-files failed, falling back to directory walk",{error:String(r)}),Y5(t,e)}return e}function Y5(t,e,r=0){if(r>10)return;let n=["node_modules",".git",".next","dist","build",".cache","__pycache__",".venv","venv",".idea",".vscode","coverage",".claude-mem",".open-next",".turbo"];try{let i=(0,cr.readdirSync)(t,{withFileTypes:!0});for(let s of i){if(!s.isDirectory()||n.includes(s.name)||s.name.startsWith(".")&&s.name!==".claude")continue;let o=ar.default.join(t,s.name);e.add(o),Y5(o,e,r+1)}}catch{}}function _Se(t,e){let r=n=>{if(!n)return!1;try{let i=JSON.parse(n);if(Array.isArray(i))return i.some(s=>ma(s,e))}catch{}return!1};return r(t.files_modified)||r(t.files_read)}function bSe(t,e,r,n){let i=n*3,s=` SELECT o.*, o.discovery_tokens FROM observations o @@ -852,7 +852,7 @@ ${a}`+s.substring(l+a.length):c=s+` ${o} ${e} -${a}`}(0,cr.writeFileSync)(i,c),(0,cr.renameSync)(i,n)}function ESe(t,e,r,n,i,s,o){try{if(!(0,cr.existsSync)(e))return{success:!1,observationCount:0,error:"Folder no longer exists"};let a=ar.default.resolve(e),c=ar.default.resolve(s);if(!a.startsWith(c+ar.default.sep))return{success:!1,observationCount:0,error:"Path escapes project root"};let u=bSe(t,r,n,o);if(u.length===0)return{success:!1,observationCount:0,error:"No observations for folder"};if(i)return{success:!0,observationCount:u.length};let l=xSe(u,r);return wSe(e,l),{success:!0,observationCount:u.length}}catch(a){return{success:!1,observationCount:0,error:String(a)}}}async function kSe(t){try{let e=process.cwd(),r=Ee.loadFromFile(mSe),n=parseInt(r.CLAUDE_MEM_CONTEXT_OBSERVATIONS,10)||50;b.info("CLAUDE_MD","Starting CLAUDE.md generation",{workingDir:e,dryRun:t,observationLimit:n});let i=ar.default.basename(e),s=ySe(e);if(s.size===0)return b.info("CLAUDE_MD","No folders found in project"),0;if(b.info("CLAUDE_MD",`Found ${s.size} folders in project`),!(0,cr.existsSync)(K5))return b.info("CLAUDE_MD","Database not found, no observations to process"),0;let o=new J5.Database(K5,{readonly:!0,create:!1}),a=0,c=0,u=0,l=Array.from(s).sort();for(let d of l){let p=ar.default.relative(e,d),f=ESe(o,d,p,i,t,e,n);f.success?(b.debug("CLAUDE_MD",`Processed folder: ${p}`,{observationCount:f.observationCount}),a++):f.error?.includes("No observations")?c++:(b.warn("CLAUDE_MD",`Error processing folder: ${p}`,{error:f.error}),u++)}return o.close(),b.info("CLAUDE_MD","CLAUDE.md generation complete",{totalFolders:l.length,withObservations:a,noObservations:c,errors:u,dryRun:t}),0}catch(e){return b.error("CLAUDE_MD","Fatal error during CLAUDE.md generation",{error:String(e)}),1}}async function TSe(t){try{let i=function(c){let u=["node_modules",".git",".next","dist","build",".cache","__pycache__",".venv","venv",".idea",".vscode","coverage",".claude-mem",".open-next",".turbo"];try{let l=(0,cr.readdirSync)(c,{withFileTypes:!0});for(let d of l){let p=ar.default.join(c,d.name);if(d.isDirectory())u.includes(d.name)||i(p);else if(d.name==="CLAUDE.md")try{(0,cr.readFileSync)(p,"utf-8").includes("")&&n.push(p)}catch{}}}catch{}};var e=i;let r=process.cwd();b.info("CLAUDE_MD","Starting CLAUDE.md cleanup",{workingDir:r,dryRun:t});let n=[];if(i(r),n.length===0)return b.info("CLAUDE_MD","No CLAUDE.md files with auto-generated content found"),0;b.info("CLAUDE_MD",`Found ${n.length} CLAUDE.md files with auto-generated content`);let s=0,o=0,a=0;for(let c of n){let u=ar.default.relative(r,c);try{let d=(0,cr.readFileSync)(c,"utf-8").replace(/[\s\S]*?<\/claude-mem-context>/g,"").trim();d===""?(t||(0,cr.unlinkSync)(c),b.debug("CLAUDE_MD",`${t?"[DRY-RUN] Would delete":"Deleted"} (empty): ${u}`),s++):(t||(0,cr.writeFileSync)(c,d),b.debug("CLAUDE_MD",`${t?"[DRY-RUN] Would clean":"Cleaned"}: ${u}`),o++)}catch(l){b.warn("CLAUDE_MD",`Error processing ${u}`,{error:String(l)}),a++}}return b.info("CLAUDE_MD","CLAUDE.md cleanup complete",{deleted:s,cleaned:o,errors:a,dryRun:t}),0}catch(r){return b.error("CLAUDE_MD","Fatal error during CLAUDE.md cleanup",{error:String(r)}),1}}var J5,ar,WI,cr,X5,K5,mSe,hSe,KI=Oe(()=>{"use strict";J5=require("bun:sqlite"),ar=Me(require("path"),1),WI=Me(require("os"),1),cr=require("fs"),X5=require("child_process");rr();ga();e$();ne();K5=ar.default.join(WI.default.homedir(),".claude-mem","claude-mem.db"),mSe=ar.default.join(WI.default.homedir(),".claude-mem","settings.json"),hSe={bugfix:"\u{1F534}",feature:"\u{1F7E3}",refactor:"\u{1F504}",change:"\u2705",discovery:"\u{1F535}",decision:"\u2696\uFE0F",session:"\u{1F3AF}",prompt:"\u{1F4AC}"}});var NSe={};_n(NSe,{WorkerService:()=>d_,buildStatusOutput:()=>eH,isPluginDisabledInClaudeSettings:()=>sg});module.exports=zf(NSe);var JI=Me(require("path"),1),ns=require("fs");var Ye;(function(t){t.assertEqual=i=>{};function e(i){}t.assertIs=e;function r(i){throw new Error}t.assertNever=r,t.arrayToEnum=i=>{let s={};for(let o of i)s[o]=o;return s},t.getValidEnumValues=i=>{let s=t.objectKeys(i).filter(a=>typeof i[i[a]]!="number"),o={};for(let a of s)o[a]=i[a];return t.objectValues(o)},t.objectValues=i=>t.objectKeys(i).map(function(s){return i[s]}),t.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let s=[];for(let o in i)Object.prototype.hasOwnProperty.call(i,o)&&s.push(o);return s},t.find=(i,s)=>{for(let o of i)if(s(o))return o},t.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function n(i,s=" | "){return i.map(o=>typeof o=="string"?`'${o}'`:o).join(s)}t.joinValues=n,t.jsonStringifyReplacer=(i,s)=>typeof s=="bigint"?s.toString():s})(Ye||(Ye={}));var tR;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(tR||(tR={}));var ie=Ye.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),is=t=>{switch(typeof t){case"undefined":return ie.undefined;case"string":return ie.string;case"number":return Number.isNaN(t)?ie.nan:ie.number;case"boolean":return ie.boolean;case"function":return ie.function;case"bigint":return ie.bigint;case"symbol":return ie.symbol;case"object":return Array.isArray(t)?ie.array:t===null?ie.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?ie.promise:typeof Map<"u"&&t instanceof Map?ie.map:typeof Set<"u"&&t instanceof Set?ie.set:typeof Date<"u"&&t instanceof Date?ie.date:ie.object;default:return ie.unknown}};var B=Ye.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 bn=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(s){return s.message},n={_errors:[]},i=s=>{for(let o of s.issues)if(o.code==="invalid_union")o.unionErrors.map(i);else if(o.code==="invalid_return_type")i(o.returnTypeError);else if(o.code==="invalid_arguments")i(o.argumentsError);else if(o.path.length===0)n._errors.push(r(o));else{let a=n,c=0;for(;cr.message){let r=Object.create(null),n=[];for(let i of this.issues)if(i.path.length>0){let s=i.path[0];r[s]=r[s]||[],r[s].push(e(i))}else n.push(e(i));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};bn.create=t=>new bn(t);var aH=(t,e)=>{let r;switch(t.code){case B.invalid_type:t.received===ie.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case B.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,Ye.jsonStringifyReplacer)}`;break;case B.unrecognized_keys:r=`Unrecognized key(s) in object: ${Ye.joinValues(t.keys,", ")}`;break;case B.invalid_union:r="Invalid input";break;case B.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${Ye.joinValues(t.options)}`;break;case B.invalid_enum_value:r=`Invalid enum value. Expected ${Ye.joinValues(t.options)}, received '${t.received}'`;break;case B.invalid_arguments:r="Invalid function arguments";break;case B.invalid_return_type:r="Invalid function return type";break;case B.invalid_date:r="Invalid date";break;case B.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:Ye.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case B.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case B.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case B.custom:r="Invalid input";break;case B.invalid_intersection_types:r="Intersection results could not be merged";break;case B.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case B.not_finite:r="Number must be finite";break;default:r=e.defaultError,Ye.assertNever(t)}return{message:r}},qs=aH;var cH=qs;function Qu(){return cH}var Lf=t=>{let{data:e,path:r,errorMaps:n,issueData:i}=t,s=[...r,...i.path||[]],o={...i,path:s};if(i.message!==void 0)return{...i,path:s,message:i.message};let a="",c=n.filter(u=>!!u).slice().reverse();for(let u of c)a=u(o,{data:e,defaultError:a}).message;return{...i,path:s,message:a}};function Q(t,e){let r=Qu(),n=Lf({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===qs?void 0:qs].filter(i=>!!i)});t.common.issues.push(n)}var Rr=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let i of r){if(i.status==="aborted")return xe;i.status==="dirty"&&e.dirty(),n.push(i.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let i of r){let s=await i.key,o=await i.value;n.push({key:s,value:o})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let i of r){let{key:s,value:o}=i;if(s.status==="aborted"||o.status==="aborted")return xe;s.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof o.value<"u"||i.alwaysSet)&&(n[s.value]=o.value)}return{status:e.value,value:n}}},xe=Object.freeze({status:"aborted"}),Ma=t=>({status:"dirty",value:t}),Hr=t=>({status:"valid",value:t}),m_=t=>t.status==="aborted",h_=t=>t.status==="dirty",Io=t=>t.status==="valid",el=t=>typeof Promise<"u"&&t instanceof Promise;var de;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(de||(de={}));var Mn=class{constructor(e,r,n,i){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=i}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},rR=(t,e)=>{if(Io(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new bn(t.common.issues);return this._error=r,this._error}}};function Pe(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:i}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:i}:{errorMap:(o,a)=>{let{message:c}=t;return o.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:o.code!=="invalid_type"?{message:a.defaultError}:{message:c??r??a.defaultError}},description:i}}var Fe=class{get description(){return this._def.description}_getType(e){return is(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:is(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Rr,ctx:{common:e.parent.common,data:e.data,parsedType:is(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(el(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:is(e)},i=this._parseSync({data:e,path:n.path,parent:n});return rR(n,i)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:is(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return Io(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>Io(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:is(e)},i=this._parse({data:e,path:n.path,parent:n}),s=await(el(i)?i:Promise.resolve(i));return rR(n,s)}refine(e,r){let n=i=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(i):r;return this._refinement((i,s)=>{let o=e(i),a=()=>s.addIssue({code:B.custom,...n(i)});return typeof Promise<"u"&&o instanceof Promise?o.then(c=>c?!0:(a(),!1)):o?!0:(a(),!1)})}refinement(e,r){return this._refinement((n,i)=>e(n)?!0:(i.addIssue(typeof r=="function"?r(n,i):r),!1))}_refinement(e){return new ii({schema:this,typeName:ye.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:r=>this["~validate"](r)}}optional(){return ni.create(this,this._def)}nullable(){return as.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Zs.create(this)}promise(){return Ro.create(this,this._def)}or(e){return Ua.create([this,e],this._def)}and(e){return Fa.create(this,e,this._def)}transform(e){return new ii({...Pe(this._def),schema:this,typeName:ye.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new Ga({...Pe(this._def),innerType:this,defaultValue:r,typeName:ye.ZodDefault})}brand(){return new Uf({typeName:ye.ZodBranded,type:this,...Pe(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Wa({...Pe(this._def),innerType:this,catchValue:r,typeName:ye.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return Ff.create(this,e)}readonly(){return Va.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},uH=/^c[^\s-]{8,}$/i,lH=/^[0-9a-z]+$/,dH=/^[0-9A-HJKMNP-TV-Z]{26}$/i,pH=/^[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,fH=/^[a-z0-9_-]{21}$/i,mH=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,hH=/^[-+]?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)?)??$/,gH=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,vH="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",g_,yH=/^(?:(?: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])$/,_H=/^(?:(?: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])$/,bH=/^(([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]))$/,SH=/^(([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])$/,xH=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,wH=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nR="((\\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])))",EH=new RegExp(`^${nR}$`);function iR(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function kH(t){return new RegExp(`^${iR(t)}$`)}function TH(t){let e=`${nR}T${iR(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function $H(t,e){return!!((e==="v4"||!e)&&yH.test(t)||(e==="v6"||!e)&&bH.test(t))}function IH(t,e){if(!mH.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),i=JSON.parse(atob(n));return!(typeof i!="object"||i===null||"typ"in i&&i?.typ!=="JWT"||!i.alg||e&&i.alg!==e)}catch{return!1}}function RH(t,e){return!!((e==="v4"||!e)&&_H.test(t)||(e==="v6"||!e)&&SH.test(t))}var ja=class t extends Fe{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==ie.string){let s=this._getOrReturnCtx(e);return Q(s,{code:B.invalid_type,expected:ie.string,received:s.parsedType}),xe}let n=new Rr,i;for(let s of this._def.checks)if(s.kind==="min")e.data.lengths.value&&(i=this._getOrReturnCtx(e,i),Q(i,{code:B.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){let o=e.data.length>s.value,a=e.data.lengthe.test(i),{validation:r,code:B.invalid_string,...de.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...de.errToObj(e)})}url(e){return this._addCheck({kind:"url",...de.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...de.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...de.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...de.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...de.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...de.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...de.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...de.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...de.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...de.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...de.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...de.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,...de.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,...de.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...de.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...de.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...de.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...de.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...de.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...de.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...de.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...de.errToObj(r)})}nonempty(e){return this.min(1,de.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...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 r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.valuenew ja({checks:[],typeName:ye.ZodString,coerce:t?.coerce??!1,...Pe(t)});function OH(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,i=r>n?r:n,s=Number.parseInt(t.toFixed(i).replace(".","")),o=Number.parseInt(e.toFixed(i).replace(".",""));return s%o/10**i}var tl=class t extends Fe{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)!==ie.number){let s=this._getOrReturnCtx(e);return Q(s,{code:B.invalid_type,expected:ie.number,received:s.parsedType}),xe}let n,i=new Rr;for(let s of this._def.checks)s.kind==="int"?Ye.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),Q(n,{code:B.invalid_type,expected:"integer",received:"float",message:s.message}),i.dirty()):s.kind==="min"?(s.inclusive?e.datas.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),Q(n,{code:B.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),i.dirty()):s.kind==="multipleOf"?OH(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),Q(n,{code:B.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),Q(n,{code:B.not_finite,message:s.message}),i.dirty()):Ye.assertNever(s);return{status:i.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,de.toString(r))}gt(e,r){return this.setLimit("min",e,!1,de.toString(r))}lte(e,r){return this.setLimit("max",e,!0,de.toString(r))}lt(e,r){return this.setLimit("max",e,!1,de.toString(r))}setLimit(e,r,n,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:de.toString(i)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:de.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:de.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:de.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:de.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:de.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:de.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:de.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:de.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:de.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.valuee.kind==="int"||e.kind==="multipleOf"&&Ye.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.valuenew tl({checks:[],typeName:ye.ZodNumber,coerce:t?.coerce||!1,...Pe(t)});var rl=class t extends Fe{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)!==ie.bigint)return this._getInvalidInput(e);let n,i=new Rr;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?e.datas.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),Q(n,{code:B.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),i.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),Q(n,{code:B.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):Ye.assertNever(s);return{status:i.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return Q(r,{code:B.invalid_type,expected:ie.bigint,received:r.parsedType}),xe}gte(e,r){return this.setLimit("min",e,!0,de.toString(r))}gt(e,r){return this.setLimit("min",e,!1,de.toString(r))}lte(e,r){return this.setLimit("max",e,!0,de.toString(r))}lt(e,r){return this.setLimit("max",e,!1,de.toString(r))}setLimit(e,r,n,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:de.toString(i)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:de.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:de.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:de.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:de.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:de.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.valuenew rl({checks:[],typeName:ye.ZodBigInt,coerce:t?.coerce??!1,...Pe(t)});var nl=class extends Fe{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==ie.boolean){let n=this._getOrReturnCtx(e);return Q(n,{code:B.invalid_type,expected:ie.boolean,received:n.parsedType}),xe}return Hr(e.data)}};nl.create=t=>new nl({typeName:ye.ZodBoolean,coerce:t?.coerce||!1,...Pe(t)});var il=class t extends Fe{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==ie.date){let s=this._getOrReturnCtx(e);return Q(s,{code:B.invalid_type,expected:ie.date,received:s.parsedType}),xe}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return Q(s,{code:B.invalid_date}),xe}let n=new Rr,i;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()s.value&&(i=this._getOrReturnCtx(e,i),Q(i,{code:B.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):Ye.assertNever(s);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:de.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:de.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.valuenew il({checks:[],coerce:t?.coerce||!1,typeName:ye.ZodDate,...Pe(t)});var sl=class extends Fe{_parse(e){if(this._getType(e)!==ie.symbol){let n=this._getOrReturnCtx(e);return Q(n,{code:B.invalid_type,expected:ie.symbol,received:n.parsedType}),xe}return Hr(e.data)}};sl.create=t=>new sl({typeName:ye.ZodSymbol,...Pe(t)});var za=class extends Fe{_parse(e){if(this._getType(e)!==ie.undefined){let n=this._getOrReturnCtx(e);return Q(n,{code:B.invalid_type,expected:ie.undefined,received:n.parsedType}),xe}return Hr(e.data)}};za.create=t=>new za({typeName:ye.ZodUndefined,...Pe(t)});var La=class extends Fe{_parse(e){if(this._getType(e)!==ie.null){let n=this._getOrReturnCtx(e);return Q(n,{code:B.invalid_type,expected:ie.null,received:n.parsedType}),xe}return Hr(e.data)}};La.create=t=>new La({typeName:ye.ZodNull,...Pe(t)});var ol=class extends Fe{constructor(){super(...arguments),this._any=!0}_parse(e){return Hr(e.data)}};ol.create=t=>new ol({typeName:ye.ZodAny,...Pe(t)});var Hs=class extends Fe{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Hr(e.data)}};Hs.create=t=>new Hs({typeName:ye.ZodUnknown,...Pe(t)});var Oi=class extends Fe{_parse(e){let r=this._getOrReturnCtx(e);return Q(r,{code:B.invalid_type,expected:ie.never,received:r.parsedType}),xe}};Oi.create=t=>new Oi({typeName:ye.ZodNever,...Pe(t)});var al=class extends Fe{_parse(e){if(this._getType(e)!==ie.undefined){let n=this._getOrReturnCtx(e);return Q(n,{code:B.invalid_type,expected:ie.void,received:n.parsedType}),xe}return Hr(e.data)}};al.create=t=>new al({typeName:ye.ZodVoid,...Pe(t)});var Zs=class t extends Fe{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),i=this._def;if(r.parsedType!==ie.array)return Q(r,{code:B.invalid_type,expected:ie.array,received:r.parsedType}),xe;if(i.exactLength!==null){let o=r.data.length>i.exactLength.value,a=r.data.lengthi.maxLength.value&&(Q(r,{code:B.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((o,a)=>i.type._parseAsync(new Mn(r,o,r.path,a)))).then(o=>Rr.mergeArray(n,o));let s=[...r.data].map((o,a)=>i.type._parseSync(new Mn(r,o,r.path,a)));return Rr.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:de.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:de.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:de.toString(r)}})}nonempty(e){return this.min(1,e)}};Zs.create=(t,e)=>new Zs({type:t,minLength:null,maxLength:null,exactLength:null,typeName:ye.ZodArray,...Pe(e)});function Da(t){if(t instanceof Sn){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=ni.create(Da(n))}return new Sn({...t._def,shape:()=>e})}else return t instanceof Zs?new Zs({...t._def,type:Da(t.element)}):t instanceof ni?ni.create(Da(t.unwrap())):t instanceof as?as.create(Da(t.unwrap())):t instanceof os?os.create(t.items.map(e=>Da(e))):t}var Sn=class t extends Fe{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(),r=Ye.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==ie.object){let u=this._getOrReturnCtx(e);return Q(u,{code:B.invalid_type,expected:ie.object,received:u.parsedType}),xe}let{status:n,ctx:i}=this._processInputParams(e),{shape:s,keys:o}=this._getCached(),a=[];if(!(this._def.catchall instanceof Oi&&this._def.unknownKeys==="strip"))for(let u in i.data)o.includes(u)||a.push(u);let c=[];for(let u of o){let l=s[u],d=i.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new Mn(i,d,i.path,u)),alwaysSet:u in i.data})}if(this._def.catchall instanceof Oi){let u=this._def.unknownKeys;if(u==="passthrough")for(let l of a)c.push({key:{status:"valid",value:l},value:{status:"valid",value:i.data[l]}});else if(u==="strict")a.length>0&&(Q(i,{code:B.unrecognized_keys,keys:a}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let l of a){let d=i.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new Mn(i,d,i.path,l)),alwaysSet:l in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let u=[];for(let l of c){let d=await l.key,p=await l.value;u.push({key:d,value:p,alwaysSet:l.alwaysSet})}return u}).then(u=>Rr.mergeObjectSync(n,u)):Rr.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return de.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let i=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:de.errToObj(e).message??i}:{message:i}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:ye.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let n of Ye.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let n of Ye.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return Da(this)}partial(e){let r={};for(let n of Ye.objectKeys(this.shape)){let i=this.shape[n];e&&!e[n]?r[n]=i:r[n]=i.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of Ye.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof ni;)s=s._def.innerType;r[n]=s}return new t({...this._def,shape:()=>r})}keyof(){return sR(Ye.objectKeys(this.shape))}};Sn.create=(t,e)=>new Sn({shape:()=>t,unknownKeys:"strip",catchall:Oi.create(),typeName:ye.ZodObject,...Pe(e)});Sn.strictCreate=(t,e)=>new Sn({shape:()=>t,unknownKeys:"strict",catchall:Oi.create(),typeName:ye.ZodObject,...Pe(e)});Sn.lazycreate=(t,e)=>new Sn({shape:t,unknownKeys:"strip",catchall:Oi.create(),typeName:ye.ZodObject,...Pe(e)});var Ua=class extends Fe{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function i(s){for(let a of s)if(a.result.status==="valid")return a.result;for(let a of s)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let o=s.map(a=>new bn(a.ctx.common.issues));return Q(r,{code:B.invalid_union,unionErrors:o}),xe}if(r.common.async)return Promise.all(n.map(async s=>{let o={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:o}),ctx:o}})).then(i);{let s,o=[];for(let c of n){let u={...r,common:{...r.common,issues:[]},parent:null},l=c._parseSync({data:r.data,path:r.path,parent:u});if(l.status==="valid")return l;l.status==="dirty"&&!s&&(s={result:l,ctx:u}),u.common.issues.length&&o.push(u.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;let a=o.map(c=>new bn(c));return Q(r,{code:B.invalid_union,unionErrors:a}),xe}}get options(){return this._def.options}};Ua.create=(t,e)=>new Ua({options:t,typeName:ye.ZodUnion,...Pe(e)});var ss=t=>t instanceof qa?ss(t.schema):t instanceof ii?ss(t.innerType()):t instanceof Ha?[t.value]:t instanceof Za?t.options:t instanceof Ba?Ye.objectValues(t.enum):t instanceof Ga?ss(t._def.innerType):t instanceof za?[void 0]:t instanceof La?[null]:t instanceof ni?[void 0,...ss(t.unwrap())]:t instanceof as?[null,...ss(t.unwrap())]:t instanceof Uf||t instanceof Va?ss(t.unwrap()):t instanceof Wa?ss(t._def.innerType):[],v_=class t extends Fe{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==ie.object)return Q(r,{code:B.invalid_type,expected:ie.object,received:r.parsedType}),xe;let n=this.discriminator,i=r.data[n],s=this.optionsMap.get(i);return s?r.common.async?s._parseAsync({data:r.data,path:r.path,parent:r}):s._parseSync({data:r.data,path:r.path,parent:r}):(Q(r,{code:B.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),xe)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let i=new Map;for(let s of r){let o=ss(s.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(i.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);i.set(a,s)}}return new t({typeName:ye.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:i,...Pe(n)})}};function y_(t,e){let r=is(t),n=is(e);if(t===e)return{valid:!0,data:t};if(r===ie.object&&n===ie.object){let i=Ye.objectKeys(e),s=Ye.objectKeys(t).filter(a=>i.indexOf(a)!==-1),o={...t,...e};for(let a of s){let c=y_(t[a],e[a]);if(!c.valid)return{valid:!1};o[a]=c.data}return{valid:!0,data:o}}else if(r===ie.array&&n===ie.array){if(t.length!==e.length)return{valid:!1};let i=[];for(let s=0;s{if(m_(s)||m_(o))return xe;let a=y_(s.value,o.value);return a.valid?((h_(s)||h_(o))&&r.dirty(),{status:r.value,value:a.data}):(Q(n,{code:B.invalid_intersection_types}),xe)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([s,o])=>i(s,o)):i(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};Fa.create=(t,e,r)=>new Fa({left:t,right:e,typeName:ye.ZodIntersection,...Pe(r)});var os=class t extends Fe{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==ie.array)return Q(n,{code:B.invalid_type,expected:ie.array,received:n.parsedType}),xe;if(n.data.lengththis._def.items.length&&(Q(n,{code:B.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let s=[...n.data].map((o,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new Mn(n,o,n.path,a)):null}).filter(o=>!!o);return n.common.async?Promise.all(s).then(o=>Rr.mergeArray(r,o)):Rr.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};os.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new os({items:t,typeName:ye.ZodTuple,rest:null,...Pe(e)})};var __=class t extends Fe{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==ie.object)return Q(n,{code:B.invalid_type,expected:ie.object,received:n.parsedType}),xe;let i=[],s=this._def.keyType,o=this._def.valueType;for(let a in n.data)i.push({key:s._parse(new Mn(n,a,n.path,a)),value:o._parse(new Mn(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?Rr.mergeObjectAsync(r,i):Rr.mergeObjectSync(r,i)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof Fe?new t({keyType:e,valueType:r,typeName:ye.ZodRecord,...Pe(n)}):new t({keyType:ja.create(),valueType:e,typeName:ye.ZodRecord,...Pe(r)})}},cl=class extends Fe{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==ie.map)return Q(n,{code:B.invalid_type,expected:ie.map,received:n.parsedType}),xe;let i=this._def.keyType,s=this._def.valueType,o=[...n.data.entries()].map(([a,c],u)=>({key:i._parse(new Mn(n,a,n.path,[u,"key"])),value:s._parse(new Mn(n,c,n.path,[u,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of o){let u=await c.key,l=await c.value;if(u.status==="aborted"||l.status==="aborted")return xe;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let c of o){let u=c.key,l=c.value;if(u.status==="aborted"||l.status==="aborted")return xe;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}}}};cl.create=(t,e,r)=>new cl({valueType:e,keyType:t,typeName:ye.ZodMap,...Pe(r)});var ul=class t extends Fe{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==ie.set)return Q(n,{code:B.invalid_type,expected:ie.set,received:n.parsedType}),xe;let i=this._def;i.minSize!==null&&n.data.sizei.maxSize.value&&(Q(n,{code:B.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),r.dirty());let s=this._def.valueType;function o(c){let u=new Set;for(let l of c){if(l.status==="aborted")return xe;l.status==="dirty"&&r.dirty(),u.add(l.value)}return{status:r.value,value:u}}let a=[...n.data.values()].map((c,u)=>s._parse(new Mn(n,c,n.path,u)));return n.common.async?Promise.all(a).then(c=>o(c)):o(a)}min(e,r){return new t({...this._def,minSize:{value:e,message:de.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:de.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};ul.create=(t,e)=>new ul({valueType:t,minSize:null,maxSize:null,typeName:ye.ZodSet,...Pe(e)});var b_=class t extends Fe{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==ie.function)return Q(r,{code:B.invalid_type,expected:ie.function,received:r.parsedType}),xe;function n(a,c){return Lf({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Qu(),qs].filter(u=>!!u),issueData:{code:B.invalid_arguments,argumentsError:c}})}function i(a,c){return Lf({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Qu(),qs].filter(u=>!!u),issueData:{code:B.invalid_return_type,returnTypeError:c}})}let s={errorMap:r.common.contextualErrorMap},o=r.data;if(this._def.returns instanceof Ro){let a=this;return Hr(async function(...c){let u=new bn([]),l=await a._def.args.parseAsync(c,s).catch(f=>{throw u.addIssue(n(c,f)),u}),d=await Reflect.apply(o,this,l);return await a._def.returns._def.type.parseAsync(d,s).catch(f=>{throw u.addIssue(i(d,f)),u})})}else{let a=this;return Hr(function(...c){let u=a._def.args.safeParse(c,s);if(!u.success)throw new bn([n(c,u.error)]);let l=Reflect.apply(o,this,u.data),d=a._def.returns.safeParse(l,s);if(!d.success)throw new bn([i(l,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:os.create(e).rest(Hs.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new t({args:e||os.create([]).rest(Hs.create()),returns:r||Hs.create(),typeName:ye.ZodFunction,...Pe(n)})}},qa=class extends Fe{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};qa.create=(t,e)=>new qa({getter:t,typeName:ye.ZodLazy,...Pe(e)});var Ha=class extends Fe{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return Q(r,{received:r.data,code:B.invalid_literal,expected:this._def.value}),xe}return{status:"valid",value:e.data}}get value(){return this._def.value}};Ha.create=(t,e)=>new Ha({value:t,typeName:ye.ZodLiteral,...Pe(e)});function sR(t,e){return new Za({values:t,typeName:ye.ZodEnum,...Pe(e)})}var Za=class t extends Fe{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return Q(r,{expected:Ye.joinValues(n),received:r.parsedType,code:B.invalid_type}),xe}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return Q(r,{received:r.data,code:B.invalid_enum_value,options:n}),xe}return Hr(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};Za.create=sR;var Ba=class extends Fe{_parse(e){let r=Ye.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==ie.string&&n.parsedType!==ie.number){let i=Ye.objectValues(r);return Q(n,{expected:Ye.joinValues(i),received:n.parsedType,code:B.invalid_type}),xe}if(this._cache||(this._cache=new Set(Ye.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let i=Ye.objectValues(r);return Q(n,{received:n.data,code:B.invalid_enum_value,options:i}),xe}return Hr(e.data)}get enum(){return this._def.values}};Ba.create=(t,e)=>new Ba({values:t,typeName:ye.ZodNativeEnum,...Pe(e)});var Ro=class extends Fe{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==ie.promise&&r.common.async===!1)return Q(r,{code:B.invalid_type,expected:ie.promise,received:r.parsedType}),xe;let n=r.parsedType===ie.promise?r.data:Promise.resolve(r.data);return Hr(n.then(i=>this._def.type.parseAsync(i,{path:r.path,errorMap:r.common.contextualErrorMap})))}};Ro.create=(t,e)=>new Ro({type:t,typeName:ye.ZodPromise,...Pe(e)});var ii=class extends Fe{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ye.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),i=this._def.effect||null,s={addIssue:o=>{Q(n,o),o.fatal?r.abort():r.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),i.type==="preprocess"){let o=i.transform(n.data,s);if(n.common.async)return Promise.resolve(o).then(async a=>{if(r.value==="aborted")return xe;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?xe:c.status==="dirty"?Ma(c.value):r.value==="dirty"?Ma(c.value):c});{if(r.value==="aborted")return xe;let a=this._def.schema._parseSync({data:o,path:n.path,parent:n});return a.status==="aborted"?xe:a.status==="dirty"?Ma(a.value):r.value==="dirty"?Ma(a.value):a}}if(i.type==="refinement"){let o=a=>{let c=i.refinement(a,s);if(n.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(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?xe:(a.status==="dirty"&&r.dirty(),o(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?xe:(a.status==="dirty"&&r.dirty(),o(a.value).then(()=>({status:r.value,value:a.value}))))}if(i.type==="transform")if(n.common.async===!1){let o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Io(o))return xe;let a=i.transform(o.value,s);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>Io(o)?Promise.resolve(i.transform(o.value,s)).then(a=>({status:r.value,value:a})):xe);Ye.assertNever(i)}};ii.create=(t,e,r)=>new ii({schema:t,typeName:ye.ZodEffects,effect:e,...Pe(r)});ii.createWithPreprocess=(t,e,r)=>new ii({schema:e,effect:{type:"preprocess",transform:t},typeName:ye.ZodEffects,...Pe(r)});var ni=class extends Fe{_parse(e){return this._getType(e)===ie.undefined?Hr(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ni.create=(t,e)=>new ni({innerType:t,typeName:ye.ZodOptional,...Pe(e)});var as=class extends Fe{_parse(e){return this._getType(e)===ie.null?Hr(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};as.create=(t,e)=>new as({innerType:t,typeName:ye.ZodNullable,...Pe(e)});var Ga=class extends Fe{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===ie.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};Ga.create=(t,e)=>new Ga({innerType:t,typeName:ye.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...Pe(e)});var Wa=class extends Fe{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},i=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return el(i)?i.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new bn(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new bn(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Wa.create=(t,e)=>new Wa({innerType:t,typeName:ye.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...Pe(e)});var ll=class extends Fe{_parse(e){if(this._getType(e)!==ie.nan){let n=this._getOrReturnCtx(e);return Q(n,{code:B.invalid_type,expected:ie.nan,received:n.parsedType}),xe}return{status:"valid",value:e.data}}};ll.create=t=>new ll({typeName:ye.ZodNaN,...Pe(t)});var Uf=class extends Fe{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},Ff=class t extends Fe{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?xe:s.status==="dirty"?(r.dirty(),Ma(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{let i=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?xe:i.status==="dirty"?(r.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:ye.ZodPipeline})}},Va=class extends Fe{_parse(e){let r=this._def.innerType._parse(e),n=i=>(Io(i)&&(i.value=Object.freeze(i.value)),i);return el(r)?r.then(i=>n(i)):n(r)}unwrap(){return this._def.innerType}};Va.create=(t,e)=>new Va({innerType:t,typeName:ye.ZodReadonly,...Pe(e)});var exe={object:Sn.lazycreate},ye;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(ye||(ye={}));var txe=ja.create,rxe=tl.create,nxe=ll.create,ixe=rl.create,sxe=nl.create,oxe=il.create,axe=sl.create,cxe=za.create,uxe=La.create,lxe=ol.create,dxe=Hs.create,pxe=Oi.create,fxe=al.create,mxe=Zs.create,CH=Sn.create,hxe=Sn.strictCreate,gxe=Ua.create,vxe=v_.create,yxe=Fa.create,_xe=os.create,bxe=__.create,Sxe=cl.create,xxe=ul.create,wxe=b_.create,Exe=qa.create,kxe=Ha.create,Txe=Za.create,$xe=Ba.create,Ixe=Ro.create,Rxe=ii.create,Oxe=ni.create,Cxe=as.create,Pxe=ii.createWithPreprocess,Axe=Ff.create;var oR=Object.freeze({status:"aborted"});function O(t,e,r){function n(a,c){if(a._zod||Object.defineProperty(a,"_zod",{value:{def:c,constr:o,traits:new Set},enumerable:!1}),a._zod.traits.has(t))return;a._zod.traits.add(t),e(a,c);let u=o.prototype,l=Object.keys(u);for(let d=0;dr?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(o,"name",{value:t}),o}var Ci=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Oo=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}},qf={};function tr(t){return t&&Object.assign(qf,t),qf}var G={};_n(G,{BIGINT_FORMAT_RANGES:()=>R_,Class:()=>x_,NUMBER_FORMAT_RANGES:()=>I_,aborted:()=>Vs,allowsEval:()=>k_,assert:()=>zH,assertEqual:()=>NH,assertIs:()=>DH,assertNever:()=>jH,assertNotEqual:()=>MH,assignProp:()=>Gs,base64ToUint8Array:()=>uR,base64urlToUint8Array:()=>t3,cached:()=>Ja,captureStackTrace:()=>Zf,cleanEnum:()=>e3,cleanRegex:()=>fl,clone:()=>Zr,cloneDef:()=>UH,createTransparentProxy:()=>GH,defineLazy:()=>Le,esc:()=>Hf,escapeRegex:()=>Dn,extend:()=>KH,finalizeIssue:()=>on,floatSafeRemainder:()=>w_,getElementAtPath:()=>FH,getEnumValues:()=>pl,getLengthableOrigin:()=>gl,getParsedType:()=>BH,getSizableOrigin:()=>hl,hexToUint8Array:()=>n3,isObject:()=>Co,isPlainObject:()=>Ws,issue:()=>Xa,joinValues:()=>_e,jsonStringifyReplacer:()=>Ka,merge:()=>XH,mergeDefs:()=>cs,normalizeParams:()=>ee,nullish:()=>Bs,numKeys:()=>ZH,objectClone:()=>LH,omit:()=>VH,optionalKeys:()=>$_,parsedType:()=>we,partial:()=>YH,pick:()=>WH,prefixIssues:()=>xn,primitiveTypes:()=>T_,promiseAllObject:()=>qH,propertyKeyTypes:()=>ml,randomString:()=>HH,required:()=>QH,safeExtend:()=>JH,shallowClone:()=>cR,slugify:()=>E_,stringifyPrimitive:()=>be,uint8ArrayToBase64:()=>lR,uint8ArrayToBase64url:()=>r3,uint8ArrayToHex:()=>i3,unwrapMessage:()=>dl});function NH(t){return t}function MH(t){return t}function DH(t){}function jH(t){throw new Error("Unexpected value in exhaustive check")}function zH(t){}function pl(t){let e=Object.values(t).filter(n=>typeof n=="number");return Object.entries(t).filter(([n,i])=>e.indexOf(+n)===-1).map(([n,i])=>i)}function _e(t,e="|"){return t.map(r=>be(r)).join(e)}function Ka(t,e){return typeof e=="bigint"?e.toString():e}function Ja(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Bs(t){return t==null}function fl(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function w_(t,e){let r=(t.toString().split(".")[1]||"").length,n=e.toString(),i=(n.split(".")[1]||"").length;if(i===0&&/\d?e-\d?/.test(n)){let c=n.match(/\d?e-(\d?)/);c?.[1]&&(i=Number.parseInt(c[1]))}let s=r>i?r:i,o=Number.parseInt(t.toFixed(s).replace(".","")),a=Number.parseInt(e.toFixed(s).replace(".",""));return o%a/10**s}var aR=Symbol("evaluating");function Le(t,e,r){let n;Object.defineProperty(t,e,{get(){if(n!==aR)return n===void 0&&(n=aR,n=r()),n},set(i){Object.defineProperty(t,e,{value:i})},configurable:!0})}function LH(t){return Object.create(Object.getPrototypeOf(t),Object.getOwnPropertyDescriptors(t))}function Gs(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function cs(...t){let e={};for(let r of t){let n=Object.getOwnPropertyDescriptors(r);Object.assign(e,n)}return Object.defineProperties({},e)}function UH(t){return cs(t._zod.def)}function FH(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function qH(t){let e=Object.keys(t),r=e.map(n=>t[n]);return Promise.all(r).then(n=>{let i={};for(let s=0;s{};function Co(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var k_=Ja(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});function Ws(t){if(Co(t)===!1)return!1;let e=t.constructor;if(e===void 0||typeof e!="function")return!0;let r=e.prototype;return!(Co(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function cR(t){return Ws(t)?{...t}:Array.isArray(t)?[...t]:t}function ZH(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}var BH=t=>{let e=typeof t;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(t)?"array":t===null?"null":t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?"promise":typeof Map<"u"&&t instanceof Map?"map":typeof Set<"u"&&t instanceof Set?"set":typeof Date<"u"&&t instanceof Date?"date":typeof File<"u"&&t instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},ml=new Set(["string","number","symbol"]),T_=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Dn(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Zr(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function ee(t){let e=t;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 GH(t){let e;return new Proxy({},{get(r,n,i){return e??(e=t()),Reflect.get(e,n,i)},set(r,n,i,s){return e??(e=t()),Reflect.set(e,n,i,s)},has(r,n){return e??(e=t()),Reflect.has(e,n)},deleteProperty(r,n){return e??(e=t()),Reflect.deleteProperty(e,n)},ownKeys(r){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(r,n){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,n)},defineProperty(r,n,i){return e??(e=t()),Reflect.defineProperty(e,n,i)}})}function be(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function $_(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}var I_={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]},R_={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function WH(t,e){let r=t._zod.def,n=r.checks;if(n&&n.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");let s=cs(t._zod.def,{get shape(){let o={};for(let a in e){if(!(a in r.shape))throw new Error(`Unrecognized key: "${a}"`);e[a]&&(o[a]=r.shape[a])}return Gs(this,"shape",o),o},checks:[]});return Zr(t,s)}function VH(t,e){let r=t._zod.def,n=r.checks;if(n&&n.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");let s=cs(t._zod.def,{get shape(){let o={...t._zod.def.shape};for(let a in e){if(!(a in r.shape))throw new Error(`Unrecognized key: "${a}"`);e[a]&&delete o[a]}return Gs(this,"shape",o),o},checks:[]});return Zr(t,s)}function KH(t,e){if(!Ws(e))throw new Error("Invalid input to extend: expected a plain object");let r=t._zod.def.checks;if(r&&r.length>0){let s=t._zod.def.shape;for(let o in e)if(Object.getOwnPropertyDescriptor(s,o)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let i=cs(t._zod.def,{get shape(){let s={...t._zod.def.shape,...e};return Gs(this,"shape",s),s}});return Zr(t,i)}function JH(t,e){if(!Ws(e))throw new Error("Invalid input to safeExtend: expected a plain object");let r=cs(t._zod.def,{get shape(){let n={...t._zod.def.shape,...e};return Gs(this,"shape",n),n}});return Zr(t,r)}function XH(t,e){let r=cs(t._zod.def,{get shape(){let n={...t._zod.def.shape,...e._zod.def.shape};return Gs(this,"shape",n),n},get catchall(){return e._zod.def.catchall},checks:[]});return Zr(t,r)}function YH(t,e,r){let i=e._zod.def.checks;if(i&&i.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");let o=cs(e._zod.def,{get shape(){let a=e._zod.def.shape,c={...a};if(r)for(let u in r){if(!(u in a))throw new Error(`Unrecognized key: "${u}"`);r[u]&&(c[u]=t?new t({type:"optional",innerType:a[u]}):a[u])}else for(let u in a)c[u]=t?new t({type:"optional",innerType:a[u]}):a[u];return Gs(this,"shape",c),c},checks:[]});return Zr(e,o)}function QH(t,e,r){let n=cs(e._zod.def,{get shape(){let i=e._zod.def.shape,s={...i};if(r)for(let o in r){if(!(o in s))throw new Error(`Unrecognized key: "${o}"`);r[o]&&(s[o]=new t({type:"nonoptional",innerType:i[o]}))}else for(let o in i)s[o]=new t({type:"nonoptional",innerType:i[o]});return Gs(this,"shape",s),s}});return Zr(e,n)}function Vs(t,e=0){if(t.aborted===!0)return!0;for(let r=e;r{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function dl(t){return typeof t=="string"?t:t?.message}function on(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let i=dl(t.inst?._zod.def?.error?.(t))??dl(e?.error?.(t))??dl(r.customError?.(t))??dl(r.localeError?.(t))??"Invalid input";n.message=i}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function hl(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function gl(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function we(t){let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"nan":"number";case"object":{if(t===null)return"null";if(Array.isArray(t))return"array";let r=t;if(r&&Object.getPrototypeOf(r)!==Object.prototype&&"constructor"in r&&r.constructor)return r.constructor.name}}return e}function Xa(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function e3(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}function uR(t){let e=atob(t),r=new Uint8Array(e.length);for(let n=0;ne.toString(16).padStart(2,"0")).join("")}var x_=class{constructor(...e){}};var dR=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),t.message=JSON.stringify(e,Ka,2),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Bf=O("$ZodError",dR),vl=O("$ZodError",dR,{Parent:Error});function Gf(t,e=r=>r.message){let r={},n=[];for(let i of t.issues)i.path.length>0?(r[i.path[0]]=r[i.path[0]]||[],r[i.path[0]].push(e(i))):n.push(e(i));return{formErrors:n,fieldErrors:r}}function Wf(t,e=r=>r.message){let r={_errors:[]},n=i=>{for(let s of i.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map(o=>n({issues:o}));else if(s.code==="invalid_key")n({issues:s.issues});else if(s.code==="invalid_element")n({issues:s.issues});else if(s.path.length===0)r._errors.push(e(s));else{let o=r,a=0;for(;a(e,r,n,i)=>{let s=n?Object.assign(n,{async:!1}):{async:!1},o=e._zod.run({value:r,issues:[]},s);if(o instanceof Promise)throw new Ci;if(o.issues.length){let a=new(i?.Err??t)(o.issues.map(c=>on(c,s,tr())));throw Zf(a,i?.callee),a}return o.value},_l=yl(vl),bl=t=>async(e,r,n,i)=>{let s=n?Object.assign(n,{async:!0}):{async:!0},o=e._zod.run({value:r,issues:[]},s);if(o instanceof Promise&&(o=await o),o.issues.length){let a=new(i?.Err??t)(o.issues.map(c=>on(c,s,tr())));throw Zf(a,i?.callee),a}return o.value},Sl=bl(vl),xl=t=>(e,r,n)=>{let i=n?{...n,async:!1}:{async:!1},s=e._zod.run({value:r,issues:[]},i);if(s instanceof Promise)throw new Ci;return s.issues.length?{success:!1,error:new(t??Bf)(s.issues.map(o=>on(o,i,tr())))}:{success:!0,data:s.value}},Ya=xl(vl),wl=t=>async(e,r,n)=>{let i=n?Object.assign(n,{async:!0}):{async:!0},s=e._zod.run({value:r,issues:[]},i);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new t(s.issues.map(o=>on(o,i,tr())))}:{success:!0,data:s.value}},El=wl(vl),pR=t=>(e,r,n)=>{let i=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return yl(t)(e,r,i)};var fR=t=>(e,r,n)=>yl(t)(e,r,n);var mR=t=>async(e,r,n)=>{let i=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return bl(t)(e,r,i)};var hR=t=>async(e,r,n)=>bl(t)(e,r,n);var gR=t=>(e,r,n)=>{let i=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return xl(t)(e,r,i)};var vR=t=>(e,r,n)=>xl(t)(e,r,n);var yR=t=>async(e,r,n)=>{let i=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return wl(t)(e,r,i)};var _R=t=>async(e,r,n)=>wl(t)(e,r,n);var jn={};_n(jn,{base64:()=>B_,base64url:()=>Vf,bigint:()=>X_,boolean:()=>Q_,browserEmail:()=>f3,cidrv4:()=>H_,cidrv6:()=>Z_,cuid:()=>O_,cuid2:()=>C_,date:()=>W_,datetime:()=>K_,domain:()=>g3,duration:()=>D_,e164:()=>G_,email:()=>z_,emoji:()=>L_,extendedDuration:()=>o3,guid:()=>j_,hex:()=>v3,hostname:()=>h3,html5Email:()=>l3,idnEmail:()=>p3,integer:()=>Y_,ipv4:()=>U_,ipv6:()=>F_,ksuid:()=>N_,lowercase:()=>rb,mac:()=>q_,md5_base64:()=>_3,md5_base64url:()=>b3,md5_hex:()=>y3,nanoid:()=>M_,null:()=>eb,number:()=>Kf,rfc5322Email:()=>d3,sha1_base64:()=>x3,sha1_base64url:()=>w3,sha1_hex:()=>S3,sha256_base64:()=>k3,sha256_base64url:()=>T3,sha256_hex:()=>E3,sha384_base64:()=>I3,sha384_base64url:()=>R3,sha384_hex:()=>$3,sha512_base64:()=>C3,sha512_base64url:()=>P3,sha512_hex:()=>O3,string:()=>J_,time:()=>V_,ulid:()=>P_,undefined:()=>tb,unicodeEmail:()=>bR,uppercase:()=>nb,uuid:()=>Po,uuid4:()=>a3,uuid6:()=>c3,uuid7:()=>u3,xid:()=>A_});var O_=/^[cC][^\s-]{8,}$/,C_=/^[0-9a-z]+$/,P_=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,A_=/^[0-9a-vA-V]{20}$/,N_=/^[A-Za-z0-9]{27}$/,M_=/^[a-zA-Z0-9_-]{21}$/,D_=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,o3=/^[-+]?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)?)??$/,j_=/^([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})$/,Po=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[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|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,a3=Po(4),c3=Po(6),u3=Po(7),z_=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,l3=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,d3=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,bR=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,p3=bR,f3=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,m3="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function L_(){return new RegExp(m3,"u")}var U_=/^(?:(?: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])$/,F_=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,q_=t=>{let e=Dn(t??":");return new RegExp(`^(?:[0-9A-F]{2}${e}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${e}){5}[0-9a-f]{2}$`)},H_=/^((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])$/,Z_=/^(([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])$/,B_=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Vf=/^[A-Za-z0-9_-]*$/,h3=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,g3=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,G_=/^\+[1-9]\d{6,14}$/,SR="(?:(?:\\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])))",W_=new RegExp(`^${SR}$`);function xR(t){let e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function V_(t){return new RegExp(`^${xR(t)}$`)}function K_(t){let e=xR({precision:t.precision}),r=["Z"];t.local&&r.push(""),t.offset&&r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let n=`${e}(?:${r.join("|")})`;return new RegExp(`^${SR}T(?:${n})$`)}var J_=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},X_=/^-?\d+n?$/,Y_=/^-?\d+$/,Kf=/^-?\d+(?:\.\d+)?$/,Q_=/^(?:true|false)$/i,eb=/^null$/i;var tb=/^undefined$/i;var rb=/^[^A-Z]*$/,nb=/^[^a-z]*$/,v3=/^[0-9a-fA-F]*$/;function kl(t,e){return new RegExp(`^[A-Za-z0-9+/]{${t}}${e}$`)}function Tl(t){return new RegExp(`^[A-Za-z0-9_-]{${t}}$`)}var y3=/^[0-9a-fA-F]{32}$/,_3=kl(22,"=="),b3=Tl(22),S3=/^[0-9a-fA-F]{40}$/,x3=kl(27,"="),w3=Tl(27),E3=/^[0-9a-fA-F]{64}$/,k3=kl(43,"="),T3=Tl(43),$3=/^[0-9a-fA-F]{96}$/,I3=kl(64,""),R3=Tl(64),O3=/^[0-9a-fA-F]{128}$/,C3=kl(86,"=="),P3=Tl(86);var _t=O("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),ER={number:"number",bigint:"bigint",object:"date"},ib=O("$ZodCheckLessThan",(t,e)=>{_t.init(t,e);let r=ER[typeof e.value];t._zod.onattach.push(n=>{let i=n._zod.bag,s=(e.inclusive?i.maximum:i.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value{(e.inclusive?n.value<=e.value:n.value{_t.init(t,e);let r=ER[typeof e.value];t._zod.onattach.push(n=>{let i=n._zod.bag,s=(e.inclusive?i.minimum:i.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>s&&(e.inclusive?i.minimum=e.value:i.exclusiveMinimum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value>=e.value:n.value>e.value)||n.issues.push({origin:r,code:"too_small",minimum:typeof e.value=="object"?e.value.getTime():e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),kR=O("$ZodCheckMultipleOf",(t,e)=>{_t.init(t,e),t._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=e.value)}),t._zod.check=r=>{if(typeof r.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%e.value===BigInt(0):w_(r.value,e.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:e.value,input:r.value,inst:t,continue:!e.abort})}}),TR=O("$ZodCheckNumberFormat",(t,e)=>{_t.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[i,s]=I_[e.format];t._zod.onattach.push(o=>{let a=o._zod.bag;a.format=e.format,a.minimum=i,a.maximum=s,r&&(a.pattern=Y_)}),t._zod.check=o=>{let a=o.value;if(r){if(!Number.isInteger(a)){o.issues.push({expected:n,format:e.format,code:"invalid_type",continue:!1,input:a,inst:t});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:t,origin:n,inclusive:!0,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:t,origin:n,inclusive:!0,continue:!e.abort});return}}as&&o.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inclusive:!0,inst:t,continue:!e.abort})}}),$R=O("$ZodCheckBigIntFormat",(t,e)=>{_t.init(t,e);let[r,n]=R_[e.format];t._zod.onattach.push(i=>{let s=i._zod.bag;s.format=e.format,s.minimum=r,s.maximum=n}),t._zod.check=i=>{let s=i.value;sn&&i.issues.push({origin:"bigint",input:s,code:"too_big",maximum:n,inclusive:!0,inst:t,continue:!e.abort})}}),IR=O("$ZodCheckMaxSize",(t,e)=>{var r;_t.init(t,e),(r=t._zod.def).when??(r.when=n=>{let i=n.value;return!Bs(i)&&i.size!==void 0}),t._zod.onattach.push(n=>{let i=n._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum{let i=n.value;i.size<=e.maximum||n.issues.push({origin:hl(i),code:"too_big",maximum:e.maximum,inclusive:!0,input:i,inst:t,continue:!e.abort})}}),RR=O("$ZodCheckMinSize",(t,e)=>{var r;_t.init(t,e),(r=t._zod.def).when??(r.when=n=>{let i=n.value;return!Bs(i)&&i.size!==void 0}),t._zod.onattach.push(n=>{let i=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>i&&(n._zod.bag.minimum=e.minimum)}),t._zod.check=n=>{let i=n.value;i.size>=e.minimum||n.issues.push({origin:hl(i),code:"too_small",minimum:e.minimum,inclusive:!0,input:i,inst:t,continue:!e.abort})}}),OR=O("$ZodCheckSizeEquals",(t,e)=>{var r;_t.init(t,e),(r=t._zod.def).when??(r.when=n=>{let i=n.value;return!Bs(i)&&i.size!==void 0}),t._zod.onattach.push(n=>{let i=n._zod.bag;i.minimum=e.size,i.maximum=e.size,i.size=e.size}),t._zod.check=n=>{let i=n.value,s=i.size;if(s===e.size)return;let o=s>e.size;n.issues.push({origin:hl(i),...o?{code:"too_big",maximum:e.size}:{code:"too_small",minimum:e.size},inclusive:!0,exact:!0,input:n.value,inst:t,continue:!e.abort})}}),CR=O("$ZodCheckMaxLength",(t,e)=>{var r;_t.init(t,e),(r=t._zod.def).when??(r.when=n=>{let i=n.value;return!Bs(i)&&i.length!==void 0}),t._zod.onattach.push(n=>{let i=n._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum{let i=n.value;if(i.length<=e.maximum)return;let o=gl(i);n.issues.push({origin:o,code:"too_big",maximum:e.maximum,inclusive:!0,input:i,inst:t,continue:!e.abort})}}),PR=O("$ZodCheckMinLength",(t,e)=>{var r;_t.init(t,e),(r=t._zod.def).when??(r.when=n=>{let i=n.value;return!Bs(i)&&i.length!==void 0}),t._zod.onattach.push(n=>{let i=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>i&&(n._zod.bag.minimum=e.minimum)}),t._zod.check=n=>{let i=n.value;if(i.length>=e.minimum)return;let o=gl(i);n.issues.push({origin:o,code:"too_small",minimum:e.minimum,inclusive:!0,input:i,inst:t,continue:!e.abort})}}),AR=O("$ZodCheckLengthEquals",(t,e)=>{var r;_t.init(t,e),(r=t._zod.def).when??(r.when=n=>{let i=n.value;return!Bs(i)&&i.length!==void 0}),t._zod.onattach.push(n=>{let i=n._zod.bag;i.minimum=e.length,i.maximum=e.length,i.length=e.length}),t._zod.check=n=>{let i=n.value,s=i.length;if(s===e.length)return;let o=gl(i),a=s>e.length;n.issues.push({origin:o,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:n.value,inst:t,continue:!e.abort})}}),$l=O("$ZodCheckStringFormat",(t,e)=>{var r,n;_t.init(t,e),t._zod.onattach.push(i=>{let s=i._zod.bag;s.format=e.format,e.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(e.pattern))}),e.pattern?(r=t._zod).check??(r.check=i=>{e.pattern.lastIndex=0,!e.pattern.test(i.value)&&i.issues.push({origin:"string",code:"invalid_format",format:e.format,input:i.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(n=t._zod).check??(n.check=()=>{})}),NR=O("$ZodCheckRegex",(t,e)=>{$l.init(t,e),t._zod.check=r=>{e.pattern.lastIndex=0,!e.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),MR=O("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=rb),$l.init(t,e)}),DR=O("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=nb),$l.init(t,e)}),jR=O("$ZodCheckIncludes",(t,e)=>{_t.init(t,e);let r=Dn(e.includes),n=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=n,t._zod.onattach.push(i=>{let s=i._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),t._zod.check=i=>{i.value.includes(e.includes,e.position)||i.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:i.value,inst:t,continue:!e.abort})}}),zR=O("$ZodCheckStartsWith",(t,e)=>{_t.init(t,e);let r=new RegExp(`^${Dn(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let i=n._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(r)}),t._zod.check=n=>{n.value.startsWith(e.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:n.value,inst:t,continue:!e.abort})}}),LR=O("$ZodCheckEndsWith",(t,e)=>{_t.init(t,e);let r=new RegExp(`.*${Dn(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let i=n._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(r)}),t._zod.check=n=>{n.value.endsWith(e.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:n.value,inst:t,continue:!e.abort})}});function wR(t,e,r){t.issues.length&&e.issues.push(...xn(r,t.issues))}var UR=O("$ZodCheckProperty",(t,e)=>{_t.init(t,e),t._zod.check=r=>{let n=e.schema._zod.run({value:r.value[e.property],issues:[]},{});if(n instanceof Promise)return n.then(i=>wR(i,r,e.property));wR(n,r,e.property)}}),FR=O("$ZodCheckMimeType",(t,e)=>{_t.init(t,e);let r=new Set(e.mime);t._zod.onattach.push(n=>{n._zod.bag.mime=e.mime}),t._zod.check=n=>{r.has(n.value.type)||n.issues.push({code:"invalid_value",values:e.mime,input:n.value.type,inst:t,continue:!e.abort})}}),qR=O("$ZodCheckOverwrite",(t,e)=>{_t.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}});var Jf=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 n=e.split(` +${a}`}(0,cr.writeFileSync)(i,c),(0,cr.renameSync)(i,n)}function ESe(t,e,r,n,i,s,o){try{if(!(0,cr.existsSync)(e))return{success:!1,observationCount:0,error:"Folder no longer exists"};let a=ar.default.resolve(e),c=ar.default.resolve(s);if(!a.startsWith(c+ar.default.sep))return{success:!1,observationCount:0,error:"Path escapes project root"};let u=bSe(t,r,n,o);if(u.length===0)return{success:!1,observationCount:0,error:"No observations for folder"};if(i)return{success:!0,observationCount:u.length};let l=xSe(u,r);return wSe(e,l),{success:!0,observationCount:u.length}}catch(a){return{success:!1,observationCount:0,error:String(a)}}}async function kSe(t){try{let e=process.cwd(),r=Ee.loadFromFile(mSe),n=parseInt(r.CLAUDE_MEM_CONTEXT_OBSERVATIONS,10)||50;b.info("CLAUDE_MD","Starting CLAUDE.md generation",{workingDir:e,dryRun:t,observationLimit:n});let i=ar.default.basename(e),s=ySe(e);if(s.size===0)return b.info("CLAUDE_MD","No folders found in project"),0;if(b.info("CLAUDE_MD",`Found ${s.size} folders in project`),!(0,cr.existsSync)(K5))return b.info("CLAUDE_MD","Database not found, no observations to process"),0;let o=new J5.Database(K5,{readonly:!0,create:!1}),a=0,c=0,u=0,l=Array.from(s).sort();for(let d of l){let p=ar.default.relative(e,d),f=ESe(o,d,p,i,t,e,n);f.success?(b.debug("CLAUDE_MD",`Processed folder: ${p}`,{observationCount:f.observationCount}),a++):f.error?.includes("No observations")?c++:(b.warn("CLAUDE_MD",`Error processing folder: ${p}`,{error:f.error}),u++)}return o.close(),b.info("CLAUDE_MD","CLAUDE.md generation complete",{totalFolders:l.length,withObservations:a,noObservations:c,errors:u,dryRun:t}),0}catch(e){return b.error("CLAUDE_MD","Fatal error during CLAUDE.md generation",{error:String(e)}),1}}async function TSe(t){try{let i=function(c){let u=["node_modules",".git",".next","dist","build",".cache","__pycache__",".venv","venv",".idea",".vscode","coverage",".claude-mem",".open-next",".turbo"];try{let l=(0,cr.readdirSync)(c,{withFileTypes:!0});for(let d of l){let p=ar.default.join(c,d.name);if(d.isDirectory())u.includes(d.name)||i(p);else if(d.name==="CLAUDE.md")try{(0,cr.readFileSync)(p,"utf-8").includes("")&&n.push(p)}catch{}}}catch{}};var e=i;let r=process.cwd();b.info("CLAUDE_MD","Starting CLAUDE.md cleanup",{workingDir:r,dryRun:t});let n=[];if(i(r),n.length===0)return b.info("CLAUDE_MD","No CLAUDE.md files with auto-generated content found"),0;b.info("CLAUDE_MD",`Found ${n.length} CLAUDE.md files with auto-generated content`);let s=0,o=0,a=0;for(let c of n){let u=ar.default.relative(r,c);try{let d=(0,cr.readFileSync)(c,"utf-8").replace(/[\s\S]*?<\/claude-mem-context>/g,"").trim();d===""?(t||(0,cr.unlinkSync)(c),b.debug("CLAUDE_MD",`${t?"[DRY-RUN] Would delete":"Deleted"} (empty): ${u}`),s++):(t||(0,cr.writeFileSync)(c,d),b.debug("CLAUDE_MD",`${t?"[DRY-RUN] Would clean":"Cleaned"}: ${u}`),o++)}catch(l){b.warn("CLAUDE_MD",`Error processing ${u}`,{error:String(l)}),a++}}return b.info("CLAUDE_MD","CLAUDE.md cleanup complete",{deleted:s,cleaned:o,errors:a,dryRun:t}),0}catch(r){return b.error("CLAUDE_MD","Fatal error during CLAUDE.md cleanup",{error:String(r)}),1}}var J5,ar,WI,cr,X5,K5,mSe,hSe,KI=Oe(()=>{"use strict";J5=require("bun:sqlite"),ar=Me(require("path"),1),WI=Me(require("os"),1),cr=require("fs"),X5=require("child_process");rr();ga();e$();se();K5=ar.default.join(WI.default.homedir(),".claude-mem","claude-mem.db"),mSe=ar.default.join(WI.default.homedir(),".claude-mem","settings.json"),hSe={bugfix:"\u{1F534}",feature:"\u{1F7E3}",refactor:"\u{1F504}",change:"\u2705",discovery:"\u{1F535}",decision:"\u2696\uFE0F",session:"\u{1F3AF}",prompt:"\u{1F4AC}"}});var NSe={};_n(NSe,{WorkerService:()=>d_,buildStatusOutput:()=>eH,isPluginDisabledInClaudeSettings:()=>sg});module.exports=zf(NSe);var JI=Me(require("path"),1),ns=require("fs");var Ye;(function(t){t.assertEqual=i=>{};function e(i){}t.assertIs=e;function r(i){throw new Error}t.assertNever=r,t.arrayToEnum=i=>{let s={};for(let o of i)s[o]=o;return s},t.getValidEnumValues=i=>{let s=t.objectKeys(i).filter(a=>typeof i[i[a]]!="number"),o={};for(let a of s)o[a]=i[a];return t.objectValues(o)},t.objectValues=i=>t.objectKeys(i).map(function(s){return i[s]}),t.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let s=[];for(let o in i)Object.prototype.hasOwnProperty.call(i,o)&&s.push(o);return s},t.find=(i,s)=>{for(let o of i)if(s(o))return o},t.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function n(i,s=" | "){return i.map(o=>typeof o=="string"?`'${o}'`:o).join(s)}t.joinValues=n,t.jsonStringifyReplacer=(i,s)=>typeof s=="bigint"?s.toString():s})(Ye||(Ye={}));var tR;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(tR||(tR={}));var ne=Ye.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),is=t=>{switch(typeof t){case"undefined":return ne.undefined;case"string":return ne.string;case"number":return Number.isNaN(t)?ne.nan:ne.number;case"boolean":return ne.boolean;case"function":return ne.function;case"bigint":return ne.bigint;case"symbol":return ne.symbol;case"object":return Array.isArray(t)?ne.array:t===null?ne.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?ne.promise:typeof Map<"u"&&t instanceof Map?ne.map:typeof Set<"u"&&t instanceof Set?ne.set:typeof Date<"u"&&t instanceof Date?ne.date:ne.object;default:return ne.unknown}};var B=Ye.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 bn=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(s){return s.message},n={_errors:[]},i=s=>{for(let o of s.issues)if(o.code==="invalid_union")o.unionErrors.map(i);else if(o.code==="invalid_return_type")i(o.returnTypeError);else if(o.code==="invalid_arguments")i(o.argumentsError);else if(o.path.length===0)n._errors.push(r(o));else{let a=n,c=0;for(;cr.message){let r=Object.create(null),n=[];for(let i of this.issues)if(i.path.length>0){let s=i.path[0];r[s]=r[s]||[],r[s].push(e(i))}else n.push(e(i));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};bn.create=t=>new bn(t);var aH=(t,e)=>{let r;switch(t.code){case B.invalid_type:t.received===ne.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case B.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,Ye.jsonStringifyReplacer)}`;break;case B.unrecognized_keys:r=`Unrecognized key(s) in object: ${Ye.joinValues(t.keys,", ")}`;break;case B.invalid_union:r="Invalid input";break;case B.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${Ye.joinValues(t.options)}`;break;case B.invalid_enum_value:r=`Invalid enum value. Expected ${Ye.joinValues(t.options)}, received '${t.received}'`;break;case B.invalid_arguments:r="Invalid function arguments";break;case B.invalid_return_type:r="Invalid function return type";break;case B.invalid_date:r="Invalid date";break;case B.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:Ye.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case B.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case B.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case B.custom:r="Invalid input";break;case B.invalid_intersection_types:r="Intersection results could not be merged";break;case B.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case B.not_finite:r="Number must be finite";break;default:r=e.defaultError,Ye.assertNever(t)}return{message:r}},qs=aH;var cH=qs;function Qu(){return cH}var Lf=t=>{let{data:e,path:r,errorMaps:n,issueData:i}=t,s=[...r,...i.path||[]],o={...i,path:s};if(i.message!==void 0)return{...i,path:s,message:i.message};let a="",c=n.filter(u=>!!u).slice().reverse();for(let u of c)a=u(o,{data:e,defaultError:a}).message;return{...i,path:s,message:a}};function Q(t,e){let r=Qu(),n=Lf({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===qs?void 0:qs].filter(i=>!!i)});t.common.issues.push(n)}var Rr=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let i of r){if(i.status==="aborted")return xe;i.status==="dirty"&&e.dirty(),n.push(i.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let i of r){let s=await i.key,o=await i.value;n.push({key:s,value:o})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let i of r){let{key:s,value:o}=i;if(s.status==="aborted"||o.status==="aborted")return xe;s.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof o.value<"u"||i.alwaysSet)&&(n[s.value]=o.value)}return{status:e.value,value:n}}},xe=Object.freeze({status:"aborted"}),Ma=t=>({status:"dirty",value:t}),Hr=t=>({status:"valid",value:t}),m_=t=>t.status==="aborted",h_=t=>t.status==="dirty",Io=t=>t.status==="valid",el=t=>typeof Promise<"u"&&t instanceof Promise;var de;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(de||(de={}));var Mn=class{constructor(e,r,n,i){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=i}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},rR=(t,e)=>{if(Io(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new bn(t.common.issues);return this._error=r,this._error}}};function Pe(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:i}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:i}:{errorMap:(o,a)=>{let{message:c}=t;return o.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:o.code!=="invalid_type"?{message:a.defaultError}:{message:c??r??a.defaultError}},description:i}}var Fe=class{get description(){return this._def.description}_getType(e){return is(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:is(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Rr,ctx:{common:e.parent.common,data:e.data,parsedType:is(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(el(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:is(e)},i=this._parseSync({data:e,path:n.path,parent:n});return rR(n,i)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:is(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return Io(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>Io(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:is(e)},i=this._parse({data:e,path:n.path,parent:n}),s=await(el(i)?i:Promise.resolve(i));return rR(n,s)}refine(e,r){let n=i=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(i):r;return this._refinement((i,s)=>{let o=e(i),a=()=>s.addIssue({code:B.custom,...n(i)});return typeof Promise<"u"&&o instanceof Promise?o.then(c=>c?!0:(a(),!1)):o?!0:(a(),!1)})}refinement(e,r){return this._refinement((n,i)=>e(n)?!0:(i.addIssue(typeof r=="function"?r(n,i):r),!1))}_refinement(e){return new ii({schema:this,typeName:ye.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:r=>this["~validate"](r)}}optional(){return ni.create(this,this._def)}nullable(){return as.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Zs.create(this)}promise(){return Ro.create(this,this._def)}or(e){return Ua.create([this,e],this._def)}and(e){return Fa.create(this,e,this._def)}transform(e){return new ii({...Pe(this._def),schema:this,typeName:ye.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new Ga({...Pe(this._def),innerType:this,defaultValue:r,typeName:ye.ZodDefault})}brand(){return new Uf({typeName:ye.ZodBranded,type:this,...Pe(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Wa({...Pe(this._def),innerType:this,catchValue:r,typeName:ye.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return Ff.create(this,e)}readonly(){return Va.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},uH=/^c[^\s-]{8,}$/i,lH=/^[0-9a-z]+$/,dH=/^[0-9A-HJKMNP-TV-Z]{26}$/i,pH=/^[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,fH=/^[a-z0-9_-]{21}$/i,mH=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,hH=/^[-+]?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)?)??$/,gH=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,vH="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",g_,yH=/^(?:(?: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])$/,_H=/^(?:(?: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])$/,bH=/^(([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]))$/,SH=/^(([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])$/,xH=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,wH=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nR="((\\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])))",EH=new RegExp(`^${nR}$`);function iR(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function kH(t){return new RegExp(`^${iR(t)}$`)}function TH(t){let e=`${nR}T${iR(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function $H(t,e){return!!((e==="v4"||!e)&&yH.test(t)||(e==="v6"||!e)&&bH.test(t))}function IH(t,e){if(!mH.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),i=JSON.parse(atob(n));return!(typeof i!="object"||i===null||"typ"in i&&i?.typ!=="JWT"||!i.alg||e&&i.alg!==e)}catch{return!1}}function RH(t,e){return!!((e==="v4"||!e)&&_H.test(t)||(e==="v6"||!e)&&SH.test(t))}var ja=class t extends Fe{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==ne.string){let s=this._getOrReturnCtx(e);return Q(s,{code:B.invalid_type,expected:ne.string,received:s.parsedType}),xe}let n=new Rr,i;for(let s of this._def.checks)if(s.kind==="min")e.data.lengths.value&&(i=this._getOrReturnCtx(e,i),Q(i,{code:B.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){let o=e.data.length>s.value,a=e.data.lengthe.test(i),{validation:r,code:B.invalid_string,...de.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...de.errToObj(e)})}url(e){return this._addCheck({kind:"url",...de.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...de.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...de.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...de.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...de.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...de.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...de.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...de.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...de.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...de.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...de.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...de.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,...de.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,...de.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...de.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...de.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...de.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...de.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...de.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...de.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...de.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...de.errToObj(r)})}nonempty(e){return this.min(1,de.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...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 r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.valuenew ja({checks:[],typeName:ye.ZodString,coerce:t?.coerce??!1,...Pe(t)});function OH(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,i=r>n?r:n,s=Number.parseInt(t.toFixed(i).replace(".","")),o=Number.parseInt(e.toFixed(i).replace(".",""));return s%o/10**i}var tl=class t extends Fe{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)!==ne.number){let s=this._getOrReturnCtx(e);return Q(s,{code:B.invalid_type,expected:ne.number,received:s.parsedType}),xe}let n,i=new Rr;for(let s of this._def.checks)s.kind==="int"?Ye.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),Q(n,{code:B.invalid_type,expected:"integer",received:"float",message:s.message}),i.dirty()):s.kind==="min"?(s.inclusive?e.datas.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),Q(n,{code:B.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),i.dirty()):s.kind==="multipleOf"?OH(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),Q(n,{code:B.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),Q(n,{code:B.not_finite,message:s.message}),i.dirty()):Ye.assertNever(s);return{status:i.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,de.toString(r))}gt(e,r){return this.setLimit("min",e,!1,de.toString(r))}lte(e,r){return this.setLimit("max",e,!0,de.toString(r))}lt(e,r){return this.setLimit("max",e,!1,de.toString(r))}setLimit(e,r,n,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:de.toString(i)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:de.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:de.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:de.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:de.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:de.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:de.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:de.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:de.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:de.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.valuee.kind==="int"||e.kind==="multipleOf"&&Ye.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.valuenew tl({checks:[],typeName:ye.ZodNumber,coerce:t?.coerce||!1,...Pe(t)});var rl=class t extends Fe{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)!==ne.bigint)return this._getInvalidInput(e);let n,i=new Rr;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?e.datas.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),Q(n,{code:B.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),i.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),Q(n,{code:B.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):Ye.assertNever(s);return{status:i.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return Q(r,{code:B.invalid_type,expected:ne.bigint,received:r.parsedType}),xe}gte(e,r){return this.setLimit("min",e,!0,de.toString(r))}gt(e,r){return this.setLimit("min",e,!1,de.toString(r))}lte(e,r){return this.setLimit("max",e,!0,de.toString(r))}lt(e,r){return this.setLimit("max",e,!1,de.toString(r))}setLimit(e,r,n,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:de.toString(i)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:de.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:de.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:de.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:de.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:de.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.valuenew rl({checks:[],typeName:ye.ZodBigInt,coerce:t?.coerce??!1,...Pe(t)});var nl=class extends Fe{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==ne.boolean){let n=this._getOrReturnCtx(e);return Q(n,{code:B.invalid_type,expected:ne.boolean,received:n.parsedType}),xe}return Hr(e.data)}};nl.create=t=>new nl({typeName:ye.ZodBoolean,coerce:t?.coerce||!1,...Pe(t)});var il=class t extends Fe{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==ne.date){let s=this._getOrReturnCtx(e);return Q(s,{code:B.invalid_type,expected:ne.date,received:s.parsedType}),xe}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return Q(s,{code:B.invalid_date}),xe}let n=new Rr,i;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()s.value&&(i=this._getOrReturnCtx(e,i),Q(i,{code:B.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):Ye.assertNever(s);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:de.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:de.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.valuenew il({checks:[],coerce:t?.coerce||!1,typeName:ye.ZodDate,...Pe(t)});var sl=class extends Fe{_parse(e){if(this._getType(e)!==ne.symbol){let n=this._getOrReturnCtx(e);return Q(n,{code:B.invalid_type,expected:ne.symbol,received:n.parsedType}),xe}return Hr(e.data)}};sl.create=t=>new sl({typeName:ye.ZodSymbol,...Pe(t)});var za=class extends Fe{_parse(e){if(this._getType(e)!==ne.undefined){let n=this._getOrReturnCtx(e);return Q(n,{code:B.invalid_type,expected:ne.undefined,received:n.parsedType}),xe}return Hr(e.data)}};za.create=t=>new za({typeName:ye.ZodUndefined,...Pe(t)});var La=class extends Fe{_parse(e){if(this._getType(e)!==ne.null){let n=this._getOrReturnCtx(e);return Q(n,{code:B.invalid_type,expected:ne.null,received:n.parsedType}),xe}return Hr(e.data)}};La.create=t=>new La({typeName:ye.ZodNull,...Pe(t)});var ol=class extends Fe{constructor(){super(...arguments),this._any=!0}_parse(e){return Hr(e.data)}};ol.create=t=>new ol({typeName:ye.ZodAny,...Pe(t)});var Hs=class extends Fe{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Hr(e.data)}};Hs.create=t=>new Hs({typeName:ye.ZodUnknown,...Pe(t)});var Oi=class extends Fe{_parse(e){let r=this._getOrReturnCtx(e);return Q(r,{code:B.invalid_type,expected:ne.never,received:r.parsedType}),xe}};Oi.create=t=>new Oi({typeName:ye.ZodNever,...Pe(t)});var al=class extends Fe{_parse(e){if(this._getType(e)!==ne.undefined){let n=this._getOrReturnCtx(e);return Q(n,{code:B.invalid_type,expected:ne.void,received:n.parsedType}),xe}return Hr(e.data)}};al.create=t=>new al({typeName:ye.ZodVoid,...Pe(t)});var Zs=class t extends Fe{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),i=this._def;if(r.parsedType!==ne.array)return Q(r,{code:B.invalid_type,expected:ne.array,received:r.parsedType}),xe;if(i.exactLength!==null){let o=r.data.length>i.exactLength.value,a=r.data.lengthi.maxLength.value&&(Q(r,{code:B.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((o,a)=>i.type._parseAsync(new Mn(r,o,r.path,a)))).then(o=>Rr.mergeArray(n,o));let s=[...r.data].map((o,a)=>i.type._parseSync(new Mn(r,o,r.path,a)));return Rr.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:de.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:de.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:de.toString(r)}})}nonempty(e){return this.min(1,e)}};Zs.create=(t,e)=>new Zs({type:t,minLength:null,maxLength:null,exactLength:null,typeName:ye.ZodArray,...Pe(e)});function Da(t){if(t instanceof Sn){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=ni.create(Da(n))}return new Sn({...t._def,shape:()=>e})}else return t instanceof Zs?new Zs({...t._def,type:Da(t.element)}):t instanceof ni?ni.create(Da(t.unwrap())):t instanceof as?as.create(Da(t.unwrap())):t instanceof os?os.create(t.items.map(e=>Da(e))):t}var Sn=class t extends Fe{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(),r=Ye.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==ne.object){let u=this._getOrReturnCtx(e);return Q(u,{code:B.invalid_type,expected:ne.object,received:u.parsedType}),xe}let{status:n,ctx:i}=this._processInputParams(e),{shape:s,keys:o}=this._getCached(),a=[];if(!(this._def.catchall instanceof Oi&&this._def.unknownKeys==="strip"))for(let u in i.data)o.includes(u)||a.push(u);let c=[];for(let u of o){let l=s[u],d=i.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new Mn(i,d,i.path,u)),alwaysSet:u in i.data})}if(this._def.catchall instanceof Oi){let u=this._def.unknownKeys;if(u==="passthrough")for(let l of a)c.push({key:{status:"valid",value:l},value:{status:"valid",value:i.data[l]}});else if(u==="strict")a.length>0&&(Q(i,{code:B.unrecognized_keys,keys:a}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let l of a){let d=i.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new Mn(i,d,i.path,l)),alwaysSet:l in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let u=[];for(let l of c){let d=await l.key,p=await l.value;u.push({key:d,value:p,alwaysSet:l.alwaysSet})}return u}).then(u=>Rr.mergeObjectSync(n,u)):Rr.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return de.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let i=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:de.errToObj(e).message??i}:{message:i}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:ye.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let n of Ye.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let n of Ye.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return Da(this)}partial(e){let r={};for(let n of Ye.objectKeys(this.shape)){let i=this.shape[n];e&&!e[n]?r[n]=i:r[n]=i.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of Ye.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof ni;)s=s._def.innerType;r[n]=s}return new t({...this._def,shape:()=>r})}keyof(){return sR(Ye.objectKeys(this.shape))}};Sn.create=(t,e)=>new Sn({shape:()=>t,unknownKeys:"strip",catchall:Oi.create(),typeName:ye.ZodObject,...Pe(e)});Sn.strictCreate=(t,e)=>new Sn({shape:()=>t,unknownKeys:"strict",catchall:Oi.create(),typeName:ye.ZodObject,...Pe(e)});Sn.lazycreate=(t,e)=>new Sn({shape:t,unknownKeys:"strip",catchall:Oi.create(),typeName:ye.ZodObject,...Pe(e)});var Ua=class extends Fe{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function i(s){for(let a of s)if(a.result.status==="valid")return a.result;for(let a of s)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let o=s.map(a=>new bn(a.ctx.common.issues));return Q(r,{code:B.invalid_union,unionErrors:o}),xe}if(r.common.async)return Promise.all(n.map(async s=>{let o={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:o}),ctx:o}})).then(i);{let s,o=[];for(let c of n){let u={...r,common:{...r.common,issues:[]},parent:null},l=c._parseSync({data:r.data,path:r.path,parent:u});if(l.status==="valid")return l;l.status==="dirty"&&!s&&(s={result:l,ctx:u}),u.common.issues.length&&o.push(u.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;let a=o.map(c=>new bn(c));return Q(r,{code:B.invalid_union,unionErrors:a}),xe}}get options(){return this._def.options}};Ua.create=(t,e)=>new Ua({options:t,typeName:ye.ZodUnion,...Pe(e)});var ss=t=>t instanceof qa?ss(t.schema):t instanceof ii?ss(t.innerType()):t instanceof Ha?[t.value]:t instanceof Za?t.options:t instanceof Ba?Ye.objectValues(t.enum):t instanceof Ga?ss(t._def.innerType):t instanceof za?[void 0]:t instanceof La?[null]:t instanceof ni?[void 0,...ss(t.unwrap())]:t instanceof as?[null,...ss(t.unwrap())]:t instanceof Uf||t instanceof Va?ss(t.unwrap()):t instanceof Wa?ss(t._def.innerType):[],v_=class t extends Fe{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==ne.object)return Q(r,{code:B.invalid_type,expected:ne.object,received:r.parsedType}),xe;let n=this.discriminator,i=r.data[n],s=this.optionsMap.get(i);return s?r.common.async?s._parseAsync({data:r.data,path:r.path,parent:r}):s._parseSync({data:r.data,path:r.path,parent:r}):(Q(r,{code:B.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),xe)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let i=new Map;for(let s of r){let o=ss(s.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(i.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);i.set(a,s)}}return new t({typeName:ye.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:i,...Pe(n)})}};function y_(t,e){let r=is(t),n=is(e);if(t===e)return{valid:!0,data:t};if(r===ne.object&&n===ne.object){let i=Ye.objectKeys(e),s=Ye.objectKeys(t).filter(a=>i.indexOf(a)!==-1),o={...t,...e};for(let a of s){let c=y_(t[a],e[a]);if(!c.valid)return{valid:!1};o[a]=c.data}return{valid:!0,data:o}}else if(r===ne.array&&n===ne.array){if(t.length!==e.length)return{valid:!1};let i=[];for(let s=0;s{if(m_(s)||m_(o))return xe;let a=y_(s.value,o.value);return a.valid?((h_(s)||h_(o))&&r.dirty(),{status:r.value,value:a.data}):(Q(n,{code:B.invalid_intersection_types}),xe)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([s,o])=>i(s,o)):i(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};Fa.create=(t,e,r)=>new Fa({left:t,right:e,typeName:ye.ZodIntersection,...Pe(r)});var os=class t extends Fe{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==ne.array)return Q(n,{code:B.invalid_type,expected:ne.array,received:n.parsedType}),xe;if(n.data.lengththis._def.items.length&&(Q(n,{code:B.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let s=[...n.data].map((o,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new Mn(n,o,n.path,a)):null}).filter(o=>!!o);return n.common.async?Promise.all(s).then(o=>Rr.mergeArray(r,o)):Rr.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};os.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new os({items:t,typeName:ye.ZodTuple,rest:null,...Pe(e)})};var __=class t extends Fe{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==ne.object)return Q(n,{code:B.invalid_type,expected:ne.object,received:n.parsedType}),xe;let i=[],s=this._def.keyType,o=this._def.valueType;for(let a in n.data)i.push({key:s._parse(new Mn(n,a,n.path,a)),value:o._parse(new Mn(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?Rr.mergeObjectAsync(r,i):Rr.mergeObjectSync(r,i)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof Fe?new t({keyType:e,valueType:r,typeName:ye.ZodRecord,...Pe(n)}):new t({keyType:ja.create(),valueType:e,typeName:ye.ZodRecord,...Pe(r)})}},cl=class extends Fe{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==ne.map)return Q(n,{code:B.invalid_type,expected:ne.map,received:n.parsedType}),xe;let i=this._def.keyType,s=this._def.valueType,o=[...n.data.entries()].map(([a,c],u)=>({key:i._parse(new Mn(n,a,n.path,[u,"key"])),value:s._parse(new Mn(n,c,n.path,[u,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of o){let u=await c.key,l=await c.value;if(u.status==="aborted"||l.status==="aborted")return xe;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let c of o){let u=c.key,l=c.value;if(u.status==="aborted"||l.status==="aborted")return xe;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}}}};cl.create=(t,e,r)=>new cl({valueType:e,keyType:t,typeName:ye.ZodMap,...Pe(r)});var ul=class t extends Fe{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==ne.set)return Q(n,{code:B.invalid_type,expected:ne.set,received:n.parsedType}),xe;let i=this._def;i.minSize!==null&&n.data.sizei.maxSize.value&&(Q(n,{code:B.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),r.dirty());let s=this._def.valueType;function o(c){let u=new Set;for(let l of c){if(l.status==="aborted")return xe;l.status==="dirty"&&r.dirty(),u.add(l.value)}return{status:r.value,value:u}}let a=[...n.data.values()].map((c,u)=>s._parse(new Mn(n,c,n.path,u)));return n.common.async?Promise.all(a).then(c=>o(c)):o(a)}min(e,r){return new t({...this._def,minSize:{value:e,message:de.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:de.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};ul.create=(t,e)=>new ul({valueType:t,minSize:null,maxSize:null,typeName:ye.ZodSet,...Pe(e)});var b_=class t extends Fe{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==ne.function)return Q(r,{code:B.invalid_type,expected:ne.function,received:r.parsedType}),xe;function n(a,c){return Lf({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Qu(),qs].filter(u=>!!u),issueData:{code:B.invalid_arguments,argumentsError:c}})}function i(a,c){return Lf({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Qu(),qs].filter(u=>!!u),issueData:{code:B.invalid_return_type,returnTypeError:c}})}let s={errorMap:r.common.contextualErrorMap},o=r.data;if(this._def.returns instanceof Ro){let a=this;return Hr(async function(...c){let u=new bn([]),l=await a._def.args.parseAsync(c,s).catch(f=>{throw u.addIssue(n(c,f)),u}),d=await Reflect.apply(o,this,l);return await a._def.returns._def.type.parseAsync(d,s).catch(f=>{throw u.addIssue(i(d,f)),u})})}else{let a=this;return Hr(function(...c){let u=a._def.args.safeParse(c,s);if(!u.success)throw new bn([n(c,u.error)]);let l=Reflect.apply(o,this,u.data),d=a._def.returns.safeParse(l,s);if(!d.success)throw new bn([i(l,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:os.create(e).rest(Hs.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new t({args:e||os.create([]).rest(Hs.create()),returns:r||Hs.create(),typeName:ye.ZodFunction,...Pe(n)})}},qa=class extends Fe{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};qa.create=(t,e)=>new qa({getter:t,typeName:ye.ZodLazy,...Pe(e)});var Ha=class extends Fe{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return Q(r,{received:r.data,code:B.invalid_literal,expected:this._def.value}),xe}return{status:"valid",value:e.data}}get value(){return this._def.value}};Ha.create=(t,e)=>new Ha({value:t,typeName:ye.ZodLiteral,...Pe(e)});function sR(t,e){return new Za({values:t,typeName:ye.ZodEnum,...Pe(e)})}var Za=class t extends Fe{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return Q(r,{expected:Ye.joinValues(n),received:r.parsedType,code:B.invalid_type}),xe}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return Q(r,{received:r.data,code:B.invalid_enum_value,options:n}),xe}return Hr(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};Za.create=sR;var Ba=class extends Fe{_parse(e){let r=Ye.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==ne.string&&n.parsedType!==ne.number){let i=Ye.objectValues(r);return Q(n,{expected:Ye.joinValues(i),received:n.parsedType,code:B.invalid_type}),xe}if(this._cache||(this._cache=new Set(Ye.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let i=Ye.objectValues(r);return Q(n,{received:n.data,code:B.invalid_enum_value,options:i}),xe}return Hr(e.data)}get enum(){return this._def.values}};Ba.create=(t,e)=>new Ba({values:t,typeName:ye.ZodNativeEnum,...Pe(e)});var Ro=class extends Fe{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==ne.promise&&r.common.async===!1)return Q(r,{code:B.invalid_type,expected:ne.promise,received:r.parsedType}),xe;let n=r.parsedType===ne.promise?r.data:Promise.resolve(r.data);return Hr(n.then(i=>this._def.type.parseAsync(i,{path:r.path,errorMap:r.common.contextualErrorMap})))}};Ro.create=(t,e)=>new Ro({type:t,typeName:ye.ZodPromise,...Pe(e)});var ii=class extends Fe{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ye.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),i=this._def.effect||null,s={addIssue:o=>{Q(n,o),o.fatal?r.abort():r.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),i.type==="preprocess"){let o=i.transform(n.data,s);if(n.common.async)return Promise.resolve(o).then(async a=>{if(r.value==="aborted")return xe;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?xe:c.status==="dirty"?Ma(c.value):r.value==="dirty"?Ma(c.value):c});{if(r.value==="aborted")return xe;let a=this._def.schema._parseSync({data:o,path:n.path,parent:n});return a.status==="aborted"?xe:a.status==="dirty"?Ma(a.value):r.value==="dirty"?Ma(a.value):a}}if(i.type==="refinement"){let o=a=>{let c=i.refinement(a,s);if(n.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(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?xe:(a.status==="dirty"&&r.dirty(),o(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?xe:(a.status==="dirty"&&r.dirty(),o(a.value).then(()=>({status:r.value,value:a.value}))))}if(i.type==="transform")if(n.common.async===!1){let o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Io(o))return xe;let a=i.transform(o.value,s);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>Io(o)?Promise.resolve(i.transform(o.value,s)).then(a=>({status:r.value,value:a})):xe);Ye.assertNever(i)}};ii.create=(t,e,r)=>new ii({schema:t,typeName:ye.ZodEffects,effect:e,...Pe(r)});ii.createWithPreprocess=(t,e,r)=>new ii({schema:e,effect:{type:"preprocess",transform:t},typeName:ye.ZodEffects,...Pe(r)});var ni=class extends Fe{_parse(e){return this._getType(e)===ne.undefined?Hr(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ni.create=(t,e)=>new ni({innerType:t,typeName:ye.ZodOptional,...Pe(e)});var as=class extends Fe{_parse(e){return this._getType(e)===ne.null?Hr(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};as.create=(t,e)=>new as({innerType:t,typeName:ye.ZodNullable,...Pe(e)});var Ga=class extends Fe{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===ne.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};Ga.create=(t,e)=>new Ga({innerType:t,typeName:ye.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...Pe(e)});var Wa=class extends Fe{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},i=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return el(i)?i.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new bn(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new bn(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Wa.create=(t,e)=>new Wa({innerType:t,typeName:ye.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...Pe(e)});var ll=class extends Fe{_parse(e){if(this._getType(e)!==ne.nan){let n=this._getOrReturnCtx(e);return Q(n,{code:B.invalid_type,expected:ne.nan,received:n.parsedType}),xe}return{status:"valid",value:e.data}}};ll.create=t=>new ll({typeName:ye.ZodNaN,...Pe(t)});var Uf=class extends Fe{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},Ff=class t extends Fe{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?xe:s.status==="dirty"?(r.dirty(),Ma(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{let i=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?xe:i.status==="dirty"?(r.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:ye.ZodPipeline})}},Va=class extends Fe{_parse(e){let r=this._def.innerType._parse(e),n=i=>(Io(i)&&(i.value=Object.freeze(i.value)),i);return el(r)?r.then(i=>n(i)):n(r)}unwrap(){return this._def.innerType}};Va.create=(t,e)=>new Va({innerType:t,typeName:ye.ZodReadonly,...Pe(e)});var exe={object:Sn.lazycreate},ye;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(ye||(ye={}));var txe=ja.create,rxe=tl.create,nxe=ll.create,ixe=rl.create,sxe=nl.create,oxe=il.create,axe=sl.create,cxe=za.create,uxe=La.create,lxe=ol.create,dxe=Hs.create,pxe=Oi.create,fxe=al.create,mxe=Zs.create,CH=Sn.create,hxe=Sn.strictCreate,gxe=Ua.create,vxe=v_.create,yxe=Fa.create,_xe=os.create,bxe=__.create,Sxe=cl.create,xxe=ul.create,wxe=b_.create,Exe=qa.create,kxe=Ha.create,Txe=Za.create,$xe=Ba.create,Ixe=Ro.create,Rxe=ii.create,Oxe=ni.create,Cxe=as.create,Pxe=ii.createWithPreprocess,Axe=Ff.create;var oR=Object.freeze({status:"aborted"});function O(t,e,r){function n(a,c){if(a._zod||Object.defineProperty(a,"_zod",{value:{def:c,constr:o,traits:new Set},enumerable:!1}),a._zod.traits.has(t))return;a._zod.traits.add(t),e(a,c);let u=o.prototype,l=Object.keys(u);for(let d=0;dr?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(o,"name",{value:t}),o}var Ci=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Oo=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}},qf={};function tr(t){return t&&Object.assign(qf,t),qf}var G={};_n(G,{BIGINT_FORMAT_RANGES:()=>R_,Class:()=>x_,NUMBER_FORMAT_RANGES:()=>I_,aborted:()=>Vs,allowsEval:()=>k_,assert:()=>zH,assertEqual:()=>NH,assertIs:()=>DH,assertNever:()=>jH,assertNotEqual:()=>MH,assignProp:()=>Gs,base64ToUint8Array:()=>uR,base64urlToUint8Array:()=>t3,cached:()=>Ja,captureStackTrace:()=>Zf,cleanEnum:()=>e3,cleanRegex:()=>fl,clone:()=>Zr,cloneDef:()=>UH,createTransparentProxy:()=>GH,defineLazy:()=>Le,esc:()=>Hf,escapeRegex:()=>Dn,extend:()=>KH,finalizeIssue:()=>on,floatSafeRemainder:()=>w_,getElementAtPath:()=>FH,getEnumValues:()=>pl,getLengthableOrigin:()=>gl,getParsedType:()=>BH,getSizableOrigin:()=>hl,hexToUint8Array:()=>n3,isObject:()=>Co,isPlainObject:()=>Ws,issue:()=>Xa,joinValues:()=>_e,jsonStringifyReplacer:()=>Ka,merge:()=>XH,mergeDefs:()=>cs,normalizeParams:()=>ee,nullish:()=>Bs,numKeys:()=>ZH,objectClone:()=>LH,omit:()=>VH,optionalKeys:()=>$_,parsedType:()=>we,partial:()=>YH,pick:()=>WH,prefixIssues:()=>xn,primitiveTypes:()=>T_,promiseAllObject:()=>qH,propertyKeyTypes:()=>ml,randomString:()=>HH,required:()=>QH,safeExtend:()=>JH,shallowClone:()=>cR,slugify:()=>E_,stringifyPrimitive:()=>be,uint8ArrayToBase64:()=>lR,uint8ArrayToBase64url:()=>r3,uint8ArrayToHex:()=>i3,unwrapMessage:()=>dl});function NH(t){return t}function MH(t){return t}function DH(t){}function jH(t){throw new Error("Unexpected value in exhaustive check")}function zH(t){}function pl(t){let e=Object.values(t).filter(n=>typeof n=="number");return Object.entries(t).filter(([n,i])=>e.indexOf(+n)===-1).map(([n,i])=>i)}function _e(t,e="|"){return t.map(r=>be(r)).join(e)}function Ka(t,e){return typeof e=="bigint"?e.toString():e}function Ja(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Bs(t){return t==null}function fl(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function w_(t,e){let r=(t.toString().split(".")[1]||"").length,n=e.toString(),i=(n.split(".")[1]||"").length;if(i===0&&/\d?e-\d?/.test(n)){let c=n.match(/\d?e-(\d?)/);c?.[1]&&(i=Number.parseInt(c[1]))}let s=r>i?r:i,o=Number.parseInt(t.toFixed(s).replace(".","")),a=Number.parseInt(e.toFixed(s).replace(".",""));return o%a/10**s}var aR=Symbol("evaluating");function Le(t,e,r){let n;Object.defineProperty(t,e,{get(){if(n!==aR)return n===void 0&&(n=aR,n=r()),n},set(i){Object.defineProperty(t,e,{value:i})},configurable:!0})}function LH(t){return Object.create(Object.getPrototypeOf(t),Object.getOwnPropertyDescriptors(t))}function Gs(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function cs(...t){let e={};for(let r of t){let n=Object.getOwnPropertyDescriptors(r);Object.assign(e,n)}return Object.defineProperties({},e)}function UH(t){return cs(t._zod.def)}function FH(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function qH(t){let e=Object.keys(t),r=e.map(n=>t[n]);return Promise.all(r).then(n=>{let i={};for(let s=0;s{};function Co(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var k_=Ja(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});function Ws(t){if(Co(t)===!1)return!1;let e=t.constructor;if(e===void 0||typeof e!="function")return!0;let r=e.prototype;return!(Co(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function cR(t){return Ws(t)?{...t}:Array.isArray(t)?[...t]:t}function ZH(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}var BH=t=>{let e=typeof t;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(t)?"array":t===null?"null":t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?"promise":typeof Map<"u"&&t instanceof Map?"map":typeof Set<"u"&&t instanceof Set?"set":typeof Date<"u"&&t instanceof Date?"date":typeof File<"u"&&t instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},ml=new Set(["string","number","symbol"]),T_=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Dn(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Zr(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function ee(t){let e=t;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 GH(t){let e;return new Proxy({},{get(r,n,i){return e??(e=t()),Reflect.get(e,n,i)},set(r,n,i,s){return e??(e=t()),Reflect.set(e,n,i,s)},has(r,n){return e??(e=t()),Reflect.has(e,n)},deleteProperty(r,n){return e??(e=t()),Reflect.deleteProperty(e,n)},ownKeys(r){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(r,n){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,n)},defineProperty(r,n,i){return e??(e=t()),Reflect.defineProperty(e,n,i)}})}function be(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function $_(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}var I_={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]},R_={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function WH(t,e){let r=t._zod.def,n=r.checks;if(n&&n.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");let s=cs(t._zod.def,{get shape(){let o={};for(let a in e){if(!(a in r.shape))throw new Error(`Unrecognized key: "${a}"`);e[a]&&(o[a]=r.shape[a])}return Gs(this,"shape",o),o},checks:[]});return Zr(t,s)}function VH(t,e){let r=t._zod.def,n=r.checks;if(n&&n.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");let s=cs(t._zod.def,{get shape(){let o={...t._zod.def.shape};for(let a in e){if(!(a in r.shape))throw new Error(`Unrecognized key: "${a}"`);e[a]&&delete o[a]}return Gs(this,"shape",o),o},checks:[]});return Zr(t,s)}function KH(t,e){if(!Ws(e))throw new Error("Invalid input to extend: expected a plain object");let r=t._zod.def.checks;if(r&&r.length>0){let s=t._zod.def.shape;for(let o in e)if(Object.getOwnPropertyDescriptor(s,o)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let i=cs(t._zod.def,{get shape(){let s={...t._zod.def.shape,...e};return Gs(this,"shape",s),s}});return Zr(t,i)}function JH(t,e){if(!Ws(e))throw new Error("Invalid input to safeExtend: expected a plain object");let r=cs(t._zod.def,{get shape(){let n={...t._zod.def.shape,...e};return Gs(this,"shape",n),n}});return Zr(t,r)}function XH(t,e){let r=cs(t._zod.def,{get shape(){let n={...t._zod.def.shape,...e._zod.def.shape};return Gs(this,"shape",n),n},get catchall(){return e._zod.def.catchall},checks:[]});return Zr(t,r)}function YH(t,e,r){let i=e._zod.def.checks;if(i&&i.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");let o=cs(e._zod.def,{get shape(){let a=e._zod.def.shape,c={...a};if(r)for(let u in r){if(!(u in a))throw new Error(`Unrecognized key: "${u}"`);r[u]&&(c[u]=t?new t({type:"optional",innerType:a[u]}):a[u])}else for(let u in a)c[u]=t?new t({type:"optional",innerType:a[u]}):a[u];return Gs(this,"shape",c),c},checks:[]});return Zr(e,o)}function QH(t,e,r){let n=cs(e._zod.def,{get shape(){let i=e._zod.def.shape,s={...i};if(r)for(let o in r){if(!(o in s))throw new Error(`Unrecognized key: "${o}"`);r[o]&&(s[o]=new t({type:"nonoptional",innerType:i[o]}))}else for(let o in i)s[o]=new t({type:"nonoptional",innerType:i[o]});return Gs(this,"shape",s),s}});return Zr(e,n)}function Vs(t,e=0){if(t.aborted===!0)return!0;for(let r=e;r{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function dl(t){return typeof t=="string"?t:t?.message}function on(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let i=dl(t.inst?._zod.def?.error?.(t))??dl(e?.error?.(t))??dl(r.customError?.(t))??dl(r.localeError?.(t))??"Invalid input";n.message=i}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function hl(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function gl(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function we(t){let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"nan":"number";case"object":{if(t===null)return"null";if(Array.isArray(t))return"array";let r=t;if(r&&Object.getPrototypeOf(r)!==Object.prototype&&"constructor"in r&&r.constructor)return r.constructor.name}}return e}function Xa(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function e3(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}function uR(t){let e=atob(t),r=new Uint8Array(e.length);for(let n=0;ne.toString(16).padStart(2,"0")).join("")}var x_=class{constructor(...e){}};var dR=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),t.message=JSON.stringify(e,Ka,2),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Bf=O("$ZodError",dR),vl=O("$ZodError",dR,{Parent:Error});function Gf(t,e=r=>r.message){let r={},n=[];for(let i of t.issues)i.path.length>0?(r[i.path[0]]=r[i.path[0]]||[],r[i.path[0]].push(e(i))):n.push(e(i));return{formErrors:n,fieldErrors:r}}function Wf(t,e=r=>r.message){let r={_errors:[]},n=i=>{for(let s of i.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map(o=>n({issues:o}));else if(s.code==="invalid_key")n({issues:s.issues});else if(s.code==="invalid_element")n({issues:s.issues});else if(s.path.length===0)r._errors.push(e(s));else{let o=r,a=0;for(;a(e,r,n,i)=>{let s=n?Object.assign(n,{async:!1}):{async:!1},o=e._zod.run({value:r,issues:[]},s);if(o instanceof Promise)throw new Ci;if(o.issues.length){let a=new(i?.Err??t)(o.issues.map(c=>on(c,s,tr())));throw Zf(a,i?.callee),a}return o.value},_l=yl(vl),bl=t=>async(e,r,n,i)=>{let s=n?Object.assign(n,{async:!0}):{async:!0},o=e._zod.run({value:r,issues:[]},s);if(o instanceof Promise&&(o=await o),o.issues.length){let a=new(i?.Err??t)(o.issues.map(c=>on(c,s,tr())));throw Zf(a,i?.callee),a}return o.value},Sl=bl(vl),xl=t=>(e,r,n)=>{let i=n?{...n,async:!1}:{async:!1},s=e._zod.run({value:r,issues:[]},i);if(s instanceof Promise)throw new Ci;return s.issues.length?{success:!1,error:new(t??Bf)(s.issues.map(o=>on(o,i,tr())))}:{success:!0,data:s.value}},Ya=xl(vl),wl=t=>async(e,r,n)=>{let i=n?Object.assign(n,{async:!0}):{async:!0},s=e._zod.run({value:r,issues:[]},i);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new t(s.issues.map(o=>on(o,i,tr())))}:{success:!0,data:s.value}},El=wl(vl),pR=t=>(e,r,n)=>{let i=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return yl(t)(e,r,i)};var fR=t=>(e,r,n)=>yl(t)(e,r,n);var mR=t=>async(e,r,n)=>{let i=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return bl(t)(e,r,i)};var hR=t=>async(e,r,n)=>bl(t)(e,r,n);var gR=t=>(e,r,n)=>{let i=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return xl(t)(e,r,i)};var vR=t=>(e,r,n)=>xl(t)(e,r,n);var yR=t=>async(e,r,n)=>{let i=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return wl(t)(e,r,i)};var _R=t=>async(e,r,n)=>wl(t)(e,r,n);var jn={};_n(jn,{base64:()=>B_,base64url:()=>Vf,bigint:()=>X_,boolean:()=>Q_,browserEmail:()=>f3,cidrv4:()=>H_,cidrv6:()=>Z_,cuid:()=>O_,cuid2:()=>C_,date:()=>W_,datetime:()=>K_,domain:()=>g3,duration:()=>D_,e164:()=>G_,email:()=>z_,emoji:()=>L_,extendedDuration:()=>o3,guid:()=>j_,hex:()=>v3,hostname:()=>h3,html5Email:()=>l3,idnEmail:()=>p3,integer:()=>Y_,ipv4:()=>U_,ipv6:()=>F_,ksuid:()=>N_,lowercase:()=>rb,mac:()=>q_,md5_base64:()=>_3,md5_base64url:()=>b3,md5_hex:()=>y3,nanoid:()=>M_,null:()=>eb,number:()=>Kf,rfc5322Email:()=>d3,sha1_base64:()=>x3,sha1_base64url:()=>w3,sha1_hex:()=>S3,sha256_base64:()=>k3,sha256_base64url:()=>T3,sha256_hex:()=>E3,sha384_base64:()=>I3,sha384_base64url:()=>R3,sha384_hex:()=>$3,sha512_base64:()=>C3,sha512_base64url:()=>P3,sha512_hex:()=>O3,string:()=>J_,time:()=>V_,ulid:()=>P_,undefined:()=>tb,unicodeEmail:()=>bR,uppercase:()=>nb,uuid:()=>Po,uuid4:()=>a3,uuid6:()=>c3,uuid7:()=>u3,xid:()=>A_});var O_=/^[cC][^\s-]{8,}$/,C_=/^[0-9a-z]+$/,P_=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,A_=/^[0-9a-vA-V]{20}$/,N_=/^[A-Za-z0-9]{27}$/,M_=/^[a-zA-Z0-9_-]{21}$/,D_=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,o3=/^[-+]?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)?)??$/,j_=/^([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})$/,Po=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[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|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,a3=Po(4),c3=Po(6),u3=Po(7),z_=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,l3=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,d3=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,bR=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,p3=bR,f3=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,m3="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function L_(){return new RegExp(m3,"u")}var U_=/^(?:(?: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])$/,F_=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,q_=t=>{let e=Dn(t??":");return new RegExp(`^(?:[0-9A-F]{2}${e}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${e}){5}[0-9a-f]{2}$`)},H_=/^((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])$/,Z_=/^(([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])$/,B_=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Vf=/^[A-Za-z0-9_-]*$/,h3=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,g3=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,G_=/^\+[1-9]\d{6,14}$/,SR="(?:(?:\\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])))",W_=new RegExp(`^${SR}$`);function xR(t){let e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function V_(t){return new RegExp(`^${xR(t)}$`)}function K_(t){let e=xR({precision:t.precision}),r=["Z"];t.local&&r.push(""),t.offset&&r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let n=`${e}(?:${r.join("|")})`;return new RegExp(`^${SR}T(?:${n})$`)}var J_=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},X_=/^-?\d+n?$/,Y_=/^-?\d+$/,Kf=/^-?\d+(?:\.\d+)?$/,Q_=/^(?:true|false)$/i,eb=/^null$/i;var tb=/^undefined$/i;var rb=/^[^A-Z]*$/,nb=/^[^a-z]*$/,v3=/^[0-9a-fA-F]*$/;function kl(t,e){return new RegExp(`^[A-Za-z0-9+/]{${t}}${e}$`)}function Tl(t){return new RegExp(`^[A-Za-z0-9_-]{${t}}$`)}var y3=/^[0-9a-fA-F]{32}$/,_3=kl(22,"=="),b3=Tl(22),S3=/^[0-9a-fA-F]{40}$/,x3=kl(27,"="),w3=Tl(27),E3=/^[0-9a-fA-F]{64}$/,k3=kl(43,"="),T3=Tl(43),$3=/^[0-9a-fA-F]{96}$/,I3=kl(64,""),R3=Tl(64),O3=/^[0-9a-fA-F]{128}$/,C3=kl(86,"=="),P3=Tl(86);var _t=O("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),ER={number:"number",bigint:"bigint",object:"date"},ib=O("$ZodCheckLessThan",(t,e)=>{_t.init(t,e);let r=ER[typeof e.value];t._zod.onattach.push(n=>{let i=n._zod.bag,s=(e.inclusive?i.maximum:i.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value{(e.inclusive?n.value<=e.value:n.value{_t.init(t,e);let r=ER[typeof e.value];t._zod.onattach.push(n=>{let i=n._zod.bag,s=(e.inclusive?i.minimum:i.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>s&&(e.inclusive?i.minimum=e.value:i.exclusiveMinimum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value>=e.value:n.value>e.value)||n.issues.push({origin:r,code:"too_small",minimum:typeof e.value=="object"?e.value.getTime():e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),kR=O("$ZodCheckMultipleOf",(t,e)=>{_t.init(t,e),t._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=e.value)}),t._zod.check=r=>{if(typeof r.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%e.value===BigInt(0):w_(r.value,e.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:e.value,input:r.value,inst:t,continue:!e.abort})}}),TR=O("$ZodCheckNumberFormat",(t,e)=>{_t.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[i,s]=I_[e.format];t._zod.onattach.push(o=>{let a=o._zod.bag;a.format=e.format,a.minimum=i,a.maximum=s,r&&(a.pattern=Y_)}),t._zod.check=o=>{let a=o.value;if(r){if(!Number.isInteger(a)){o.issues.push({expected:n,format:e.format,code:"invalid_type",continue:!1,input:a,inst:t});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:t,origin:n,inclusive:!0,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:t,origin:n,inclusive:!0,continue:!e.abort});return}}as&&o.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inclusive:!0,inst:t,continue:!e.abort})}}),$R=O("$ZodCheckBigIntFormat",(t,e)=>{_t.init(t,e);let[r,n]=R_[e.format];t._zod.onattach.push(i=>{let s=i._zod.bag;s.format=e.format,s.minimum=r,s.maximum=n}),t._zod.check=i=>{let s=i.value;sn&&i.issues.push({origin:"bigint",input:s,code:"too_big",maximum:n,inclusive:!0,inst:t,continue:!e.abort})}}),IR=O("$ZodCheckMaxSize",(t,e)=>{var r;_t.init(t,e),(r=t._zod.def).when??(r.when=n=>{let i=n.value;return!Bs(i)&&i.size!==void 0}),t._zod.onattach.push(n=>{let i=n._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum{let i=n.value;i.size<=e.maximum||n.issues.push({origin:hl(i),code:"too_big",maximum:e.maximum,inclusive:!0,input:i,inst:t,continue:!e.abort})}}),RR=O("$ZodCheckMinSize",(t,e)=>{var r;_t.init(t,e),(r=t._zod.def).when??(r.when=n=>{let i=n.value;return!Bs(i)&&i.size!==void 0}),t._zod.onattach.push(n=>{let i=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>i&&(n._zod.bag.minimum=e.minimum)}),t._zod.check=n=>{let i=n.value;i.size>=e.minimum||n.issues.push({origin:hl(i),code:"too_small",minimum:e.minimum,inclusive:!0,input:i,inst:t,continue:!e.abort})}}),OR=O("$ZodCheckSizeEquals",(t,e)=>{var r;_t.init(t,e),(r=t._zod.def).when??(r.when=n=>{let i=n.value;return!Bs(i)&&i.size!==void 0}),t._zod.onattach.push(n=>{let i=n._zod.bag;i.minimum=e.size,i.maximum=e.size,i.size=e.size}),t._zod.check=n=>{let i=n.value,s=i.size;if(s===e.size)return;let o=s>e.size;n.issues.push({origin:hl(i),...o?{code:"too_big",maximum:e.size}:{code:"too_small",minimum:e.size},inclusive:!0,exact:!0,input:n.value,inst:t,continue:!e.abort})}}),CR=O("$ZodCheckMaxLength",(t,e)=>{var r;_t.init(t,e),(r=t._zod.def).when??(r.when=n=>{let i=n.value;return!Bs(i)&&i.length!==void 0}),t._zod.onattach.push(n=>{let i=n._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum{let i=n.value;if(i.length<=e.maximum)return;let o=gl(i);n.issues.push({origin:o,code:"too_big",maximum:e.maximum,inclusive:!0,input:i,inst:t,continue:!e.abort})}}),PR=O("$ZodCheckMinLength",(t,e)=>{var r;_t.init(t,e),(r=t._zod.def).when??(r.when=n=>{let i=n.value;return!Bs(i)&&i.length!==void 0}),t._zod.onattach.push(n=>{let i=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>i&&(n._zod.bag.minimum=e.minimum)}),t._zod.check=n=>{let i=n.value;if(i.length>=e.minimum)return;let o=gl(i);n.issues.push({origin:o,code:"too_small",minimum:e.minimum,inclusive:!0,input:i,inst:t,continue:!e.abort})}}),AR=O("$ZodCheckLengthEquals",(t,e)=>{var r;_t.init(t,e),(r=t._zod.def).when??(r.when=n=>{let i=n.value;return!Bs(i)&&i.length!==void 0}),t._zod.onattach.push(n=>{let i=n._zod.bag;i.minimum=e.length,i.maximum=e.length,i.length=e.length}),t._zod.check=n=>{let i=n.value,s=i.length;if(s===e.length)return;let o=gl(i),a=s>e.length;n.issues.push({origin:o,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:n.value,inst:t,continue:!e.abort})}}),$l=O("$ZodCheckStringFormat",(t,e)=>{var r,n;_t.init(t,e),t._zod.onattach.push(i=>{let s=i._zod.bag;s.format=e.format,e.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(e.pattern))}),e.pattern?(r=t._zod).check??(r.check=i=>{e.pattern.lastIndex=0,!e.pattern.test(i.value)&&i.issues.push({origin:"string",code:"invalid_format",format:e.format,input:i.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(n=t._zod).check??(n.check=()=>{})}),NR=O("$ZodCheckRegex",(t,e)=>{$l.init(t,e),t._zod.check=r=>{e.pattern.lastIndex=0,!e.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),MR=O("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=rb),$l.init(t,e)}),DR=O("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=nb),$l.init(t,e)}),jR=O("$ZodCheckIncludes",(t,e)=>{_t.init(t,e);let r=Dn(e.includes),n=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=n,t._zod.onattach.push(i=>{let s=i._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),t._zod.check=i=>{i.value.includes(e.includes,e.position)||i.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:i.value,inst:t,continue:!e.abort})}}),zR=O("$ZodCheckStartsWith",(t,e)=>{_t.init(t,e);let r=new RegExp(`^${Dn(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let i=n._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(r)}),t._zod.check=n=>{n.value.startsWith(e.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:n.value,inst:t,continue:!e.abort})}}),LR=O("$ZodCheckEndsWith",(t,e)=>{_t.init(t,e);let r=new RegExp(`.*${Dn(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let i=n._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(r)}),t._zod.check=n=>{n.value.endsWith(e.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:n.value,inst:t,continue:!e.abort})}});function wR(t,e,r){t.issues.length&&e.issues.push(...xn(r,t.issues))}var UR=O("$ZodCheckProperty",(t,e)=>{_t.init(t,e),t._zod.check=r=>{let n=e.schema._zod.run({value:r.value[e.property],issues:[]},{});if(n instanceof Promise)return n.then(i=>wR(i,r,e.property));wR(n,r,e.property)}}),FR=O("$ZodCheckMimeType",(t,e)=>{_t.init(t,e);let r=new Set(e.mime);t._zod.onattach.push(n=>{n._zod.bag.mime=e.mime}),t._zod.check=n=>{r.has(n.value.type)||n.issues.push({code:"invalid_value",values:e.mime,input:n.value.type,inst:t,continue:!e.abort})}}),qR=O("$ZodCheckOverwrite",(t,e)=>{_t.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}});var Jf=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 n=e.split(` `).filter(o=>o),i=Math.min(...n.map(o=>o.length-o.trimStart().length)),s=n.map(o=>o.slice(i)).map(o=>" ".repeat(this.indent*2)+o);for(let o of s)this.content.push(o)}compile(){let e=Function,r=this?.args,i=[...(this?.content??[""]).map(s=>` ${s}`)];return new e(...r,i.join(` `))}};var ZR={major:4,minor:3,patch:4};var Ce=O("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=ZR;let n=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&n.unshift(t);for(let i of n)for(let s of i._zod.onattach)s(t);if(n.length===0)(r=t._zod).deferred??(r.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let i=(o,a,c)=>{let u=Vs(o),l;for(let d of a){if(d._zod.def.when){if(!d._zod.def.when(o))continue}else if(u)continue;let p=o.issues.length,f=d._zod.check(o);if(f instanceof Promise&&c?.async===!1)throw new Ci;if(l||f instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await f,o.issues.length!==p&&(u||(u=Vs(o,p)))});else{if(o.issues.length===p)continue;u||(u=Vs(o,p))}}return l?l.then(()=>o):o},s=(o,a,c)=>{if(Vs(o))return o.aborted=!0,o;let u=i(a,n,c);if(u instanceof Promise){if(c.async===!1)throw new Ci;return u.then(l=>t._zod.parse(l,c))}return t._zod.parse(u,c)};t._zod.run=(o,a)=>{if(a.skipChecks)return t._zod.parse(o,a);if(a.direction==="backward"){let u=t._zod.parse({value:o.value,issues:[]},{...a,skipChecks:!0});return u instanceof Promise?u.then(l=>s(l,o,a)):s(u,o,a)}let c=t._zod.parse(o,a);if(c instanceof Promise){if(a.async===!1)throw new Ci;return c.then(u=>i(u,n,a))}return i(c,n,a)}}Le(t,"~standard",()=>({validate:i=>{try{let s=Ya(t,i);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return El(t,i).then(o=>o.success?{value:o.data}:{issues:o.error?.issues})}},vendor:"zod",version:1}))}),Ao=O("$ZodString",(t,e)=>{Ce.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??J_(t._zod.bag),t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:t}),r}}),mt=O("$ZodStringFormat",(t,e)=>{$l.init(t,e),Ao.init(t,e)}),ab=O("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=j_),mt.init(t,e)}),cb=O("$ZodUUID",(t,e)=>{if(e.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(n===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=Po(n))}else e.pattern??(e.pattern=Po());mt.init(t,e)}),ub=O("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=z_),mt.init(t,e)}),lb=O("$ZodURL",(t,e)=>{mt.init(t,e),t._zod.check=r=>{try{let n=r.value.trim(),i=new URL(n);e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(i.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:e.hostname.source,input:r.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(i.protocol.endsWith(":")?i.protocol.slice(0,-1):i.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:r.value,inst:t,continue:!e.abort})),e.normalize?r.value=i.href:r.value=n;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:t,continue:!e.abort})}}}),db=O("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=L_()),mt.init(t,e)}),pb=O("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=M_),mt.init(t,e)}),fb=O("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=O_),mt.init(t,e)}),mb=O("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=C_),mt.init(t,e)}),hb=O("$ZodULID",(t,e)=>{e.pattern??(e.pattern=P_),mt.init(t,e)}),gb=O("$ZodXID",(t,e)=>{e.pattern??(e.pattern=A_),mt.init(t,e)}),vb=O("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=N_),mt.init(t,e)}),yb=O("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=K_(e)),mt.init(t,e)}),_b=O("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=W_),mt.init(t,e)}),bb=O("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=V_(e)),mt.init(t,e)}),Sb=O("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=D_),mt.init(t,e)}),xb=O("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=U_),mt.init(t,e),t._zod.bag.format="ipv4"}),wb=O("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=F_),mt.init(t,e),t._zod.bag.format="ipv6",t._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:t,continue:!e.abort})}}}),Eb=O("$ZodMAC",(t,e)=>{e.pattern??(e.pattern=q_(e.delimiter)),mt.init(t,e),t._zod.bag.format="mac"}),kb=O("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=H_),mt.init(t,e)}),Tb=O("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=Z_),mt.init(t,e),t._zod.check=r=>{let n=r.value.split("/");try{if(n.length!==2)throw new Error;let[i,s]=n;if(!s)throw new Error;let o=Number(s);if(`${o}`!==s)throw new Error;if(o<0||o>128)throw new Error;new URL(`http://[${i}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:t,continue:!e.abort})}}});function r1(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}var $b=O("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=B_),mt.init(t,e),t._zod.bag.contentEncoding="base64",t._zod.check=r=>{r1(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});function A3(t){if(!Vf.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return r1(r)}var Ib=O("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Vf),mt.init(t,e),t._zod.bag.contentEncoding="base64url",t._zod.check=r=>{A3(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),Rb=O("$ZodE164",(t,e)=>{e.pattern??(e.pattern=G_),mt.init(t,e)});function N3(t,e=null){try{let r=t.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let i=JSON.parse(atob(n));return!("typ"in i&&i?.typ!=="JWT"||!i.alg||e&&(!("alg"in i)||i.alg!==e))}catch{return!1}}var Ob=O("$ZodJWT",(t,e)=>{mt.init(t,e),t._zod.check=r=>{N3(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}}),Cb=O("$ZodCustomStringFormat",(t,e)=>{mt.init(t,e),t._zod.check=r=>{e.fn(r.value)||r.issues.push({code:"invalid_format",format:e.format,input:r.value,inst:t,continue:!e.abort})}}),rm=O("$ZodNumber",(t,e)=>{Ce.init(t,e),t._zod.pattern=t._zod.bag.pattern??Kf,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=Number(r.value)}catch{}let i=r.value;if(typeof i=="number"&&!Number.isNaN(i)&&Number.isFinite(i))return r;let s=typeof i=="number"?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:i,inst:t,...s?{received:s}:{}}),r}}),Pb=O("$ZodNumberFormat",(t,e)=>{TR.init(t,e),rm.init(t,e)}),Il=O("$ZodBoolean",(t,e)=>{Ce.init(t,e),t._zod.pattern=Q_,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=!!r.value}catch{}let i=r.value;return typeof i=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:t}),r}}),nm=O("$ZodBigInt",(t,e)=>{Ce.init(t,e),t._zod.pattern=X_,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=BigInt(r.value)}catch{}return typeof r.value=="bigint"||r.issues.push({expected:"bigint",code:"invalid_type",input:r.value,inst:t}),r}}),Ab=O("$ZodBigIntFormat",(t,e)=>{$R.init(t,e),nm.init(t,e)}),Nb=O("$ZodSymbol",(t,e)=>{Ce.init(t,e),t._zod.parse=(r,n)=>{let i=r.value;return typeof i=="symbol"||r.issues.push({expected:"symbol",code:"invalid_type",input:i,inst:t}),r}}),Mb=O("$ZodUndefined",(t,e)=>{Ce.init(t,e),t._zod.pattern=tb,t._zod.values=new Set([void 0]),t._zod.optin="optional",t._zod.optout="optional",t._zod.parse=(r,n)=>{let i=r.value;return typeof i>"u"||r.issues.push({expected:"undefined",code:"invalid_type",input:i,inst:t}),r}}),Db=O("$ZodNull",(t,e)=>{Ce.init(t,e),t._zod.pattern=eb,t._zod.values=new Set([null]),t._zod.parse=(r,n)=>{let i=r.value;return i===null||r.issues.push({expected:"null",code:"invalid_type",input:i,inst:t}),r}}),jb=O("$ZodAny",(t,e)=>{Ce.init(t,e),t._zod.parse=r=>r}),zb=O("$ZodUnknown",(t,e)=>{Ce.init(t,e),t._zod.parse=r=>r}),Lb=O("$ZodNever",(t,e)=>{Ce.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)}),Ub=O("$ZodVoid",(t,e)=>{Ce.init(t,e),t._zod.parse=(r,n)=>{let i=r.value;return typeof i>"u"||r.issues.push({expected:"void",code:"invalid_type",input:i,inst:t}),r}}),Fb=O("$ZodDate",(t,e)=>{Ce.init(t,e),t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=new Date(r.value)}catch{}let i=r.value,s=i instanceof Date;return s&&!Number.isNaN(i.getTime())||r.issues.push({expected:"date",code:"invalid_type",input:i,...s?{received:"Invalid Date"}:{},inst:t}),r}});function BR(t,e,r){t.issues.length&&e.issues.push(...xn(r,t.issues)),e.value[r]=t.value}var qb=O("$ZodArray",(t,e)=>{Ce.init(t,e),t._zod.parse=(r,n)=>{let i=r.value;if(!Array.isArray(i))return r.issues.push({expected:"array",code:"invalid_type",input:i,inst:t}),r;r.value=Array(i.length);let s=[];for(let o=0;oBR(u,r,o))):BR(c,r,o)}return s.length?Promise.all(s).then(()=>r):r}});function tm(t,e,r,n,i){if(t.issues.length){if(i&&!(r in n))return;e.issues.push(...xn(r,t.issues))}t.value===void 0?r in n&&(e.value[r]=void 0):e.value[r]=t.value}function n1(t){let e=Object.keys(t.shape);for(let n of e)if(!t.shape?.[n]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${n}": expected a Zod schema`);let r=$_(t.shape);return{...t,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(r)}}function i1(t,e,r,n,i,s){let o=[],a=i.keySet,c=i.catchall._zod,u=c.def.type,l=c.optout==="optional";for(let d in e){if(a.has(d))continue;if(u==="never"){o.push(d);continue}let p=c.run({value:e[d],issues:[]},n);p instanceof Promise?t.push(p.then(f=>tm(f,r,d,e,l))):tm(p,r,d,e,l)}return o.length&&r.issues.push({code:"unrecognized_keys",keys:o,input:e,inst:s}),t.length?Promise.all(t).then(()=>r):r}var s1=O("$ZodObject",(t,e)=>{if(Ce.init(t,e),!Object.getOwnPropertyDescriptor(e,"shape")?.get){let a=e.shape;Object.defineProperty(e,"shape",{get:()=>{let c={...a};return Object.defineProperty(e,"shape",{value:c}),c}})}let n=Ja(()=>n1(e));Le(t._zod,"propValues",()=>{let a=e.shape,c={};for(let u in a){let l=a[u]._zod;if(l.values){c[u]??(c[u]=new Set);for(let d of l.values)c[u].add(d)}}return c});let i=Co,s=e.catchall,o;t._zod.parse=(a,c)=>{o??(o=n.value);let u=a.value;if(!i(u))return a.issues.push({expected:"object",code:"invalid_type",input:u,inst:t}),a;a.value={};let l=[],d=o.shape;for(let p of o.keys){let f=d[p],m=f._zod.optout==="optional",h=f._zod.run({value:u[p],issues:[]},c);h instanceof Promise?l.push(h.then(g=>tm(g,a,p,u,m))):tm(h,a,p,u,m)}return s?i1(l,u,a,c,n.value,t):l.length?Promise.all(l).then(()=>a):a}}),o1=O("$ZodObjectJIT",(t,e)=>{s1.init(t,e);let r=t._zod.parse,n=Ja(()=>n1(e)),i=p=>{let f=new Jf(["shape","payload","ctx"]),m=n.value,h=_=>{let y=Hf(_);return`shape[${y}]._zod.run({ value: input[${y}], issues: [] }, ctx)`};f.write("const input = payload.value;");let g=Object.create(null),v=0;for(let _ of m.keys)g[_]=`key_${v++}`;f.write("const newResult = {};");for(let _ of m.keys){let y=g[_],x=Hf(_),E=p[_]?._zod?.optout==="optional";f.write(`const ${y} = ${h(_)};`),E?f.write(` if (${y}.issues.length) { @@ -890,11 +890,11 @@ ${a}`}(0,cr.writeFileSync)(i,c),(0,cr.renameSync)(i,n)}function ESe(t,e,r,n,i,s, `)}f.write("payload.value = newResult;"),f.write("return payload;");let S=f.compile();return(_,y)=>S(p,_,y)},s,o=Co,a=!qf.jitless,u=a&&k_.value,l=e.catchall,d;t._zod.parse=(p,f)=>{d??(d=n.value);let m=p.value;return o(m)?a&&u&&f?.async===!1&&f.jitless!==!0?(s||(s=i(e.shape)),p=s(p,f),l?i1([],m,p,f,d,t):p):r(p,f):(p.issues.push({expected:"object",code:"invalid_type",input:m,inst:t}),p)}});function GR(t,e,r,n){for(let s of t)if(s.issues.length===0)return e.value=s.value,e;let i=t.filter(s=>!Vs(s));return i.length===1?(e.value=i[0].value,i[0]):(e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(s=>s.issues.map(o=>on(o,n,tr())))}),e)}var Rl=O("$ZodUnion",(t,e)=>{Ce.init(t,e),Le(t._zod,"optin",()=>e.options.some(i=>i._zod.optin==="optional")?"optional":void 0),Le(t._zod,"optout",()=>e.options.some(i=>i._zod.optout==="optional")?"optional":void 0),Le(t._zod,"values",()=>{if(e.options.every(i=>i._zod.values))return new Set(e.options.flatMap(i=>Array.from(i._zod.values)))}),Le(t._zod,"pattern",()=>{if(e.options.every(i=>i._zod.pattern)){let i=e.options.map(s=>s._zod.pattern);return new RegExp(`^(${i.map(s=>fl(s.source)).join("|")})$`)}});let r=e.options.length===1,n=e.options[0]._zod.run;t._zod.parse=(i,s)=>{if(r)return n(i,s);let o=!1,a=[];for(let c of e.options){let u=c._zod.run({value:i.value,issues:[]},s);if(u instanceof Promise)a.push(u),o=!0;else{if(u.issues.length===0)return u;a.push(u)}}return o?Promise.all(a).then(c=>GR(c,i,t,s)):GR(a,i,t,s)}});function WR(t,e,r,n){let i=t.filter(s=>s.issues.length===0);return i.length===1?(e.value=i[0].value,e):(i.length===0?e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(s=>s.issues.map(o=>on(o,n,tr())))}):e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:[],inclusive:!1}),e)}var Hb=O("$ZodXor",(t,e)=>{Rl.init(t,e),e.inclusive=!1;let r=e.options.length===1,n=e.options[0]._zod.run;t._zod.parse=(i,s)=>{if(r)return n(i,s);let o=!1,a=[];for(let c of e.options){let u=c._zod.run({value:i.value,issues:[]},s);u instanceof Promise?(a.push(u),o=!0):a.push(u)}return o?Promise.all(a).then(c=>WR(c,i,t,s)):WR(a,i,t,s)}}),Zb=O("$ZodDiscriminatedUnion",(t,e)=>{e.inclusive=!1,Rl.init(t,e);let r=t._zod.parse;Le(t._zod,"propValues",()=>{let i={};for(let s of e.options){let o=s._zod.propValues;if(!o||Object.keys(o).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(let[a,c]of Object.entries(o)){i[a]||(i[a]=new Set);for(let u of c)i[a].add(u)}}return i});let n=Ja(()=>{let i=e.options,s=new Map;for(let o of i){let a=o._zod.propValues?.[e.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(o)}"`);for(let c of a){if(s.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);s.set(c,o)}}return s});t._zod.parse=(i,s)=>{let o=i.value;if(!Co(o))return i.issues.push({code:"invalid_type",expected:"object",input:o,inst:t}),i;let a=n.value.get(o?.[e.discriminator]);return a?a._zod.run(i,s):e.unionFallback?r(i,s):(i.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:e.discriminator,input:o,path:[e.discriminator],inst:t}),i)}}),Bb=O("$ZodIntersection",(t,e)=>{Ce.init(t,e),t._zod.parse=(r,n)=>{let i=r.value,s=e.left._zod.run({value:i,issues:[]},n),o=e.right._zod.run({value:i,issues:[]},n);return s instanceof Promise||o instanceof Promise?Promise.all([s,o]).then(([c,u])=>VR(r,c,u)):VR(r,s,o)}});function ob(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(Ws(t)&&Ws(e)){let r=Object.keys(e),n=Object.keys(t).filter(s=>r.indexOf(s)!==-1),i={...t,...e};for(let s of n){let o=ob(t[s],e[s]);if(!o.valid)return{valid:!1,mergeErrorPath:[s,...o.mergeErrorPath]};i[s]=o.data}return{valid:!0,data:i}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;na.l&&a.r).map(([a])=>a);if(s.length&&i&&t.issues.push({...i,keys:s}),Vs(t))return t;let o=ob(e.value,r.value);if(!o.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(o.mergeErrorPath)}`);return t.value=o.data,t}var im=O("$ZodTuple",(t,e)=>{Ce.init(t,e);let r=e.items;t._zod.parse=(n,i)=>{let s=n.value;if(!Array.isArray(s))return n.issues.push({input:s,inst:t,expected:"tuple",code:"invalid_type"}),n;n.value=[];let o=[],a=[...r].reverse().findIndex(l=>l._zod.optin!=="optional"),c=a===-1?0:r.length-a;if(!e.rest){let l=s.length>r.length,d=s.length=s.length&&u>=c)continue;let d=l._zod.run({value:s[u],issues:[]},i);d instanceof Promise?o.push(d.then(p=>Xf(p,n,u))):Xf(d,n,u)}if(e.rest){let l=s.slice(r.length);for(let d of l){u++;let p=e.rest._zod.run({value:d,issues:[]},i);p instanceof Promise?o.push(p.then(f=>Xf(f,n,u))):Xf(p,n,u)}}return o.length?Promise.all(o).then(()=>n):n}});function Xf(t,e,r){t.issues.length&&e.issues.push(...xn(r,t.issues)),e.value[r]=t.value}var Gb=O("$ZodRecord",(t,e)=>{Ce.init(t,e),t._zod.parse=(r,n)=>{let i=r.value;if(!Ws(i))return r.issues.push({expected:"record",code:"invalid_type",input:i,inst:t}),r;let s=[],o=e.keyType._zod.values;if(o){r.value={};let a=new Set;for(let u of o)if(typeof u=="string"||typeof u=="number"||typeof u=="symbol"){a.add(typeof u=="number"?u.toString():u);let l=e.valueType._zod.run({value:i[u],issues:[]},n);l instanceof Promise?s.push(l.then(d=>{d.issues.length&&r.issues.push(...xn(u,d.issues)),r.value[u]=d.value})):(l.issues.length&&r.issues.push(...xn(u,l.issues)),r.value[u]=l.value)}let c;for(let u in i)a.has(u)||(c=c??[],c.push(u));c&&c.length>0&&r.issues.push({code:"unrecognized_keys",input:i,inst:t,keys:c})}else{r.value={};for(let a of Reflect.ownKeys(i)){if(a==="__proto__")continue;let c=e.keyType._zod.run({value:a,issues:[]},n);if(c instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof a=="string"&&Kf.test(a)&&c.issues.length&&c.issues.some(d=>d.code==="invalid_type"&&d.expected==="number")){let d=e.keyType._zod.run({value:Number(a),issues:[]},n);if(d instanceof Promise)throw new Error("Async schemas not supported in object keys currently");d.issues.length===0&&(c=d)}if(c.issues.length){e.mode==="loose"?r.value[a]=i[a]:r.issues.push({code:"invalid_key",origin:"record",issues:c.issues.map(d=>on(d,n,tr())),input:a,path:[a],inst:t});continue}let l=e.valueType._zod.run({value:i[a],issues:[]},n);l instanceof Promise?s.push(l.then(d=>{d.issues.length&&r.issues.push(...xn(a,d.issues)),r.value[c.value]=d.value})):(l.issues.length&&r.issues.push(...xn(a,l.issues)),r.value[c.value]=l.value)}}return s.length?Promise.all(s).then(()=>r):r}}),Wb=O("$ZodMap",(t,e)=>{Ce.init(t,e),t._zod.parse=(r,n)=>{let i=r.value;if(!(i instanceof Map))return r.issues.push({expected:"map",code:"invalid_type",input:i,inst:t}),r;let s=[];r.value=new Map;for(let[o,a]of i){let c=e.keyType._zod.run({value:o,issues:[]},n),u=e.valueType._zod.run({value:a,issues:[]},n);c instanceof Promise||u instanceof Promise?s.push(Promise.all([c,u]).then(([l,d])=>{KR(l,d,r,o,i,t,n)})):KR(c,u,r,o,i,t,n)}return s.length?Promise.all(s).then(()=>r):r}});function KR(t,e,r,n,i,s,o){t.issues.length&&(ml.has(typeof n)?r.issues.push(...xn(n,t.issues)):r.issues.push({code:"invalid_key",origin:"map",input:i,inst:s,issues:t.issues.map(a=>on(a,o,tr()))})),e.issues.length&&(ml.has(typeof n)?r.issues.push(...xn(n,e.issues)):r.issues.push({origin:"map",code:"invalid_element",input:i,inst:s,key:n,issues:e.issues.map(a=>on(a,o,tr()))})),r.value.set(t.value,e.value)}var Vb=O("$ZodSet",(t,e)=>{Ce.init(t,e),t._zod.parse=(r,n)=>{let i=r.value;if(!(i instanceof Set))return r.issues.push({input:i,inst:t,expected:"set",code:"invalid_type"}),r;let s=[];r.value=new Set;for(let o of i){let a=e.valueType._zod.run({value:o,issues:[]},n);a instanceof Promise?s.push(a.then(c=>JR(c,r))):JR(a,r)}return s.length?Promise.all(s).then(()=>r):r}});function JR(t,e){t.issues.length&&e.issues.push(...t.issues),e.value.add(t.value)}var Kb=O("$ZodEnum",(t,e)=>{Ce.init(t,e);let r=pl(e.entries),n=new Set(r);t._zod.values=n,t._zod.pattern=new RegExp(`^(${r.filter(i=>ml.has(typeof i)).map(i=>typeof i=="string"?Dn(i):i.toString()).join("|")})$`),t._zod.parse=(i,s)=>{let o=i.value;return n.has(o)||i.issues.push({code:"invalid_value",values:r,input:o,inst:t}),i}}),Jb=O("$ZodLiteral",(t,e)=>{if(Ce.init(t,e),e.values.length===0)throw new Error("Cannot create literal schema with no valid values");let r=new Set(e.values);t._zod.values=r,t._zod.pattern=new RegExp(`^(${e.values.map(n=>typeof n=="string"?Dn(n):n?Dn(n.toString()):String(n)).join("|")})$`),t._zod.parse=(n,i)=>{let s=n.value;return r.has(s)||n.issues.push({code:"invalid_value",values:e.values,input:s,inst:t}),n}}),Xb=O("$ZodFile",(t,e)=>{Ce.init(t,e),t._zod.parse=(r,n)=>{let i=r.value;return i instanceof File||r.issues.push({expected:"file",code:"invalid_type",input:i,inst:t}),r}}),Yb=O("$ZodTransform",(t,e)=>{Ce.init(t,e),t._zod.parse=(r,n)=>{if(n.direction==="backward")throw new Oo(t.constructor.name);let i=e.transform(r.value,r);if(n.async)return(i instanceof Promise?i:Promise.resolve(i)).then(o=>(r.value=o,r));if(i instanceof Promise)throw new Ci;return r.value=i,r}});function XR(t,e){return t.issues.length&&e===void 0?{issues:[],value:void 0}:t}var sm=O("$ZodOptional",(t,e)=>{Ce.init(t,e),t._zod.optin="optional",t._zod.optout="optional",Le(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),Le(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${fl(r.source)})?$`):void 0}),t._zod.parse=(r,n)=>{if(e.innerType._zod.optin==="optional"){let i=e.innerType._zod.run(r,n);return i instanceof Promise?i.then(s=>XR(s,r.value)):XR(i,r.value)}return r.value===void 0?r:e.innerType._zod.run(r,n)}}),Qb=O("$ZodExactOptional",(t,e)=>{sm.init(t,e),Le(t._zod,"values",()=>e.innerType._zod.values),Le(t._zod,"pattern",()=>e.innerType._zod.pattern),t._zod.parse=(r,n)=>e.innerType._zod.run(r,n)}),eS=O("$ZodNullable",(t,e)=>{Ce.init(t,e),Le(t._zod,"optin",()=>e.innerType._zod.optin),Le(t._zod,"optout",()=>e.innerType._zod.optout),Le(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${fl(r.source)}|null)$`):void 0}),Le(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(r,n)=>r.value===null?r:e.innerType._zod.run(r,n)}),tS=O("$ZodDefault",(t,e)=>{Ce.init(t,e),t._zod.optin="optional",Le(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(n.direction==="backward")return e.innerType._zod.run(r,n);if(r.value===void 0)return r.value=e.defaultValue,r;let i=e.innerType._zod.run(r,n);return i instanceof Promise?i.then(s=>YR(s,e)):YR(i,e)}});function YR(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}var rS=O("$ZodPrefault",(t,e)=>{Ce.init(t,e),t._zod.optin="optional",Le(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>(n.direction==="backward"||r.value===void 0&&(r.value=e.defaultValue),e.innerType._zod.run(r,n))}),nS=O("$ZodNonOptional",(t,e)=>{Ce.init(t,e),Le(t._zod,"values",()=>{let r=e.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),t._zod.parse=(r,n)=>{let i=e.innerType._zod.run(r,n);return i instanceof Promise?i.then(s=>QR(s,t)):QR(i,t)}});function QR(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}var iS=O("$ZodSuccess",(t,e)=>{Ce.init(t,e),t._zod.parse=(r,n)=>{if(n.direction==="backward")throw new Oo("ZodSuccess");let i=e.innerType._zod.run(r,n);return i instanceof Promise?i.then(s=>(r.value=s.issues.length===0,r)):(r.value=i.issues.length===0,r)}}),sS=O("$ZodCatch",(t,e)=>{Ce.init(t,e),Le(t._zod,"optin",()=>e.innerType._zod.optin),Le(t._zod,"optout",()=>e.innerType._zod.optout),Le(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(n.direction==="backward")return e.innerType._zod.run(r,n);let i=e.innerType._zod.run(r,n);return i instanceof Promise?i.then(s=>(r.value=s.value,s.issues.length&&(r.value=e.catchValue({...r,error:{issues:s.issues.map(o=>on(o,n,tr()))},input:r.value}),r.issues=[]),r)):(r.value=i.value,i.issues.length&&(r.value=e.catchValue({...r,error:{issues:i.issues.map(s=>on(s,n,tr()))},input:r.value}),r.issues=[]),r)}}),oS=O("$ZodNaN",(t,e)=>{Ce.init(t,e),t._zod.parse=(r,n)=>((typeof r.value!="number"||!Number.isNaN(r.value))&&r.issues.push({input:r.value,inst:t,expected:"nan",code:"invalid_type"}),r)}),aS=O("$ZodPipe",(t,e)=>{Ce.init(t,e),Le(t._zod,"values",()=>e.in._zod.values),Le(t._zod,"optin",()=>e.in._zod.optin),Le(t._zod,"optout",()=>e.out._zod.optout),Le(t._zod,"propValues",()=>e.in._zod.propValues),t._zod.parse=(r,n)=>{if(n.direction==="backward"){let s=e.out._zod.run(r,n);return s instanceof Promise?s.then(o=>Yf(o,e.in,n)):Yf(s,e.in,n)}let i=e.in._zod.run(r,n);return i instanceof Promise?i.then(s=>Yf(s,e.out,n)):Yf(i,e.out,n)}});function Yf(t,e,r){return t.issues.length?(t.aborted=!0,t):e._zod.run({value:t.value,issues:t.issues},r)}var Ol=O("$ZodCodec",(t,e)=>{Ce.init(t,e),Le(t._zod,"values",()=>e.in._zod.values),Le(t._zod,"optin",()=>e.in._zod.optin),Le(t._zod,"optout",()=>e.out._zod.optout),Le(t._zod,"propValues",()=>e.in._zod.propValues),t._zod.parse=(r,n)=>{if((n.direction||"forward")==="forward"){let s=e.in._zod.run(r,n);return s instanceof Promise?s.then(o=>Qf(o,e,n)):Qf(s,e,n)}else{let s=e.out._zod.run(r,n);return s instanceof Promise?s.then(o=>Qf(o,e,n)):Qf(s,e,n)}}});function Qf(t,e,r){if(t.issues.length)return t.aborted=!0,t;if((r.direction||"forward")==="forward"){let i=e.transform(t.value,t);return i instanceof Promise?i.then(s=>em(t,s,e.out,r)):em(t,i,e.out,r)}else{let i=e.reverseTransform(t.value,t);return i instanceof Promise?i.then(s=>em(t,s,e.in,r)):em(t,i,e.in,r)}}function em(t,e,r,n){return t.issues.length?(t.aborted=!0,t):r._zod.run({value:e,issues:t.issues},n)}var cS=O("$ZodReadonly",(t,e)=>{Ce.init(t,e),Le(t._zod,"propValues",()=>e.innerType._zod.propValues),Le(t._zod,"values",()=>e.innerType._zod.values),Le(t._zod,"optin",()=>e.innerType?._zod?.optin),Le(t._zod,"optout",()=>e.innerType?._zod?.optout),t._zod.parse=(r,n)=>{if(n.direction==="backward")return e.innerType._zod.run(r,n);let i=e.innerType._zod.run(r,n);return i instanceof Promise?i.then(e1):e1(i)}});function e1(t){return t.value=Object.freeze(t.value),t}var uS=O("$ZodTemplateLiteral",(t,e)=>{Ce.init(t,e);let r=[];for(let n of e.parts)if(typeof n=="object"&&n!==null){if(!n._zod.pattern)throw new Error(`Invalid template literal part, no pattern found: ${[...n._zod.traits].shift()}`);let i=n._zod.pattern instanceof RegExp?n._zod.pattern.source:n._zod.pattern;if(!i)throw new Error(`Invalid template literal part: ${n._zod.traits}`);let s=i.startsWith("^")?1:0,o=i.endsWith("$")?i.length-1:i.length;r.push(i.slice(s,o))}else if(n===null||T_.has(typeof n))r.push(Dn(`${n}`));else throw new Error(`Invalid template literal part: ${n}`);t._zod.pattern=new RegExp(`^${r.join("")}$`),t._zod.parse=(n,i)=>typeof n.value!="string"?(n.issues.push({input:n.value,inst:t,expected:"string",code:"invalid_type"}),n):(t._zod.pattern.lastIndex=0,t._zod.pattern.test(n.value)||n.issues.push({input:n.value,inst:t,code:"invalid_format",format:e.format??"template_literal",pattern:t._zod.pattern.source}),n)}),lS=O("$ZodFunction",(t,e)=>(Ce.init(t,e),t._def=e,t._zod.def=e,t.implement=r=>{if(typeof r!="function")throw new Error("implement() must be called with a function");return function(...n){let i=t._def.input?_l(t._def.input,n):n,s=Reflect.apply(r,this,i);return t._def.output?_l(t._def.output,s):s}},t.implementAsync=r=>{if(typeof r!="function")throw new Error("implementAsync() must be called with a function");return async function(...n){let i=t._def.input?await Sl(t._def.input,n):n,s=await Reflect.apply(r,this,i);return t._def.output?await Sl(t._def.output,s):s}},t._zod.parse=(r,n)=>typeof r.value!="function"?(r.issues.push({code:"invalid_type",expected:"function",input:r.value,inst:t}),r):(t._def.output&&t._def.output._zod.def.type==="promise"?r.value=t.implementAsync(r.value):r.value=t.implement(r.value),r),t.input=(...r)=>{let n=t.constructor;return Array.isArray(r[0])?new n({type:"function",input:new im({type:"tuple",items:r[0],rest:r[1]}),output:t._def.output}):new n({type:"function",input:r[0],output:t._def.output})},t.output=r=>{let n=t.constructor;return new n({type:"function",input:t._def.input,output:r})},t)),dS=O("$ZodPromise",(t,e)=>{Ce.init(t,e),t._zod.parse=(r,n)=>Promise.resolve(r.value).then(i=>e.innerType._zod.run({value:i,issues:[]},n))}),pS=O("$ZodLazy",(t,e)=>{Ce.init(t,e),Le(t._zod,"innerType",()=>e.getter()),Le(t._zod,"pattern",()=>t._zod.innerType?._zod?.pattern),Le(t._zod,"propValues",()=>t._zod.innerType?._zod?.propValues),Le(t._zod,"optin",()=>t._zod.innerType?._zod?.optin??void 0),Le(t._zod,"optout",()=>t._zod.innerType?._zod?.optout??void 0),t._zod.parse=(r,n)=>t._zod.innerType._zod.run(r,n)}),fS=O("$ZodCustom",(t,e)=>{_t.init(t,e),Ce.init(t,e),t._zod.parse=(r,n)=>r,t._zod.check=r=>{let n=r.value,i=e.fn(n);if(i instanceof Promise)return i.then(s=>t1(s,r,n,t));t1(i,r,n,t)}});function t1(t,e,r,n){if(!t){let i={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(i.params=n._zod.def.params),e.issues.push(Xa(i))}}var D3=()=>{let t={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function e(i){return t[i]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},n={nan:"NaN"};return i=>{switch(i.code){case"invalid_type":{let s=n[i.expected]??i.expected,o=we(i.input),a=n[o]??o;return`Invalid input: expected ${s}, received ${a}`}case"invalid_value":return i.values.length===1?`Invalid input: expected ${be(i.values[0])}`:`Invalid option: expected one of ${_e(i.values,"|")}`;case"too_big":{let s=i.inclusive?"<=":"<",o=e(i.origin);return o?`Too big: expected ${i.origin??"value"} to have ${s}${i.maximum.toString()} ${o.unit??"elements"}`:`Too big: expected ${i.origin??"value"} to be ${s}${i.maximum.toString()}`}case"too_small":{let s=i.inclusive?">=":">",o=e(i.origin);return o?`Too small: expected ${i.origin} to have ${s}${i.minimum.toString()} ${o.unit}`:`Too small: expected ${i.origin} to be ${s}${i.minimum.toString()}`}case"invalid_format":{let s=i;return s.format==="starts_with"?`Invalid string: must start with "${s.prefix}"`:s.format==="ends_with"?`Invalid string: must end with "${s.suffix}"`:s.format==="includes"?`Invalid string: must include "${s.includes}"`:s.format==="regex"?`Invalid string: must match pattern ${s.pattern}`:`Invalid ${r[s.format]??i.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${i.divisor}`;case"unrecognized_keys":return`Unrecognized key${i.keys.length>1?"s":""}: ${_e(i.keys,", ")}`;case"invalid_key":return`Invalid key in ${i.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${i.origin}`;default:return"Invalid input"}}};function mS(){return{localeError:D3()}}var a1;var gS=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...r){let n=r[0];return this._map.set(e,n),n&&typeof n=="object"&&"id"in n&&this._idmap.set(n.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let r=this._map.get(e);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(e),this}get(e){let r=e._zod.parent;if(r){let n={...this.get(r)??{}};delete n.id;let i={...n,...this._map.get(e)};return Object.keys(i).length?i:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function vS(){return new gS}(a1=globalThis).__zod_globalRegistry??(a1.__zod_globalRegistry=vS());var Br=globalThis.__zod_globalRegistry;function yS(t,e){return new t({type:"string",...ee(e)})}function om(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...ee(e)})}function Cl(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...ee(e)})}function am(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...ee(e)})}function cm(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...ee(e)})}function um(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...ee(e)})}function lm(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...ee(e)})}function Pl(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...ee(e)})}function dm(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...ee(e)})}function pm(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...ee(e)})}function fm(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...ee(e)})}function mm(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...ee(e)})}function hm(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...ee(e)})}function gm(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...ee(e)})}function vm(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...ee(e)})}function ym(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...ee(e)})}function _m(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...ee(e)})}function _S(t,e){return new t({type:"string",format:"mac",check:"string_format",abort:!1,...ee(e)})}function bm(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...ee(e)})}function Sm(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...ee(e)})}function xm(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...ee(e)})}function wm(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...ee(e)})}function Em(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...ee(e)})}function km(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...ee(e)})}function bS(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...ee(e)})}function SS(t,e){return new t({type:"string",format:"date",check:"string_format",...ee(e)})}function xS(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...ee(e)})}function wS(t,e){return new t({type:"string",format:"duration",check:"string_format",...ee(e)})}function ES(t,e){return new t({type:"number",checks:[],...ee(e)})}function kS(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...ee(e)})}function TS(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"float32",...ee(e)})}function $S(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"float64",...ee(e)})}function IS(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"int32",...ee(e)})}function RS(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"uint32",...ee(e)})}function OS(t,e){return new t({type:"boolean",...ee(e)})}function CS(t,e){return new t({type:"bigint",...ee(e)})}function PS(t,e){return new t({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...ee(e)})}function AS(t,e){return new t({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...ee(e)})}function NS(t,e){return new t({type:"symbol",...ee(e)})}function MS(t,e){return new t({type:"undefined",...ee(e)})}function DS(t,e){return new t({type:"null",...ee(e)})}function jS(t){return new t({type:"any"})}function zS(t){return new t({type:"unknown"})}function LS(t,e){return new t({type:"never",...ee(e)})}function US(t,e){return new t({type:"void",...ee(e)})}function FS(t,e){return new t({type:"date",...ee(e)})}function qS(t,e){return new t({type:"nan",...ee(e)})}function us(t,e){return new ib({check:"less_than",...ee(e),value:t,inclusive:!1})}function wn(t,e){return new ib({check:"less_than",...ee(e),value:t,inclusive:!0})}function ls(t,e){return new sb({check:"greater_than",...ee(e),value:t,inclusive:!1})}function Gr(t,e){return new sb({check:"greater_than",...ee(e),value:t,inclusive:!0})}function HS(t){return ls(0,t)}function ZS(t){return us(0,t)}function BS(t){return wn(0,t)}function GS(t){return Gr(0,t)}function No(t,e){return new kR({check:"multiple_of",...ee(e),value:t})}function Mo(t,e){return new IR({check:"max_size",...ee(e),maximum:t})}function ds(t,e){return new RR({check:"min_size",...ee(e),minimum:t})}function Qa(t,e){return new OR({check:"size_equals",...ee(e),size:t})}function ec(t,e){return new CR({check:"max_length",...ee(e),maximum:t})}function Ks(t,e){return new PR({check:"min_length",...ee(e),minimum:t})}function tc(t,e){return new AR({check:"length_equals",...ee(e),length:t})}function Al(t,e){return new NR({check:"string_format",format:"regex",...ee(e),pattern:t})}function Nl(t){return new MR({check:"string_format",format:"lowercase",...ee(t)})}function Ml(t){return new DR({check:"string_format",format:"uppercase",...ee(t)})}function Dl(t,e){return new jR({check:"string_format",format:"includes",...ee(e),includes:t})}function jl(t,e){return new zR({check:"string_format",format:"starts_with",...ee(e),prefix:t})}function zl(t,e){return new LR({check:"string_format",format:"ends_with",...ee(e),suffix:t})}function WS(t,e,r){return new UR({check:"property",property:t,schema:e,...ee(r)})}function Ll(t,e){return new FR({check:"mime_type",mime:t,...ee(e)})}function Pi(t){return new qR({check:"overwrite",tx:t})}function Ul(t){return Pi(e=>e.normalize(t))}function Fl(){return Pi(t=>t.trim())}function ql(){return Pi(t=>t.toLowerCase())}function Hl(){return Pi(t=>t.toUpperCase())}function Tm(){return Pi(t=>E_(t))}function c1(t,e,r){return new t({type:"array",element:e,...ee(r)})}function VS(t,e){return new t({type:"file",...ee(e)})}function KS(t,e,r){let n=ee(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function JS(t,e,r){return new t({type:"custom",check:"custom",fn:e,...ee(r)})}function XS(t){let e=U3(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(Xa(n,r.value,e._zod.def));else{let i=n;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=e),i.continue??(i.continue=!e._zod.def.abort),r.issues.push(Xa(i))}},t(r.value,r)));return e}function U3(t,e){let r=new _t({check:"custom",...ee(e)});return r._zod.check=t,r}function YS(t){let e=new _t({check:"describe"});return e._zod.onattach=[r=>{let n=Br.get(r)??{};Br.add(r,{...n,description:t})}],e._zod.check=()=>{},e}function QS(t){let e=new _t({check:"meta"});return e._zod.onattach=[r=>{let n=Br.get(r)??{};Br.add(r,{...n,...t})}],e._zod.check=()=>{},e}function ex(t,e){let r=ee(e),n=r.truthy??["true","1","yes","on","y","enabled"],i=r.falsy??["false","0","no","off","n","disabled"];r.case!=="sensitive"&&(n=n.map(f=>typeof f=="string"?f.toLowerCase():f),i=i.map(f=>typeof f=="string"?f.toLowerCase():f));let s=new Set(n),o=new Set(i),a=t.Codec??Ol,c=t.Boolean??Il,u=t.String??Ao,l=new u({type:"string",error:r.error}),d=new c({type:"boolean",error:r.error}),p=new a({type:"pipe",in:l,out:d,transform:((f,m)=>{let h=f;return r.case!=="sensitive"&&(h=h.toLowerCase()),s.has(h)?!0:o.has(h)?!1:(m.issues.push({code:"invalid_value",expected:"stringbool",values:[...s,...o],input:m.value,inst:p,continue:!1}),{})}),reverseTransform:((f,m)=>f===!0?n[0]||"true":i[0]||"false"),error:r.error});return p}function rc(t,e,r,n={}){let i=ee(n),s={...ee(n),check:"string_format",type:"string",format:e,fn:typeof r=="function"?r:a=>r.test(a),...i};return r instanceof RegExp&&(s.pattern=r),new t(s)}function $m(t){let e=t?.target??"draft-2020-12";return e==="draft-4"&&(e="draft-04"),e==="draft-7"&&(e="draft-07"),{processors:t.processors??{},metadataRegistry:t?.metadata??Br,target:e,unrepresentable:t?.unrepresentable??"throw",override:t?.override??(()=>{}),io:t?.io??"output",counter:0,seen:new Map,cycles:t?.cycles??"ref",reused:t?.reused??"inline",external:t?.external??void 0}}function kt(t,e,r={path:[],schemaPath:[]}){var n;let i=t._zod.def,s=e.seen.get(t);if(s)return s.count++,r.schemaPath.includes(t)&&(s.cycle=r.path),s.schema;let o={schema:{},count:1,cycle:void 0,path:r.path};e.seen.set(t,o);let a=t._zod.toJSONSchema?.();if(a)o.schema=a;else{let l={...r,schemaPath:[...r.schemaPath,t],path:r.path};if(t._zod.processJSONSchema)t._zod.processJSONSchema(e,o.schema,l);else{let p=o.schema,f=e.processors[i.type];if(!f)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);f(t,e,p,l)}let d=t._zod.parent;d&&(o.ref||(o.ref=d),kt(d,e,l),e.seen.get(d).isParent=!0)}let c=e.metadataRegistry.get(t);return c&&Object.assign(o.schema,c),e.io==="input"&&Wr(t)&&(delete o.schema.examples,delete o.schema.default),e.io==="input"&&o.schema._prefault&&((n=o.schema).default??(n.default=o.schema._prefault)),delete o.schema._prefault,e.seen.get(t).schema}function Im(t,e){let r=t.seen.get(e);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let n=new Map;for(let o of t.seen.entries()){let a=t.metadataRegistry.get(o[0])?.id;if(a){let c=n.get(a);if(c&&c!==o[0])throw new Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);n.set(a,o[0])}}let i=o=>{let a=t.target==="draft-2020-12"?"$defs":"definitions";if(t.external){let d=t.external.registry.get(o[0])?.id,p=t.external.uri??(m=>m);if(d)return{ref:p(d)};let f=o[1].defId??o[1].schema.id??`schema${t.counter++}`;return o[1].defId=f,{defId:f,ref:`${p("__shared")}#/${a}/${f}`}}if(o[1]===r)return{ref:"#"};let u=`#/${a}/`,l=o[1].schema.id??`__schema${t.counter++}`;return{defId:l,ref:u+l}},s=o=>{if(o[1].schema.$ref)return;let a=o[1],{ref:c,defId:u}=i(o);a.def={...a.schema},u&&(a.defId=u);let l=a.schema;for(let d in l)delete l[d];l.$ref=c};if(t.cycles==="throw")for(let o of t.seen.entries()){let a=o[1];if(a.cycle)throw new Error(`Cycle detected: #/${a.cycle?.join("/")}/ -Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let o of t.seen.entries()){let a=o[1];if(e===o[0]){s(o);continue}if(t.external){let u=t.external.registry.get(o[0])?.id;if(e!==o[0]&&u){s(o);continue}}if(t.metadataRegistry.get(o[0])?.id){s(o);continue}if(a.cycle){s(o);continue}if(a.count>1&&t.reused==="ref"){s(o);continue}}}function Rm(t,e){let r=t.seen.get(e);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let n=o=>{let a=t.seen.get(o);if(a.ref===null)return;let c=a.def??a.schema,u={...c},l=a.ref;if(a.ref=null,l){n(l);let p=t.seen.get(l),f=p.schema;if(f.$ref&&(t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0")?(c.allOf=c.allOf??[],c.allOf.push(f)):Object.assign(c,f),Object.assign(c,u),o._zod.parent===l)for(let h in c)h==="$ref"||h==="allOf"||h in u||delete c[h];if(f.$ref)for(let h in c)h==="$ref"||h==="allOf"||h in p.def&&JSON.stringify(c[h])===JSON.stringify(p.def[h])&&delete c[h]}let d=o._zod.parent;if(d&&d!==l){n(d);let p=t.seen.get(d);if(p?.schema.$ref&&(c.$ref=p.schema.$ref,p.def))for(let f in c)f==="$ref"||f==="allOf"||f in p.def&&JSON.stringify(c[f])===JSON.stringify(p.def[f])&&delete c[f]}t.override({zodSchema:o,jsonSchema:c,path:a.path??[]})};for(let o of[...t.seen.entries()].reverse())n(o[0]);let i={};if(t.target==="draft-2020-12"?i.$schema="https://json-schema.org/draft/2020-12/schema":t.target==="draft-07"?i.$schema="http://json-schema.org/draft-07/schema#":t.target==="draft-04"?i.$schema="http://json-schema.org/draft-04/schema#":t.target,t.external?.uri){let o=t.external.registry.get(e)?.id;if(!o)throw new Error("Schema is missing an `id` property");i.$id=t.external.uri(o)}Object.assign(i,r.def??r.schema);let s=t.external?.defs??{};for(let o of t.seen.entries()){let a=o[1];a.def&&a.defId&&(s[a.defId]=a.def)}t.external||Object.keys(s).length>0&&(t.target==="draft-2020-12"?i.$defs=s:i.definitions=s);try{let o=JSON.parse(JSON.stringify(i));return Object.defineProperty(o,"~standard",{value:{...e["~standard"],jsonSchema:{input:Zl(e,"input",t.processors),output:Zl(e,"output",t.processors)}},enumerable:!1,writable:!1}),o}catch{throw new Error("Error converting schema to JSON.")}}function Wr(t,e){let r=e??{seen:new Set};if(r.seen.has(t))return!1;r.seen.add(t);let n=t._zod.def;if(n.type==="transform")return!0;if(n.type==="array")return Wr(n.element,r);if(n.type==="set")return Wr(n.valueType,r);if(n.type==="lazy")return Wr(n.getter(),r);if(n.type==="promise"||n.type==="optional"||n.type==="nonoptional"||n.type==="nullable"||n.type==="readonly"||n.type==="default"||n.type==="prefault")return Wr(n.innerType,r);if(n.type==="intersection")return Wr(n.left,r)||Wr(n.right,r);if(n.type==="record"||n.type==="map")return Wr(n.keyType,r)||Wr(n.valueType,r);if(n.type==="pipe")return Wr(n.in,r)||Wr(n.out,r);if(n.type==="object"){for(let i in n.shape)if(Wr(n.shape[i],r))return!0;return!1}if(n.type==="union"){for(let i of n.options)if(Wr(i,r))return!0;return!1}if(n.type==="tuple"){for(let i of n.items)if(Wr(i,r))return!0;return!!(n.rest&&Wr(n.rest,r))}return!1}var u1=(t,e={})=>r=>{let n=$m({...r,processors:e});return kt(t,n),Im(n,t),Rm(n,t)},Zl=(t,e,r={})=>n=>{let{libraryOptions:i,target:s}=n??{},o=$m({...i??{},target:s,io:e,processors:r});return kt(t,o),Im(o,t),Rm(o,t)};var F3={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},l1=(t,e,r,n)=>{let i=r;i.type="string";let{minimum:s,maximum:o,format:a,patterns:c,contentEncoding:u}=t._zod.bag;if(typeof s=="number"&&(i.minLength=s),typeof o=="number"&&(i.maxLength=o),a&&(i.format=F3[a]??a,i.format===""&&delete i.format,a==="time"&&delete i.format),u&&(i.contentEncoding=u),c&&c.size>0){let l=[...c];l.length===1?i.pattern=l[0].source:l.length>1&&(i.allOf=[...l.map(d=>({...e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"?{type:"string"}:{},pattern:d.source}))])}},d1=(t,e,r,n)=>{let i=r,{minimum:s,maximum:o,format:a,multipleOf:c,exclusiveMaximum:u,exclusiveMinimum:l}=t._zod.bag;typeof a=="string"&&a.includes("int")?i.type="integer":i.type="number",typeof l=="number"&&(e.target==="draft-04"||e.target==="openapi-3.0"?(i.minimum=l,i.exclusiveMinimum=!0):i.exclusiveMinimum=l),typeof s=="number"&&(i.minimum=s,typeof l=="number"&&e.target!=="draft-04"&&(l>=s?delete i.minimum:delete i.exclusiveMinimum)),typeof u=="number"&&(e.target==="draft-04"||e.target==="openapi-3.0"?(i.maximum=u,i.exclusiveMaximum=!0):i.exclusiveMaximum=u),typeof o=="number"&&(i.maximum=o,typeof u=="number"&&e.target!=="draft-04"&&(u<=o?delete i.maximum:delete i.exclusiveMaximum)),typeof c=="number"&&(i.multipleOf=c)},p1=(t,e,r,n)=>{r.type="boolean"},f1=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema")},m1=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema")},h1=(t,e,r,n)=>{e.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"},g1=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema")},v1=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema")},y1=(t,e,r,n)=>{r.not={}},_1=(t,e,r,n)=>{},b1=(t,e,r,n)=>{},S1=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema")},x1=(t,e,r,n)=>{let i=t._zod.def,s=pl(i.entries);s.every(o=>typeof o=="number")&&(r.type="number"),s.every(o=>typeof o=="string")&&(r.type="string"),r.enum=s},w1=(t,e,r,n)=>{let i=t._zod.def,s=[];for(let o of i.values)if(o===void 0){if(e.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof o=="bigint"){if(e.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");s.push(Number(o))}else s.push(o);if(s.length!==0)if(s.length===1){let o=s[0];r.type=o===null?"null":typeof o,e.target==="draft-04"||e.target==="openapi-3.0"?r.enum=[o]:r.const=o}else s.every(o=>typeof o=="number")&&(r.type="number"),s.every(o=>typeof o=="string")&&(r.type="string"),s.every(o=>typeof o=="boolean")&&(r.type="boolean"),s.every(o=>o===null)&&(r.type="null"),r.enum=s},E1=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema")},k1=(t,e,r,n)=>{let i=r,s=t._zod.pattern;if(!s)throw new Error("Pattern not found in template literal");i.type="string",i.pattern=s.source},T1=(t,e,r,n)=>{let i=r,s={type:"string",format:"binary",contentEncoding:"binary"},{minimum:o,maximum:a,mime:c}=t._zod.bag;o!==void 0&&(s.minLength=o),a!==void 0&&(s.maxLength=a),c?c.length===1?(s.contentMediaType=c[0],Object.assign(i,s)):(Object.assign(i,s),i.anyOf=c.map(u=>({contentMediaType:u}))):Object.assign(i,s)},$1=(t,e,r,n)=>{r.type="boolean"},I1=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},R1=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Function types cannot be represented in JSON Schema")},O1=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},C1=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema")},P1=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema")},A1=(t,e,r,n)=>{let i=r,s=t._zod.def,{minimum:o,maximum:a}=t._zod.bag;typeof o=="number"&&(i.minItems=o),typeof a=="number"&&(i.maxItems=a),i.type="array",i.items=kt(s.element,e,{...n,path:[...n.path,"items"]})},N1=(t,e,r,n)=>{let i=r,s=t._zod.def;i.type="object",i.properties={};let o=s.shape;for(let u in o)i.properties[u]=kt(o[u],e,{...n,path:[...n.path,"properties",u]});let a=new Set(Object.keys(o)),c=new Set([...a].filter(u=>{let l=s.shape[u]._zod;return e.io==="input"?l.optin===void 0:l.optout===void 0}));c.size>0&&(i.required=Array.from(c)),s.catchall?._zod.def.type==="never"?i.additionalProperties=!1:s.catchall?s.catchall&&(i.additionalProperties=kt(s.catchall,e,{...n,path:[...n.path,"additionalProperties"]})):e.io==="output"&&(i.additionalProperties=!1)},tx=(t,e,r,n)=>{let i=t._zod.def,s=i.inclusive===!1,o=i.options.map((a,c)=>kt(a,e,{...n,path:[...n.path,s?"oneOf":"anyOf",c]}));s?r.oneOf=o:r.anyOf=o},M1=(t,e,r,n)=>{let i=t._zod.def,s=kt(i.left,e,{...n,path:[...n.path,"allOf",0]}),o=kt(i.right,e,{...n,path:[...n.path,"allOf",1]}),a=u=>"allOf"in u&&Object.keys(u).length===1,c=[...a(s)?s.allOf:[s],...a(o)?o.allOf:[o]];r.allOf=c},D1=(t,e,r,n)=>{let i=r,s=t._zod.def;i.type="array";let o=e.target==="draft-2020-12"?"prefixItems":"items",a=e.target==="draft-2020-12"||e.target==="openapi-3.0"?"items":"additionalItems",c=s.items.map((p,f)=>kt(p,e,{...n,path:[...n.path,o,f]})),u=s.rest?kt(s.rest,e,{...n,path:[...n.path,a,...e.target==="openapi-3.0"?[s.items.length]:[]]}):null;e.target==="draft-2020-12"?(i.prefixItems=c,u&&(i.items=u)):e.target==="openapi-3.0"?(i.items={anyOf:c},u&&i.items.anyOf.push(u),i.minItems=c.length,u||(i.maxItems=c.length)):(i.items=c,u&&(i.additionalItems=u));let{minimum:l,maximum:d}=t._zod.bag;typeof l=="number"&&(i.minItems=l),typeof d=="number"&&(i.maxItems=d)},j1=(t,e,r,n)=>{let i=r,s=t._zod.def;i.type="object";let o=s.keyType,c=o._zod.bag?.patterns;if(s.mode==="loose"&&c&&c.size>0){let l=kt(s.valueType,e,{...n,path:[...n.path,"patternProperties","*"]});i.patternProperties={};for(let d of c)i.patternProperties[d.source]=l}else(e.target==="draft-07"||e.target==="draft-2020-12")&&(i.propertyNames=kt(s.keyType,e,{...n,path:[...n.path,"propertyNames"]})),i.additionalProperties=kt(s.valueType,e,{...n,path:[...n.path,"additionalProperties"]});let u=o._zod.values;if(u){let l=[...u].filter(d=>typeof d=="string"||typeof d=="number");l.length>0&&(i.required=l)}},z1=(t,e,r,n)=>{let i=t._zod.def,s=kt(i.innerType,e,n),o=e.seen.get(t);e.target==="openapi-3.0"?(o.ref=i.innerType,r.nullable=!0):r.anyOf=[s,{type:"null"}]},L1=(t,e,r,n)=>{let i=t._zod.def;kt(i.innerType,e,n);let s=e.seen.get(t);s.ref=i.innerType},U1=(t,e,r,n)=>{let i=t._zod.def;kt(i.innerType,e,n);let s=e.seen.get(t);s.ref=i.innerType,r.default=JSON.parse(JSON.stringify(i.defaultValue))},F1=(t,e,r,n)=>{let i=t._zod.def;kt(i.innerType,e,n);let s=e.seen.get(t);s.ref=i.innerType,e.io==="input"&&(r._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},q1=(t,e,r,n)=>{let i=t._zod.def;kt(i.innerType,e,n);let s=e.seen.get(t);s.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}r.default=o},H1=(t,e,r,n)=>{let i=t._zod.def,s=e.io==="input"?i.in._zod.def.type==="transform"?i.out:i.in:i.out;kt(s,e,n);let o=e.seen.get(t);o.ref=s},Z1=(t,e,r,n)=>{let i=t._zod.def;kt(i.innerType,e,n);let s=e.seen.get(t);s.ref=i.innerType,r.readOnly=!0},B1=(t,e,r,n)=>{let i=t._zod.def;kt(i.innerType,e,n);let s=e.seen.get(t);s.ref=i.innerType},rx=(t,e,r,n)=>{let i=t._zod.def;kt(i.innerType,e,n);let s=e.seen.get(t);s.ref=i.innerType},G1=(t,e,r,n)=>{let i=t._zod.innerType;kt(i,e,n);let s=e.seen.get(t);s.ref=i};function nc(t){return!!t._zod}function oi(t,e){return nc(t)?Ya(t,e):t.safeParse(e)}function Om(t){if(!t)return;let e;if(nc(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function J1(t){if(nc(t)){let s=t._zod?.def;if(s){if(s.value!==void 0)return s.value;if(Array.isArray(s.values)&&s.values.length>0)return s.values[0]}}let r=t._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=t.value;if(n!==void 0)return n}var Bl={};_n(Bl,{ZodAny:()=>mO,ZodArray:()=>yO,ZodBase64:()=>Tx,ZodBase64URL:()=>$x,ZodBigInt:()=>Lm,ZodBigIntFormat:()=>Ox,ZodBoolean:()=>zm,ZodCIDRv4:()=>Ex,ZodCIDRv6:()=>kx,ZodCUID:()=>vx,ZodCUID2:()=>yx,ZodCatch:()=>zO,ZodCodec:()=>jx,ZodCustom:()=>Zm,ZodCustomStringFormat:()=>Wl,ZodDate:()=>Px,ZodDefault:()=>PO,ZodDiscriminatedUnion:()=>bO,ZodE164:()=>Ix,ZodEmail:()=>mx,ZodEmoji:()=>hx,ZodEnum:()=>Gl,ZodExactOptional:()=>RO,ZodFile:()=>$O,ZodFunction:()=>WO,ZodGUID:()=>Pm,ZodIPv4:()=>xx,ZodIPv6:()=>wx,ZodIntersection:()=>SO,ZodJWT:()=>Rx,ZodKSUID:()=>Sx,ZodLazy:()=>ZO,ZodLiteral:()=>TO,ZodMAC:()=>lO,ZodMap:()=>EO,ZodNaN:()=>UO,ZodNanoID:()=>gx,ZodNever:()=>gO,ZodNonOptional:()=>Mx,ZodNull:()=>fO,ZodNullable:()=>CO,ZodNumber:()=>jm,ZodNumberFormat:()=>ic,ZodObject:()=>Um,ZodOptional:()=>Nx,ZodPipe:()=>Dx,ZodPrefault:()=>NO,ZodPromise:()=>GO,ZodReadonly:()=>FO,ZodRecord:()=>Hm,ZodSet:()=>kO,ZodString:()=>Mm,ZodStringFormat:()=>bt,ZodSuccess:()=>jO,ZodSymbol:()=>dO,ZodTemplateLiteral:()=>HO,ZodTransform:()=>IO,ZodTuple:()=>xO,ZodType:()=>De,ZodULID:()=>_x,ZodURL:()=>Dm,ZodUUID:()=>ps,ZodUndefined:()=>pO,ZodUnion:()=>Fm,ZodUnknown:()=>hO,ZodVoid:()=>vO,ZodXID:()=>bx,ZodXor:()=>_O,_ZodString:()=>fx,_default:()=>AO,_function:()=>sB,any:()=>FZ,array:()=>Ve,base64:()=>EZ,base64url:()=>kZ,bigint:()=>DZ,boolean:()=>Yt,catch:()=>LO,check:()=>oB,cidrv4:()=>xZ,cidrv6:()=>wZ,codec:()=>rB,cuid:()=>mZ,cuid2:()=>hZ,custom:()=>zx,date:()=>HZ,describe:()=>aB,discriminatedUnion:()=>qm,e164:()=>TZ,email:()=>iZ,emoji:()=>pZ,enum:()=>Cr,exactOptional:()=>OO,file:()=>YZ,float32:()=>PZ,float64:()=>AZ,function:()=>sB,guid:()=>sZ,hash:()=>CZ,hex:()=>OZ,hostname:()=>RZ,httpUrl:()=>dZ,instanceof:()=>uB,int:()=>px,int32:()=>NZ,int64:()=>jZ,intersection:()=>Kl,ipv4:()=>_Z,ipv6:()=>SZ,json:()=>dB,jwt:()=>$Z,keyof:()=>ZZ,ksuid:()=>yZ,lazy:()=>BO,literal:()=>fe,looseObject:()=>Or,looseRecord:()=>VZ,mac:()=>bZ,map:()=>KZ,meta:()=>cB,nan:()=>tB,nanoid:()=>fZ,nativeEnum:()=>XZ,never:()=>Cx,nonoptional:()=>DO,null:()=>Vl,nullable:()=>Am,nullish:()=>QZ,number:()=>ct,object:()=>se,optional:()=>Ot,partialRecord:()=>WZ,pipe:()=>Nm,prefault:()=>MO,preprocess:()=>Bm,promise:()=>iB,readonly:()=>qO,record:()=>Tt,refine:()=>VO,set:()=>JZ,strictObject:()=>BZ,string:()=>z,stringFormat:()=>IZ,stringbool:()=>lB,success:()=>eB,superRefine:()=>KO,symbol:()=>LZ,templateLiteral:()=>nB,transform:()=>Ax,tuple:()=>wO,uint32:()=>MZ,uint64:()=>zZ,ulid:()=>gZ,undefined:()=>UZ,union:()=>ht,unknown:()=>St,url:()=>lZ,uuid:()=>oZ,uuidv4:()=>aZ,uuidv6:()=>cZ,uuidv7:()=>uZ,void:()=>qZ,xid:()=>vZ,xor:()=>GZ});var Cm={};_n(Cm,{endsWith:()=>zl,gt:()=>ls,gte:()=>Gr,includes:()=>Dl,length:()=>tc,lowercase:()=>Nl,lt:()=>us,lte:()=>wn,maxLength:()=>ec,maxSize:()=>Mo,mime:()=>Ll,minLength:()=>Ks,minSize:()=>ds,multipleOf:()=>No,negative:()=>ZS,nonnegative:()=>GS,nonpositive:()=>BS,normalize:()=>Ul,overwrite:()=>Pi,positive:()=>HS,property:()=>WS,regex:()=>Al,size:()=>Qa,slugify:()=>Tm,startsWith:()=>jl,toLowerCase:()=>ql,toUpperCase:()=>Hl,trim:()=>Fl,uppercase:()=>Ml});var Do={};_n(Do,{ZodISODate:()=>ox,ZodISODateTime:()=>ix,ZodISODuration:()=>lx,ZodISOTime:()=>cx,date:()=>ax,datetime:()=>sx,duration:()=>dx,time:()=>ux});var ix=O("ZodISODateTime",(t,e)=>{yb.init(t,e),bt.init(t,e)});function sx(t){return bS(ix,t)}var ox=O("ZodISODate",(t,e)=>{_b.init(t,e),bt.init(t,e)});function ax(t){return SS(ox,t)}var cx=O("ZodISOTime",(t,e)=>{bb.init(t,e),bt.init(t,e)});function ux(t){return xS(cx,t)}var lx=O("ZodISODuration",(t,e)=>{Sb.init(t,e),bt.init(t,e)});function dx(t){return wS(lx,t)}var X1=(t,e)=>{Bf.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>Wf(t,r)},flatten:{value:r=>Gf(t,r)},addIssue:{value:r=>{t.issues.push(r),t.message=JSON.stringify(t.issues,Ka,2)}},addIssues:{value:r=>{t.issues.push(...r),t.message=JSON.stringify(t.issues,Ka,2)}},isEmpty:{get(){return t.issues.length===0}}})},zke=O("ZodError",X1),En=O("ZodError",X1,{Parent:Error});var Y1=yl(En),Q1=bl(En),eO=xl(En),tO=wl(En),rO=pR(En),nO=fR(En),iO=mR(En),sO=hR(En),oO=gR(En),aO=vR(En),cO=yR(En),uO=_R(En);var De=O("ZodType",(t,e)=>(Ce.init(t,e),Object.assign(t["~standard"],{jsonSchema:{input:Zl(t,"input"),output:Zl(t,"output")}}),t.toJSONSchema=u1(t,{}),t.def=e,t.type=e.type,Object.defineProperty(t,"_def",{value:e}),t.check=(...r)=>t.clone(G.mergeDefs(e,{checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),{parent:!0}),t.with=t.check,t.clone=(r,n)=>Zr(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>Y1(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>eO(t,r,n),t.parseAsync=async(r,n)=>Q1(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>tO(t,r,n),t.spa=t.safeParseAsync,t.encode=(r,n)=>rO(t,r,n),t.decode=(r,n)=>nO(t,r,n),t.encodeAsync=async(r,n)=>iO(t,r,n),t.decodeAsync=async(r,n)=>sO(t,r,n),t.safeEncode=(r,n)=>oO(t,r,n),t.safeDecode=(r,n)=>aO(t,r,n),t.safeEncodeAsync=async(r,n)=>cO(t,r,n),t.safeDecodeAsync=async(r,n)=>uO(t,r,n),t.refine=(r,n)=>t.check(VO(r,n)),t.superRefine=r=>t.check(KO(r)),t.overwrite=r=>t.check(Pi(r)),t.optional=()=>Ot(t),t.exactOptional=()=>OO(t),t.nullable=()=>Am(t),t.nullish=()=>Ot(Am(t)),t.nonoptional=r=>DO(t,r),t.array=()=>Ve(t),t.or=r=>ht([t,r]),t.and=r=>Kl(t,r),t.transform=r=>Nm(t,Ax(r)),t.default=r=>AO(t,r),t.prefault=r=>MO(t,r),t.catch=r=>LO(t,r),t.pipe=r=>Nm(t,r),t.readonly=()=>qO(t),t.describe=r=>{let n=t.clone();return Br.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return Br.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return Br.get(t);let n=t.clone();return Br.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t.apply=r=>r(t),t)),fx=O("_ZodString",(t,e)=>{Ao.init(t,e),De.init(t,e),t._zod.processJSONSchema=(n,i,s)=>l1(t,n,i,s);let r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,t.regex=(...n)=>t.check(Al(...n)),t.includes=(...n)=>t.check(Dl(...n)),t.startsWith=(...n)=>t.check(jl(...n)),t.endsWith=(...n)=>t.check(zl(...n)),t.min=(...n)=>t.check(Ks(...n)),t.max=(...n)=>t.check(ec(...n)),t.length=(...n)=>t.check(tc(...n)),t.nonempty=(...n)=>t.check(Ks(1,...n)),t.lowercase=n=>t.check(Nl(n)),t.uppercase=n=>t.check(Ml(n)),t.trim=()=>t.check(Fl()),t.normalize=(...n)=>t.check(Ul(...n)),t.toLowerCase=()=>t.check(ql()),t.toUpperCase=()=>t.check(Hl()),t.slugify=()=>t.check(Tm())}),Mm=O("ZodString",(t,e)=>{Ao.init(t,e),fx.init(t,e),t.email=r=>t.check(om(mx,r)),t.url=r=>t.check(Pl(Dm,r)),t.jwt=r=>t.check(km(Rx,r)),t.emoji=r=>t.check(dm(hx,r)),t.guid=r=>t.check(Cl(Pm,r)),t.uuid=r=>t.check(am(ps,r)),t.uuidv4=r=>t.check(cm(ps,r)),t.uuidv6=r=>t.check(um(ps,r)),t.uuidv7=r=>t.check(lm(ps,r)),t.nanoid=r=>t.check(pm(gx,r)),t.guid=r=>t.check(Cl(Pm,r)),t.cuid=r=>t.check(fm(vx,r)),t.cuid2=r=>t.check(mm(yx,r)),t.ulid=r=>t.check(hm(_x,r)),t.base64=r=>t.check(xm(Tx,r)),t.base64url=r=>t.check(wm($x,r)),t.xid=r=>t.check(gm(bx,r)),t.ksuid=r=>t.check(vm(Sx,r)),t.ipv4=r=>t.check(ym(xx,r)),t.ipv6=r=>t.check(_m(wx,r)),t.cidrv4=r=>t.check(bm(Ex,r)),t.cidrv6=r=>t.check(Sm(kx,r)),t.e164=r=>t.check(Em(Ix,r)),t.datetime=r=>t.check(sx(r)),t.date=r=>t.check(ax(r)),t.time=r=>t.check(ux(r)),t.duration=r=>t.check(dx(r))});function z(t){return yS(Mm,t)}var bt=O("ZodStringFormat",(t,e)=>{mt.init(t,e),fx.init(t,e)}),mx=O("ZodEmail",(t,e)=>{ub.init(t,e),bt.init(t,e)});function iZ(t){return om(mx,t)}var Pm=O("ZodGUID",(t,e)=>{ab.init(t,e),bt.init(t,e)});function sZ(t){return Cl(Pm,t)}var ps=O("ZodUUID",(t,e)=>{cb.init(t,e),bt.init(t,e)});function oZ(t){return am(ps,t)}function aZ(t){return cm(ps,t)}function cZ(t){return um(ps,t)}function uZ(t){return lm(ps,t)}var Dm=O("ZodURL",(t,e)=>{lb.init(t,e),bt.init(t,e)});function lZ(t){return Pl(Dm,t)}function dZ(t){return Pl(Dm,{protocol:/^https?$/,hostname:jn.domain,...G.normalizeParams(t)})}var hx=O("ZodEmoji",(t,e)=>{db.init(t,e),bt.init(t,e)});function pZ(t){return dm(hx,t)}var gx=O("ZodNanoID",(t,e)=>{pb.init(t,e),bt.init(t,e)});function fZ(t){return pm(gx,t)}var vx=O("ZodCUID",(t,e)=>{fb.init(t,e),bt.init(t,e)});function mZ(t){return fm(vx,t)}var yx=O("ZodCUID2",(t,e)=>{mb.init(t,e),bt.init(t,e)});function hZ(t){return mm(yx,t)}var _x=O("ZodULID",(t,e)=>{hb.init(t,e),bt.init(t,e)});function gZ(t){return hm(_x,t)}var bx=O("ZodXID",(t,e)=>{gb.init(t,e),bt.init(t,e)});function vZ(t){return gm(bx,t)}var Sx=O("ZodKSUID",(t,e)=>{vb.init(t,e),bt.init(t,e)});function yZ(t){return vm(Sx,t)}var xx=O("ZodIPv4",(t,e)=>{xb.init(t,e),bt.init(t,e)});function _Z(t){return ym(xx,t)}var lO=O("ZodMAC",(t,e)=>{Eb.init(t,e),bt.init(t,e)});function bZ(t){return _S(lO,t)}var wx=O("ZodIPv6",(t,e)=>{wb.init(t,e),bt.init(t,e)});function SZ(t){return _m(wx,t)}var Ex=O("ZodCIDRv4",(t,e)=>{kb.init(t,e),bt.init(t,e)});function xZ(t){return bm(Ex,t)}var kx=O("ZodCIDRv6",(t,e)=>{Tb.init(t,e),bt.init(t,e)});function wZ(t){return Sm(kx,t)}var Tx=O("ZodBase64",(t,e)=>{$b.init(t,e),bt.init(t,e)});function EZ(t){return xm(Tx,t)}var $x=O("ZodBase64URL",(t,e)=>{Ib.init(t,e),bt.init(t,e)});function kZ(t){return wm($x,t)}var Ix=O("ZodE164",(t,e)=>{Rb.init(t,e),bt.init(t,e)});function TZ(t){return Em(Ix,t)}var Rx=O("ZodJWT",(t,e)=>{Ob.init(t,e),bt.init(t,e)});function $Z(t){return km(Rx,t)}var Wl=O("ZodCustomStringFormat",(t,e)=>{Cb.init(t,e),bt.init(t,e)});function IZ(t,e,r={}){return rc(Wl,t,e,r)}function RZ(t){return rc(Wl,"hostname",jn.hostname,t)}function OZ(t){return rc(Wl,"hex",jn.hex,t)}function CZ(t,e){let r=e?.enc??"hex",n=`${t}_${r}`,i=jn[n];if(!i)throw new Error(`Unrecognized hash format: ${n}`);return rc(Wl,n,i,e)}var jm=O("ZodNumber",(t,e)=>{rm.init(t,e),De.init(t,e),t._zod.processJSONSchema=(n,i,s)=>d1(t,n,i,s),t.gt=(n,i)=>t.check(ls(n,i)),t.gte=(n,i)=>t.check(Gr(n,i)),t.min=(n,i)=>t.check(Gr(n,i)),t.lt=(n,i)=>t.check(us(n,i)),t.lte=(n,i)=>t.check(wn(n,i)),t.max=(n,i)=>t.check(wn(n,i)),t.int=n=>t.check(px(n)),t.safe=n=>t.check(px(n)),t.positive=n=>t.check(ls(0,n)),t.nonnegative=n=>t.check(Gr(0,n)),t.negative=n=>t.check(us(0,n)),t.nonpositive=n=>t.check(wn(0,n)),t.multipleOf=(n,i)=>t.check(No(n,i)),t.step=(n,i)=>t.check(No(n,i)),t.finite=()=>t;let r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});function ct(t){return ES(jm,t)}var ic=O("ZodNumberFormat",(t,e)=>{Pb.init(t,e),jm.init(t,e)});function px(t){return kS(ic,t)}function PZ(t){return TS(ic,t)}function AZ(t){return $S(ic,t)}function NZ(t){return IS(ic,t)}function MZ(t){return RS(ic,t)}var zm=O("ZodBoolean",(t,e)=>{Il.init(t,e),De.init(t,e),t._zod.processJSONSchema=(r,n,i)=>p1(t,r,n,i)});function Yt(t){return OS(zm,t)}var Lm=O("ZodBigInt",(t,e)=>{nm.init(t,e),De.init(t,e),t._zod.processJSONSchema=(n,i,s)=>f1(t,n,i,s),t.gte=(n,i)=>t.check(Gr(n,i)),t.min=(n,i)=>t.check(Gr(n,i)),t.gt=(n,i)=>t.check(ls(n,i)),t.gte=(n,i)=>t.check(Gr(n,i)),t.min=(n,i)=>t.check(Gr(n,i)),t.lt=(n,i)=>t.check(us(n,i)),t.lte=(n,i)=>t.check(wn(n,i)),t.max=(n,i)=>t.check(wn(n,i)),t.positive=n=>t.check(ls(BigInt(0),n)),t.negative=n=>t.check(us(BigInt(0),n)),t.nonpositive=n=>t.check(wn(BigInt(0),n)),t.nonnegative=n=>t.check(Gr(BigInt(0),n)),t.multipleOf=(n,i)=>t.check(No(n,i));let r=t._zod.bag;t.minValue=r.minimum??null,t.maxValue=r.maximum??null,t.format=r.format??null});function DZ(t){return CS(Lm,t)}var Ox=O("ZodBigIntFormat",(t,e)=>{Ab.init(t,e),Lm.init(t,e)});function jZ(t){return PS(Ox,t)}function zZ(t){return AS(Ox,t)}var dO=O("ZodSymbol",(t,e)=>{Nb.init(t,e),De.init(t,e),t._zod.processJSONSchema=(r,n,i)=>m1(t,r,n,i)});function LZ(t){return NS(dO,t)}var pO=O("ZodUndefined",(t,e)=>{Mb.init(t,e),De.init(t,e),t._zod.processJSONSchema=(r,n,i)=>g1(t,r,n,i)});function UZ(t){return MS(pO,t)}var fO=O("ZodNull",(t,e)=>{Db.init(t,e),De.init(t,e),t._zod.processJSONSchema=(r,n,i)=>h1(t,r,n,i)});function Vl(t){return DS(fO,t)}var mO=O("ZodAny",(t,e)=>{jb.init(t,e),De.init(t,e),t._zod.processJSONSchema=(r,n,i)=>_1(t,r,n,i)});function FZ(){return jS(mO)}var hO=O("ZodUnknown",(t,e)=>{zb.init(t,e),De.init(t,e),t._zod.processJSONSchema=(r,n,i)=>b1(t,r,n,i)});function St(){return zS(hO)}var gO=O("ZodNever",(t,e)=>{Lb.init(t,e),De.init(t,e),t._zod.processJSONSchema=(r,n,i)=>y1(t,r,n,i)});function Cx(t){return LS(gO,t)}var vO=O("ZodVoid",(t,e)=>{Ub.init(t,e),De.init(t,e),t._zod.processJSONSchema=(r,n,i)=>v1(t,r,n,i)});function qZ(t){return US(vO,t)}var Px=O("ZodDate",(t,e)=>{Fb.init(t,e),De.init(t,e),t._zod.processJSONSchema=(n,i,s)=>S1(t,n,i,s),t.min=(n,i)=>t.check(Gr(n,i)),t.max=(n,i)=>t.check(wn(n,i));let r=t._zod.bag;t.minDate=r.minimum?new Date(r.minimum):null,t.maxDate=r.maximum?new Date(r.maximum):null});function HZ(t){return FS(Px,t)}var yO=O("ZodArray",(t,e)=>{qb.init(t,e),De.init(t,e),t._zod.processJSONSchema=(r,n,i)=>A1(t,r,n,i),t.element=e.element,t.min=(r,n)=>t.check(Ks(r,n)),t.nonempty=r=>t.check(Ks(1,r)),t.max=(r,n)=>t.check(ec(r,n)),t.length=(r,n)=>t.check(tc(r,n)),t.unwrap=()=>t.element});function Ve(t,e){return c1(yO,t,e)}function ZZ(t){let e=t._zod.def.shape;return Cr(Object.keys(e))}var Um=O("ZodObject",(t,e)=>{o1.init(t,e),De.init(t,e),t._zod.processJSONSchema=(r,n,i)=>N1(t,r,n,i),G.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>Cr(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:St()}),t.loose=()=>t.clone({...t._zod.def,catchall:St()}),t.strict=()=>t.clone({...t._zod.def,catchall:Cx()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>G.extend(t,r),t.safeExtend=r=>G.safeExtend(t,r),t.merge=r=>G.merge(t,r),t.pick=r=>G.pick(t,r),t.omit=r=>G.omit(t,r),t.partial=(...r)=>G.partial(Nx,t,r[0]),t.required=(...r)=>G.required(Mx,t,r[0])});function se(t,e){let r={type:"object",shape:t??{},...G.normalizeParams(e)};return new Um(r)}function BZ(t,e){return new Um({type:"object",shape:t,catchall:Cx(),...G.normalizeParams(e)})}function Or(t,e){return new Um({type:"object",shape:t,catchall:St(),...G.normalizeParams(e)})}var Fm=O("ZodUnion",(t,e)=>{Rl.init(t,e),De.init(t,e),t._zod.processJSONSchema=(r,n,i)=>tx(t,r,n,i),t.options=e.options});function ht(t,e){return new Fm({type:"union",options:t,...G.normalizeParams(e)})}var _O=O("ZodXor",(t,e)=>{Fm.init(t,e),Hb.init(t,e),t._zod.processJSONSchema=(r,n,i)=>tx(t,r,n,i),t.options=e.options});function GZ(t,e){return new _O({type:"union",options:t,inclusive:!1,...G.normalizeParams(e)})}var bO=O("ZodDiscriminatedUnion",(t,e)=>{Fm.init(t,e),Zb.init(t,e)});function qm(t,e,r){return new bO({type:"union",options:e,discriminator:t,...G.normalizeParams(r)})}var SO=O("ZodIntersection",(t,e)=>{Bb.init(t,e),De.init(t,e),t._zod.processJSONSchema=(r,n,i)=>M1(t,r,n,i)});function Kl(t,e){return new SO({type:"intersection",left:t,right:e})}var xO=O("ZodTuple",(t,e)=>{im.init(t,e),De.init(t,e),t._zod.processJSONSchema=(r,n,i)=>D1(t,r,n,i),t.rest=r=>t.clone({...t._zod.def,rest:r})});function wO(t,e,r){let n=e instanceof Ce,i=n?r:e,s=n?e:null;return new xO({type:"tuple",items:t,rest:s,...G.normalizeParams(i)})}var Hm=O("ZodRecord",(t,e)=>{Gb.init(t,e),De.init(t,e),t._zod.processJSONSchema=(r,n,i)=>j1(t,r,n,i),t.keyType=e.keyType,t.valueType=e.valueType});function Tt(t,e,r){return new Hm({type:"record",keyType:t,valueType:e,...G.normalizeParams(r)})}function WZ(t,e,r){let n=Zr(t);return n._zod.values=void 0,new Hm({type:"record",keyType:n,valueType:e,...G.normalizeParams(r)})}function VZ(t,e,r){return new Hm({type:"record",keyType:t,valueType:e,mode:"loose",...G.normalizeParams(r)})}var EO=O("ZodMap",(t,e)=>{Wb.init(t,e),De.init(t,e),t._zod.processJSONSchema=(r,n,i)=>C1(t,r,n,i),t.keyType=e.keyType,t.valueType=e.valueType,t.min=(...r)=>t.check(ds(...r)),t.nonempty=r=>t.check(ds(1,r)),t.max=(...r)=>t.check(Mo(...r)),t.size=(...r)=>t.check(Qa(...r))});function KZ(t,e,r){return new EO({type:"map",keyType:t,valueType:e,...G.normalizeParams(r)})}var kO=O("ZodSet",(t,e)=>{Vb.init(t,e),De.init(t,e),t._zod.processJSONSchema=(r,n,i)=>P1(t,r,n,i),t.min=(...r)=>t.check(ds(...r)),t.nonempty=r=>t.check(ds(1,r)),t.max=(...r)=>t.check(Mo(...r)),t.size=(...r)=>t.check(Qa(...r))});function JZ(t,e){return new kO({type:"set",valueType:t,...G.normalizeParams(e)})}var Gl=O("ZodEnum",(t,e)=>{Kb.init(t,e),De.init(t,e),t._zod.processJSONSchema=(n,i,s)=>x1(t,n,i,s),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(n,i)=>{let s={};for(let o of n)if(r.has(o))s[o]=e.entries[o];else throw new Error(`Key ${o} not found in enum`);return new Gl({...e,checks:[],...G.normalizeParams(i),entries:s})},t.exclude=(n,i)=>{let s={...e.entries};for(let o of n)if(r.has(o))delete s[o];else throw new Error(`Key ${o} not found in enum`);return new Gl({...e,checks:[],...G.normalizeParams(i),entries:s})}});function Cr(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new Gl({type:"enum",entries:r,...G.normalizeParams(e)})}function XZ(t,e){return new Gl({type:"enum",entries:t,...G.normalizeParams(e)})}var TO=O("ZodLiteral",(t,e)=>{Jb.init(t,e),De.init(t,e),t._zod.processJSONSchema=(r,n,i)=>w1(t,r,n,i),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function fe(t,e){return new TO({type:"literal",values:Array.isArray(t)?t:[t],...G.normalizeParams(e)})}var $O=O("ZodFile",(t,e)=>{Xb.init(t,e),De.init(t,e),t._zod.processJSONSchema=(r,n,i)=>T1(t,r,n,i),t.min=(r,n)=>t.check(ds(r,n)),t.max=(r,n)=>t.check(Mo(r,n)),t.mime=(r,n)=>t.check(Ll(Array.isArray(r)?r:[r],n))});function YZ(t){return VS($O,t)}var IO=O("ZodTransform",(t,e)=>{Yb.init(t,e),De.init(t,e),t._zod.processJSONSchema=(r,n,i)=>O1(t,r,n,i),t._zod.parse=(r,n)=>{if(n.direction==="backward")throw new Oo(t.constructor.name);r.addIssue=s=>{if(typeof s=="string")r.issues.push(G.issue(s,r.value,e));else{let o=s;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=t),r.issues.push(G.issue(o))}};let i=e.transform(r.value,r);return i instanceof Promise?i.then(s=>(r.value=s,r)):(r.value=i,r)}});function Ax(t){return new IO({type:"transform",transform:t})}var Nx=O("ZodOptional",(t,e)=>{sm.init(t,e),De.init(t,e),t._zod.processJSONSchema=(r,n,i)=>rx(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function Ot(t){return new Nx({type:"optional",innerType:t})}var RO=O("ZodExactOptional",(t,e)=>{Qb.init(t,e),De.init(t,e),t._zod.processJSONSchema=(r,n,i)=>rx(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function OO(t){return new RO({type:"optional",innerType:t})}var CO=O("ZodNullable",(t,e)=>{eS.init(t,e),De.init(t,e),t._zod.processJSONSchema=(r,n,i)=>z1(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function Am(t){return new CO({type:"nullable",innerType:t})}function QZ(t){return Ot(Am(t))}var PO=O("ZodDefault",(t,e)=>{tS.init(t,e),De.init(t,e),t._zod.processJSONSchema=(r,n,i)=>U1(t,r,n,i),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function AO(t,e){return new PO({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():G.shallowClone(e)}})}var NO=O("ZodPrefault",(t,e)=>{rS.init(t,e),De.init(t,e),t._zod.processJSONSchema=(r,n,i)=>F1(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function MO(t,e){return new NO({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():G.shallowClone(e)}})}var Mx=O("ZodNonOptional",(t,e)=>{nS.init(t,e),De.init(t,e),t._zod.processJSONSchema=(r,n,i)=>L1(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function DO(t,e){return new Mx({type:"nonoptional",innerType:t,...G.normalizeParams(e)})}var jO=O("ZodSuccess",(t,e)=>{iS.init(t,e),De.init(t,e),t._zod.processJSONSchema=(r,n,i)=>$1(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function eB(t){return new jO({type:"success",innerType:t})}var zO=O("ZodCatch",(t,e)=>{sS.init(t,e),De.init(t,e),t._zod.processJSONSchema=(r,n,i)=>q1(t,r,n,i),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function LO(t,e){return new zO({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var UO=O("ZodNaN",(t,e)=>{oS.init(t,e),De.init(t,e),t._zod.processJSONSchema=(r,n,i)=>E1(t,r,n,i)});function tB(t){return qS(UO,t)}var Dx=O("ZodPipe",(t,e)=>{aS.init(t,e),De.init(t,e),t._zod.processJSONSchema=(r,n,i)=>H1(t,r,n,i),t.in=e.in,t.out=e.out});function Nm(t,e){return new Dx({type:"pipe",in:t,out:e})}var jx=O("ZodCodec",(t,e)=>{Dx.init(t,e),Ol.init(t,e)});function rB(t,e,r){return new jx({type:"pipe",in:t,out:e,transform:r.decode,reverseTransform:r.encode})}var FO=O("ZodReadonly",(t,e)=>{cS.init(t,e),De.init(t,e),t._zod.processJSONSchema=(r,n,i)=>Z1(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function qO(t){return new FO({type:"readonly",innerType:t})}var HO=O("ZodTemplateLiteral",(t,e)=>{uS.init(t,e),De.init(t,e),t._zod.processJSONSchema=(r,n,i)=>k1(t,r,n,i)});function nB(t,e){return new HO({type:"template_literal",parts:t,...G.normalizeParams(e)})}var ZO=O("ZodLazy",(t,e)=>{pS.init(t,e),De.init(t,e),t._zod.processJSONSchema=(r,n,i)=>G1(t,r,n,i),t.unwrap=()=>t._zod.def.getter()});function BO(t){return new ZO({type:"lazy",getter:t})}var GO=O("ZodPromise",(t,e)=>{dS.init(t,e),De.init(t,e),t._zod.processJSONSchema=(r,n,i)=>B1(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function iB(t){return new GO({type:"promise",innerType:t})}var WO=O("ZodFunction",(t,e)=>{lS.init(t,e),De.init(t,e),t._zod.processJSONSchema=(r,n,i)=>R1(t,r,n,i)});function sB(t){return new WO({type:"function",input:Array.isArray(t?.input)?wO(t?.input):t?.input??Ve(St()),output:t?.output??St()})}var Zm=O("ZodCustom",(t,e)=>{fS.init(t,e),De.init(t,e),t._zod.processJSONSchema=(r,n,i)=>I1(t,r,n,i)});function oB(t){let e=new _t({check:"custom"});return e._zod.check=t,e}function zx(t,e){return KS(Zm,t??(()=>!0),e)}function VO(t,e={}){return JS(Zm,t,e)}function KO(t){return XS(t)}var aB=YS,cB=QS;function uB(t,e={}){let r=new Zm({type:"custom",check:"custom",fn:n=>n instanceof t,abort:!0,...G.normalizeParams(e)});return r._zod.bag.Class=t,r._zod.check=n=>{n.value instanceof t||n.issues.push({code:"invalid_type",expected:t.name,input:n.value,inst:r,path:[...r._zod.def.path??[]]})},r}var lB=(...t)=>ex({Codec:jx,Boolean:zm,String:Mm},...t);function dB(t){let e=BO(()=>ht([z(t),ct(),Yt(),Vl(),Ve(e),Tt(z(),e)]));return e}function Bm(t,e){return Nm(Ax(t),e)}var JO;JO||(JO={});var Gke={...Bl,...Cm,iso:Do};tr(mS());var Ux="2025-11-25";var XO=[Ux,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Js="io.modelcontextprotocol/related-task",Wm="2.0",yr=zx(t=>t!==null&&(typeof t=="object"||typeof t=="function")),YO=ht([z(),ct().int()]),QO=z(),dTe=Or({ttl:ht([ct(),Vl()]).optional(),pollInterval:ct().optional()}),hB=se({ttl:ct().optional()}),gB=se({taskId:z()}),Fx=Or({progressToken:YO.optional(),[Js]:gB.optional()}),kn=se({_meta:Fx.optional()}),Jl=kn.extend({task:hB.optional()}),eC=t=>Jl.safeParse(t).success,_r=se({method:z(),params:kn.loose().optional()}),zn=se({_meta:Fx.optional()}),Ln=se({method:z(),params:zn.loose().optional()}),br=Or({_meta:Fx.optional()}),Vm=ht([z(),ct().int()]),tC=se({jsonrpc:fe(Wm),id:Vm,..._r.shape}).strict(),qx=t=>tC.safeParse(t).success,rC=se({jsonrpc:fe(Wm),...Ln.shape}).strict(),nC=t=>rC.safeParse(t).success,Hx=se({jsonrpc:fe(Wm),id:Vm,result:br}).strict(),Xl=t=>Hx.safeParse(t).success;var Ie;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(Ie||(Ie={}));var Zx=se({jsonrpc:fe(Wm),id:Vm.optional(),error:se({code:ct().int(),message:z(),data:St().optional()})}).strict();var iC=t=>Zx.safeParse(t).success;var sC=ht([tC,rC,Hx,Zx]),pTe=ht([Hx,Zx]),jo=br.strict(),vB=zn.extend({requestId:Vm.optional(),reason:z().optional()}),Km=Ln.extend({method:fe("notifications/cancelled"),params:vB}),yB=se({src:z(),mimeType:z().optional(),sizes:Ve(z()).optional(),theme:Cr(["light","dark"]).optional()}),Yl=se({icons:Ve(yB).optional()}),sc=se({name:z(),title:z().optional()}),oC=sc.extend({...sc.shape,...Yl.shape,version:z(),websiteUrl:z().optional(),description:z().optional()}),_B=Kl(se({applyDefaults:Yt().optional()}),Tt(z(),St())),bB=Bm(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,Kl(se({form:_B.optional(),url:yr.optional()}),Tt(z(),St()).optional())),SB=Or({list:yr.optional(),cancel:yr.optional(),requests:Or({sampling:Or({createMessage:yr.optional()}).optional(),elicitation:Or({create:yr.optional()}).optional()}).optional()}),xB=Or({list:yr.optional(),cancel:yr.optional(),requests:Or({tools:Or({call:yr.optional()}).optional()}).optional()}),wB=se({experimental:Tt(z(),yr).optional(),sampling:se({context:yr.optional(),tools:yr.optional()}).optional(),elicitation:bB.optional(),roots:se({listChanged:Yt().optional()}).optional(),tasks:SB.optional()}),EB=kn.extend({protocolVersion:z(),capabilities:wB,clientInfo:oC}),kB=_r.extend({method:fe("initialize"),params:EB});var TB=se({experimental:Tt(z(),yr).optional(),logging:yr.optional(),completions:yr.optional(),prompts:se({listChanged:Yt().optional()}).optional(),resources:se({subscribe:Yt().optional(),listChanged:Yt().optional()}).optional(),tools:se({listChanged:Yt().optional()}).optional(),tasks:xB.optional()}),Bx=br.extend({protocolVersion:z(),capabilities:TB,serverInfo:oC,instructions:z().optional()}),$B=Ln.extend({method:fe("notifications/initialized"),params:zn.optional()});var Jm=_r.extend({method:fe("ping"),params:kn.optional()}),IB=se({progress:ct(),total:Ot(ct()),message:Ot(z())}),RB=se({...zn.shape,...IB.shape,progressToken:YO}),Xm=Ln.extend({method:fe("notifications/progress"),params:RB}),OB=kn.extend({cursor:QO.optional()}),Ql=_r.extend({params:OB.optional()}),ed=br.extend({nextCursor:QO.optional()}),CB=Cr(["working","input_required","completed","failed","cancelled"]),td=se({taskId:z(),status:CB,ttl:ht([ct(),Vl()]),createdAt:z(),lastUpdatedAt:z(),pollInterval:Ot(ct()),statusMessage:Ot(z())}),zo=br.extend({task:td}),PB=zn.merge(td),rd=Ln.extend({method:fe("notifications/tasks/status"),params:PB}),Ym=_r.extend({method:fe("tasks/get"),params:kn.extend({taskId:z()})}),Qm=br.merge(td),eh=_r.extend({method:fe("tasks/result"),params:kn.extend({taskId:z()})}),fTe=br.loose(),th=Ql.extend({method:fe("tasks/list")}),rh=ed.extend({tasks:Ve(td)}),nh=_r.extend({method:fe("tasks/cancel"),params:kn.extend({taskId:z()})}),aC=br.merge(td),cC=se({uri:z(),mimeType:Ot(z()),_meta:Tt(z(),St()).optional()}),uC=cC.extend({text:z()}),Gx=z().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),lC=cC.extend({blob:Gx}),nd=Cr(["user","assistant"]),oc=se({audience:Ve(nd).optional(),priority:ct().min(0).max(1).optional(),lastModified:Do.datetime({offset:!0}).optional()}),dC=se({...sc.shape,...Yl.shape,uri:z(),description:Ot(z()),mimeType:Ot(z()),annotations:oc.optional(),_meta:Ot(Or({}))}),AB=se({...sc.shape,...Yl.shape,uriTemplate:z(),description:Ot(z()),mimeType:Ot(z()),annotations:oc.optional(),_meta:Ot(Or({}))}),NB=Ql.extend({method:fe("resources/list")}),Wx=ed.extend({resources:Ve(dC)}),MB=Ql.extend({method:fe("resources/templates/list")}),Vx=ed.extend({resourceTemplates:Ve(AB)}),Kx=kn.extend({uri:z()}),DB=Kx,jB=_r.extend({method:fe("resources/read"),params:DB}),Jx=br.extend({contents:Ve(ht([uC,lC]))}),Xx=Ln.extend({method:fe("notifications/resources/list_changed"),params:zn.optional()}),zB=Kx,LB=_r.extend({method:fe("resources/subscribe"),params:zB}),UB=Kx,FB=_r.extend({method:fe("resources/unsubscribe"),params:UB}),qB=zn.extend({uri:z()}),HB=Ln.extend({method:fe("notifications/resources/updated"),params:qB}),ZB=se({name:z(),description:Ot(z()),required:Ot(Yt())}),BB=se({...sc.shape,...Yl.shape,description:Ot(z()),arguments:Ot(Ve(ZB)),_meta:Ot(Or({}))}),GB=Ql.extend({method:fe("prompts/list")}),Yx=ed.extend({prompts:Ve(BB)}),WB=kn.extend({name:z(),arguments:Tt(z(),z()).optional()}),VB=_r.extend({method:fe("prompts/get"),params:WB}),Qx=se({type:fe("text"),text:z(),annotations:oc.optional(),_meta:Tt(z(),St()).optional()}),ew=se({type:fe("image"),data:Gx,mimeType:z(),annotations:oc.optional(),_meta:Tt(z(),St()).optional()}),tw=se({type:fe("audio"),data:Gx,mimeType:z(),annotations:oc.optional(),_meta:Tt(z(),St()).optional()}),KB=se({type:fe("tool_use"),name:z(),id:z(),input:Tt(z(),St()),_meta:Tt(z(),St()).optional()}),JB=se({type:fe("resource"),resource:ht([uC,lC]),annotations:oc.optional(),_meta:Tt(z(),St()).optional()}),XB=dC.extend({type:fe("resource_link")}),rw=ht([Qx,ew,tw,XB,JB]),YB=se({role:nd,content:rw}),nw=br.extend({description:z().optional(),messages:Ve(YB)}),iw=Ln.extend({method:fe("notifications/prompts/list_changed"),params:zn.optional()}),QB=se({title:z().optional(),readOnlyHint:Yt().optional(),destructiveHint:Yt().optional(),idempotentHint:Yt().optional(),openWorldHint:Yt().optional()}),eG=se({taskSupport:Cr(["required","optional","forbidden"]).optional()}),pC=se({...sc.shape,...Yl.shape,description:z().optional(),inputSchema:se({type:fe("object"),properties:Tt(z(),yr).optional(),required:Ve(z()).optional()}).catchall(St()),outputSchema:se({type:fe("object"),properties:Tt(z(),yr).optional(),required:Ve(z()).optional()}).catchall(St()).optional(),annotations:QB.optional(),execution:eG.optional(),_meta:Tt(z(),St()).optional()}),tG=Ql.extend({method:fe("tools/list")}),sw=ed.extend({tools:Ve(pC)}),ac=br.extend({content:Ve(rw).default([]),structuredContent:Tt(z(),St()).optional(),isError:Yt().optional()}),mTe=ac.or(br.extend({toolResult:St()})),rG=Jl.extend({name:z(),arguments:Tt(z(),St()).optional()}),nG=_r.extend({method:fe("tools/call"),params:rG}),ow=Ln.extend({method:fe("notifications/tools/list_changed"),params:zn.optional()}),fC=se({autoRefresh:Yt().default(!0),debounceMs:ct().int().nonnegative().default(300)}),mC=Cr(["debug","info","notice","warning","error","critical","alert","emergency"]),iG=kn.extend({level:mC}),sG=_r.extend({method:fe("logging/setLevel"),params:iG}),oG=zn.extend({level:mC,logger:z().optional(),data:St()}),aG=Ln.extend({method:fe("notifications/message"),params:oG}),cG=se({name:z().optional()}),uG=se({hints:Ve(cG).optional(),costPriority:ct().min(0).max(1).optional(),speedPriority:ct().min(0).max(1).optional(),intelligencePriority:ct().min(0).max(1).optional()}),lG=se({mode:Cr(["auto","required","none"]).optional()}),dG=se({type:fe("tool_result"),toolUseId:z().describe("The unique identifier for the corresponding tool call."),content:Ve(rw).default([]),structuredContent:se({}).loose().optional(),isError:Yt().optional(),_meta:Tt(z(),St()).optional()}),pG=qm("type",[Qx,ew,tw]),Gm=qm("type",[Qx,ew,tw,KB,dG]),fG=se({role:nd,content:ht([Gm,Ve(Gm)]),_meta:Tt(z(),St()).optional()}),mG=Jl.extend({messages:Ve(fG),modelPreferences:uG.optional(),systemPrompt:z().optional(),includeContext:Cr(["none","thisServer","allServers"]).optional(),temperature:ct().optional(),maxTokens:ct().int(),stopSequences:Ve(z()).optional(),metadata:yr.optional(),tools:Ve(pC).optional(),toolChoice:lG.optional()}),aw=_r.extend({method:fe("sampling/createMessage"),params:mG}),cw=br.extend({model:z(),stopReason:Ot(Cr(["endTurn","stopSequence","maxTokens"]).or(z())),role:nd,content:pG}),hG=br.extend({model:z(),stopReason:Ot(Cr(["endTurn","stopSequence","maxTokens","toolUse"]).or(z())),role:nd,content:ht([Gm,Ve(Gm)])}),gG=se({type:fe("boolean"),title:z().optional(),description:z().optional(),default:Yt().optional()}),vG=se({type:fe("string"),title:z().optional(),description:z().optional(),minLength:ct().optional(),maxLength:ct().optional(),format:Cr(["email","uri","date","date-time"]).optional(),default:z().optional()}),yG=se({type:Cr(["number","integer"]),title:z().optional(),description:z().optional(),minimum:ct().optional(),maximum:ct().optional(),default:ct().optional()}),_G=se({type:fe("string"),title:z().optional(),description:z().optional(),enum:Ve(z()),default:z().optional()}),bG=se({type:fe("string"),title:z().optional(),description:z().optional(),oneOf:Ve(se({const:z(),title:z()})),default:z().optional()}),SG=se({type:fe("string"),title:z().optional(),description:z().optional(),enum:Ve(z()),enumNames:Ve(z()).optional(),default:z().optional()}),xG=ht([_G,bG]),wG=se({type:fe("array"),title:z().optional(),description:z().optional(),minItems:ct().optional(),maxItems:ct().optional(),items:se({type:fe("string"),enum:Ve(z())}),default:Ve(z()).optional()}),EG=se({type:fe("array"),title:z().optional(),description:z().optional(),minItems:ct().optional(),maxItems:ct().optional(),items:se({anyOf:Ve(se({const:z(),title:z()}))}),default:Ve(z()).optional()}),kG=ht([wG,EG]),TG=ht([SG,xG,kG]),$G=ht([TG,gG,vG,yG]),IG=Jl.extend({mode:fe("form").optional(),message:z(),requestedSchema:se({type:fe("object"),properties:Tt(z(),$G),required:Ve(z()).optional()})}),RG=Jl.extend({mode:fe("url"),message:z(),elicitationId:z(),url:z().url()}),OG=ht([IG,RG]),uw=_r.extend({method:fe("elicitation/create"),params:OG}),CG=zn.extend({elicitationId:z()}),PG=Ln.extend({method:fe("notifications/elicitation/complete"),params:CG}),lw=br.extend({action:Cr(["accept","decline","cancel"]),content:Bm(t=>t===null?void 0:t,Tt(z(),ht([z(),ct(),Yt(),Ve(z())])).optional())}),AG=se({type:fe("ref/resource"),uri:z()});var NG=se({type:fe("ref/prompt"),name:z()}),MG=kn.extend({ref:ht([NG,AG]),argument:se({name:z(),value:z()}),context:se({arguments:Tt(z(),z()).optional()}).optional()}),DG=_r.extend({method:fe("completion/complete"),params:MG});var dw=br.extend({completion:Or({values:Ve(z()).max(100),total:Ot(ct().int()),hasMore:Ot(Yt())})}),jG=se({uri:z().startsWith("file://"),name:z().optional(),_meta:Tt(z(),St()).optional()}),zG=_r.extend({method:fe("roots/list"),params:kn.optional()}),LG=br.extend({roots:Ve(jG)}),UG=Ln.extend({method:fe("notifications/roots/list_changed"),params:zn.optional()}),hTe=ht([Jm,kB,DG,sG,VB,GB,NB,MB,jB,LB,FB,nG,tG,Ym,eh,th,nh]),gTe=ht([Km,Xm,$B,UG,rd]),vTe=ht([jo,cw,hG,lw,LG,Qm,rh,zo]),yTe=ht([Jm,aw,uw,zG,Ym,eh,th,nh]),_Te=ht([Km,Xm,aG,HB,Xx,ow,iw,rd,PG]),bTe=ht([jo,Bx,dw,nw,Yx,Wx,Vx,Jx,ac,sw,Qm,rh,zo]),ve=class t extends Error{constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,r,n){if(e===Ie.UrlElicitationRequired&&n){let i=n;if(i.elicitations)return new Lx(i.elicitations,r)}return new t(e,r,n)}},Lx=class extends ve{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(Ie.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function Xs(t){return t==="completed"||t==="failed"||t==="cancelled"}var e$e=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function pw(t){let r=Om(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=J1(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function fw(t,e){let r=oi(t,e);if(!r.success)throw r.error;return r.data}var GG=6e4,ih=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(Km,r=>{this._oncancel(r)}),this.setNotificationHandler(Xm,r=>{this._onprogress(r)}),this.setRequestHandler(Jm,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Ym,async(r,n)=>{let i=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!i)throw new ve(Ie.InvalidParams,"Failed to retrieve task: Task not found");return{...i}}),this.setRequestHandler(eh,async(r,n)=>{let i=async()=>{let s=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(s,n.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,u=c.id,l=this._requestResolvers.get(u);if(l)if(this._requestResolvers.delete(u),a.type==="response")l(c);else{let d=c,p=new ve(d.error.code,d.error.message,d.error.data);l(p)}else{let d=a.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${u}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let o=await this._taskStore.getTask(s,n.sessionId);if(!o)throw new ve(Ie.InvalidParams,`Task not found: ${s}`);if(!Xs(o.status))return await this._waitForTaskUpdate(s,n.signal),await i();if(Xs(o.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[Js]:{taskId:s}}}}return await i()};return await i()}),this.setRequestHandler(th,async(r,n)=>{try{let{tasks:i,nextCursor:s}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:i,nextCursor:s,_meta:{}}}catch(i){throw new ve(Ie.InvalidParams,`Failed to list tasks: ${i instanceof Error?i.message:String(i)}`)}}),this.setRequestHandler(nh,async(r,n)=>{try{let i=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!i)throw new ve(Ie.InvalidParams,`Task not found: ${r.params.taskId}`);if(Xs(i.status))throw new ve(Ie.InvalidParams,`Cannot cancel task in terminal status: ${i.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new ve(Ie.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(i){throw i instanceof ve?i:new ve(Ie.InvalidRequest,`Failed to cancel task: ${i instanceof Error?i.message:String(i)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,n,i,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(i,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:s,onTimeout:i})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),ve.fromError(Ie.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){this._transport=e;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=s=>{n?.(s),this._onerror(s)};let i=this._transport?.onmessage;this._transport.onmessage=(s,o)=>{i?.(s,o),Xl(s)||iC(s)?this._onresponse(s):qx(s)?this._onrequest(s,o):nC(s)?this._onnotification(s):this._onerror(new Error(`Unknown message type: ${JSON.stringify(s)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();let r=ve.fromError(Ie.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of e.values())n(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){let r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,i=this._transport,s=e.params?._meta?.[Js]?.taskId;if(n===void 0){let l={jsonrpc:"2.0",id:e.id,error:{code:Ie.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:l,timestamp:Date.now()},i?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):i?.send(l).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}let o=new AbortController;this._requestHandlerAbortControllers.set(e.id,o);let a=eC(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,i?.sessionId):void 0,u={signal:o.signal,sessionId:i?.sessionId,_meta:e.params?._meta,sendNotification:async l=>{let d={relatedRequestId:e.id};s&&(d.relatedTask={taskId:s}),await this.notification(l,d)},sendRequest:async(l,d,p)=>{let f={...p,relatedRequestId:e.id};s&&!f.relatedTask&&(f.relatedTask={taskId:s});let m=f.relatedTask?.taskId??s;return m&&c&&await c.updateTaskStatus(m,"input_required"),await this.request(l,d,f)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:s,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,u)).then(async l=>{if(o.signal.aborted)return;let d={result:l,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:d,timestamp:Date.now()},i?.sessionId):await i?.send(d)},async l=>{if(o.signal.aborted)return;let d={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(l.code)?l.code:Ie.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:d,timestamp:Date.now()},i?.sessionId):await i?.send(d)}).catch(l=>this._onerror(new Error(`Failed to send response: ${l}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,i=Number(r),s=this._progressHandlers.get(i);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let o=this._responseHandlers.get(i),a=this._timeoutInfo.get(i);if(a&&o&&a.resetTimeoutOnProgress)try{this._resetTimeout(i)}catch(c){this._responseHandlers.delete(i),this._progressHandlers.delete(i),this._cleanupTimeout(i),o(c);return}s(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),Xl(e))n(e);else{let o=new ve(e.error.code,e.error.message,e.error.data);n(o)}return}let i=this._responseHandlers.get(r);if(i===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let s=!1;if(Xl(e)&&e.result&&typeof e.result=="object"){let o=e.result;if(o.task&&typeof o.task=="object"){let a=o.task;typeof a.taskId=="string"&&(s=!0,this._taskProgressTokens.set(a.taskId,r))}}if(s||this._progressHandlers.delete(r),Xl(e))i(e);else{let o=ve.fromError(e.error.code,e.error.message,e.error.data);i(o)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,n){let{task:i}=n??{};if(!i){try{yield{type:"result",result:await this.request(e,r,n)}}catch(o){yield{type:"error",error:o instanceof ve?o:new ve(Ie.InternalError,String(o))}}return}let s;try{let o=await this.request(e,zo,n);if(o.task)s=o.task.taskId,yield{type:"taskCreated",task:o.task};else throw new ve(Ie.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},Xs(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:a.status==="failed"?yield{type:"error",error:new ve(Ie.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new ve(Ie.InternalError,`Task ${s} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),n?.signal?.throwIfAborted()}}catch(o){yield{type:"error",error:o instanceof ve?o:new ve(Ie.InternalError,String(o))}}}request(e,r,n){let{relatedRequestId:i,resumptionToken:s,onresumptiontoken:o,task:a,relatedTask:c}=n??{};return new Promise((u,l)=>{let d=S=>{l(S)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(S){d(S);return}n?.signal?.throwIfAborted();let p=this._requestMessageId++,f={...e,jsonrpc:"2.0",id:p};n?.onprogress&&(this._progressHandlers.set(p,n.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:p}}),a&&(f.params={...f.params,task:a}),c&&(f.params={...f.params,_meta:{...f.params?._meta||{},[Js]:c}});let m=S=>{this._responseHandlers.delete(p),this._progressHandlers.delete(p),this._cleanupTimeout(p),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:p,reason:String(S)}},{relatedRequestId:i,resumptionToken:s,onresumptiontoken:o}).catch(y=>this._onerror(new Error(`Failed to send cancellation: ${y}`)));let _=S instanceof ve?S:new ve(Ie.RequestTimeout,String(S));l(_)};this._responseHandlers.set(p,S=>{if(!n?.signal?.aborted){if(S instanceof Error)return l(S);try{let _=oi(r,S.result);_.success?u(_.data):l(_.error)}catch(_){l(_)}}}),n?.signal?.addEventListener("abort",()=>{m(n?.signal?.reason)});let h=n?.timeout??GG,g=()=>m(ve.fromError(Ie.RequestTimeout,"Request timed out",{timeout:h}));this._setupTimeout(p,h,n?.maxTotalTimeout,g,n?.resetTimeoutOnProgress??!1);let v=c?.taskId;if(v){let S=_=>{let y=this._responseHandlers.get(p);y?y(_):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,S),this._enqueueTaskMessage(v,{type:"request",message:f,timestamp:Date.now()}).catch(_=>{this._cleanupTimeout(p),l(_)})}else this._transport.send(f,{relatedRequestId:i,resumptionToken:s,onresumptiontoken:o}).catch(S=>{this._cleanupTimeout(p),l(S)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},Qm,r)}async getTaskResult(e,r,n){return this.request({method:"tasks/result",params:e},r,n)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},rh,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},aC,r)}async notification(e,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let n=r?.relatedTask?.taskId;if(n){let a={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[Js]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let a={...e,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[Js]:r.relatedTask}}}),this._transport?.send(a,r).catch(c=>this._onerror(c))});return}let o={...e,jsonrpc:"2.0"};r?.relatedTask&&(o={...o,params:{...o.params,_meta:{...o.params?._meta||{},[Js]:r.relatedTask}}}),await this._transport.send(o,r)}setRequestHandler(e,r){let n=pw(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(i,s)=>{let o=fw(e,i);return Promise.resolve(r(o,s))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){let n=pw(e);this._notificationHandlers.set(n,i=>{let s=fw(e,i);return Promise.resolve(r(s))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let i=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,i)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let i of n)if(i.type==="request"&&qx(i.message)){let s=i.message.id,o=this._requestResolvers.get(s);o?(o(new ve(Ie.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s)):this._onerror(new Error(`Resolver missing for request ${s} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let i=await this._taskStore?.getTask(e);i?.pollInterval&&(n=i.pollInterval)}catch{}return new Promise((i,s)=>{if(r.aborted){s(new ve(Ie.InvalidRequest,"Request cancelled"));return}let o=setTimeout(i,n);r.addEventListener("abort",()=>{clearTimeout(o),s(new ve(Ie.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async i=>{if(!e)throw new Error("No request provided");return await n.createTask(i,e.id,{method:e.method,params:e.params},r)},getTask:async i=>{let s=await n.getTask(i,r);if(!s)throw new ve(Ie.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(i,s,o)=>{await n.storeTaskResult(i,s,o,r);let a=await n.getTask(i,r);if(a){let c=rd.parse({method:"notifications/tasks/status",params:a});await this.notification(c),Xs(a.status)&&this._cleanupTaskProgressHandler(i)}},getTaskResult:i=>n.getTaskResult(i,r),updateTaskStatus:async(i,s,o)=>{let a=await n.getTask(i,r);if(!a)throw new ve(Ie.InvalidParams,`Task "${i}" not found - it may have been cleaned up`);if(Xs(a.status))throw new ve(Ie.InvalidParams,`Cannot update task "${i}" from terminal status "${a.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(i,s,o,r);let c=await n.getTask(i,r);if(c){let u=rd.parse({method:"notifications/tasks/status",params:c});await this.notification(u),Xs(c.status)&&this._cleanupTaskProgressHandler(i)}},listTasks:i=>n.listTasks(i,r)}}};function hC(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function gC(t,e){let r={...t};for(let n in e){let i=n,s=e[i];if(s===void 0)continue;let o=r[i];hC(o)&&hC(s)?r[i]={...o,...s}:r[i]=s}return r}var rN=Me(Y0(),1),nN=Me(tN(),1);function DX(){let t=new rN.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,nN.default)(t),t}var Fh=class{constructor(e){this._ajv=e??DX()}getValidator(e){let r="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}};var qh=class{constructor(e){this._client=e}async*callToolStream(e,r=ac,n){let i=this._client,s={...n,task:n?.task??(i.isToolTask(e.name)?{}:void 0)},o=i.requestStream({method:"tools/call",params:e},r,s),a=i.getToolOutputValidator(e.name);for await(let c of o){if(c.type==="result"&&a){let u=c.result;if(!u.structuredContent&&!u.isError){yield{type:"error",error:new ve(Ie.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`)};return}if(u.structuredContent)try{let l=a(u.structuredContent);if(!l.valid){yield{type:"error",error:new ve(Ie.InvalidParams,`Structured content does not match the tool's output schema: ${l.errorMessage}`)};return}}catch(l){if(l instanceof ve){yield{type:"error",error:l};return}yield{type:"error",error:new ve(Ie.InvalidParams,`Failed to validate structured content: ${l instanceof Error?l.message:String(l)}`)};return}}yield c}}async getTask(e,r){return this._client.getTask({taskId:e},r)}async getTaskResult(e,r,n){return this._client.getTaskResult({taskId:e},r,n)}async listTasks(e,r){return this._client.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._client.cancelTask({taskId:e},r)}requestStream(e,r,n){return this._client.requestStream(e,r,n)}};function iN(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${e})`);break;default:break}}function sN(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}function Hh(t,e){if(!(!t||e===null||typeof e!="object")){if(t.type==="object"&&t.properties&&typeof t.properties=="object"){let r=e,n=t.properties;for(let i of Object.keys(n)){let s=n[i];r[i]===void 0&&Object.prototype.hasOwnProperty.call(s,"default")&&(r[i]=s.default),r[i]!==void 0&&Hh(s,r[i])}}if(Array.isArray(t.anyOf))for(let r of t.anyOf)typeof r!="boolean"&&Hh(r,e);if(Array.isArray(t.oneOf))for(let r of t.oneOf)typeof r!="boolean"&&Hh(r,e)}}function jX(t){if(!t)return{supportsFormMode:!1,supportsUrlMode:!1};let e=t.form!==void 0,r=t.url!==void 0;return{supportsFormMode:e||!e&&!r,supportsUrlMode:r}}var Ec=class extends ih{constructor(e,r){super(r),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._listChangedDebounceTimers=new Map,this._capabilities=r?.capabilities??{},this._jsonSchemaValidator=r?.jsonSchemaValidator??new Fh,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",ow,e.tools,async()=>(await this.listTools()).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",iw,e.prompts,async()=>(await this.listPrompts()).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",Xx,e.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new qh(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=gC(this._capabilities,e)}setRequestHandler(e,r){let i=Om(e)?.method;if(!i)throw new Error("Schema is missing a method literal");let s;if(nc(i)){let a=i;s=a._zod?.def?.value??a.value}else{let a=i;s=a._def?.value??a.value}if(typeof s!="string")throw new Error("Schema method literal must be a string");let o=s;if(o==="elicitation/create"){let a=async(c,u)=>{let l=oi(uw,c);if(!l.success){let S=l.error instanceof Error?l.error.message:String(l.error);throw new ve(Ie.InvalidParams,`Invalid elicitation request: ${S}`)}let{params:d}=l.data;d.mode=d.mode??"form";let{supportsFormMode:p,supportsUrlMode:f}=jX(this._capabilities.elicitation);if(d.mode==="form"&&!p)throw new ve(Ie.InvalidParams,"Client does not support form-mode elicitation requests");if(d.mode==="url"&&!f)throw new ve(Ie.InvalidParams,"Client does not support URL-mode elicitation requests");let m=await Promise.resolve(r(c,u));if(d.task){let S=oi(zo,m);if(!S.success){let _=S.error instanceof Error?S.error.message:String(S.error);throw new ve(Ie.InvalidParams,`Invalid task creation result: ${_}`)}return S.data}let h=oi(lw,m);if(!h.success){let S=h.error instanceof Error?h.error.message:String(h.error);throw new ve(Ie.InvalidParams,`Invalid elicitation result: ${S}`)}let g=h.data,v=d.mode==="form"?d.requestedSchema:void 0;if(d.mode==="form"&&g.action==="accept"&&g.content&&v&&this._capabilities.elicitation?.form?.applyDefaults)try{Hh(v,g.content)}catch{}return g};return super.setRequestHandler(e,a)}if(o==="sampling/createMessage"){let a=async(c,u)=>{let l=oi(aw,c);if(!l.success){let m=l.error instanceof Error?l.error.message:String(l.error);throw new ve(Ie.InvalidParams,`Invalid sampling request: ${m}`)}let{params:d}=l.data,p=await Promise.resolve(r(c,u));if(d.task){let m=oi(zo,p);if(!m.success){let h=m.error instanceof Error?m.error.message:String(m.error);throw new ve(Ie.InvalidParams,`Invalid task creation result: ${h}`)}return m.data}let f=oi(cw,p);if(!f.success){let m=f.error instanceof Error?f.error.message:String(f.error);throw new ve(Ie.InvalidParams,`Invalid sampling result: ${m}`)}return f.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,r)}assertCapability(e,r){if(!this._serverCapabilities?.[e])throw new Error(`Server does not support ${e} (required for ${r})`)}async connect(e,r){if(await super.connect(e),e.sessionId===void 0)try{let n=await this.request({method:"initialize",params:{protocolVersion:Ux,capabilities:this._capabilities,clientInfo:this._clientInfo}},Bx,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!XO.includes(n.protocolVersion))throw new Error(`Server's protocol version is not supported: ${n.protocolVersion}`);this._serverCapabilities=n.capabilities,this._serverVersion=n.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(n.protocolVersion),this._instructions=n.instructions,await this.notification({method:"notifications/initialized"}),this._pendingListChangedConfig&&(this._setupListChangedHandlers(this._pendingListChangedConfig),this._pendingListChangedConfig=void 0)}catch(n){throw this.close(),n}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){switch(e){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!this._serverCapabilities?.resources)throw new Error(`Server does not support resources (required for ${e})`);if(e==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"initialize":break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/roots/list_changed":if(!this._capabilities.roots?.listChanged)throw new Error(`Client does not support roots list changed notifications (required for ${e})`);break;case"notifications/initialized":break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Client does not support tasks capability (required for ${e})`);break;case"ping":break}}assertTaskCapability(e){iN(this._serverCapabilities?.tasks?.requests,e,"Server")}assertTaskHandlerCapability(e){this._capabilities&&sN(this._capabilities.tasks?.requests,e,"Client")}async ping(e){return this.request({method:"ping"},jo,e)}async complete(e,r){return this.request({method:"completion/complete",params:e},dw,r)}async setLoggingLevel(e,r){return this.request({method:"logging/setLevel",params:{level:e}},jo,r)}async getPrompt(e,r){return this.request({method:"prompts/get",params:e},nw,r)}async listPrompts(e,r){return this.request({method:"prompts/list",params:e},Yx,r)}async listResources(e,r){return this.request({method:"resources/list",params:e},Wx,r)}async listResourceTemplates(e,r){return this.request({method:"resources/templates/list",params:e},Vx,r)}async readResource(e,r){return this.request({method:"resources/read",params:e},Jx,r)}async subscribeResource(e,r){return this.request({method:"resources/subscribe",params:e},jo,r)}async unsubscribeResource(e,r){return this.request({method:"resources/unsubscribe",params:e},jo,r)}async callTool(e,r=ac,n){if(this.isToolTaskRequired(e.name))throw new ve(Ie.InvalidRequest,`Tool "${e.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);let i=await this.request({method:"tools/call",params:e},r,n),s=this.getToolOutputValidator(e.name);if(s){if(!i.structuredContent&&!i.isError)throw new ve(Ie.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(i.structuredContent)try{let o=s(i.structuredContent);if(!o.valid)throw new ve(Ie.InvalidParams,`Structured content does not match the tool's output schema: ${o.errorMessage}`)}catch(o){throw o instanceof ve?o:new ve(Ie.InvalidParams,`Failed to validate structured content: ${o instanceof Error?o.message:String(o)}`)}}return i}isToolTask(e){return this._serverCapabilities?.tasks?.requests?.tools?.call?this._cachedKnownTaskTools.has(e):!1}isToolTaskRequired(e){return this._cachedRequiredTaskTools.has(e)}cacheToolMetadata(e){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(let r of e){if(r.outputSchema){let i=this._jsonSchemaValidator.getValidator(r.outputSchema);this._cachedToolOutputValidators.set(r.name,i)}let n=r.execution?.taskSupport;(n==="required"||n==="optional")&&this._cachedKnownTaskTools.add(r.name),n==="required"&&this._cachedRequiredTaskTools.add(r.name)}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,r){let n=await this.request({method:"tools/list",params:e},sw,r);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(e,r,n,i){let s=fC.safeParse(n);if(!s.success)throw new Error(`Invalid ${e} listChanged options: ${s.error.message}`);if(typeof n.onChanged!="function")throw new Error(`Invalid ${e} listChanged options: onChanged must be a function`);let{autoRefresh:o,debounceMs:a}=s.data,{onChanged:c}=n,u=async()=>{if(!o){c(null,null);return}try{let d=await i();c(null,d)}catch(d){let p=d instanceof Error?d:new Error(String(d));c(p,null)}},l=()=>{if(a){let d=this._listChangedDebounceTimers.get(e);d&&clearTimeout(d);let p=setTimeout(u,a);this._listChangedDebounceTimers.set(e,p)}else u()};this.setNotificationHandler(r,l)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};var KN=Me(WN(),1),Nd=Me(require("node:process"),1),JN=require("node:stream");var Bh=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(` +Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let o of t.seen.entries()){let a=o[1];if(e===o[0]){s(o);continue}if(t.external){let u=t.external.registry.get(o[0])?.id;if(e!==o[0]&&u){s(o);continue}}if(t.metadataRegistry.get(o[0])?.id){s(o);continue}if(a.cycle){s(o);continue}if(a.count>1&&t.reused==="ref"){s(o);continue}}}function Rm(t,e){let r=t.seen.get(e);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let n=o=>{let a=t.seen.get(o);if(a.ref===null)return;let c=a.def??a.schema,u={...c},l=a.ref;if(a.ref=null,l){n(l);let p=t.seen.get(l),f=p.schema;if(f.$ref&&(t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0")?(c.allOf=c.allOf??[],c.allOf.push(f)):Object.assign(c,f),Object.assign(c,u),o._zod.parent===l)for(let h in c)h==="$ref"||h==="allOf"||h in u||delete c[h];if(f.$ref)for(let h in c)h==="$ref"||h==="allOf"||h in p.def&&JSON.stringify(c[h])===JSON.stringify(p.def[h])&&delete c[h]}let d=o._zod.parent;if(d&&d!==l){n(d);let p=t.seen.get(d);if(p?.schema.$ref&&(c.$ref=p.schema.$ref,p.def))for(let f in c)f==="$ref"||f==="allOf"||f in p.def&&JSON.stringify(c[f])===JSON.stringify(p.def[f])&&delete c[f]}t.override({zodSchema:o,jsonSchema:c,path:a.path??[]})};for(let o of[...t.seen.entries()].reverse())n(o[0]);let i={};if(t.target==="draft-2020-12"?i.$schema="https://json-schema.org/draft/2020-12/schema":t.target==="draft-07"?i.$schema="http://json-schema.org/draft-07/schema#":t.target==="draft-04"?i.$schema="http://json-schema.org/draft-04/schema#":t.target,t.external?.uri){let o=t.external.registry.get(e)?.id;if(!o)throw new Error("Schema is missing an `id` property");i.$id=t.external.uri(o)}Object.assign(i,r.def??r.schema);let s=t.external?.defs??{};for(let o of t.seen.entries()){let a=o[1];a.def&&a.defId&&(s[a.defId]=a.def)}t.external||Object.keys(s).length>0&&(t.target==="draft-2020-12"?i.$defs=s:i.definitions=s);try{let o=JSON.parse(JSON.stringify(i));return Object.defineProperty(o,"~standard",{value:{...e["~standard"],jsonSchema:{input:Zl(e,"input",t.processors),output:Zl(e,"output",t.processors)}},enumerable:!1,writable:!1}),o}catch{throw new Error("Error converting schema to JSON.")}}function Wr(t,e){let r=e??{seen:new Set};if(r.seen.has(t))return!1;r.seen.add(t);let n=t._zod.def;if(n.type==="transform")return!0;if(n.type==="array")return Wr(n.element,r);if(n.type==="set")return Wr(n.valueType,r);if(n.type==="lazy")return Wr(n.getter(),r);if(n.type==="promise"||n.type==="optional"||n.type==="nonoptional"||n.type==="nullable"||n.type==="readonly"||n.type==="default"||n.type==="prefault")return Wr(n.innerType,r);if(n.type==="intersection")return Wr(n.left,r)||Wr(n.right,r);if(n.type==="record"||n.type==="map")return Wr(n.keyType,r)||Wr(n.valueType,r);if(n.type==="pipe")return Wr(n.in,r)||Wr(n.out,r);if(n.type==="object"){for(let i in n.shape)if(Wr(n.shape[i],r))return!0;return!1}if(n.type==="union"){for(let i of n.options)if(Wr(i,r))return!0;return!1}if(n.type==="tuple"){for(let i of n.items)if(Wr(i,r))return!0;return!!(n.rest&&Wr(n.rest,r))}return!1}var u1=(t,e={})=>r=>{let n=$m({...r,processors:e});return kt(t,n),Im(n,t),Rm(n,t)},Zl=(t,e,r={})=>n=>{let{libraryOptions:i,target:s}=n??{},o=$m({...i??{},target:s,io:e,processors:r});return kt(t,o),Im(o,t),Rm(o,t)};var F3={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},l1=(t,e,r,n)=>{let i=r;i.type="string";let{minimum:s,maximum:o,format:a,patterns:c,contentEncoding:u}=t._zod.bag;if(typeof s=="number"&&(i.minLength=s),typeof o=="number"&&(i.maxLength=o),a&&(i.format=F3[a]??a,i.format===""&&delete i.format,a==="time"&&delete i.format),u&&(i.contentEncoding=u),c&&c.size>0){let l=[...c];l.length===1?i.pattern=l[0].source:l.length>1&&(i.allOf=[...l.map(d=>({...e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"?{type:"string"}:{},pattern:d.source}))])}},d1=(t,e,r,n)=>{let i=r,{minimum:s,maximum:o,format:a,multipleOf:c,exclusiveMaximum:u,exclusiveMinimum:l}=t._zod.bag;typeof a=="string"&&a.includes("int")?i.type="integer":i.type="number",typeof l=="number"&&(e.target==="draft-04"||e.target==="openapi-3.0"?(i.minimum=l,i.exclusiveMinimum=!0):i.exclusiveMinimum=l),typeof s=="number"&&(i.minimum=s,typeof l=="number"&&e.target!=="draft-04"&&(l>=s?delete i.minimum:delete i.exclusiveMinimum)),typeof u=="number"&&(e.target==="draft-04"||e.target==="openapi-3.0"?(i.maximum=u,i.exclusiveMaximum=!0):i.exclusiveMaximum=u),typeof o=="number"&&(i.maximum=o,typeof u=="number"&&e.target!=="draft-04"&&(u<=o?delete i.maximum:delete i.exclusiveMaximum)),typeof c=="number"&&(i.multipleOf=c)},p1=(t,e,r,n)=>{r.type="boolean"},f1=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema")},m1=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema")},h1=(t,e,r,n)=>{e.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"},g1=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema")},v1=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema")},y1=(t,e,r,n)=>{r.not={}},_1=(t,e,r,n)=>{},b1=(t,e,r,n)=>{},S1=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema")},x1=(t,e,r,n)=>{let i=t._zod.def,s=pl(i.entries);s.every(o=>typeof o=="number")&&(r.type="number"),s.every(o=>typeof o=="string")&&(r.type="string"),r.enum=s},w1=(t,e,r,n)=>{let i=t._zod.def,s=[];for(let o of i.values)if(o===void 0){if(e.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof o=="bigint"){if(e.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");s.push(Number(o))}else s.push(o);if(s.length!==0)if(s.length===1){let o=s[0];r.type=o===null?"null":typeof o,e.target==="draft-04"||e.target==="openapi-3.0"?r.enum=[o]:r.const=o}else s.every(o=>typeof o=="number")&&(r.type="number"),s.every(o=>typeof o=="string")&&(r.type="string"),s.every(o=>typeof o=="boolean")&&(r.type="boolean"),s.every(o=>o===null)&&(r.type="null"),r.enum=s},E1=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema")},k1=(t,e,r,n)=>{let i=r,s=t._zod.pattern;if(!s)throw new Error("Pattern not found in template literal");i.type="string",i.pattern=s.source},T1=(t,e,r,n)=>{let i=r,s={type:"string",format:"binary",contentEncoding:"binary"},{minimum:o,maximum:a,mime:c}=t._zod.bag;o!==void 0&&(s.minLength=o),a!==void 0&&(s.maxLength=a),c?c.length===1?(s.contentMediaType=c[0],Object.assign(i,s)):(Object.assign(i,s),i.anyOf=c.map(u=>({contentMediaType:u}))):Object.assign(i,s)},$1=(t,e,r,n)=>{r.type="boolean"},I1=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},R1=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Function types cannot be represented in JSON Schema")},O1=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},C1=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema")},P1=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema")},A1=(t,e,r,n)=>{let i=r,s=t._zod.def,{minimum:o,maximum:a}=t._zod.bag;typeof o=="number"&&(i.minItems=o),typeof a=="number"&&(i.maxItems=a),i.type="array",i.items=kt(s.element,e,{...n,path:[...n.path,"items"]})},N1=(t,e,r,n)=>{let i=r,s=t._zod.def;i.type="object",i.properties={};let o=s.shape;for(let u in o)i.properties[u]=kt(o[u],e,{...n,path:[...n.path,"properties",u]});let a=new Set(Object.keys(o)),c=new Set([...a].filter(u=>{let l=s.shape[u]._zod;return e.io==="input"?l.optin===void 0:l.optout===void 0}));c.size>0&&(i.required=Array.from(c)),s.catchall?._zod.def.type==="never"?i.additionalProperties=!1:s.catchall?s.catchall&&(i.additionalProperties=kt(s.catchall,e,{...n,path:[...n.path,"additionalProperties"]})):e.io==="output"&&(i.additionalProperties=!1)},tx=(t,e,r,n)=>{let i=t._zod.def,s=i.inclusive===!1,o=i.options.map((a,c)=>kt(a,e,{...n,path:[...n.path,s?"oneOf":"anyOf",c]}));s?r.oneOf=o:r.anyOf=o},M1=(t,e,r,n)=>{let i=t._zod.def,s=kt(i.left,e,{...n,path:[...n.path,"allOf",0]}),o=kt(i.right,e,{...n,path:[...n.path,"allOf",1]}),a=u=>"allOf"in u&&Object.keys(u).length===1,c=[...a(s)?s.allOf:[s],...a(o)?o.allOf:[o]];r.allOf=c},D1=(t,e,r,n)=>{let i=r,s=t._zod.def;i.type="array";let o=e.target==="draft-2020-12"?"prefixItems":"items",a=e.target==="draft-2020-12"||e.target==="openapi-3.0"?"items":"additionalItems",c=s.items.map((p,f)=>kt(p,e,{...n,path:[...n.path,o,f]})),u=s.rest?kt(s.rest,e,{...n,path:[...n.path,a,...e.target==="openapi-3.0"?[s.items.length]:[]]}):null;e.target==="draft-2020-12"?(i.prefixItems=c,u&&(i.items=u)):e.target==="openapi-3.0"?(i.items={anyOf:c},u&&i.items.anyOf.push(u),i.minItems=c.length,u||(i.maxItems=c.length)):(i.items=c,u&&(i.additionalItems=u));let{minimum:l,maximum:d}=t._zod.bag;typeof l=="number"&&(i.minItems=l),typeof d=="number"&&(i.maxItems=d)},j1=(t,e,r,n)=>{let i=r,s=t._zod.def;i.type="object";let o=s.keyType,c=o._zod.bag?.patterns;if(s.mode==="loose"&&c&&c.size>0){let l=kt(s.valueType,e,{...n,path:[...n.path,"patternProperties","*"]});i.patternProperties={};for(let d of c)i.patternProperties[d.source]=l}else(e.target==="draft-07"||e.target==="draft-2020-12")&&(i.propertyNames=kt(s.keyType,e,{...n,path:[...n.path,"propertyNames"]})),i.additionalProperties=kt(s.valueType,e,{...n,path:[...n.path,"additionalProperties"]});let u=o._zod.values;if(u){let l=[...u].filter(d=>typeof d=="string"||typeof d=="number");l.length>0&&(i.required=l)}},z1=(t,e,r,n)=>{let i=t._zod.def,s=kt(i.innerType,e,n),o=e.seen.get(t);e.target==="openapi-3.0"?(o.ref=i.innerType,r.nullable=!0):r.anyOf=[s,{type:"null"}]},L1=(t,e,r,n)=>{let i=t._zod.def;kt(i.innerType,e,n);let s=e.seen.get(t);s.ref=i.innerType},U1=(t,e,r,n)=>{let i=t._zod.def;kt(i.innerType,e,n);let s=e.seen.get(t);s.ref=i.innerType,r.default=JSON.parse(JSON.stringify(i.defaultValue))},F1=(t,e,r,n)=>{let i=t._zod.def;kt(i.innerType,e,n);let s=e.seen.get(t);s.ref=i.innerType,e.io==="input"&&(r._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},q1=(t,e,r,n)=>{let i=t._zod.def;kt(i.innerType,e,n);let s=e.seen.get(t);s.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}r.default=o},H1=(t,e,r,n)=>{let i=t._zod.def,s=e.io==="input"?i.in._zod.def.type==="transform"?i.out:i.in:i.out;kt(s,e,n);let o=e.seen.get(t);o.ref=s},Z1=(t,e,r,n)=>{let i=t._zod.def;kt(i.innerType,e,n);let s=e.seen.get(t);s.ref=i.innerType,r.readOnly=!0},B1=(t,e,r,n)=>{let i=t._zod.def;kt(i.innerType,e,n);let s=e.seen.get(t);s.ref=i.innerType},rx=(t,e,r,n)=>{let i=t._zod.def;kt(i.innerType,e,n);let s=e.seen.get(t);s.ref=i.innerType},G1=(t,e,r,n)=>{let i=t._zod.innerType;kt(i,e,n);let s=e.seen.get(t);s.ref=i};function nc(t){return!!t._zod}function oi(t,e){return nc(t)?Ya(t,e):t.safeParse(e)}function Om(t){if(!t)return;let e;if(nc(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function J1(t){if(nc(t)){let s=t._zod?.def;if(s){if(s.value!==void 0)return s.value;if(Array.isArray(s.values)&&s.values.length>0)return s.values[0]}}let r=t._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=t.value;if(n!==void 0)return n}var Bl={};_n(Bl,{ZodAny:()=>mO,ZodArray:()=>yO,ZodBase64:()=>Tx,ZodBase64URL:()=>$x,ZodBigInt:()=>Lm,ZodBigIntFormat:()=>Ox,ZodBoolean:()=>zm,ZodCIDRv4:()=>Ex,ZodCIDRv6:()=>kx,ZodCUID:()=>vx,ZodCUID2:()=>yx,ZodCatch:()=>zO,ZodCodec:()=>jx,ZodCustom:()=>Zm,ZodCustomStringFormat:()=>Wl,ZodDate:()=>Px,ZodDefault:()=>PO,ZodDiscriminatedUnion:()=>bO,ZodE164:()=>Ix,ZodEmail:()=>mx,ZodEmoji:()=>hx,ZodEnum:()=>Gl,ZodExactOptional:()=>RO,ZodFile:()=>$O,ZodFunction:()=>WO,ZodGUID:()=>Pm,ZodIPv4:()=>xx,ZodIPv6:()=>wx,ZodIntersection:()=>SO,ZodJWT:()=>Rx,ZodKSUID:()=>Sx,ZodLazy:()=>ZO,ZodLiteral:()=>TO,ZodMAC:()=>lO,ZodMap:()=>EO,ZodNaN:()=>UO,ZodNanoID:()=>gx,ZodNever:()=>gO,ZodNonOptional:()=>Mx,ZodNull:()=>fO,ZodNullable:()=>CO,ZodNumber:()=>jm,ZodNumberFormat:()=>ic,ZodObject:()=>Um,ZodOptional:()=>Nx,ZodPipe:()=>Dx,ZodPrefault:()=>NO,ZodPromise:()=>GO,ZodReadonly:()=>FO,ZodRecord:()=>Hm,ZodSet:()=>kO,ZodString:()=>Mm,ZodStringFormat:()=>bt,ZodSuccess:()=>jO,ZodSymbol:()=>dO,ZodTemplateLiteral:()=>HO,ZodTransform:()=>IO,ZodTuple:()=>xO,ZodType:()=>De,ZodULID:()=>_x,ZodURL:()=>Dm,ZodUUID:()=>ps,ZodUndefined:()=>pO,ZodUnion:()=>Fm,ZodUnknown:()=>hO,ZodVoid:()=>vO,ZodXID:()=>bx,ZodXor:()=>_O,_ZodString:()=>fx,_default:()=>AO,_function:()=>sB,any:()=>FZ,array:()=>Ve,base64:()=>EZ,base64url:()=>kZ,bigint:()=>DZ,boolean:()=>Yt,catch:()=>LO,check:()=>oB,cidrv4:()=>xZ,cidrv6:()=>wZ,codec:()=>rB,cuid:()=>mZ,cuid2:()=>hZ,custom:()=>zx,date:()=>HZ,describe:()=>aB,discriminatedUnion:()=>qm,e164:()=>TZ,email:()=>iZ,emoji:()=>pZ,enum:()=>Cr,exactOptional:()=>OO,file:()=>YZ,float32:()=>PZ,float64:()=>AZ,function:()=>sB,guid:()=>sZ,hash:()=>CZ,hex:()=>OZ,hostname:()=>RZ,httpUrl:()=>dZ,instanceof:()=>uB,int:()=>px,int32:()=>NZ,int64:()=>jZ,intersection:()=>Kl,ipv4:()=>_Z,ipv6:()=>SZ,json:()=>dB,jwt:()=>$Z,keyof:()=>ZZ,ksuid:()=>yZ,lazy:()=>BO,literal:()=>fe,looseObject:()=>Or,looseRecord:()=>VZ,mac:()=>bZ,map:()=>KZ,meta:()=>cB,nan:()=>tB,nanoid:()=>fZ,nativeEnum:()=>XZ,never:()=>Cx,nonoptional:()=>DO,null:()=>Vl,nullable:()=>Am,nullish:()=>QZ,number:()=>ct,object:()=>ie,optional:()=>Ot,partialRecord:()=>WZ,pipe:()=>Nm,prefault:()=>MO,preprocess:()=>Bm,promise:()=>iB,readonly:()=>qO,record:()=>Tt,refine:()=>VO,set:()=>JZ,strictObject:()=>BZ,string:()=>z,stringFormat:()=>IZ,stringbool:()=>lB,success:()=>eB,superRefine:()=>KO,symbol:()=>LZ,templateLiteral:()=>nB,transform:()=>Ax,tuple:()=>wO,uint32:()=>MZ,uint64:()=>zZ,ulid:()=>gZ,undefined:()=>UZ,union:()=>ht,unknown:()=>St,url:()=>lZ,uuid:()=>oZ,uuidv4:()=>aZ,uuidv6:()=>cZ,uuidv7:()=>uZ,void:()=>qZ,xid:()=>vZ,xor:()=>GZ});var Cm={};_n(Cm,{endsWith:()=>zl,gt:()=>ls,gte:()=>Gr,includes:()=>Dl,length:()=>tc,lowercase:()=>Nl,lt:()=>us,lte:()=>wn,maxLength:()=>ec,maxSize:()=>Mo,mime:()=>Ll,minLength:()=>Ks,minSize:()=>ds,multipleOf:()=>No,negative:()=>ZS,nonnegative:()=>GS,nonpositive:()=>BS,normalize:()=>Ul,overwrite:()=>Pi,positive:()=>HS,property:()=>WS,regex:()=>Al,size:()=>Qa,slugify:()=>Tm,startsWith:()=>jl,toLowerCase:()=>ql,toUpperCase:()=>Hl,trim:()=>Fl,uppercase:()=>Ml});var Do={};_n(Do,{ZodISODate:()=>ox,ZodISODateTime:()=>ix,ZodISODuration:()=>lx,ZodISOTime:()=>cx,date:()=>ax,datetime:()=>sx,duration:()=>dx,time:()=>ux});var ix=O("ZodISODateTime",(t,e)=>{yb.init(t,e),bt.init(t,e)});function sx(t){return bS(ix,t)}var ox=O("ZodISODate",(t,e)=>{_b.init(t,e),bt.init(t,e)});function ax(t){return SS(ox,t)}var cx=O("ZodISOTime",(t,e)=>{bb.init(t,e),bt.init(t,e)});function ux(t){return xS(cx,t)}var lx=O("ZodISODuration",(t,e)=>{Sb.init(t,e),bt.init(t,e)});function dx(t){return wS(lx,t)}var X1=(t,e)=>{Bf.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>Wf(t,r)},flatten:{value:r=>Gf(t,r)},addIssue:{value:r=>{t.issues.push(r),t.message=JSON.stringify(t.issues,Ka,2)}},addIssues:{value:r=>{t.issues.push(...r),t.message=JSON.stringify(t.issues,Ka,2)}},isEmpty:{get(){return t.issues.length===0}}})},zke=O("ZodError",X1),En=O("ZodError",X1,{Parent:Error});var Y1=yl(En),Q1=bl(En),eO=xl(En),tO=wl(En),rO=pR(En),nO=fR(En),iO=mR(En),sO=hR(En),oO=gR(En),aO=vR(En),cO=yR(En),uO=_R(En);var De=O("ZodType",(t,e)=>(Ce.init(t,e),Object.assign(t["~standard"],{jsonSchema:{input:Zl(t,"input"),output:Zl(t,"output")}}),t.toJSONSchema=u1(t,{}),t.def=e,t.type=e.type,Object.defineProperty(t,"_def",{value:e}),t.check=(...r)=>t.clone(G.mergeDefs(e,{checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),{parent:!0}),t.with=t.check,t.clone=(r,n)=>Zr(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>Y1(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>eO(t,r,n),t.parseAsync=async(r,n)=>Q1(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>tO(t,r,n),t.spa=t.safeParseAsync,t.encode=(r,n)=>rO(t,r,n),t.decode=(r,n)=>nO(t,r,n),t.encodeAsync=async(r,n)=>iO(t,r,n),t.decodeAsync=async(r,n)=>sO(t,r,n),t.safeEncode=(r,n)=>oO(t,r,n),t.safeDecode=(r,n)=>aO(t,r,n),t.safeEncodeAsync=async(r,n)=>cO(t,r,n),t.safeDecodeAsync=async(r,n)=>uO(t,r,n),t.refine=(r,n)=>t.check(VO(r,n)),t.superRefine=r=>t.check(KO(r)),t.overwrite=r=>t.check(Pi(r)),t.optional=()=>Ot(t),t.exactOptional=()=>OO(t),t.nullable=()=>Am(t),t.nullish=()=>Ot(Am(t)),t.nonoptional=r=>DO(t,r),t.array=()=>Ve(t),t.or=r=>ht([t,r]),t.and=r=>Kl(t,r),t.transform=r=>Nm(t,Ax(r)),t.default=r=>AO(t,r),t.prefault=r=>MO(t,r),t.catch=r=>LO(t,r),t.pipe=r=>Nm(t,r),t.readonly=()=>qO(t),t.describe=r=>{let n=t.clone();return Br.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return Br.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return Br.get(t);let n=t.clone();return Br.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t.apply=r=>r(t),t)),fx=O("_ZodString",(t,e)=>{Ao.init(t,e),De.init(t,e),t._zod.processJSONSchema=(n,i,s)=>l1(t,n,i,s);let r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,t.regex=(...n)=>t.check(Al(...n)),t.includes=(...n)=>t.check(Dl(...n)),t.startsWith=(...n)=>t.check(jl(...n)),t.endsWith=(...n)=>t.check(zl(...n)),t.min=(...n)=>t.check(Ks(...n)),t.max=(...n)=>t.check(ec(...n)),t.length=(...n)=>t.check(tc(...n)),t.nonempty=(...n)=>t.check(Ks(1,...n)),t.lowercase=n=>t.check(Nl(n)),t.uppercase=n=>t.check(Ml(n)),t.trim=()=>t.check(Fl()),t.normalize=(...n)=>t.check(Ul(...n)),t.toLowerCase=()=>t.check(ql()),t.toUpperCase=()=>t.check(Hl()),t.slugify=()=>t.check(Tm())}),Mm=O("ZodString",(t,e)=>{Ao.init(t,e),fx.init(t,e),t.email=r=>t.check(om(mx,r)),t.url=r=>t.check(Pl(Dm,r)),t.jwt=r=>t.check(km(Rx,r)),t.emoji=r=>t.check(dm(hx,r)),t.guid=r=>t.check(Cl(Pm,r)),t.uuid=r=>t.check(am(ps,r)),t.uuidv4=r=>t.check(cm(ps,r)),t.uuidv6=r=>t.check(um(ps,r)),t.uuidv7=r=>t.check(lm(ps,r)),t.nanoid=r=>t.check(pm(gx,r)),t.guid=r=>t.check(Cl(Pm,r)),t.cuid=r=>t.check(fm(vx,r)),t.cuid2=r=>t.check(mm(yx,r)),t.ulid=r=>t.check(hm(_x,r)),t.base64=r=>t.check(xm(Tx,r)),t.base64url=r=>t.check(wm($x,r)),t.xid=r=>t.check(gm(bx,r)),t.ksuid=r=>t.check(vm(Sx,r)),t.ipv4=r=>t.check(ym(xx,r)),t.ipv6=r=>t.check(_m(wx,r)),t.cidrv4=r=>t.check(bm(Ex,r)),t.cidrv6=r=>t.check(Sm(kx,r)),t.e164=r=>t.check(Em(Ix,r)),t.datetime=r=>t.check(sx(r)),t.date=r=>t.check(ax(r)),t.time=r=>t.check(ux(r)),t.duration=r=>t.check(dx(r))});function z(t){return yS(Mm,t)}var bt=O("ZodStringFormat",(t,e)=>{mt.init(t,e),fx.init(t,e)}),mx=O("ZodEmail",(t,e)=>{ub.init(t,e),bt.init(t,e)});function iZ(t){return om(mx,t)}var Pm=O("ZodGUID",(t,e)=>{ab.init(t,e),bt.init(t,e)});function sZ(t){return Cl(Pm,t)}var ps=O("ZodUUID",(t,e)=>{cb.init(t,e),bt.init(t,e)});function oZ(t){return am(ps,t)}function aZ(t){return cm(ps,t)}function cZ(t){return um(ps,t)}function uZ(t){return lm(ps,t)}var Dm=O("ZodURL",(t,e)=>{lb.init(t,e),bt.init(t,e)});function lZ(t){return Pl(Dm,t)}function dZ(t){return Pl(Dm,{protocol:/^https?$/,hostname:jn.domain,...G.normalizeParams(t)})}var hx=O("ZodEmoji",(t,e)=>{db.init(t,e),bt.init(t,e)});function pZ(t){return dm(hx,t)}var gx=O("ZodNanoID",(t,e)=>{pb.init(t,e),bt.init(t,e)});function fZ(t){return pm(gx,t)}var vx=O("ZodCUID",(t,e)=>{fb.init(t,e),bt.init(t,e)});function mZ(t){return fm(vx,t)}var yx=O("ZodCUID2",(t,e)=>{mb.init(t,e),bt.init(t,e)});function hZ(t){return mm(yx,t)}var _x=O("ZodULID",(t,e)=>{hb.init(t,e),bt.init(t,e)});function gZ(t){return hm(_x,t)}var bx=O("ZodXID",(t,e)=>{gb.init(t,e),bt.init(t,e)});function vZ(t){return gm(bx,t)}var Sx=O("ZodKSUID",(t,e)=>{vb.init(t,e),bt.init(t,e)});function yZ(t){return vm(Sx,t)}var xx=O("ZodIPv4",(t,e)=>{xb.init(t,e),bt.init(t,e)});function _Z(t){return ym(xx,t)}var lO=O("ZodMAC",(t,e)=>{Eb.init(t,e),bt.init(t,e)});function bZ(t){return _S(lO,t)}var wx=O("ZodIPv6",(t,e)=>{wb.init(t,e),bt.init(t,e)});function SZ(t){return _m(wx,t)}var Ex=O("ZodCIDRv4",(t,e)=>{kb.init(t,e),bt.init(t,e)});function xZ(t){return bm(Ex,t)}var kx=O("ZodCIDRv6",(t,e)=>{Tb.init(t,e),bt.init(t,e)});function wZ(t){return Sm(kx,t)}var Tx=O("ZodBase64",(t,e)=>{$b.init(t,e),bt.init(t,e)});function EZ(t){return xm(Tx,t)}var $x=O("ZodBase64URL",(t,e)=>{Ib.init(t,e),bt.init(t,e)});function kZ(t){return wm($x,t)}var Ix=O("ZodE164",(t,e)=>{Rb.init(t,e),bt.init(t,e)});function TZ(t){return Em(Ix,t)}var Rx=O("ZodJWT",(t,e)=>{Ob.init(t,e),bt.init(t,e)});function $Z(t){return km(Rx,t)}var Wl=O("ZodCustomStringFormat",(t,e)=>{Cb.init(t,e),bt.init(t,e)});function IZ(t,e,r={}){return rc(Wl,t,e,r)}function RZ(t){return rc(Wl,"hostname",jn.hostname,t)}function OZ(t){return rc(Wl,"hex",jn.hex,t)}function CZ(t,e){let r=e?.enc??"hex",n=`${t}_${r}`,i=jn[n];if(!i)throw new Error(`Unrecognized hash format: ${n}`);return rc(Wl,n,i,e)}var jm=O("ZodNumber",(t,e)=>{rm.init(t,e),De.init(t,e),t._zod.processJSONSchema=(n,i,s)=>d1(t,n,i,s),t.gt=(n,i)=>t.check(ls(n,i)),t.gte=(n,i)=>t.check(Gr(n,i)),t.min=(n,i)=>t.check(Gr(n,i)),t.lt=(n,i)=>t.check(us(n,i)),t.lte=(n,i)=>t.check(wn(n,i)),t.max=(n,i)=>t.check(wn(n,i)),t.int=n=>t.check(px(n)),t.safe=n=>t.check(px(n)),t.positive=n=>t.check(ls(0,n)),t.nonnegative=n=>t.check(Gr(0,n)),t.negative=n=>t.check(us(0,n)),t.nonpositive=n=>t.check(wn(0,n)),t.multipleOf=(n,i)=>t.check(No(n,i)),t.step=(n,i)=>t.check(No(n,i)),t.finite=()=>t;let r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});function ct(t){return ES(jm,t)}var ic=O("ZodNumberFormat",(t,e)=>{Pb.init(t,e),jm.init(t,e)});function px(t){return kS(ic,t)}function PZ(t){return TS(ic,t)}function AZ(t){return $S(ic,t)}function NZ(t){return IS(ic,t)}function MZ(t){return RS(ic,t)}var zm=O("ZodBoolean",(t,e)=>{Il.init(t,e),De.init(t,e),t._zod.processJSONSchema=(r,n,i)=>p1(t,r,n,i)});function Yt(t){return OS(zm,t)}var Lm=O("ZodBigInt",(t,e)=>{nm.init(t,e),De.init(t,e),t._zod.processJSONSchema=(n,i,s)=>f1(t,n,i,s),t.gte=(n,i)=>t.check(Gr(n,i)),t.min=(n,i)=>t.check(Gr(n,i)),t.gt=(n,i)=>t.check(ls(n,i)),t.gte=(n,i)=>t.check(Gr(n,i)),t.min=(n,i)=>t.check(Gr(n,i)),t.lt=(n,i)=>t.check(us(n,i)),t.lte=(n,i)=>t.check(wn(n,i)),t.max=(n,i)=>t.check(wn(n,i)),t.positive=n=>t.check(ls(BigInt(0),n)),t.negative=n=>t.check(us(BigInt(0),n)),t.nonpositive=n=>t.check(wn(BigInt(0),n)),t.nonnegative=n=>t.check(Gr(BigInt(0),n)),t.multipleOf=(n,i)=>t.check(No(n,i));let r=t._zod.bag;t.minValue=r.minimum??null,t.maxValue=r.maximum??null,t.format=r.format??null});function DZ(t){return CS(Lm,t)}var Ox=O("ZodBigIntFormat",(t,e)=>{Ab.init(t,e),Lm.init(t,e)});function jZ(t){return PS(Ox,t)}function zZ(t){return AS(Ox,t)}var dO=O("ZodSymbol",(t,e)=>{Nb.init(t,e),De.init(t,e),t._zod.processJSONSchema=(r,n,i)=>m1(t,r,n,i)});function LZ(t){return NS(dO,t)}var pO=O("ZodUndefined",(t,e)=>{Mb.init(t,e),De.init(t,e),t._zod.processJSONSchema=(r,n,i)=>g1(t,r,n,i)});function UZ(t){return MS(pO,t)}var fO=O("ZodNull",(t,e)=>{Db.init(t,e),De.init(t,e),t._zod.processJSONSchema=(r,n,i)=>h1(t,r,n,i)});function Vl(t){return DS(fO,t)}var mO=O("ZodAny",(t,e)=>{jb.init(t,e),De.init(t,e),t._zod.processJSONSchema=(r,n,i)=>_1(t,r,n,i)});function FZ(){return jS(mO)}var hO=O("ZodUnknown",(t,e)=>{zb.init(t,e),De.init(t,e),t._zod.processJSONSchema=(r,n,i)=>b1(t,r,n,i)});function St(){return zS(hO)}var gO=O("ZodNever",(t,e)=>{Lb.init(t,e),De.init(t,e),t._zod.processJSONSchema=(r,n,i)=>y1(t,r,n,i)});function Cx(t){return LS(gO,t)}var vO=O("ZodVoid",(t,e)=>{Ub.init(t,e),De.init(t,e),t._zod.processJSONSchema=(r,n,i)=>v1(t,r,n,i)});function qZ(t){return US(vO,t)}var Px=O("ZodDate",(t,e)=>{Fb.init(t,e),De.init(t,e),t._zod.processJSONSchema=(n,i,s)=>S1(t,n,i,s),t.min=(n,i)=>t.check(Gr(n,i)),t.max=(n,i)=>t.check(wn(n,i));let r=t._zod.bag;t.minDate=r.minimum?new Date(r.minimum):null,t.maxDate=r.maximum?new Date(r.maximum):null});function HZ(t){return FS(Px,t)}var yO=O("ZodArray",(t,e)=>{qb.init(t,e),De.init(t,e),t._zod.processJSONSchema=(r,n,i)=>A1(t,r,n,i),t.element=e.element,t.min=(r,n)=>t.check(Ks(r,n)),t.nonempty=r=>t.check(Ks(1,r)),t.max=(r,n)=>t.check(ec(r,n)),t.length=(r,n)=>t.check(tc(r,n)),t.unwrap=()=>t.element});function Ve(t,e){return c1(yO,t,e)}function ZZ(t){let e=t._zod.def.shape;return Cr(Object.keys(e))}var Um=O("ZodObject",(t,e)=>{o1.init(t,e),De.init(t,e),t._zod.processJSONSchema=(r,n,i)=>N1(t,r,n,i),G.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>Cr(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:St()}),t.loose=()=>t.clone({...t._zod.def,catchall:St()}),t.strict=()=>t.clone({...t._zod.def,catchall:Cx()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>G.extend(t,r),t.safeExtend=r=>G.safeExtend(t,r),t.merge=r=>G.merge(t,r),t.pick=r=>G.pick(t,r),t.omit=r=>G.omit(t,r),t.partial=(...r)=>G.partial(Nx,t,r[0]),t.required=(...r)=>G.required(Mx,t,r[0])});function ie(t,e){let r={type:"object",shape:t??{},...G.normalizeParams(e)};return new Um(r)}function BZ(t,e){return new Um({type:"object",shape:t,catchall:Cx(),...G.normalizeParams(e)})}function Or(t,e){return new Um({type:"object",shape:t,catchall:St(),...G.normalizeParams(e)})}var Fm=O("ZodUnion",(t,e)=>{Rl.init(t,e),De.init(t,e),t._zod.processJSONSchema=(r,n,i)=>tx(t,r,n,i),t.options=e.options});function ht(t,e){return new Fm({type:"union",options:t,...G.normalizeParams(e)})}var _O=O("ZodXor",(t,e)=>{Fm.init(t,e),Hb.init(t,e),t._zod.processJSONSchema=(r,n,i)=>tx(t,r,n,i),t.options=e.options});function GZ(t,e){return new _O({type:"union",options:t,inclusive:!1,...G.normalizeParams(e)})}var bO=O("ZodDiscriminatedUnion",(t,e)=>{Fm.init(t,e),Zb.init(t,e)});function qm(t,e,r){return new bO({type:"union",options:e,discriminator:t,...G.normalizeParams(r)})}var SO=O("ZodIntersection",(t,e)=>{Bb.init(t,e),De.init(t,e),t._zod.processJSONSchema=(r,n,i)=>M1(t,r,n,i)});function Kl(t,e){return new SO({type:"intersection",left:t,right:e})}var xO=O("ZodTuple",(t,e)=>{im.init(t,e),De.init(t,e),t._zod.processJSONSchema=(r,n,i)=>D1(t,r,n,i),t.rest=r=>t.clone({...t._zod.def,rest:r})});function wO(t,e,r){let n=e instanceof Ce,i=n?r:e,s=n?e:null;return new xO({type:"tuple",items:t,rest:s,...G.normalizeParams(i)})}var Hm=O("ZodRecord",(t,e)=>{Gb.init(t,e),De.init(t,e),t._zod.processJSONSchema=(r,n,i)=>j1(t,r,n,i),t.keyType=e.keyType,t.valueType=e.valueType});function Tt(t,e,r){return new Hm({type:"record",keyType:t,valueType:e,...G.normalizeParams(r)})}function WZ(t,e,r){let n=Zr(t);return n._zod.values=void 0,new Hm({type:"record",keyType:n,valueType:e,...G.normalizeParams(r)})}function VZ(t,e,r){return new Hm({type:"record",keyType:t,valueType:e,mode:"loose",...G.normalizeParams(r)})}var EO=O("ZodMap",(t,e)=>{Wb.init(t,e),De.init(t,e),t._zod.processJSONSchema=(r,n,i)=>C1(t,r,n,i),t.keyType=e.keyType,t.valueType=e.valueType,t.min=(...r)=>t.check(ds(...r)),t.nonempty=r=>t.check(ds(1,r)),t.max=(...r)=>t.check(Mo(...r)),t.size=(...r)=>t.check(Qa(...r))});function KZ(t,e,r){return new EO({type:"map",keyType:t,valueType:e,...G.normalizeParams(r)})}var kO=O("ZodSet",(t,e)=>{Vb.init(t,e),De.init(t,e),t._zod.processJSONSchema=(r,n,i)=>P1(t,r,n,i),t.min=(...r)=>t.check(ds(...r)),t.nonempty=r=>t.check(ds(1,r)),t.max=(...r)=>t.check(Mo(...r)),t.size=(...r)=>t.check(Qa(...r))});function JZ(t,e){return new kO({type:"set",valueType:t,...G.normalizeParams(e)})}var Gl=O("ZodEnum",(t,e)=>{Kb.init(t,e),De.init(t,e),t._zod.processJSONSchema=(n,i,s)=>x1(t,n,i,s),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(n,i)=>{let s={};for(let o of n)if(r.has(o))s[o]=e.entries[o];else throw new Error(`Key ${o} not found in enum`);return new Gl({...e,checks:[],...G.normalizeParams(i),entries:s})},t.exclude=(n,i)=>{let s={...e.entries};for(let o of n)if(r.has(o))delete s[o];else throw new Error(`Key ${o} not found in enum`);return new Gl({...e,checks:[],...G.normalizeParams(i),entries:s})}});function Cr(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new Gl({type:"enum",entries:r,...G.normalizeParams(e)})}function XZ(t,e){return new Gl({type:"enum",entries:t,...G.normalizeParams(e)})}var TO=O("ZodLiteral",(t,e)=>{Jb.init(t,e),De.init(t,e),t._zod.processJSONSchema=(r,n,i)=>w1(t,r,n,i),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function fe(t,e){return new TO({type:"literal",values:Array.isArray(t)?t:[t],...G.normalizeParams(e)})}var $O=O("ZodFile",(t,e)=>{Xb.init(t,e),De.init(t,e),t._zod.processJSONSchema=(r,n,i)=>T1(t,r,n,i),t.min=(r,n)=>t.check(ds(r,n)),t.max=(r,n)=>t.check(Mo(r,n)),t.mime=(r,n)=>t.check(Ll(Array.isArray(r)?r:[r],n))});function YZ(t){return VS($O,t)}var IO=O("ZodTransform",(t,e)=>{Yb.init(t,e),De.init(t,e),t._zod.processJSONSchema=(r,n,i)=>O1(t,r,n,i),t._zod.parse=(r,n)=>{if(n.direction==="backward")throw new Oo(t.constructor.name);r.addIssue=s=>{if(typeof s=="string")r.issues.push(G.issue(s,r.value,e));else{let o=s;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=t),r.issues.push(G.issue(o))}};let i=e.transform(r.value,r);return i instanceof Promise?i.then(s=>(r.value=s,r)):(r.value=i,r)}});function Ax(t){return new IO({type:"transform",transform:t})}var Nx=O("ZodOptional",(t,e)=>{sm.init(t,e),De.init(t,e),t._zod.processJSONSchema=(r,n,i)=>rx(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function Ot(t){return new Nx({type:"optional",innerType:t})}var RO=O("ZodExactOptional",(t,e)=>{Qb.init(t,e),De.init(t,e),t._zod.processJSONSchema=(r,n,i)=>rx(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function OO(t){return new RO({type:"optional",innerType:t})}var CO=O("ZodNullable",(t,e)=>{eS.init(t,e),De.init(t,e),t._zod.processJSONSchema=(r,n,i)=>z1(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function Am(t){return new CO({type:"nullable",innerType:t})}function QZ(t){return Ot(Am(t))}var PO=O("ZodDefault",(t,e)=>{tS.init(t,e),De.init(t,e),t._zod.processJSONSchema=(r,n,i)=>U1(t,r,n,i),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function AO(t,e){return new PO({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():G.shallowClone(e)}})}var NO=O("ZodPrefault",(t,e)=>{rS.init(t,e),De.init(t,e),t._zod.processJSONSchema=(r,n,i)=>F1(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function MO(t,e){return new NO({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():G.shallowClone(e)}})}var Mx=O("ZodNonOptional",(t,e)=>{nS.init(t,e),De.init(t,e),t._zod.processJSONSchema=(r,n,i)=>L1(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function DO(t,e){return new Mx({type:"nonoptional",innerType:t,...G.normalizeParams(e)})}var jO=O("ZodSuccess",(t,e)=>{iS.init(t,e),De.init(t,e),t._zod.processJSONSchema=(r,n,i)=>$1(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function eB(t){return new jO({type:"success",innerType:t})}var zO=O("ZodCatch",(t,e)=>{sS.init(t,e),De.init(t,e),t._zod.processJSONSchema=(r,n,i)=>q1(t,r,n,i),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function LO(t,e){return new zO({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var UO=O("ZodNaN",(t,e)=>{oS.init(t,e),De.init(t,e),t._zod.processJSONSchema=(r,n,i)=>E1(t,r,n,i)});function tB(t){return qS(UO,t)}var Dx=O("ZodPipe",(t,e)=>{aS.init(t,e),De.init(t,e),t._zod.processJSONSchema=(r,n,i)=>H1(t,r,n,i),t.in=e.in,t.out=e.out});function Nm(t,e){return new Dx({type:"pipe",in:t,out:e})}var jx=O("ZodCodec",(t,e)=>{Dx.init(t,e),Ol.init(t,e)});function rB(t,e,r){return new jx({type:"pipe",in:t,out:e,transform:r.decode,reverseTransform:r.encode})}var FO=O("ZodReadonly",(t,e)=>{cS.init(t,e),De.init(t,e),t._zod.processJSONSchema=(r,n,i)=>Z1(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function qO(t){return new FO({type:"readonly",innerType:t})}var HO=O("ZodTemplateLiteral",(t,e)=>{uS.init(t,e),De.init(t,e),t._zod.processJSONSchema=(r,n,i)=>k1(t,r,n,i)});function nB(t,e){return new HO({type:"template_literal",parts:t,...G.normalizeParams(e)})}var ZO=O("ZodLazy",(t,e)=>{pS.init(t,e),De.init(t,e),t._zod.processJSONSchema=(r,n,i)=>G1(t,r,n,i),t.unwrap=()=>t._zod.def.getter()});function BO(t){return new ZO({type:"lazy",getter:t})}var GO=O("ZodPromise",(t,e)=>{dS.init(t,e),De.init(t,e),t._zod.processJSONSchema=(r,n,i)=>B1(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function iB(t){return new GO({type:"promise",innerType:t})}var WO=O("ZodFunction",(t,e)=>{lS.init(t,e),De.init(t,e),t._zod.processJSONSchema=(r,n,i)=>R1(t,r,n,i)});function sB(t){return new WO({type:"function",input:Array.isArray(t?.input)?wO(t?.input):t?.input??Ve(St()),output:t?.output??St()})}var Zm=O("ZodCustom",(t,e)=>{fS.init(t,e),De.init(t,e),t._zod.processJSONSchema=(r,n,i)=>I1(t,r,n,i)});function oB(t){let e=new _t({check:"custom"});return e._zod.check=t,e}function zx(t,e){return KS(Zm,t??(()=>!0),e)}function VO(t,e={}){return JS(Zm,t,e)}function KO(t){return XS(t)}var aB=YS,cB=QS;function uB(t,e={}){let r=new Zm({type:"custom",check:"custom",fn:n=>n instanceof t,abort:!0,...G.normalizeParams(e)});return r._zod.bag.Class=t,r._zod.check=n=>{n.value instanceof t||n.issues.push({code:"invalid_type",expected:t.name,input:n.value,inst:r,path:[...r._zod.def.path??[]]})},r}var lB=(...t)=>ex({Codec:jx,Boolean:zm,String:Mm},...t);function dB(t){let e=BO(()=>ht([z(t),ct(),Yt(),Vl(),Ve(e),Tt(z(),e)]));return e}function Bm(t,e){return Nm(Ax(t),e)}var JO;JO||(JO={});var Gke={...Bl,...Cm,iso:Do};tr(mS());var Ux="2025-11-25";var XO=[Ux,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Js="io.modelcontextprotocol/related-task",Wm="2.0",yr=zx(t=>t!==null&&(typeof t=="object"||typeof t=="function")),YO=ht([z(),ct().int()]),QO=z(),dTe=Or({ttl:ht([ct(),Vl()]).optional(),pollInterval:ct().optional()}),hB=ie({ttl:ct().optional()}),gB=ie({taskId:z()}),Fx=Or({progressToken:YO.optional(),[Js]:gB.optional()}),kn=ie({_meta:Fx.optional()}),Jl=kn.extend({task:hB.optional()}),eC=t=>Jl.safeParse(t).success,_r=ie({method:z(),params:kn.loose().optional()}),zn=ie({_meta:Fx.optional()}),Ln=ie({method:z(),params:zn.loose().optional()}),br=Or({_meta:Fx.optional()}),Vm=ht([z(),ct().int()]),tC=ie({jsonrpc:fe(Wm),id:Vm,..._r.shape}).strict(),qx=t=>tC.safeParse(t).success,rC=ie({jsonrpc:fe(Wm),...Ln.shape}).strict(),nC=t=>rC.safeParse(t).success,Hx=ie({jsonrpc:fe(Wm),id:Vm,result:br}).strict(),Xl=t=>Hx.safeParse(t).success;var Ie;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(Ie||(Ie={}));var Zx=ie({jsonrpc:fe(Wm),id:Vm.optional(),error:ie({code:ct().int(),message:z(),data:St().optional()})}).strict();var iC=t=>Zx.safeParse(t).success;var sC=ht([tC,rC,Hx,Zx]),pTe=ht([Hx,Zx]),jo=br.strict(),vB=zn.extend({requestId:Vm.optional(),reason:z().optional()}),Km=Ln.extend({method:fe("notifications/cancelled"),params:vB}),yB=ie({src:z(),mimeType:z().optional(),sizes:Ve(z()).optional(),theme:Cr(["light","dark"]).optional()}),Yl=ie({icons:Ve(yB).optional()}),sc=ie({name:z(),title:z().optional()}),oC=sc.extend({...sc.shape,...Yl.shape,version:z(),websiteUrl:z().optional(),description:z().optional()}),_B=Kl(ie({applyDefaults:Yt().optional()}),Tt(z(),St())),bB=Bm(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,Kl(ie({form:_B.optional(),url:yr.optional()}),Tt(z(),St()).optional())),SB=Or({list:yr.optional(),cancel:yr.optional(),requests:Or({sampling:Or({createMessage:yr.optional()}).optional(),elicitation:Or({create:yr.optional()}).optional()}).optional()}),xB=Or({list:yr.optional(),cancel:yr.optional(),requests:Or({tools:Or({call:yr.optional()}).optional()}).optional()}),wB=ie({experimental:Tt(z(),yr).optional(),sampling:ie({context:yr.optional(),tools:yr.optional()}).optional(),elicitation:bB.optional(),roots:ie({listChanged:Yt().optional()}).optional(),tasks:SB.optional()}),EB=kn.extend({protocolVersion:z(),capabilities:wB,clientInfo:oC}),kB=_r.extend({method:fe("initialize"),params:EB});var TB=ie({experimental:Tt(z(),yr).optional(),logging:yr.optional(),completions:yr.optional(),prompts:ie({listChanged:Yt().optional()}).optional(),resources:ie({subscribe:Yt().optional(),listChanged:Yt().optional()}).optional(),tools:ie({listChanged:Yt().optional()}).optional(),tasks:xB.optional()}),Bx=br.extend({protocolVersion:z(),capabilities:TB,serverInfo:oC,instructions:z().optional()}),$B=Ln.extend({method:fe("notifications/initialized"),params:zn.optional()});var Jm=_r.extend({method:fe("ping"),params:kn.optional()}),IB=ie({progress:ct(),total:Ot(ct()),message:Ot(z())}),RB=ie({...zn.shape,...IB.shape,progressToken:YO}),Xm=Ln.extend({method:fe("notifications/progress"),params:RB}),OB=kn.extend({cursor:QO.optional()}),Ql=_r.extend({params:OB.optional()}),ed=br.extend({nextCursor:QO.optional()}),CB=Cr(["working","input_required","completed","failed","cancelled"]),td=ie({taskId:z(),status:CB,ttl:ht([ct(),Vl()]),createdAt:z(),lastUpdatedAt:z(),pollInterval:Ot(ct()),statusMessage:Ot(z())}),zo=br.extend({task:td}),PB=zn.merge(td),rd=Ln.extend({method:fe("notifications/tasks/status"),params:PB}),Ym=_r.extend({method:fe("tasks/get"),params:kn.extend({taskId:z()})}),Qm=br.merge(td),eh=_r.extend({method:fe("tasks/result"),params:kn.extend({taskId:z()})}),fTe=br.loose(),th=Ql.extend({method:fe("tasks/list")}),rh=ed.extend({tasks:Ve(td)}),nh=_r.extend({method:fe("tasks/cancel"),params:kn.extend({taskId:z()})}),aC=br.merge(td),cC=ie({uri:z(),mimeType:Ot(z()),_meta:Tt(z(),St()).optional()}),uC=cC.extend({text:z()}),Gx=z().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),lC=cC.extend({blob:Gx}),nd=Cr(["user","assistant"]),oc=ie({audience:Ve(nd).optional(),priority:ct().min(0).max(1).optional(),lastModified:Do.datetime({offset:!0}).optional()}),dC=ie({...sc.shape,...Yl.shape,uri:z(),description:Ot(z()),mimeType:Ot(z()),annotations:oc.optional(),_meta:Ot(Or({}))}),AB=ie({...sc.shape,...Yl.shape,uriTemplate:z(),description:Ot(z()),mimeType:Ot(z()),annotations:oc.optional(),_meta:Ot(Or({}))}),NB=Ql.extend({method:fe("resources/list")}),Wx=ed.extend({resources:Ve(dC)}),MB=Ql.extend({method:fe("resources/templates/list")}),Vx=ed.extend({resourceTemplates:Ve(AB)}),Kx=kn.extend({uri:z()}),DB=Kx,jB=_r.extend({method:fe("resources/read"),params:DB}),Jx=br.extend({contents:Ve(ht([uC,lC]))}),Xx=Ln.extend({method:fe("notifications/resources/list_changed"),params:zn.optional()}),zB=Kx,LB=_r.extend({method:fe("resources/subscribe"),params:zB}),UB=Kx,FB=_r.extend({method:fe("resources/unsubscribe"),params:UB}),qB=zn.extend({uri:z()}),HB=Ln.extend({method:fe("notifications/resources/updated"),params:qB}),ZB=ie({name:z(),description:Ot(z()),required:Ot(Yt())}),BB=ie({...sc.shape,...Yl.shape,description:Ot(z()),arguments:Ot(Ve(ZB)),_meta:Ot(Or({}))}),GB=Ql.extend({method:fe("prompts/list")}),Yx=ed.extend({prompts:Ve(BB)}),WB=kn.extend({name:z(),arguments:Tt(z(),z()).optional()}),VB=_r.extend({method:fe("prompts/get"),params:WB}),Qx=ie({type:fe("text"),text:z(),annotations:oc.optional(),_meta:Tt(z(),St()).optional()}),ew=ie({type:fe("image"),data:Gx,mimeType:z(),annotations:oc.optional(),_meta:Tt(z(),St()).optional()}),tw=ie({type:fe("audio"),data:Gx,mimeType:z(),annotations:oc.optional(),_meta:Tt(z(),St()).optional()}),KB=ie({type:fe("tool_use"),name:z(),id:z(),input:Tt(z(),St()),_meta:Tt(z(),St()).optional()}),JB=ie({type:fe("resource"),resource:ht([uC,lC]),annotations:oc.optional(),_meta:Tt(z(),St()).optional()}),XB=dC.extend({type:fe("resource_link")}),rw=ht([Qx,ew,tw,XB,JB]),YB=ie({role:nd,content:rw}),nw=br.extend({description:z().optional(),messages:Ve(YB)}),iw=Ln.extend({method:fe("notifications/prompts/list_changed"),params:zn.optional()}),QB=ie({title:z().optional(),readOnlyHint:Yt().optional(),destructiveHint:Yt().optional(),idempotentHint:Yt().optional(),openWorldHint:Yt().optional()}),eG=ie({taskSupport:Cr(["required","optional","forbidden"]).optional()}),pC=ie({...sc.shape,...Yl.shape,description:z().optional(),inputSchema:ie({type:fe("object"),properties:Tt(z(),yr).optional(),required:Ve(z()).optional()}).catchall(St()),outputSchema:ie({type:fe("object"),properties:Tt(z(),yr).optional(),required:Ve(z()).optional()}).catchall(St()).optional(),annotations:QB.optional(),execution:eG.optional(),_meta:Tt(z(),St()).optional()}),tG=Ql.extend({method:fe("tools/list")}),sw=ed.extend({tools:Ve(pC)}),ac=br.extend({content:Ve(rw).default([]),structuredContent:Tt(z(),St()).optional(),isError:Yt().optional()}),mTe=ac.or(br.extend({toolResult:St()})),rG=Jl.extend({name:z(),arguments:Tt(z(),St()).optional()}),nG=_r.extend({method:fe("tools/call"),params:rG}),ow=Ln.extend({method:fe("notifications/tools/list_changed"),params:zn.optional()}),fC=ie({autoRefresh:Yt().default(!0),debounceMs:ct().int().nonnegative().default(300)}),mC=Cr(["debug","info","notice","warning","error","critical","alert","emergency"]),iG=kn.extend({level:mC}),sG=_r.extend({method:fe("logging/setLevel"),params:iG}),oG=zn.extend({level:mC,logger:z().optional(),data:St()}),aG=Ln.extend({method:fe("notifications/message"),params:oG}),cG=ie({name:z().optional()}),uG=ie({hints:Ve(cG).optional(),costPriority:ct().min(0).max(1).optional(),speedPriority:ct().min(0).max(1).optional(),intelligencePriority:ct().min(0).max(1).optional()}),lG=ie({mode:Cr(["auto","required","none"]).optional()}),dG=ie({type:fe("tool_result"),toolUseId:z().describe("The unique identifier for the corresponding tool call."),content:Ve(rw).default([]),structuredContent:ie({}).loose().optional(),isError:Yt().optional(),_meta:Tt(z(),St()).optional()}),pG=qm("type",[Qx,ew,tw]),Gm=qm("type",[Qx,ew,tw,KB,dG]),fG=ie({role:nd,content:ht([Gm,Ve(Gm)]),_meta:Tt(z(),St()).optional()}),mG=Jl.extend({messages:Ve(fG),modelPreferences:uG.optional(),systemPrompt:z().optional(),includeContext:Cr(["none","thisServer","allServers"]).optional(),temperature:ct().optional(),maxTokens:ct().int(),stopSequences:Ve(z()).optional(),metadata:yr.optional(),tools:Ve(pC).optional(),toolChoice:lG.optional()}),aw=_r.extend({method:fe("sampling/createMessage"),params:mG}),cw=br.extend({model:z(),stopReason:Ot(Cr(["endTurn","stopSequence","maxTokens"]).or(z())),role:nd,content:pG}),hG=br.extend({model:z(),stopReason:Ot(Cr(["endTurn","stopSequence","maxTokens","toolUse"]).or(z())),role:nd,content:ht([Gm,Ve(Gm)])}),gG=ie({type:fe("boolean"),title:z().optional(),description:z().optional(),default:Yt().optional()}),vG=ie({type:fe("string"),title:z().optional(),description:z().optional(),minLength:ct().optional(),maxLength:ct().optional(),format:Cr(["email","uri","date","date-time"]).optional(),default:z().optional()}),yG=ie({type:Cr(["number","integer"]),title:z().optional(),description:z().optional(),minimum:ct().optional(),maximum:ct().optional(),default:ct().optional()}),_G=ie({type:fe("string"),title:z().optional(),description:z().optional(),enum:Ve(z()),default:z().optional()}),bG=ie({type:fe("string"),title:z().optional(),description:z().optional(),oneOf:Ve(ie({const:z(),title:z()})),default:z().optional()}),SG=ie({type:fe("string"),title:z().optional(),description:z().optional(),enum:Ve(z()),enumNames:Ve(z()).optional(),default:z().optional()}),xG=ht([_G,bG]),wG=ie({type:fe("array"),title:z().optional(),description:z().optional(),minItems:ct().optional(),maxItems:ct().optional(),items:ie({type:fe("string"),enum:Ve(z())}),default:Ve(z()).optional()}),EG=ie({type:fe("array"),title:z().optional(),description:z().optional(),minItems:ct().optional(),maxItems:ct().optional(),items:ie({anyOf:Ve(ie({const:z(),title:z()}))}),default:Ve(z()).optional()}),kG=ht([wG,EG]),TG=ht([SG,xG,kG]),$G=ht([TG,gG,vG,yG]),IG=Jl.extend({mode:fe("form").optional(),message:z(),requestedSchema:ie({type:fe("object"),properties:Tt(z(),$G),required:Ve(z()).optional()})}),RG=Jl.extend({mode:fe("url"),message:z(),elicitationId:z(),url:z().url()}),OG=ht([IG,RG]),uw=_r.extend({method:fe("elicitation/create"),params:OG}),CG=zn.extend({elicitationId:z()}),PG=Ln.extend({method:fe("notifications/elicitation/complete"),params:CG}),lw=br.extend({action:Cr(["accept","decline","cancel"]),content:Bm(t=>t===null?void 0:t,Tt(z(),ht([z(),ct(),Yt(),Ve(z())])).optional())}),AG=ie({type:fe("ref/resource"),uri:z()});var NG=ie({type:fe("ref/prompt"),name:z()}),MG=kn.extend({ref:ht([NG,AG]),argument:ie({name:z(),value:z()}),context:ie({arguments:Tt(z(),z()).optional()}).optional()}),DG=_r.extend({method:fe("completion/complete"),params:MG});var dw=br.extend({completion:Or({values:Ve(z()).max(100),total:Ot(ct().int()),hasMore:Ot(Yt())})}),jG=ie({uri:z().startsWith("file://"),name:z().optional(),_meta:Tt(z(),St()).optional()}),zG=_r.extend({method:fe("roots/list"),params:kn.optional()}),LG=br.extend({roots:Ve(jG)}),UG=Ln.extend({method:fe("notifications/roots/list_changed"),params:zn.optional()}),hTe=ht([Jm,kB,DG,sG,VB,GB,NB,MB,jB,LB,FB,nG,tG,Ym,eh,th,nh]),gTe=ht([Km,Xm,$B,UG,rd]),vTe=ht([jo,cw,hG,lw,LG,Qm,rh,zo]),yTe=ht([Jm,aw,uw,zG,Ym,eh,th,nh]),_Te=ht([Km,Xm,aG,HB,Xx,ow,iw,rd,PG]),bTe=ht([jo,Bx,dw,nw,Yx,Wx,Vx,Jx,ac,sw,Qm,rh,zo]),ve=class t extends Error{constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,r,n){if(e===Ie.UrlElicitationRequired&&n){let i=n;if(i.elicitations)return new Lx(i.elicitations,r)}return new t(e,r,n)}},Lx=class extends ve{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(Ie.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function Xs(t){return t==="completed"||t==="failed"||t==="cancelled"}var e$e=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function pw(t){let r=Om(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=J1(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function fw(t,e){let r=oi(t,e);if(!r.success)throw r.error;return r.data}var GG=6e4,ih=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(Km,r=>{this._oncancel(r)}),this.setNotificationHandler(Xm,r=>{this._onprogress(r)}),this.setRequestHandler(Jm,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Ym,async(r,n)=>{let i=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!i)throw new ve(Ie.InvalidParams,"Failed to retrieve task: Task not found");return{...i}}),this.setRequestHandler(eh,async(r,n)=>{let i=async()=>{let s=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(s,n.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,u=c.id,l=this._requestResolvers.get(u);if(l)if(this._requestResolvers.delete(u),a.type==="response")l(c);else{let d=c,p=new ve(d.error.code,d.error.message,d.error.data);l(p)}else{let d=a.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${u}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let o=await this._taskStore.getTask(s,n.sessionId);if(!o)throw new ve(Ie.InvalidParams,`Task not found: ${s}`);if(!Xs(o.status))return await this._waitForTaskUpdate(s,n.signal),await i();if(Xs(o.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[Js]:{taskId:s}}}}return await i()};return await i()}),this.setRequestHandler(th,async(r,n)=>{try{let{tasks:i,nextCursor:s}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:i,nextCursor:s,_meta:{}}}catch(i){throw new ve(Ie.InvalidParams,`Failed to list tasks: ${i instanceof Error?i.message:String(i)}`)}}),this.setRequestHandler(nh,async(r,n)=>{try{let i=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!i)throw new ve(Ie.InvalidParams,`Task not found: ${r.params.taskId}`);if(Xs(i.status))throw new ve(Ie.InvalidParams,`Cannot cancel task in terminal status: ${i.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new ve(Ie.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(i){throw i instanceof ve?i:new ve(Ie.InvalidRequest,`Failed to cancel task: ${i instanceof Error?i.message:String(i)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,n,i,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(i,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:s,onTimeout:i})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),ve.fromError(Ie.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){this._transport=e;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=s=>{n?.(s),this._onerror(s)};let i=this._transport?.onmessage;this._transport.onmessage=(s,o)=>{i?.(s,o),Xl(s)||iC(s)?this._onresponse(s):qx(s)?this._onrequest(s,o):nC(s)?this._onnotification(s):this._onerror(new Error(`Unknown message type: ${JSON.stringify(s)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();let r=ve.fromError(Ie.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of e.values())n(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){let r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,i=this._transport,s=e.params?._meta?.[Js]?.taskId;if(n===void 0){let l={jsonrpc:"2.0",id:e.id,error:{code:Ie.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:l,timestamp:Date.now()},i?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):i?.send(l).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}let o=new AbortController;this._requestHandlerAbortControllers.set(e.id,o);let a=eC(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,i?.sessionId):void 0,u={signal:o.signal,sessionId:i?.sessionId,_meta:e.params?._meta,sendNotification:async l=>{let d={relatedRequestId:e.id};s&&(d.relatedTask={taskId:s}),await this.notification(l,d)},sendRequest:async(l,d,p)=>{let f={...p,relatedRequestId:e.id};s&&!f.relatedTask&&(f.relatedTask={taskId:s});let m=f.relatedTask?.taskId??s;return m&&c&&await c.updateTaskStatus(m,"input_required"),await this.request(l,d,f)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:s,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,u)).then(async l=>{if(o.signal.aborted)return;let d={result:l,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:d,timestamp:Date.now()},i?.sessionId):await i?.send(d)},async l=>{if(o.signal.aborted)return;let d={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(l.code)?l.code:Ie.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:d,timestamp:Date.now()},i?.sessionId):await i?.send(d)}).catch(l=>this._onerror(new Error(`Failed to send response: ${l}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,i=Number(r),s=this._progressHandlers.get(i);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let o=this._responseHandlers.get(i),a=this._timeoutInfo.get(i);if(a&&o&&a.resetTimeoutOnProgress)try{this._resetTimeout(i)}catch(c){this._responseHandlers.delete(i),this._progressHandlers.delete(i),this._cleanupTimeout(i),o(c);return}s(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),Xl(e))n(e);else{let o=new ve(e.error.code,e.error.message,e.error.data);n(o)}return}let i=this._responseHandlers.get(r);if(i===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let s=!1;if(Xl(e)&&e.result&&typeof e.result=="object"){let o=e.result;if(o.task&&typeof o.task=="object"){let a=o.task;typeof a.taskId=="string"&&(s=!0,this._taskProgressTokens.set(a.taskId,r))}}if(s||this._progressHandlers.delete(r),Xl(e))i(e);else{let o=ve.fromError(e.error.code,e.error.message,e.error.data);i(o)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,n){let{task:i}=n??{};if(!i){try{yield{type:"result",result:await this.request(e,r,n)}}catch(o){yield{type:"error",error:o instanceof ve?o:new ve(Ie.InternalError,String(o))}}return}let s;try{let o=await this.request(e,zo,n);if(o.task)s=o.task.taskId,yield{type:"taskCreated",task:o.task};else throw new ve(Ie.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},Xs(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:a.status==="failed"?yield{type:"error",error:new ve(Ie.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new ve(Ie.InternalError,`Task ${s} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),n?.signal?.throwIfAborted()}}catch(o){yield{type:"error",error:o instanceof ve?o:new ve(Ie.InternalError,String(o))}}}request(e,r,n){let{relatedRequestId:i,resumptionToken:s,onresumptiontoken:o,task:a,relatedTask:c}=n??{};return new Promise((u,l)=>{let d=S=>{l(S)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(S){d(S);return}n?.signal?.throwIfAborted();let p=this._requestMessageId++,f={...e,jsonrpc:"2.0",id:p};n?.onprogress&&(this._progressHandlers.set(p,n.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:p}}),a&&(f.params={...f.params,task:a}),c&&(f.params={...f.params,_meta:{...f.params?._meta||{},[Js]:c}});let m=S=>{this._responseHandlers.delete(p),this._progressHandlers.delete(p),this._cleanupTimeout(p),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:p,reason:String(S)}},{relatedRequestId:i,resumptionToken:s,onresumptiontoken:o}).catch(y=>this._onerror(new Error(`Failed to send cancellation: ${y}`)));let _=S instanceof ve?S:new ve(Ie.RequestTimeout,String(S));l(_)};this._responseHandlers.set(p,S=>{if(!n?.signal?.aborted){if(S instanceof Error)return l(S);try{let _=oi(r,S.result);_.success?u(_.data):l(_.error)}catch(_){l(_)}}}),n?.signal?.addEventListener("abort",()=>{m(n?.signal?.reason)});let h=n?.timeout??GG,g=()=>m(ve.fromError(Ie.RequestTimeout,"Request timed out",{timeout:h}));this._setupTimeout(p,h,n?.maxTotalTimeout,g,n?.resetTimeoutOnProgress??!1);let v=c?.taskId;if(v){let S=_=>{let y=this._responseHandlers.get(p);y?y(_):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,S),this._enqueueTaskMessage(v,{type:"request",message:f,timestamp:Date.now()}).catch(_=>{this._cleanupTimeout(p),l(_)})}else this._transport.send(f,{relatedRequestId:i,resumptionToken:s,onresumptiontoken:o}).catch(S=>{this._cleanupTimeout(p),l(S)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},Qm,r)}async getTaskResult(e,r,n){return this.request({method:"tasks/result",params:e},r,n)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},rh,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},aC,r)}async notification(e,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let n=r?.relatedTask?.taskId;if(n){let a={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[Js]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let a={...e,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[Js]:r.relatedTask}}}),this._transport?.send(a,r).catch(c=>this._onerror(c))});return}let o={...e,jsonrpc:"2.0"};r?.relatedTask&&(o={...o,params:{...o.params,_meta:{...o.params?._meta||{},[Js]:r.relatedTask}}}),await this._transport.send(o,r)}setRequestHandler(e,r){let n=pw(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(i,s)=>{let o=fw(e,i);return Promise.resolve(r(o,s))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){let n=pw(e);this._notificationHandlers.set(n,i=>{let s=fw(e,i);return Promise.resolve(r(s))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let i=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,i)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let i of n)if(i.type==="request"&&qx(i.message)){let s=i.message.id,o=this._requestResolvers.get(s);o?(o(new ve(Ie.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s)):this._onerror(new Error(`Resolver missing for request ${s} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let i=await this._taskStore?.getTask(e);i?.pollInterval&&(n=i.pollInterval)}catch{}return new Promise((i,s)=>{if(r.aborted){s(new ve(Ie.InvalidRequest,"Request cancelled"));return}let o=setTimeout(i,n);r.addEventListener("abort",()=>{clearTimeout(o),s(new ve(Ie.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async i=>{if(!e)throw new Error("No request provided");return await n.createTask(i,e.id,{method:e.method,params:e.params},r)},getTask:async i=>{let s=await n.getTask(i,r);if(!s)throw new ve(Ie.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(i,s,o)=>{await n.storeTaskResult(i,s,o,r);let a=await n.getTask(i,r);if(a){let c=rd.parse({method:"notifications/tasks/status",params:a});await this.notification(c),Xs(a.status)&&this._cleanupTaskProgressHandler(i)}},getTaskResult:i=>n.getTaskResult(i,r),updateTaskStatus:async(i,s,o)=>{let a=await n.getTask(i,r);if(!a)throw new ve(Ie.InvalidParams,`Task "${i}" not found - it may have been cleaned up`);if(Xs(a.status))throw new ve(Ie.InvalidParams,`Cannot update task "${i}" from terminal status "${a.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(i,s,o,r);let c=await n.getTask(i,r);if(c){let u=rd.parse({method:"notifications/tasks/status",params:c});await this.notification(u),Xs(c.status)&&this._cleanupTaskProgressHandler(i)}},listTasks:i=>n.listTasks(i,r)}}};function hC(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function gC(t,e){let r={...t};for(let n in e){let i=n,s=e[i];if(s===void 0)continue;let o=r[i];hC(o)&&hC(s)?r[i]={...o,...s}:r[i]=s}return r}var rN=Me(Y0(),1),nN=Me(tN(),1);function DX(){let t=new rN.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,nN.default)(t),t}var Fh=class{constructor(e){this._ajv=e??DX()}getValidator(e){let r="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}};var qh=class{constructor(e){this._client=e}async*callToolStream(e,r=ac,n){let i=this._client,s={...n,task:n?.task??(i.isToolTask(e.name)?{}:void 0)},o=i.requestStream({method:"tools/call",params:e},r,s),a=i.getToolOutputValidator(e.name);for await(let c of o){if(c.type==="result"&&a){let u=c.result;if(!u.structuredContent&&!u.isError){yield{type:"error",error:new ve(Ie.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`)};return}if(u.structuredContent)try{let l=a(u.structuredContent);if(!l.valid){yield{type:"error",error:new ve(Ie.InvalidParams,`Structured content does not match the tool's output schema: ${l.errorMessage}`)};return}}catch(l){if(l instanceof ve){yield{type:"error",error:l};return}yield{type:"error",error:new ve(Ie.InvalidParams,`Failed to validate structured content: ${l instanceof Error?l.message:String(l)}`)};return}}yield c}}async getTask(e,r){return this._client.getTask({taskId:e},r)}async getTaskResult(e,r,n){return this._client.getTaskResult({taskId:e},r,n)}async listTasks(e,r){return this._client.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._client.cancelTask({taskId:e},r)}requestStream(e,r,n){return this._client.requestStream(e,r,n)}};function iN(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${e})`);break;default:break}}function sN(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}function Hh(t,e){if(!(!t||e===null||typeof e!="object")){if(t.type==="object"&&t.properties&&typeof t.properties=="object"){let r=e,n=t.properties;for(let i of Object.keys(n)){let s=n[i];r[i]===void 0&&Object.prototype.hasOwnProperty.call(s,"default")&&(r[i]=s.default),r[i]!==void 0&&Hh(s,r[i])}}if(Array.isArray(t.anyOf))for(let r of t.anyOf)typeof r!="boolean"&&Hh(r,e);if(Array.isArray(t.oneOf))for(let r of t.oneOf)typeof r!="boolean"&&Hh(r,e)}}function jX(t){if(!t)return{supportsFormMode:!1,supportsUrlMode:!1};let e=t.form!==void 0,r=t.url!==void 0;return{supportsFormMode:e||!e&&!r,supportsUrlMode:r}}var Ec=class extends ih{constructor(e,r){super(r),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._listChangedDebounceTimers=new Map,this._capabilities=r?.capabilities??{},this._jsonSchemaValidator=r?.jsonSchemaValidator??new Fh,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",ow,e.tools,async()=>(await this.listTools()).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",iw,e.prompts,async()=>(await this.listPrompts()).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",Xx,e.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new qh(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=gC(this._capabilities,e)}setRequestHandler(e,r){let i=Om(e)?.method;if(!i)throw new Error("Schema is missing a method literal");let s;if(nc(i)){let a=i;s=a._zod?.def?.value??a.value}else{let a=i;s=a._def?.value??a.value}if(typeof s!="string")throw new Error("Schema method literal must be a string");let o=s;if(o==="elicitation/create"){let a=async(c,u)=>{let l=oi(uw,c);if(!l.success){let S=l.error instanceof Error?l.error.message:String(l.error);throw new ve(Ie.InvalidParams,`Invalid elicitation request: ${S}`)}let{params:d}=l.data;d.mode=d.mode??"form";let{supportsFormMode:p,supportsUrlMode:f}=jX(this._capabilities.elicitation);if(d.mode==="form"&&!p)throw new ve(Ie.InvalidParams,"Client does not support form-mode elicitation requests");if(d.mode==="url"&&!f)throw new ve(Ie.InvalidParams,"Client does not support URL-mode elicitation requests");let m=await Promise.resolve(r(c,u));if(d.task){let S=oi(zo,m);if(!S.success){let _=S.error instanceof Error?S.error.message:String(S.error);throw new ve(Ie.InvalidParams,`Invalid task creation result: ${_}`)}return S.data}let h=oi(lw,m);if(!h.success){let S=h.error instanceof Error?h.error.message:String(h.error);throw new ve(Ie.InvalidParams,`Invalid elicitation result: ${S}`)}let g=h.data,v=d.mode==="form"?d.requestedSchema:void 0;if(d.mode==="form"&&g.action==="accept"&&g.content&&v&&this._capabilities.elicitation?.form?.applyDefaults)try{Hh(v,g.content)}catch{}return g};return super.setRequestHandler(e,a)}if(o==="sampling/createMessage"){let a=async(c,u)=>{let l=oi(aw,c);if(!l.success){let m=l.error instanceof Error?l.error.message:String(l.error);throw new ve(Ie.InvalidParams,`Invalid sampling request: ${m}`)}let{params:d}=l.data,p=await Promise.resolve(r(c,u));if(d.task){let m=oi(zo,p);if(!m.success){let h=m.error instanceof Error?m.error.message:String(m.error);throw new ve(Ie.InvalidParams,`Invalid task creation result: ${h}`)}return m.data}let f=oi(cw,p);if(!f.success){let m=f.error instanceof Error?f.error.message:String(f.error);throw new ve(Ie.InvalidParams,`Invalid sampling result: ${m}`)}return f.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,r)}assertCapability(e,r){if(!this._serverCapabilities?.[e])throw new Error(`Server does not support ${e} (required for ${r})`)}async connect(e,r){if(await super.connect(e),e.sessionId===void 0)try{let n=await this.request({method:"initialize",params:{protocolVersion:Ux,capabilities:this._capabilities,clientInfo:this._clientInfo}},Bx,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!XO.includes(n.protocolVersion))throw new Error(`Server's protocol version is not supported: ${n.protocolVersion}`);this._serverCapabilities=n.capabilities,this._serverVersion=n.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(n.protocolVersion),this._instructions=n.instructions,await this.notification({method:"notifications/initialized"}),this._pendingListChangedConfig&&(this._setupListChangedHandlers(this._pendingListChangedConfig),this._pendingListChangedConfig=void 0)}catch(n){throw this.close(),n}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){switch(e){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!this._serverCapabilities?.resources)throw new Error(`Server does not support resources (required for ${e})`);if(e==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"initialize":break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/roots/list_changed":if(!this._capabilities.roots?.listChanged)throw new Error(`Client does not support roots list changed notifications (required for ${e})`);break;case"notifications/initialized":break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Client does not support tasks capability (required for ${e})`);break;case"ping":break}}assertTaskCapability(e){iN(this._serverCapabilities?.tasks?.requests,e,"Server")}assertTaskHandlerCapability(e){this._capabilities&&sN(this._capabilities.tasks?.requests,e,"Client")}async ping(e){return this.request({method:"ping"},jo,e)}async complete(e,r){return this.request({method:"completion/complete",params:e},dw,r)}async setLoggingLevel(e,r){return this.request({method:"logging/setLevel",params:{level:e}},jo,r)}async getPrompt(e,r){return this.request({method:"prompts/get",params:e},nw,r)}async listPrompts(e,r){return this.request({method:"prompts/list",params:e},Yx,r)}async listResources(e,r){return this.request({method:"resources/list",params:e},Wx,r)}async listResourceTemplates(e,r){return this.request({method:"resources/templates/list",params:e},Vx,r)}async readResource(e,r){return this.request({method:"resources/read",params:e},Jx,r)}async subscribeResource(e,r){return this.request({method:"resources/subscribe",params:e},jo,r)}async unsubscribeResource(e,r){return this.request({method:"resources/unsubscribe",params:e},jo,r)}async callTool(e,r=ac,n){if(this.isToolTaskRequired(e.name))throw new ve(Ie.InvalidRequest,`Tool "${e.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);let i=await this.request({method:"tools/call",params:e},r,n),s=this.getToolOutputValidator(e.name);if(s){if(!i.structuredContent&&!i.isError)throw new ve(Ie.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(i.structuredContent)try{let o=s(i.structuredContent);if(!o.valid)throw new ve(Ie.InvalidParams,`Structured content does not match the tool's output schema: ${o.errorMessage}`)}catch(o){throw o instanceof ve?o:new ve(Ie.InvalidParams,`Failed to validate structured content: ${o instanceof Error?o.message:String(o)}`)}}return i}isToolTask(e){return this._serverCapabilities?.tasks?.requests?.tools?.call?this._cachedKnownTaskTools.has(e):!1}isToolTaskRequired(e){return this._cachedRequiredTaskTools.has(e)}cacheToolMetadata(e){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(let r of e){if(r.outputSchema){let i=this._jsonSchemaValidator.getValidator(r.outputSchema);this._cachedToolOutputValidators.set(r.name,i)}let n=r.execution?.taskSupport;(n==="required"||n==="optional")&&this._cachedKnownTaskTools.add(r.name),n==="required"&&this._cachedRequiredTaskTools.add(r.name)}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,r){let n=await this.request({method:"tools/list",params:e},sw,r);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(e,r,n,i){let s=fC.safeParse(n);if(!s.success)throw new Error(`Invalid ${e} listChanged options: ${s.error.message}`);if(typeof n.onChanged!="function")throw new Error(`Invalid ${e} listChanged options: onChanged must be a function`);let{autoRefresh:o,debounceMs:a}=s.data,{onChanged:c}=n,u=async()=>{if(!o){c(null,null);return}try{let d=await i();c(null,d)}catch(d){let p=d instanceof Error?d:new Error(String(d));c(p,null)}},l=()=>{if(a){let d=this._listChangedDebounceTimers.get(e);d&&clearTimeout(d);let p=setTimeout(u,a);this._listChangedDebounceTimers.set(e,p)}else u()};this.setNotificationHandler(r,l)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};var KN=Me(WN(),1),Nd=Me(require("node:process"),1),JN=require("node:stream");var Bh=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(` `);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),lY(r)}clear(){this._buffer=void 0}};function lY(t){return sC.parse(JSON.parse(t))}function VN(t){return JSON.stringify(t)+` -`}var dY=Nd.default.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function pY(){let t={};for(let e of dY){let r=Nd.default.env[e];r!==void 0&&(r.startsWith("()")||(t[e]=r))}return t}var $c=class{constructor(e){this._readBuffer=new Bh,this._stderrStream=null,this._serverParams=e,(e.stderr==="pipe"||e.stderr==="overlapped")&&(this._stderrStream=new JN.PassThrough)}async start(){if(this._process)throw new Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((e,r)=>{this._process=(0,KN.default)(this._serverParams.command,this._serverParams.args??[],{env:{...pY(),...this._serverParams.env},stdio:["pipe","pipe",this._serverParams.stderr??"inherit"],shell:!1,windowsHide:Nd.default.platform==="win32"&&fY(),cwd:this._serverParams.cwd}),this._process.on("error",n=>{r(n),this.onerror?.(n)}),this._process.on("spawn",()=>{e()}),this._process.on("close",n=>{this._process=void 0,this.onclose?.()}),this._process.stdin?.on("error",n=>{this.onerror?.(n)}),this._process.stdout?.on("data",n=>{this._readBuffer.append(n),this.processReadBuffer()}),this._process.stdout?.on("error",n=>{this.onerror?.(n)}),this._stderrStream&&this._process.stderr&&this._process.stderr.pipe(this._stderrStream)})}get stderr(){return this._stderrStream?this._stderrStream:this._process?.stderr??null}get pid(){return this._process?.pid??null}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){if(this._process){let e=this._process;this._process=void 0;let r=new Promise(n=>{e.once("close",()=>{n()})});try{e.stdin?.end()}catch{}if(await Promise.race([r,new Promise(n=>setTimeout(n,2e3).unref())]),e.exitCode===null){try{e.kill("SIGTERM")}catch{}await Promise.race([r,new Promise(n=>setTimeout(n,2e3).unref())])}if(e.exitCode===null)try{e.kill("SIGKILL")}catch{}}this._readBuffer.clear()}send(e){return new Promise(r=>{if(!this._process?.stdin)throw new Error("Not connected");let n=VN(e);this._process.stdin.write(n)?r():this._process.stdin.once("drain",r)})}};function fY(){return"type"in Nd.default}Dr();Tn();rr();var Ic=require("fs"),wE=require("path"),dM=require("os");ne();var NY=(0,wE.join)((0,dM.homedir)(),".claude-mem"),xE=(0,wE.join)(NY,".env"),MY=["ANTHROPIC_API_KEY","CLAUDECODE"];function DY(t){let e={};for(let r of t.split(` -`)){let n=r.trim();if(!n||n.startsWith("#"))continue;let i=n.indexOf("=");if(i===-1)continue;let s=n.slice(0,i).trim(),o=n.slice(i+1).trim();(o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'"))&&(o=o.slice(1,-1)),s&&(e[s]=o)}return e}function EE(){if(!(0,Ic.existsSync)(xE))return{};try{let t=(0,Ic.readFileSync)(xE,"utf-8"),e=DY(t),r={};return e.ANTHROPIC_API_KEY&&(r.ANTHROPIC_API_KEY=e.ANTHROPIC_API_KEY),e.GEMINI_API_KEY&&(r.GEMINI_API_KEY=e.GEMINI_API_KEY),e.OPENROUTER_API_KEY&&(r.OPENROUTER_API_KEY=e.OPENROUTER_API_KEY),r}catch(t){return b.warn("ENV","Failed to load .env file",{path:xE},t),{}}}function pM(t=!0){let e={};for(let[r,n]of Object.entries(process.env))n!==void 0&&!MY.includes(r)&&(e[r]=n);if(e.CLAUDE_CODE_ENTRYPOINT="sdk-ts",t){let r=EE();r.ANTHROPIC_API_KEY&&(e.ANTHROPIC_API_KEY=r.ANTHROPIC_API_KEY),r.GEMINI_API_KEY&&(e.GEMINI_API_KEY=r.GEMINI_API_KEY),r.OPENROUTER_API_KEY&&(e.OPENROUTER_API_KEY=r.OPENROUTER_API_KEY),!e.ANTHROPIC_API_KEY&&process.env.CLAUDE_CODE_OAUTH_TOKEN&&(e.CLAUDE_CODE_OAUTH_TOKEN=process.env.CLAUDE_CODE_OAUTH_TOKEN)}return e}function Rc(t){return EE()[t]}function jY(){return!!EE().ANTHROPIC_API_KEY}function Xh(){return jY()?"API key (from ~/.claude-mem/.env)":process.env.CLAUDE_CODE_OAUTH_TOKEN?"Claude Code OAuth token (from parent process)":"Claude Code CLI (subscription billing)"}ne();var AE=require("child_process"),NE=Me(require("path"),1),ME=Me(require("os"),1),Jo=Me(require("fs"),1);ne();rr();jt();var kE=["CLAUDECODE_","CLAUDE_CODE_"],TE=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID"]),zY=new Set(["CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_GIT_BASH_PATH"]);function Ui(t=process.env){let e={};for(let[r,n]of Object.entries(t))if(n!==void 0){if(zY.has(r)){e[r]=n;continue}TE.has(r)||kE.some(i=>r.startsWith(i))||(e[r]=n)}return e}var Ko=require("fs"),EM=require("os"),CE=Me(require("path"),1);ne();var xs=require("fs"),fM=require("os"),Ld=Me(require("path"),1);ne();var LY=5e3,UY=1e3,FY=Ld.default.join((0,fM.homedir)(),".claude-mem"),qY=Ld.default.join(FY,"supervisor.json");function $n(t){if(!Number.isInteger(t)||t<0||t===0)return!1;try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}var IE=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;constructor(e=qY){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,(0,xs.mkdirSync)(Ld.default.dirname(this.registryPath),{recursive:!0}),!(0,xs.existsSync)(this.registryPath)){this.persist();return}try{let n=JSON.parse((0,xs.readFileSync)(this.registryPath,"utf-8")).processes??{};for(let[i,s]of Object.entries(n))this.entries.set(i,s)}catch(r){b.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath},r),this.entries.clear()}let e=this.pruneDeadEntries();e>0&&b.info("SYSTEM","Removed dead processes from supervisor registry",{removed:e}),this.persist()}register(e,r,n){this.initialize(),this.entries.set(e,r),n&&this.runtimeProcesses.set(e,n),this.persist()}unregister(e){this.initialize(),this.entries.delete(e),this.runtimeProcesses.delete(e),this.persist()}clear(){this.entries.clear(),this.runtimeProcesses.clear(),this.persist()}getAll(){return this.initialize(),Array.from(this.entries.entries()).map(([e,r])=>({id:e,...r})).sort((e,r)=>{let n=Date.parse(e.startedAt),i=Date.parse(r.startedAt);return(Number.isNaN(n)?0:n)-(Number.isNaN(i)?0:i)})}getBySession(e){let r=String(e);return this.getAll().filter(n=>n.sessionId!==void 0&&String(n.sessionId)===r)}getRuntimeProcess(e){return this.runtimeProcesses.get(e)}getByPid(e){return this.getAll().filter(r=>r.pid===e)}pruneDeadEntries(){this.initialize();let e=0;for(let[r,n]of this.entries)$n(n.pid)||(this.entries.delete(r),this.runtimeProcesses.delete(r),e+=1);return e>0&&this.persist(),e}async reapSession(e){this.initialize();let r=this.getBySession(e);if(r.length===0)return 0;let n=typeof e=="number"?e:Number(e)||void 0;b.info("SYSTEM",`Reaping ${r.length} process(es) for session ${e}`,{sessionId:n,pids:r.map(a=>a.pid)});let i=r.filter(a=>$n(a.pid));for(let a of i)try{process.kill(a.pid,"SIGTERM")}catch(c){c.code!=="ESRCH"&&b.debug("SYSTEM",`Failed to SIGTERM session process PID ${a.pid}`,{pid:a.pid},c)}let s=Date.now()+LY;for(;Date.now()$n(c.pid)).length!==0;)await new Promise(c=>setTimeout(c,100));let o=i.filter(a=>$n(a.pid));for(let a of o){b.warn("SYSTEM",`Session process PID ${a.pid} did not exit after SIGTERM, sending SIGKILL`,{pid:a.pid,sessionId:n});try{process.kill(a.pid,"SIGKILL")}catch(c){c.code!=="ESRCH"&&b.debug("SYSTEM",`Failed to SIGKILL session process PID ${a.pid}`,{pid:a.pid},c)}}if(o.length>0){let a=Date.now()+UY;for(;Date.now()$n(u.pid)).length!==0;)await new Promise(u=>setTimeout(u,100))}for(let a of r)this.entries.delete(a.id),this.runtimeProcesses.delete(a.id);return this.persist(),b.info("SYSTEM",`Reaped ${r.length} process(es) for session ${e}`,{sessionId:n,reaped:r.length}),r.length}persist(){let e={processes:Object.fromEntries(this.entries.entries())};(0,xs.mkdirSync)(Ld.default.dirname(this.registryPath),{recursive:!0}),(0,xs.writeFileSync)(this.registryPath,JSON.stringify(e,null,2))}},$E=null;function Yh(){return $E||($E=new IE),$E}var gM=require("child_process"),vM=require("fs"),yM=require("os"),RE=Me(require("path"),1),_M=require("util");ne();Tn();var HY=(0,_M.promisify)(gM.execFile),ZY=RE.default.join((0,yM.homedir)(),".claude-mem"),BY=RE.default.join(ZY,"worker.pid");async function bM(t){let e=t.currentPid??process.pid,r=t.pidFilePath??BY,n=t.registry.getAll(),i=[...n].filter(o=>o.pid!==e).sort((o,a)=>Date.parse(a.startedAt)-Date.parse(o.startedAt));for(let o of i){if(!$n(o.pid)){t.registry.unregister(o.id);continue}try{await hM(o.pid,"SIGTERM")}catch(a){b.debug("SYSTEM","Failed to send SIGTERM to child process",{pid:o.pid,type:o.type},a)}}await mM(i,5e3);let s=i.filter(o=>$n(o.pid));for(let o of s)try{await hM(o.pid,"SIGKILL")}catch(a){b.debug("SYSTEM","Failed to force kill child process",{pid:o.pid,type:o.type},a)}await mM(s,1e3);for(let o of i)t.registry.unregister(o.id);for(let o of n.filter(a=>a.pid===e))t.registry.unregister(o.id);try{(0,vM.rmSync)(r,{force:!0})}catch(o){b.debug("SYSTEM","Failed to remove PID file during shutdown",{pidFilePath:r},o)}t.registry.pruneDeadEntries()}async function mM(t,e){let r=Date.now()+e;for(;Date.now()$n(i.pid)).length===0)return;await new Promise(i=>setTimeout(i,100))}}async function hM(t,e){if(e==="SIGTERM"){try{process.kill(t,e)}catch(r){if(r.code==="ESRCH")return;throw r}return}if(process.platform==="win32"){let r=await GY();if(r){await new Promise((i,s)=>{r(t,e,o=>{if(!o){i();return}if(o.code==="ESRCH"){i();return}s(o)})});return}let n=["/PID",String(t),"/T"];e==="SIGKILL"&&n.push("/F"),await HY("taskkill",n,{timeout:Er.POWERSHELL_COMMAND,windowsHide:!0});return}try{process.kill(t,e)}catch(r){if(r.code==="ESRCH")return;throw r}}async function GY(){let t="tree-kill";try{let e=await import(t);return e.default??e}catch{return null}}ne();var SM=3e4,Oc=null;function WY(){let e=Yh().pruneDeadEntries();e>0&&b.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function xM(){Oc===null&&(Oc=setInterval(WY,SM),Oc.unref(),b.debug("SYSTEM","Health checker started",{intervalMs:SM}))}function wM(){Oc!==null&&(clearInterval(Oc),Oc=null,b.debug("SYSTEM","Health checker stopped"))}var VY=CE.default.join((0,EM.homedir)(),".claude-mem"),KY=CE.default.join(VY,"worker.pid"),OE=class{registry;started=!1;stopPromise=null;signalHandlersRegistered=!1;shutdownInitiated=!1;shutdownHandler=null;constructor(e){this.registry=e}async start(){if(this.started)return;if(this.registry.initialize(),PE({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,xM()}configureSignalHandlers(e){if(this.shutdownHandler=e,this.signalHandlersRegistered)return;this.signalHandlersRegistered=!0;let r=async n=>{if(this.shutdownInitiated){b.warn("SYSTEM",`Received ${n} but shutdown already in progress`);return}this.shutdownInitiated=!0,b.info("SYSTEM",`Received ${n}, shutting down...`);try{this.shutdownHandler?await this.shutdownHandler():await this.stop()}catch(i){b.error("SYSTEM","Error during shutdown",{},i);try{await this.stop()}catch(s){b.debug("SYSTEM","Supervisor shutdown fallback failed",{},s)}}process.exit(0)};process.on("SIGTERM",()=>{r("SIGTERM")}),process.on("SIGINT",()=>{r("SIGINT")}),process.platform!=="win32"&&(process.argv.includes("--daemon")?process.on("SIGHUP",()=>{b.debug("SYSTEM","Ignoring SIGHUP in daemon mode")}):process.on("SIGHUP",()=>{r("SIGHUP")}))}async stop(){if(this.stopPromise){await this.stopPromise;return}wM(),this.stopPromise=bM({registry:this.registry,currentPid:process.pid}).finally(()=>{this.started=!1,this.stopPromise=null}),await this.stopPromise}assertCanSpawn(e){if(this.stopPromise!==null)throw new Error(`Supervisor is shutting down, refusing to spawn ${e}`)}registerProcess(e,r,n){this.registry.register(e,r,n)}unregisterProcess(e){this.registry.unregister(e)}getRegistry(){return this.registry}},Qh=new OE(Yh());async function kM(){await Qh.start()}async function TM(){await Qh.stop()}function vt(){return Qh}function $M(t){Qh.configureSignalHandlers(t)}function PE(t={}){let e=t.pidFilePath??KY;if(!(0,Ko.existsSync)(e))return"missing";let r=null;try{r=JSON.parse((0,Ko.readFileSync)(e,"utf-8"))}catch(n){return b.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e},n),(0,Ko.rmSync)(e,{force:!0}),"invalid"}return $n(r.pid)?((t.logAlive??!0)&&b.info("SYSTEM","Worker already running (PID alive)",{existingPid:r.pid,existingPort:r.port,startedAt:r.startedAt}),"alive"):(b.info("SYSTEM","Removing stale PID file (worker process is dead)",{pid:r.pid,port:r.port,startedAt:r.startedAt}),(0,Ko.rmSync)(e,{force:!0}),"stale")}var JY="claude-mem-chroma",XY="1.0.0",IM=3e4,RM=1e4,YY=NE.default.join(ME.default.homedir(),".claude-mem","chroma"),eg="chroma-mcp",ws=class t{static instance=null;client=null;transport=null;connected=!1;lastConnectionFailureTimestamp=0;connecting=null;constructor(){}static getInstance(){return t.instance||(t.instance=new t),t.instance}async ensureConnected(){if(this.connected&&this.client)return;let e=Date.now()-this.lastConnectionFailureTimestamp;if(this.lastConnectionFailureTimestamp>0&&e{a=setTimeout(()=>d(new Error(`MCP connection to chroma-mcp timed out after ${IM}ms`)),IM)});try{await Promise.race([o,c])}catch(l){clearTimeout(a),b.warn("CHROMA_MCP","Connection failed, killing subprocess to prevent zombie",{error:l instanceof Error?l.message:String(l)});try{await this.transport.close()}catch{}try{await this.client.close()}catch{}throw this.client=null,this.transport=null,this.connected=!1,l}clearTimeout(a),this.connected=!0,this.registerManagedProcess(),b.info("CHROMA_MCP","Connected to chroma-mcp successfully");let u=this.transport;this.transport.onclose=()=>{if(this.transport!==u){b.debug("CHROMA_MCP","Ignoring stale onclose from previous transport");return}b.warn("CHROMA_MCP","chroma-mcp subprocess closed unexpectedly, applying reconnect backoff"),this.connected=!1,vt().unregisterProcess(eg),this.client=null,this.transport=null,this.lastConnectionFailureTimestamp=Date.now()}}buildCommandArgs(){let e=Ee.loadFromFile(qt),r=e.CLAUDE_MEM_CHROMA_MODE||"local",n=process.env.CLAUDE_MEM_PYTHON_VERSION||e.CLAUDE_MEM_PYTHON_VERSION||"3.13";if(r==="remote"){let i=e.CLAUDE_MEM_CHROMA_HOST||"127.0.0.1",s=e.CLAUDE_MEM_CHROMA_PORT||"8000",o=e.CLAUDE_MEM_CHROMA_SSL==="true",a=e.CLAUDE_MEM_CHROMA_TENANT||"default_tenant",c=e.CLAUDE_MEM_CHROMA_DATABASE||"default_database",u=e.CLAUDE_MEM_CHROMA_API_KEY||"",l=["--python",n,"chroma-mcp","--client-type","http","--host",i,"--port",s];return l.push("--ssl",o?"true":"false"),a!=="default_tenant"&&l.push("--tenant",a),c!=="default_database"&&l.push("--database",c),u&&l.push("--api-key",u),l}return["--python",n,"chroma-mcp","--client-type","persistent","--data-dir",YY.replace(/\\/g,"/")]}async callTool(e,r){await this.ensureConnected(),b.debug("CHROMA_MCP",`Calling tool: ${e}`,{arguments:JSON.stringify(r).slice(0,200)});let n;try{n=await this.client.callTool({name:e,arguments:r})}catch(o){this.connected=!1,this.client=null,this.transport=null,b.warn("CHROMA_MCP",`Transport error during "${e}", reconnecting and retrying once`,{error:o instanceof Error?o.message:String(o)});try{await this.ensureConnected(),n=await this.client.callTool({name:e,arguments:r})}catch(a){throw this.connected=!1,new Error(`chroma-mcp transport error during "${e}" (retry failed): ${a instanceof Error?a.message:String(a)}`)}}if(n.isError){let o=n.content?.find(a=>a.type==="text")?.text||"Unknown chroma-mcp error";throw new Error(`chroma-mcp tool "${e}" returned error: ${o}`)}let i=n.content;if(!i||i.length===0)return null;let s=i.find(o=>o.type==="text"&&o.text);if(!s||!s.text)return null;try{return JSON.parse(s.text)}catch{return null}}async isHealthy(){try{return await this.callTool("chroma_list_collections",{limit:1}),!0}catch{return!1}}async stop(){if(!this.client){b.debug("CHROMA_MCP","No active MCP connection to stop");return}b.info("CHROMA_MCP","Stopping chroma-mcp MCP connection");try{await this.client.close()}catch(e){b.debug("CHROMA_MCP","Error during client close (subprocess may already be dead)",{},e)}vt().unregisterProcess(eg),this.client=null,this.transport=null,this.connected=!1,this.connecting=null,b.info("CHROMA_MCP","chroma-mcp MCP connection stopped")}static async reset(){t.instance&&await t.instance.stop(),t.instance=null}getCombinedCertPath(){let e=NE.default.join(ME.default.homedir(),".claude-mem","combined_certs.pem");if(Jo.default.existsSync(e)){let r=Jo.default.statSync(e);if(Date.now()-r.mtimeMs<1440*60*1e3)return e}if(process.platform==="darwin")try{let r;try{r=(0,AE.execSync)('uvx --with certifi python -c "import certifi; print(certifi.where())"',{encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:1e4}).trim()}catch{return}if(!r||!Jo.default.existsSync(r))return;let n="";try{n=(0,AE.execSync)('security find-certificate -a -c "Zscaler" -p /Library/Keychains/System.keychain',{encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:5e3})}catch{return}if(!n||!n.includes("-----BEGIN CERTIFICATE-----")||!n.includes("-----END CERTIFICATE-----"))return;let i=Jo.default.readFileSync(r,"utf8"),s=e+".tmp";return Jo.default.writeFileSync(s,i+` -`+n),Jo.default.renameSync(s,e),b.info("CHROMA_MCP","Created combined SSL certificate bundle for Zscaler",{path:e}),e}catch(r){b.debug("CHROMA_MCP","Could not create combined cert bundle",{},r);return}}getSpawnEnv(){let e={};for(let[n,i]of Object.entries(Ui(process.env)))i!==void 0&&(e[n]=i);let r=this.getCombinedCertPath();return r?(b.info("CHROMA_MCP","Using combined SSL certificates for enterprise compatibility",{certPath:r}),{...e,SSL_CERT_FILE:r,REQUESTS_CA_BUNDLE:r,CURL_CA_BUNDLE:r,NODE_EXTRA_CA_CERTS:r}):e}registerManagedProcess(){let e=this.transport._process;e?.pid&&(vt().registerProcess(eg,{pid:e.pid,type:"chroma",startedAt:new Date().toISOString()},e),e.once("exit",()=>{vt().unregisterProcess(eg)}))}};ng();ne();var Cc=class t{project;collectionName;collectionCreated=!1;BATCH_SIZE=100;constructor(e){this.project=e;let r=e.replace(/[^a-zA-Z0-9._-]/g,"_").replace(/[^a-zA-Z0-9]+$/,"");this.collectionName=`cm__${r||"unknown"}`}async ensureCollectionExists(){if(this.collectionCreated)return;let e=ws.getInstance();try{await e.callTool("chroma_create_collection",{collection_name:this.collectionName})}catch(r){if(!(r instanceof Error?r.message:String(r)).includes("already exists"))throw r}this.collectionCreated=!0,b.debug("CHROMA_SYNC","Collection ready",{collection:this.collectionName})}formatObservationDocs(e){let r=[],n=e.facts?JSON.parse(e.facts):[],i=e.concepts?JSON.parse(e.concepts):[],s=e.files_read?JSON.parse(e.files_read):[],o=e.files_modified?JSON.parse(e.files_modified):[],a={sqlite_id:e.id,doc_type:"observation",memory_session_id:e.memory_session_id,project:e.project,created_at_epoch:e.created_at_epoch,type:e.type||"discovery",title:e.title||"Untitled"};return e.subtitle&&(a.subtitle=e.subtitle),i.length>0&&(a.concepts=i.join(",")),s.length>0&&(a.files_read=s.join(",")),o.length>0&&(a.files_modified=o.join(",")),e.narrative&&r.push({id:`obs_${e.id}_narrative`,document:e.narrative,metadata:{...a,field_type:"narrative"}}),e.text&&r.push({id:`obs_${e.id}_text`,document:e.text,metadata:{...a,field_type:"text"}}),n.forEach((c,u)=>{r.push({id:`obs_${e.id}_fact_${u}`,document:c,metadata:{...a,field_type:"fact",fact_index:u}})}),r}formatSummaryDocs(e){let r=[],n={sqlite_id:e.id,doc_type:"session_summary",memory_session_id:e.memory_session_id,project:e.project,created_at_epoch:e.created_at_epoch,prompt_number:e.prompt_number||0};return e.request&&r.push({id:`summary_${e.id}_request`,document:e.request,metadata:{...n,field_type:"request"}}),e.investigated&&r.push({id:`summary_${e.id}_investigated`,document:e.investigated,metadata:{...n,field_type:"investigated"}}),e.learned&&r.push({id:`summary_${e.id}_learned`,document:e.learned,metadata:{...n,field_type:"learned"}}),e.completed&&r.push({id:`summary_${e.id}_completed`,document:e.completed,metadata:{...n,field_type:"completed"}}),e.next_steps&&r.push({id:`summary_${e.id}_next_steps`,document:e.next_steps,metadata:{...n,field_type:"next_steps"}}),e.notes&&r.push({id:`summary_${e.id}_notes`,document:e.notes,metadata:{...n,field_type:"notes"}}),r}async addDocuments(e){if(e.length===0)return;await this.ensureCollectionExists();let r=ws.getInstance();for(let n=0;nObject.fromEntries(Object.entries(o.metadata).filter(([a,c])=>c!=null&&c!=="")));try{await r.callTool("chroma_add_documents",{collection_name:this.collectionName,ids:i.map(o=>o.id),documents:i.map(o=>o.document),metadatas:s})}catch(o){b.error("CHROMA_SYNC","Batch add failed, continuing with remaining batches",{collection:this.collectionName,batchStart:n,batchSize:i.length},o)}}b.debug("CHROMA_SYNC","Documents added",{collection:this.collectionName,count:e.length})}async syncObservation(e,r,n,i,s,o,a=0){let c={id:e,memory_session_id:r,project:n,text:null,type:i.type,title:i.title,subtitle:i.subtitle,facts:JSON.stringify(i.facts),narrative:i.narrative,concepts:JSON.stringify(i.concepts),files_read:JSON.stringify(i.files_read),files_modified:JSON.stringify(i.files_modified),prompt_number:s,discovery_tokens:a,created_at:new Date(o*1e3).toISOString(),created_at_epoch:o},u=this.formatObservationDocs(c);b.info("CHROMA_SYNC","Syncing observation",{observationId:e,documentCount:u.length,project:n}),await this.addDocuments(u)}async syncSummary(e,r,n,i,s,o,a=0){let c={id:e,memory_session_id:r,project:n,request:i.request,investigated:i.investigated,learned:i.learned,completed:i.completed,next_steps:i.next_steps,notes:i.notes,prompt_number:s,discovery_tokens:a,created_at:new Date(o*1e3).toISOString(),created_at_epoch:o},u=this.formatSummaryDocs(c);b.info("CHROMA_SYNC","Syncing summary",{summaryId:e,documentCount:u.length,project:n}),await this.addDocuments(u)}formatUserPromptDoc(e){return{id:`prompt_${e.id}`,document:e.prompt_text,metadata:{sqlite_id:e.id,doc_type:"user_prompt",memory_session_id:e.memory_session_id,project:e.project,created_at_epoch:e.created_at_epoch,prompt_number:e.prompt_number}}}async syncUserPrompt(e,r,n,i,s,o){let a={id:e,content_session_id:"",prompt_number:s,prompt_text:i,created_at:new Date(o*1e3).toISOString(),created_at_epoch:o,memory_session_id:r,project:n},c=this.formatUserPromptDoc(a);b.info("CHROMA_SYNC","Syncing user prompt",{promptId:e,project:n}),await this.addDocuments([c])}async getExistingChromaIds(e){let r=e??this.project;await this.ensureCollectionExists();let n=ws.getInstance(),i=new Set,s=new Set,o=new Set,a=0,c=1e3;for(b.info("CHROMA_SYNC","Fetching existing Chroma document IDs...",{project:r});;){let l=(await n.callTool("chroma_get_documents",{collection_name:this.collectionName,limit:c,offset:a,where:{project:r},include:["metadatas"]}))?.metadatas||[];if(l.length===0)break;for(let d of l)if(d&&d.sqlite_id){let p=d.sqlite_id;d.doc_type==="observation"?i.add(p):d.doc_type==="session_summary"?s.add(p):d.doc_type==="user_prompt"&&o.add(p)}a+=c,b.debug("CHROMA_SYNC","Fetched batch of existing IDs",{project:r,offset:a,batchSize:l.length})}return b.info("CHROMA_SYNC","Existing IDs fetched",{project:r,observations:i.size,summaries:s.size,prompts:o.size}),{observations:i,summaries:s,prompts:o}}async ensureBackfilled(e){let r=e??this.project;b.info("CHROMA_SYNC","Starting smart backfill",{project:r}),await this.ensureCollectionExists();let n=await this.getExistingChromaIds(r),i=new Es;try{let s=Array.from(n.observations).filter(y=>Number.isInteger(y)&&y>0),o=s.length>0?`AND id NOT IN (${s.join(",")})`:"",a=i.db.prepare(` +`}var dY=Nd.default.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function pY(){let t={};for(let e of dY){let r=Nd.default.env[e];r!==void 0&&(r.startsWith("()")||(t[e]=r))}return t}var $c=class{constructor(e){this._readBuffer=new Bh,this._stderrStream=null,this._serverParams=e,(e.stderr==="pipe"||e.stderr==="overlapped")&&(this._stderrStream=new JN.PassThrough)}async start(){if(this._process)throw new Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((e,r)=>{this._process=(0,KN.default)(this._serverParams.command,this._serverParams.args??[],{env:{...pY(),...this._serverParams.env},stdio:["pipe","pipe",this._serverParams.stderr??"inherit"],shell:!1,windowsHide:Nd.default.platform==="win32"&&fY(),cwd:this._serverParams.cwd}),this._process.on("error",n=>{r(n),this.onerror?.(n)}),this._process.on("spawn",()=>{e()}),this._process.on("close",n=>{this._process=void 0,this.onclose?.()}),this._process.stdin?.on("error",n=>{this.onerror?.(n)}),this._process.stdout?.on("data",n=>{this._readBuffer.append(n),this.processReadBuffer()}),this._process.stdout?.on("error",n=>{this.onerror?.(n)}),this._stderrStream&&this._process.stderr&&this._process.stderr.pipe(this._stderrStream)})}get stderr(){return this._stderrStream?this._stderrStream:this._process?.stderr??null}get pid(){return this._process?.pid??null}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){if(this._process){let e=this._process;this._process=void 0;let r=new Promise(n=>{e.once("close",()=>{n()})});try{e.stdin?.end()}catch{}if(await Promise.race([r,new Promise(n=>setTimeout(n,2e3).unref())]),e.exitCode===null){try{e.kill("SIGTERM")}catch{}await Promise.race([r,new Promise(n=>setTimeout(n,2e3).unref())])}if(e.exitCode===null)try{e.kill("SIGKILL")}catch{}}this._readBuffer.clear()}send(e){return new Promise(r=>{if(!this._process?.stdin)throw new Error("Not connected");let n=VN(e);this._process.stdin.write(n)?r():this._process.stdin.once("drain",r)})}};function fY(){return"type"in Nd.default}Dr();Tn();rr();var Ic=require("fs"),wE=require("path"),dM=require("os");se();var NY=(0,wE.join)((0,dM.homedir)(),".claude-mem"),xE=(0,wE.join)(NY,".env"),MY=["ANTHROPIC_API_KEY","CLAUDECODE"];function DY(t){let e={};for(let r of t.split(` +`)){let n=r.trim();if(!n||n.startsWith("#"))continue;let i=n.indexOf("=");if(i===-1)continue;let s=n.slice(0,i).trim(),o=n.slice(i+1).trim();(o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'"))&&(o=o.slice(1,-1)),s&&(e[s]=o)}return e}function EE(){if(!(0,Ic.existsSync)(xE))return{};try{let t=(0,Ic.readFileSync)(xE,"utf-8"),e=DY(t),r={};return e.ANTHROPIC_API_KEY&&(r.ANTHROPIC_API_KEY=e.ANTHROPIC_API_KEY),e.GEMINI_API_KEY&&(r.GEMINI_API_KEY=e.GEMINI_API_KEY),e.OPENROUTER_API_KEY&&(r.OPENROUTER_API_KEY=e.OPENROUTER_API_KEY),r}catch(t){return b.warn("ENV","Failed to load .env file",{path:xE},t),{}}}function pM(t=!0){let e={};for(let[r,n]of Object.entries(process.env))n!==void 0&&!MY.includes(r)&&(e[r]=n);if(e.CLAUDE_CODE_ENTRYPOINT="sdk-ts",t){let r=EE();r.ANTHROPIC_API_KEY&&(e.ANTHROPIC_API_KEY=r.ANTHROPIC_API_KEY),r.GEMINI_API_KEY&&(e.GEMINI_API_KEY=r.GEMINI_API_KEY),r.OPENROUTER_API_KEY&&(e.OPENROUTER_API_KEY=r.OPENROUTER_API_KEY),!e.ANTHROPIC_API_KEY&&process.env.CLAUDE_CODE_OAUTH_TOKEN&&(e.CLAUDE_CODE_OAUTH_TOKEN=process.env.CLAUDE_CODE_OAUTH_TOKEN)}return e}function Rc(t){return EE()[t]}function jY(){return!!EE().ANTHROPIC_API_KEY}function Xh(){return jY()?"API key (from ~/.claude-mem/.env)":process.env.CLAUDE_CODE_OAUTH_TOKEN?"Claude Code OAuth token (from parent process)":"Claude Code CLI (subscription billing)"}se();var AE=require("child_process"),NE=Me(require("path"),1),ME=Me(require("os"),1),Jo=Me(require("fs"),1);se();rr();jt();var kE=["CLAUDECODE_","CLAUDE_CODE_"],TE=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID"]),zY=new Set(["CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_GIT_BASH_PATH"]);function Ui(t=process.env){let e={};for(let[r,n]of Object.entries(t))if(n!==void 0){if(zY.has(r)){e[r]=n;continue}TE.has(r)||kE.some(i=>r.startsWith(i))||(e[r]=n)}return e}var Ko=require("fs"),EM=require("os"),CE=Me(require("path"),1);se();var xs=require("fs"),fM=require("os"),Ld=Me(require("path"),1);se();var LY=5e3,UY=1e3,FY=Ld.default.join((0,fM.homedir)(),".claude-mem"),qY=Ld.default.join(FY,"supervisor.json");function $n(t){if(!Number.isInteger(t)||t<0||t===0)return!1;try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}var IE=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;constructor(e=qY){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,(0,xs.mkdirSync)(Ld.default.dirname(this.registryPath),{recursive:!0}),!(0,xs.existsSync)(this.registryPath)){this.persist();return}try{let n=JSON.parse((0,xs.readFileSync)(this.registryPath,"utf-8")).processes??{};for(let[i,s]of Object.entries(n))this.entries.set(i,s)}catch(r){b.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath},r),this.entries.clear()}let e=this.pruneDeadEntries();e>0&&b.info("SYSTEM","Removed dead processes from supervisor registry",{removed:e}),this.persist()}register(e,r,n){this.initialize(),this.entries.set(e,r),n&&this.runtimeProcesses.set(e,n),this.persist()}unregister(e){this.initialize(),this.entries.delete(e),this.runtimeProcesses.delete(e),this.persist()}clear(){this.entries.clear(),this.runtimeProcesses.clear(),this.persist()}getAll(){return this.initialize(),Array.from(this.entries.entries()).map(([e,r])=>({id:e,...r})).sort((e,r)=>{let n=Date.parse(e.startedAt),i=Date.parse(r.startedAt);return(Number.isNaN(n)?0:n)-(Number.isNaN(i)?0:i)})}getBySession(e){let r=String(e);return this.getAll().filter(n=>n.sessionId!==void 0&&String(n.sessionId)===r)}getRuntimeProcess(e){return this.runtimeProcesses.get(e)}getByPid(e){return this.getAll().filter(r=>r.pid===e)}pruneDeadEntries(){this.initialize();let e=0;for(let[r,n]of this.entries)$n(n.pid)||(this.entries.delete(r),this.runtimeProcesses.delete(r),e+=1);return e>0&&this.persist(),e}async reapSession(e){this.initialize();let r=this.getBySession(e);if(r.length===0)return 0;let n=typeof e=="number"?e:Number(e)||void 0;b.info("SYSTEM",`Reaping ${r.length} process(es) for session ${e}`,{sessionId:n,pids:r.map(a=>a.pid)});let i=r.filter(a=>$n(a.pid));for(let a of i)try{process.kill(a.pid,"SIGTERM")}catch(c){c.code!=="ESRCH"&&b.debug("SYSTEM",`Failed to SIGTERM session process PID ${a.pid}`,{pid:a.pid},c)}let s=Date.now()+LY;for(;Date.now()$n(c.pid)).length!==0;)await new Promise(c=>setTimeout(c,100));let o=i.filter(a=>$n(a.pid));for(let a of o){b.warn("SYSTEM",`Session process PID ${a.pid} did not exit after SIGTERM, sending SIGKILL`,{pid:a.pid,sessionId:n});try{process.kill(a.pid,"SIGKILL")}catch(c){c.code!=="ESRCH"&&b.debug("SYSTEM",`Failed to SIGKILL session process PID ${a.pid}`,{pid:a.pid},c)}}if(o.length>0){let a=Date.now()+UY;for(;Date.now()$n(u.pid)).length!==0;)await new Promise(u=>setTimeout(u,100))}for(let a of r)this.entries.delete(a.id),this.runtimeProcesses.delete(a.id);return this.persist(),b.info("SYSTEM",`Reaped ${r.length} process(es) for session ${e}`,{sessionId:n,reaped:r.length}),r.length}persist(){let e={processes:Object.fromEntries(this.entries.entries())};(0,xs.mkdirSync)(Ld.default.dirname(this.registryPath),{recursive:!0}),(0,xs.writeFileSync)(this.registryPath,JSON.stringify(e,null,2))}},$E=null;function Yh(){return $E||($E=new IE),$E}var gM=require("child_process"),vM=require("fs"),yM=require("os"),RE=Me(require("path"),1),_M=require("util");se();Tn();var HY=(0,_M.promisify)(gM.execFile),ZY=RE.default.join((0,yM.homedir)(),".claude-mem"),BY=RE.default.join(ZY,"worker.pid");async function bM(t){let e=t.currentPid??process.pid,r=t.pidFilePath??BY,n=t.registry.getAll(),i=[...n].filter(o=>o.pid!==e).sort((o,a)=>Date.parse(a.startedAt)-Date.parse(o.startedAt));for(let o of i){if(!$n(o.pid)){t.registry.unregister(o.id);continue}try{await hM(o.pid,"SIGTERM")}catch(a){b.debug("SYSTEM","Failed to send SIGTERM to child process",{pid:o.pid,type:o.type},a)}}await mM(i,5e3);let s=i.filter(o=>$n(o.pid));for(let o of s)try{await hM(o.pid,"SIGKILL")}catch(a){b.debug("SYSTEM","Failed to force kill child process",{pid:o.pid,type:o.type},a)}await mM(s,1e3);for(let o of i)t.registry.unregister(o.id);for(let o of n.filter(a=>a.pid===e))t.registry.unregister(o.id);try{(0,vM.rmSync)(r,{force:!0})}catch(o){b.debug("SYSTEM","Failed to remove PID file during shutdown",{pidFilePath:r},o)}t.registry.pruneDeadEntries()}async function mM(t,e){let r=Date.now()+e;for(;Date.now()$n(i.pid)).length===0)return;await new Promise(i=>setTimeout(i,100))}}async function hM(t,e){if(e==="SIGTERM"){try{process.kill(t,e)}catch(r){if(r.code==="ESRCH")return;throw r}return}if(process.platform==="win32"){let r=await GY();if(r){await new Promise((i,s)=>{r(t,e,o=>{if(!o){i();return}if(o.code==="ESRCH"){i();return}s(o)})});return}let n=["/PID",String(t),"/T"];e==="SIGKILL"&&n.push("/F"),await HY("taskkill",n,{timeout:Er.POWERSHELL_COMMAND,windowsHide:!0});return}try{process.kill(t,e)}catch(r){if(r.code==="ESRCH")return;throw r}}async function GY(){let t="tree-kill";try{let e=await import(t);return e.default??e}catch{return null}}se();var SM=3e4,Oc=null;function WY(){let e=Yh().pruneDeadEntries();e>0&&b.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function xM(){Oc===null&&(Oc=setInterval(WY,SM),Oc.unref(),b.debug("SYSTEM","Health checker started",{intervalMs:SM}))}function wM(){Oc!==null&&(clearInterval(Oc),Oc=null,b.debug("SYSTEM","Health checker stopped"))}var VY=CE.default.join((0,EM.homedir)(),".claude-mem"),KY=CE.default.join(VY,"worker.pid"),OE=class{registry;started=!1;stopPromise=null;signalHandlersRegistered=!1;shutdownInitiated=!1;shutdownHandler=null;constructor(e){this.registry=e}async start(){if(this.started)return;if(this.registry.initialize(),PE({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,xM()}configureSignalHandlers(e){if(this.shutdownHandler=e,this.signalHandlersRegistered)return;this.signalHandlersRegistered=!0;let r=async n=>{if(this.shutdownInitiated){b.warn("SYSTEM",`Received ${n} but shutdown already in progress`);return}this.shutdownInitiated=!0,b.info("SYSTEM",`Received ${n}, shutting down...`);try{this.shutdownHandler?await this.shutdownHandler():await this.stop()}catch(i){b.error("SYSTEM","Error during shutdown",{},i);try{await this.stop()}catch(s){b.debug("SYSTEM","Supervisor shutdown fallback failed",{},s)}}process.exit(0)};process.on("SIGTERM",()=>{r("SIGTERM")}),process.on("SIGINT",()=>{r("SIGINT")}),process.platform!=="win32"&&(process.argv.includes("--daemon")?process.on("SIGHUP",()=>{b.debug("SYSTEM","Ignoring SIGHUP in daemon mode")}):process.on("SIGHUP",()=>{r("SIGHUP")}))}async stop(){if(this.stopPromise){await this.stopPromise;return}wM(),this.stopPromise=bM({registry:this.registry,currentPid:process.pid}).finally(()=>{this.started=!1,this.stopPromise=null}),await this.stopPromise}assertCanSpawn(e){if(this.stopPromise!==null)throw new Error(`Supervisor is shutting down, refusing to spawn ${e}`)}registerProcess(e,r,n){this.registry.register(e,r,n)}unregisterProcess(e){this.registry.unregister(e)}getRegistry(){return this.registry}},Qh=new OE(Yh());async function kM(){await Qh.start()}async function TM(){await Qh.stop()}function vt(){return Qh}function $M(t){Qh.configureSignalHandlers(t)}function PE(t={}){let e=t.pidFilePath??KY;if(!(0,Ko.existsSync)(e))return"missing";let r=null;try{r=JSON.parse((0,Ko.readFileSync)(e,"utf-8"))}catch(n){return b.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e},n),(0,Ko.rmSync)(e,{force:!0}),"invalid"}return $n(r.pid)?((t.logAlive??!0)&&b.info("SYSTEM","Worker already running (PID alive)",{existingPid:r.pid,existingPort:r.port,startedAt:r.startedAt}),"alive"):(b.info("SYSTEM","Removing stale PID file (worker process is dead)",{pid:r.pid,port:r.port,startedAt:r.startedAt}),(0,Ko.rmSync)(e,{force:!0}),"stale")}var JY="claude-mem-chroma",XY="1.0.0",IM=3e4,RM=1e4,YY=NE.default.join(ME.default.homedir(),".claude-mem","chroma"),eg="chroma-mcp",ws=class t{static instance=null;client=null;transport=null;connected=!1;lastConnectionFailureTimestamp=0;connecting=null;constructor(){}static getInstance(){return t.instance||(t.instance=new t),t.instance}async ensureConnected(){if(this.connected&&this.client)return;let e=Date.now()-this.lastConnectionFailureTimestamp;if(this.lastConnectionFailureTimestamp>0&&e{a=setTimeout(()=>d(new Error(`MCP connection to chroma-mcp timed out after ${IM}ms`)),IM)});try{await Promise.race([o,c])}catch(l){clearTimeout(a),b.warn("CHROMA_MCP","Connection failed, killing subprocess to prevent zombie",{error:l instanceof Error?l.message:String(l)});try{await this.transport.close()}catch{}try{await this.client.close()}catch{}throw this.client=null,this.transport=null,this.connected=!1,l}clearTimeout(a),this.connected=!0,this.registerManagedProcess(),b.info("CHROMA_MCP","Connected to chroma-mcp successfully");let u=this.transport;this.transport.onclose=()=>{if(this.transport!==u){b.debug("CHROMA_MCP","Ignoring stale onclose from previous transport");return}b.warn("CHROMA_MCP","chroma-mcp subprocess closed unexpectedly, applying reconnect backoff"),this.connected=!1,vt().unregisterProcess(eg),this.client=null,this.transport=null,this.lastConnectionFailureTimestamp=Date.now()}}buildCommandArgs(){let e=Ee.loadFromFile(qt),r=e.CLAUDE_MEM_CHROMA_MODE||"local",n=process.env.CLAUDE_MEM_PYTHON_VERSION||e.CLAUDE_MEM_PYTHON_VERSION||"3.13";if(r==="remote"){let i=e.CLAUDE_MEM_CHROMA_HOST||"127.0.0.1",s=e.CLAUDE_MEM_CHROMA_PORT||"8000",o=e.CLAUDE_MEM_CHROMA_SSL==="true",a=e.CLAUDE_MEM_CHROMA_TENANT||"default_tenant",c=e.CLAUDE_MEM_CHROMA_DATABASE||"default_database",u=e.CLAUDE_MEM_CHROMA_API_KEY||"",l=["--python",n,"chroma-mcp","--client-type","http","--host",i,"--port",s];return l.push("--ssl",o?"true":"false"),a!=="default_tenant"&&l.push("--tenant",a),c!=="default_database"&&l.push("--database",c),u&&l.push("--api-key",u),l}return["--python",n,"chroma-mcp","--client-type","persistent","--data-dir",YY.replace(/\\/g,"/")]}async callTool(e,r){await this.ensureConnected(),b.debug("CHROMA_MCP",`Calling tool: ${e}`,{arguments:JSON.stringify(r).slice(0,200)});let n;try{n=await this.client.callTool({name:e,arguments:r})}catch(o){this.connected=!1,this.client=null,this.transport=null,b.warn("CHROMA_MCP",`Transport error during "${e}", reconnecting and retrying once`,{error:o instanceof Error?o.message:String(o)});try{await this.ensureConnected(),n=await this.client.callTool({name:e,arguments:r})}catch(a){throw this.connected=!1,new Error(`chroma-mcp transport error during "${e}" (retry failed): ${a instanceof Error?a.message:String(a)}`)}}if(n.isError){let o=n.content?.find(a=>a.type==="text")?.text||"Unknown chroma-mcp error";throw new Error(`chroma-mcp tool "${e}" returned error: ${o}`)}let i=n.content;if(!i||i.length===0)return null;let s=i.find(o=>o.type==="text"&&o.text);if(!s||!s.text)return null;try{return JSON.parse(s.text)}catch{return null}}async isHealthy(){try{return await this.callTool("chroma_list_collections",{limit:1}),!0}catch{return!1}}async stop(){if(!this.client){b.debug("CHROMA_MCP","No active MCP connection to stop");return}b.info("CHROMA_MCP","Stopping chroma-mcp MCP connection");try{await this.client.close()}catch(e){b.debug("CHROMA_MCP","Error during client close (subprocess may already be dead)",{},e)}vt().unregisterProcess(eg),this.client=null,this.transport=null,this.connected=!1,this.connecting=null,b.info("CHROMA_MCP","chroma-mcp MCP connection stopped")}static async reset(){t.instance&&await t.instance.stop(),t.instance=null}getCombinedCertPath(){let e=NE.default.join(ME.default.homedir(),".claude-mem","combined_certs.pem");if(Jo.default.existsSync(e)){let r=Jo.default.statSync(e);if(Date.now()-r.mtimeMs<1440*60*1e3)return e}if(process.platform==="darwin")try{let r;try{r=(0,AE.execSync)('uvx --with certifi python -c "import certifi; print(certifi.where())"',{encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:1e4}).trim()}catch{return}if(!r||!Jo.default.existsSync(r))return;let n="";try{n=(0,AE.execSync)('security find-certificate -a -c "Zscaler" -p /Library/Keychains/System.keychain',{encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:5e3})}catch{return}if(!n||!n.includes("-----BEGIN CERTIFICATE-----")||!n.includes("-----END CERTIFICATE-----"))return;let i=Jo.default.readFileSync(r,"utf8"),s=e+".tmp";return Jo.default.writeFileSync(s,i+` +`+n),Jo.default.renameSync(s,e),b.info("CHROMA_MCP","Created combined SSL certificate bundle for Zscaler",{path:e}),e}catch(r){b.debug("CHROMA_MCP","Could not create combined cert bundle",{},r);return}}getSpawnEnv(){let e={};for(let[n,i]of Object.entries(Ui(process.env)))i!==void 0&&(e[n]=i);let r=this.getCombinedCertPath();return r?(b.info("CHROMA_MCP","Using combined SSL certificates for enterprise compatibility",{certPath:r}),{...e,SSL_CERT_FILE:r,REQUESTS_CA_BUNDLE:r,CURL_CA_BUNDLE:r,NODE_EXTRA_CA_CERTS:r}):e}registerManagedProcess(){let e=this.transport._process;e?.pid&&(vt().registerProcess(eg,{pid:e.pid,type:"chroma",startedAt:new Date().toISOString()},e),e.once("exit",()=>{vt().unregisterProcess(eg)}))}};ng();se();var Cc=class t{project;collectionName;collectionCreated=!1;BATCH_SIZE=100;constructor(e){this.project=e;let r=e.replace(/[^a-zA-Z0-9._-]/g,"_").replace(/[^a-zA-Z0-9]+$/,"");this.collectionName=`cm__${r||"unknown"}`}async ensureCollectionExists(){if(this.collectionCreated)return;let e=ws.getInstance();try{await e.callTool("chroma_create_collection",{collection_name:this.collectionName})}catch(r){if(!(r instanceof Error?r.message:String(r)).includes("already exists"))throw r}this.collectionCreated=!0,b.debug("CHROMA_SYNC","Collection ready",{collection:this.collectionName})}formatObservationDocs(e){let r=[],n=e.facts?JSON.parse(e.facts):[],i=e.concepts?JSON.parse(e.concepts):[],s=e.files_read?JSON.parse(e.files_read):[],o=e.files_modified?JSON.parse(e.files_modified):[],a={sqlite_id:e.id,doc_type:"observation",memory_session_id:e.memory_session_id,project:e.project,created_at_epoch:e.created_at_epoch,type:e.type||"discovery",title:e.title||"Untitled"};return e.subtitle&&(a.subtitle=e.subtitle),i.length>0&&(a.concepts=i.join(",")),s.length>0&&(a.files_read=s.join(",")),o.length>0&&(a.files_modified=o.join(",")),e.narrative&&r.push({id:`obs_${e.id}_narrative`,document:e.narrative,metadata:{...a,field_type:"narrative"}}),e.text&&r.push({id:`obs_${e.id}_text`,document:e.text,metadata:{...a,field_type:"text"}}),n.forEach((c,u)=>{r.push({id:`obs_${e.id}_fact_${u}`,document:c,metadata:{...a,field_type:"fact",fact_index:u}})}),r}formatSummaryDocs(e){let r=[],n={sqlite_id:e.id,doc_type:"session_summary",memory_session_id:e.memory_session_id,project:e.project,created_at_epoch:e.created_at_epoch,prompt_number:e.prompt_number||0};return e.request&&r.push({id:`summary_${e.id}_request`,document:e.request,metadata:{...n,field_type:"request"}}),e.investigated&&r.push({id:`summary_${e.id}_investigated`,document:e.investigated,metadata:{...n,field_type:"investigated"}}),e.learned&&r.push({id:`summary_${e.id}_learned`,document:e.learned,metadata:{...n,field_type:"learned"}}),e.completed&&r.push({id:`summary_${e.id}_completed`,document:e.completed,metadata:{...n,field_type:"completed"}}),e.next_steps&&r.push({id:`summary_${e.id}_next_steps`,document:e.next_steps,metadata:{...n,field_type:"next_steps"}}),e.notes&&r.push({id:`summary_${e.id}_notes`,document:e.notes,metadata:{...n,field_type:"notes"}}),r}async addDocuments(e){if(e.length===0)return;await this.ensureCollectionExists();let r=ws.getInstance();for(let n=0;nObject.fromEntries(Object.entries(o.metadata).filter(([a,c])=>c!=null&&c!=="")));try{await r.callTool("chroma_add_documents",{collection_name:this.collectionName,ids:i.map(o=>o.id),documents:i.map(o=>o.document),metadatas:s})}catch(o){b.error("CHROMA_SYNC","Batch add failed, continuing with remaining batches",{collection:this.collectionName,batchStart:n,batchSize:i.length},o)}}b.debug("CHROMA_SYNC","Documents added",{collection:this.collectionName,count:e.length})}async syncObservation(e,r,n,i,s,o,a=0){let c={id:e,memory_session_id:r,project:n,text:null,type:i.type,title:i.title,subtitle:i.subtitle,facts:JSON.stringify(i.facts),narrative:i.narrative,concepts:JSON.stringify(i.concepts),files_read:JSON.stringify(i.files_read),files_modified:JSON.stringify(i.files_modified),prompt_number:s,discovery_tokens:a,created_at:new Date(o*1e3).toISOString(),created_at_epoch:o},u=this.formatObservationDocs(c);b.info("CHROMA_SYNC","Syncing observation",{observationId:e,documentCount:u.length,project:n}),await this.addDocuments(u)}async syncSummary(e,r,n,i,s,o,a=0){let c={id:e,memory_session_id:r,project:n,request:i.request,investigated:i.investigated,learned:i.learned,completed:i.completed,next_steps:i.next_steps,notes:i.notes,prompt_number:s,discovery_tokens:a,created_at:new Date(o*1e3).toISOString(),created_at_epoch:o},u=this.formatSummaryDocs(c);b.info("CHROMA_SYNC","Syncing summary",{summaryId:e,documentCount:u.length,project:n}),await this.addDocuments(u)}formatUserPromptDoc(e){return{id:`prompt_${e.id}`,document:e.prompt_text,metadata:{sqlite_id:e.id,doc_type:"user_prompt",memory_session_id:e.memory_session_id,project:e.project,created_at_epoch:e.created_at_epoch,prompt_number:e.prompt_number}}}async syncUserPrompt(e,r,n,i,s,o){let a={id:e,content_session_id:"",prompt_number:s,prompt_text:i,created_at:new Date(o*1e3).toISOString(),created_at_epoch:o,memory_session_id:r,project:n},c=this.formatUserPromptDoc(a);b.info("CHROMA_SYNC","Syncing user prompt",{promptId:e,project:n}),await this.addDocuments([c])}async getExistingChromaIds(e){let r=e??this.project;await this.ensureCollectionExists();let n=ws.getInstance(),i=new Set,s=new Set,o=new Set,a=0,c=1e3;for(b.info("CHROMA_SYNC","Fetching existing Chroma document IDs...",{project:r});;){let l=(await n.callTool("chroma_get_documents",{collection_name:this.collectionName,limit:c,offset:a,where:{project:r},include:["metadatas"]}))?.metadatas||[];if(l.length===0)break;for(let d of l)if(d&&d.sqlite_id){let p=d.sqlite_id;d.doc_type==="observation"?i.add(p):d.doc_type==="session_summary"?s.add(p):d.doc_type==="user_prompt"&&o.add(p)}a+=c,b.debug("CHROMA_SYNC","Fetched batch of existing IDs",{project:r,offset:a,batchSize:l.length})}return b.info("CHROMA_SYNC","Existing IDs fetched",{project:r,observations:i.size,summaries:s.size,prompts:o.size}),{observations:i,summaries:s,prompts:o}}async ensureBackfilled(e){let r=e??this.project;b.info("CHROMA_SYNC","Starting smart backfill",{project:r}),await this.ensureCollectionExists();let n=await this.getExistingChromaIds(r),i=new Es;try{let s=Array.from(n.observations).filter(y=>Number.isInteger(y)&&y>0),o=s.length>0?`AND id NOT IN (${s.join(",")})`:"",a=i.db.prepare(` SELECT * FROM observations WHERE project = ? ${o} ORDER BY id ASC @@ -920,8 +920,8 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs. FROM user_prompts up JOIN sdk_sessions s ON up.content_session_id = s.content_session_id WHERE s.project = ? - `).get(r);b.info("CHROMA_SYNC","Backfilling user prompts",{project:r,missing:v.length,existing:n.prompts.size,total:S.count});let _=[];for(let y of v)_.push(this.formatUserPromptDoc(y));for(let y=0;y<_.length;y+=this.BATCH_SIZE){let x=_.slice(y,y+this.BATCH_SIZE);await this.addDocuments(x),b.debug("CHROMA_SYNC","Backfill progress",{project:r,progress:`${Math.min(y+this.BATCH_SIZE,_.length)}/${_.length}`})}b.info("CHROMA_SYNC","Smart backfill complete",{project:r,synced:{observationDocs:u.length,summaryDocs:m.length,promptDocs:_.length},skipped:{observations:n.observations.size,summaries:n.summaries.size,prompts:n.prompts.size}})}catch(s){throw b.error("CHROMA_SYNC","Backfill failed",{project:r},s),new Error(`Backfill failed: ${s instanceof Error?s.message:String(s)}`)}finally{i.close()}}async queryChroma(e,r,n){await this.ensureCollectionExists();try{let s=await ws.getInstance().callTool("chroma_query_documents",{collection_name:this.collectionName,query_texts:[e],n_results:r,...n&&{where:n},include:["documents","metadatas","distances"]}),o=[],a=new Set,c=s?.ids?.[0]||[],u=s?.metadatas?.[0]||[],l=s?.distances?.[0]||[],d=[],p=[];for(let f=0;fs.trim()).find(s=>s.length>0)||null}catch{return null}}function rQ(t={}){let e=t.platform??process.platform,r=t.execPath??process.execPath;if(e!=="win32"||DM(r))return r;let n=t.env??process.env,i=t.homeDirectory??(0,zE.homedir)(),s=t.pathExists??zt.existsSync,o=t.lookupInPath??tQ,a=[n.BUN,n.BUN_PATH,Fi.default.join(i,".bun","bin","bun.exe"),Fi.default.join(i,".bun","bin","bun"),n.USERPROFILE?Fi.default.join(n.USERPROFILE,".bun","bin","bun.exe"):void 0,n.LOCALAPPDATA?Fi.default.join(n.LOCALAPPDATA,"bun","bun.exe"):void 0,n.LOCALAPPDATA?Fi.default.join(n.LOCALAPPDATA,"bun","bin","bun.exe"):void 0];for(let c of a){let u=c?.trim();if(u&&(DM(u)&&s(u)||u.toLowerCase()==="bun"))return u}return o("bun",e)}function zM(t){(0,zt.mkdirSync)(LE,{recursive:!0}),(0,zt.writeFileSync)(qi,JSON.stringify(t,null,2))}function UE(){if(!(0,zt.existsSync)(qi))return null;try{return JSON.parse((0,zt.readFileSync)(qi,"utf-8"))}catch(t){return b.warn("SYSTEM","Failed to parse PID file",{path:qi},t),null}}function Xo(){if((0,zt.existsSync)(qi))try{(0,zt.unlinkSync)(qi)}catch(t){b.warn("SYSTEM","Failed to remove PID file",{path:qi},t)}}function Ts(t){return process.platform==="win32"?Math.round(t*2):t}function nQ(t){if(!t||t.trim()==="")return-1;let e=t.trim(),r=0,n=e.match(/^(\d+)-(\d+):(\d+):(\d+)$/);if(n)return r=parseInt(n[1],10)*24*60+parseInt(n[2],10)*60+parseInt(n[3],10),r;let i=e.match(/^(\d+):(\d+):(\d+)$/);if(i)return r=parseInt(i[1],10)*60+parseInt(i[2],10),r;let s=e.match(/^(\d+):(\d+)$/);return s?parseInt(s[1],10):-1}var jE=["worker-service.cjs","chroma-mcp"],iQ=["mcp-server.cjs"];async function LM(){let t=process.platform==="win32",e=process.pid,r=[],n=[...jE,...iQ];try{if(t){let s=`powershell -NoProfile -NonInteractive -Command "Get-CimInstance Win32_Process -Filter '(${n.map(l=>`CommandLine LIKE '%${l}%'`).join(" OR ")}) AND ProcessId != ${e}' | Select-Object ProcessId, CommandLine, CreationDate | ConvertTo-Json"`,{stdout:o}=await NM(s,{timeout:Er.POWERSHELL_COMMAND,windowsHide:!0});if(!o.trim()||o.trim()==="null"){b.debug("SYSTEM","No orphaned claude-mem processes found (Windows)");return}let a=JSON.parse(o),c=Array.isArray(a)?a:[a],u=Date.now();for(let l of c){let d=l.ProcessId;if(!Number.isInteger(d)||d<=0||d===e)continue;let p=l.CommandLine||"";if(jE.some(m=>p.includes(m)))r.push(d),b.debug("SYSTEM","Found orphaned process (aggressive)",{pid:d,commandLine:p.substring(0,80)});else{let m=l.CreationDate?.match(/\/Date\((\d+)\)\//);if(m){let h=parseInt(m[1],10),g=(u-h)/(1e3*60);g>=MM&&(r.push(d),b.debug("SYSTEM","Found orphaned process (age-gated)",{pid:d,ageMinutes:Math.round(g)}))}}}}else{let i=n.join("|"),{stdout:s}=await NM(`ps -eo pid,etime,command | grep -E "${i}" | grep -v grep || true`);if(!s.trim()){b.debug("SYSTEM","No orphaned claude-mem processes found (Unix)");return}let o=s.trim().split(` -`);for(let a of o){let c=a.trim().match(/^(\d+)\s+(\S+)\s+(.*)$/);if(!c)continue;let u=parseInt(c[1],10),l=c[2],d=c[3];if(!Number.isInteger(u)||u<=0||u===e)continue;if(jE.some(f=>d.includes(f)))r.push(u),b.debug("SYSTEM","Found orphaned process (aggressive)",{pid:u,command:d.substring(0,80)});else{let f=nQ(l);f>=MM&&(r.push(u),b.debug("SYSTEM","Found orphaned process (age-gated)",{pid:u,ageMinutes:f,command:d.substring(0,80)}))}}}}catch(i){b.error("SYSTEM","Failed to enumerate orphaned processes during aggressive cleanup",{},i);return}if(r.length!==0){if(b.info("SYSTEM","Aggressive startup cleanup: killing orphaned processes",{platform:t?"Windows":"Unix",count:r.length,pids:r}),t){for(let i of r)if(!(!Number.isInteger(i)||i<=0))try{(0,ks.execSync)(`taskkill /PID ${i} /T /F`,{timeout:Er.POWERSHELL_COMMAND,stdio:"ignore",windowsHide:!0})}catch(s){b.debug("SYSTEM","Failed to kill process, may have already exited",{pid:i},s)}}else for(let i of r)try{process.kill(i,"SIGKILL")}catch(s){b.debug("SYSTEM","Process already exited",{pid:i},s)}b.info("SYSTEM","Aggressive startup cleanup complete",{count:r.length})}}var sQ=".chroma-cleaned-v10.3";function UM(t){let e=t??LE,r=Fi.default.join(e,sQ),n=Fi.default.join(e,"chroma");if((0,zt.existsSync)(r)){b.debug("SYSTEM","Chroma migration marker exists, skipping wipe");return}b.warn("SYSTEM","Running one-time chroma data wipe (upgrade from pre-v10.3)",{chromaDir:n}),(0,zt.existsSync)(n)&&((0,zt.rmSync)(n,{recursive:!0,force:!0}),b.info("SYSTEM","Chroma data directory removed",{chromaDir:n})),(0,zt.mkdirSync)(e,{recursive:!0}),(0,zt.writeFileSync)(r,new Date().toISOString()),b.info("SYSTEM","Chroma migration marker written",{markerPath:r})}function FE(t,e,r={}){let n=process.platform==="win32";vt().assertCanSpawn("worker daemon");let i=Ui({...process.env,CLAUDE_MEM_WORKER_PORT:String(e),...r});if(n){let a=rQ();if(!a){b.error("SYSTEM","Failed to locate Bun runtime for Windows worker spawn");return}let c=`Start-Process -FilePath '${a.replace(/'/g,"''")}' -ArgumentList @('${t.replace(/'/g,"''")}','--daemon') -WindowStyle Hidden`,u=Buffer.from(c,"utf16le").toString("base64");try{return(0,ks.execSync)(`powershell -NoProfile -EncodedCommand ${u}`,{stdio:"ignore",windowsHide:!0,env:i}),0}catch(l){b.error("SYSTEM","Failed to spawn worker daemon on Windows",{runtimePath:a},l);return}}let s="/usr/bin/setsid";if((0,zt.existsSync)(s)){let a=(0,ks.spawn)(s,[process.execPath,t,"--daemon"],{detached:!0,stdio:"ignore",env:i});return a.pid===void 0?void 0:(a.unref(),a.pid)}let o=(0,ks.spawn)(process.execPath,[t,"--daemon"],{detached:!0,stdio:"ignore",env:i});if(o.pid!==void 0)return o.unref(),o.pid}function FM(t){if(t===0)return!0;if(!Number.isInteger(t)||t<0)return!1;try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function qM(t=15e3){try{let e=(0,zt.statSync)(qi);return Date.now()-e.mtimeMssetTimeout(s,500))}return!1}function Yo(t,e=3e4){return WM(t,"/api/health",e,"Service not ready yet, will retry")}function VM(t,e=3e4){return WM(t,"/api/readiness",e,"Worker not ready yet, will retry")}async function og(t,e=1e4){let r=Date.now();for(;Date.now()-rsetTimeout(n,500))}return!1}async function ag(t){try{let e=await qE(t,"/api/admin/shutdown","POST");return e.ok?!0:(b.warn("SYSTEM","Shutdown request returned error",{status:e.statusCode}),!1)}catch(e){return e instanceof Error&&e.message?.includes("ECONNREFUSED")?(b.debug("SYSTEM","Worker already stopped",{},e),!1):(b.error("SYSTEM","Shutdown request failed unexpectedly",{},e),!1)}}function oQ(){try{let t=BM.default.join(Ss,"package.json");return JSON.parse((0,GM.readFileSync)(t,"utf-8")).version}catch(t){let e=t.code;if(e==="ENOENT"||e==="EBUSY")return b.debug("SYSTEM","Could not read plugin version (shutdown race)",{code:e}),"unknown";throw t}}async function aQ(t){try{let e=await qE(t,"/api/version");return e.ok?JSON.parse(e.body).version:null}catch{return b.debug("SYSTEM","Could not fetch worker version",{}),null}}async function KM(t){let e=oQ(),r=await aQ(t);return!r||e==="unknown"?{matches:!0,pluginVersion:e,workerVersion:r}:{matches:e===r,pluginVersion:e,workerVersion:r}}ne();async function JM(t){b.info("SYSTEM","Shutdown initiated"),t.server&&(await cQ(t.server),b.info("SYSTEM","HTTP server closed")),await t.sessionManager.shutdownAll(),t.mcpClient&&(await t.mcpClient.close(),b.info("SYSTEM","MCP client closed")),t.chromaMcpManager&&(b.info("SHUTDOWN","Stopping Chroma MCP connection..."),await t.chromaMcpManager.stop(),b.info("SHUTDOWN","Chroma MCP connection stopped")),t.dbManager&&await t.dbManager.close(),await TM(),b.info("SYSTEM","Worker shutdown complete")}async function cQ(t){t.closeAllConnections(),process.platform==="win32"&&await new Promise(e=>setTimeout(e,500)),await new Promise((e,r)=>{t.close(n=>n?r(n):e())}),process.platform==="win32"&&(await new Promise(e=>setTimeout(e,500)),b.info("SYSTEM","Waited for Windows port cleanup"))}var u6=Me(hv(),1),VT=Me(require("fs"),1),wp=Me(require("path"),1);var J2=["search","context","summarize","import","export"],X2=["workflow","search_params","examples","all"];ne();var BT=Me(hv(),1),n6=Me(r6(),1),i6=Me(require("path"),1);jt();ne();function GT(t){let e=[];e.push(BT.default.json({limit:"50mb"})),e.push((0,n6.default)({origin:(i,s)=>{!i||i.startsWith("http://localhost:")||i.startsWith("http://127.0.0.1:")?s(null,!0):s(new Error("CORS not allowed"))},methods:["GET","HEAD","POST","PUT","PATCH","DELETE"],allowedHeaders:["Content-Type","Authorization","X-Requested-With"],credentials:!1})),e.push((i,s,o)=>{let c=[".html",".js",".css",".svg",".png",".jpg",".jpeg",".webp",".woff",".woff2",".ttf",".eot"].some(m=>i.path.endsWith(m)),u=i.path==="/api/logs";if(i.path.startsWith("/health")||i.path==="/"||c||u)return o();let l=Date.now(),d=`${i.method}-${Date.now()}`,p=t(i.method,i.path,i.body);b.debug("HTTP",`\u2192 ${i.method} ${i.path}`,{requestId:d},p);let f=s.send.bind(s);s.send=function(m){let h=Date.now()-l;return b.debug("HTTP",`\u2190 ${s.statusCode} ${i.path}`,{requestId:d,duration:`${h}ms`}),f(m)},o()});let r=dn(),n=i6.default.join(r,"plugin","ui");return e.push(BT.default.static(n)),e}function xp(t,e,r){let n=t.ip||t.connection.remoteAddress||"";if(!(n==="127.0.0.1"||n==="::1"||n==="::ffff:127.0.0.1"||n==="localhost")){b.warn("SECURITY","Admin endpoint access denied - not localhost",{endpoint:t.path,clientIp:n,method:t.method}),e.status(403).json({error:"Forbidden",message:"Admin endpoints are only accessible from localhost"});return}r()}function WT(t,e,r){if(!r||Object.keys(r).length===0||e.includes("/init"))return"";if(e.includes("/observations")){let n=r.tool_name||"?",i=r.tool_input;return`tool=${b.formatTool(n,i)}`}return e.includes("/summarize")?"requesting summary":""}ne();var iu=class extends Error{constructor(r,n=500,i,s){super(r);this.statusCode=n;this.code=i;this.details=s;this.name="AppError"}};function s6(t,e,r,n){let i={error:t,message:e};return r&&(i.code=r),n&&(i.details=n),i}var o6=(t,e,r,n)=>{let i=t instanceof iu?t.statusCode:500;b.error("HTTP",`Error handling ${e.method} ${e.path}`,{statusCode:i,error:t.message,code:t instanceof iu?t.code:void 0},t);let s=s6(t.name||"Error",t.message,t instanceof iu?t.code:void 0,t instanceof iu?t.details:void 0);r.status(i).json(s)};function a6(t,e){e.status(404).json(s6("NotFound",`Cannot ${t.method} ${t.path}`))}var c6="10.6.3",gv=class{app;server=null;options;startTime=Date.now();constructor(e){this.options=e,this.app=(0,u6.default)(),this.setupMiddleware(),this.setupCoreRoutes()}getHttpServer(){return this.server}async listen(e,r){return new Promise((n,i)=>{this.server=this.app.listen(e,r,()=>{b.info("SYSTEM","HTTP server started",{host:r,port:e,pid:process.pid}),n()}),this.server.on("error",i)})}async close(){this.server&&(this.server.closeAllConnections(),process.platform==="win32"&&await new Promise(e=>setTimeout(e,500)),await new Promise((e,r)=>{this.server.close(n=>n?r(n):e())}),process.platform==="win32"&&await new Promise(e=>setTimeout(e,500)),this.server=null,b.info("SYSTEM","HTTP server closed"))}registerRoutes(e){e.setupRoutes(this.app)}finalizeRoutes(){this.app.use(a6),this.app.use(o6)}setupMiddleware(){GT(WT).forEach(r=>this.app.use(r))}setupCoreRoutes(){this.app.get("/api/health",(e,r)=>{r.status(200).json({status:"ok",version:c6,workerPath:this.options.workerPath,uptime:Date.now()-this.startTime,managed:process.env.CLAUDE_MEM_MANAGED==="true",hasIpc:typeof process.send=="function",platform:process.platform,pid:process.pid,initialized:this.options.getInitializationComplete(),mcpReady:this.options.getMcpReady(),ai:this.options.getAiStatus()})}),this.app.get("/api/readiness",(e,r)=>{this.options.getInitializationComplete()?r.status(200).json({status:"ready",mcpReady:this.options.getMcpReady()}):r.status(503).json({status:"initializing",message:"Worker is still initializing, please retry"})}),this.app.get("/api/version",(e,r)=>{r.status(200).json({version:c6})}),this.app.get("/api/instructions",async(e,r)=>{let n=e.query.topic||"all",i=e.query.operation;if(n&&!X2.includes(n))return r.status(400).json({error:"Invalid topic"});try{let s;if(i){if(!J2.includes(i))return r.status(400).json({error:"Invalid operation"});let o=wp.default.resolve(__dirname,"../skills/mem-search/operations"),a=wp.default.resolve(o,`${i}.md`);if(!a.startsWith(o+wp.default.sep))return r.status(400).json({error:"Invalid request"});s=await VT.promises.readFile(a,"utf-8")}else{let o=wp.default.join(__dirname,"../skills/mem-search/SKILL.md"),a=await VT.promises.readFile(o,"utf-8");s=this.extractInstructionSection(a,n)}r.json({content:[{type:"text",text:s}]})}catch{r.status(404).json({error:"Instruction not found"})}}),this.app.post("/api/admin/restart",xp,async(e,r)=>{r.json({status:"restarting"}),process.platform==="win32"&&process.env.CLAUDE_MEM_MANAGED==="true"&&process.send?(b.info("SYSTEM","Sending restart request to wrapper"),process.send({type:"restart"})):setTimeout(async()=>{try{await this.options.onRestart()}finally{process.exit(0)}},100)}),this.app.post("/api/admin/shutdown",xp,async(e,r)=>{r.json({status:"shutting_down"}),process.platform==="win32"&&process.env.CLAUDE_MEM_MANAGED==="true"&&process.send?(b.info("SYSTEM","Sending shutdown request to wrapper"),process.send({type:"shutdown"})):setTimeout(async()=>{try{await this.options.onShutdown()}finally{process.exit(0)}},100)}),this.app.get("/api/admin/doctor",xp,(e,r)=>{let o=vt().getRegistry().getAll().map(m=>({id:m.id,pid:m.pid,type:m.type,status:$n(m.pid)?"alive":"dead",startedAt:m.startedAt})),a=o.filter(m=>m.status==="dead").map(m=>m.pid),c=!Object.keys(process.env).some(m=>TE.has(m)||kE.some(h=>m.startsWith(h))),u=Date.now()-this.startTime,l=Math.floor(u/1e3),d=Math.floor(l/3600),p=Math.floor(l%3600/60),f=d>0?`${d}h ${p}m`:`${p}m`;r.json({supervisor:{running:!0,pid:process.pid,uptime:f},processes:o,health:{deadProcessPids:a,envClean:c}})})}extractInstructionSection(e,r){let n={workflow:this.extractBetween(e,"## The Workflow","## Search Parameters"),search_params:this.extractBetween(e,"## Search Parameters","## Examples"),examples:this.extractBetween(e,"## Examples","## Why This Workflow"),all:e};return n[r]||n.all}extractBetween(e,r,n){let i=e.indexOf(r),s=e.indexOf(n);return i===-1?e:s===-1?e.substring(i):e.substring(i,s).trim()}};var It=Me(require("path"),1),kp=require("os"),Kt=require("fs"),p6=require("child_process"),f6=require("util");ne();Dr();jt();var Vn=require("fs"),Ep=require("path");ne();function l6(t){try{return(0,Vn.existsSync)(t)?JSON.parse((0,Vn.readFileSync)(t,"utf-8")):{}}catch(e){return b.error("CONFIG","Failed to read Cursor registry, using empty registry",{file:t,error:e instanceof Error?e.message:String(e)}),{}}}function d6(t,e){let r=(0,Ep.join)(t,"..");(0,Vn.mkdirSync)(r,{recursive:!0}),(0,Vn.writeFileSync)(t,JSON.stringify(e,null,2))}function KT(t,e){let r=(0,Ep.join)(t,".cursor","rules"),n=(0,Ep.join)(r,"claude-mem-context.mdc"),i=`${n}.tmp`;(0,Vn.mkdirSync)(r,{recursive:!0});let s=`--- + `).get(r);b.info("CHROMA_SYNC","Backfilling user prompts",{project:r,missing:v.length,existing:n.prompts.size,total:S.count});let _=[];for(let y of v)_.push(this.formatUserPromptDoc(y));for(let y=0;y<_.length;y+=this.BATCH_SIZE){let x=_.slice(y,y+this.BATCH_SIZE);await this.addDocuments(x),b.debug("CHROMA_SYNC","Backfill progress",{project:r,progress:`${Math.min(y+this.BATCH_SIZE,_.length)}/${_.length}`})}b.info("CHROMA_SYNC","Smart backfill complete",{project:r,synced:{observationDocs:u.length,summaryDocs:m.length,promptDocs:_.length},skipped:{observations:n.observations.size,summaries:n.summaries.size,prompts:n.prompts.size}})}catch(s){throw b.error("CHROMA_SYNC","Backfill failed",{project:r},s),new Error(`Backfill failed: ${s instanceof Error?s.message:String(s)}`)}finally{i.close()}}async queryChroma(e,r,n){await this.ensureCollectionExists();try{let s=await ws.getInstance().callTool("chroma_query_documents",{collection_name:this.collectionName,query_texts:[e],n_results:r,...n&&{where:n},include:["documents","metadatas","distances"]}),o=[],a=new Set,c=s?.ids?.[0]||[],u=s?.metadatas?.[0]||[],l=s?.distances?.[0]||[],d=[],p=[];for(let f=0;fs.trim()).find(s=>s.length>0)||null}catch{return null}}function rQ(t={}){let e=t.platform??process.platform,r=t.execPath??process.execPath;if(e!=="win32"||DM(r))return r;let n=t.env??process.env,i=t.homeDirectory??(0,zE.homedir)(),s=t.pathExists??zt.existsSync,o=t.lookupInPath??tQ,a=[n.BUN,n.BUN_PATH,Fi.default.join(i,".bun","bin","bun.exe"),Fi.default.join(i,".bun","bin","bun"),n.USERPROFILE?Fi.default.join(n.USERPROFILE,".bun","bin","bun.exe"):void 0,n.LOCALAPPDATA?Fi.default.join(n.LOCALAPPDATA,"bun","bun.exe"):void 0,n.LOCALAPPDATA?Fi.default.join(n.LOCALAPPDATA,"bun","bin","bun.exe"):void 0];for(let c of a){let u=c?.trim();if(u&&(DM(u)&&s(u)||u.toLowerCase()==="bun"))return u}return o("bun",e)}function zM(t){(0,zt.mkdirSync)(LE,{recursive:!0}),(0,zt.writeFileSync)(qi,JSON.stringify(t,null,2))}function UE(){if(!(0,zt.existsSync)(qi))return null;try{return JSON.parse((0,zt.readFileSync)(qi,"utf-8"))}catch(t){return b.warn("SYSTEM","Failed to parse PID file",{path:qi},t),null}}function Xo(){if((0,zt.existsSync)(qi))try{(0,zt.unlinkSync)(qi)}catch(t){b.warn("SYSTEM","Failed to remove PID file",{path:qi},t)}}function Ts(t){return process.platform==="win32"?Math.round(t*2):t}function nQ(t){if(!t||t.trim()==="")return-1;let e=t.trim(),r=0,n=e.match(/^(\d+)-(\d+):(\d+):(\d+)$/);if(n)return r=parseInt(n[1],10)*24*60+parseInt(n[2],10)*60+parseInt(n[3],10),r;let i=e.match(/^(\d+):(\d+):(\d+)$/);if(i)return r=parseInt(i[1],10)*60+parseInt(i[2],10),r;let s=e.match(/^(\d+):(\d+)$/);return s?parseInt(s[1],10):-1}var jE=["worker-service.cjs","chroma-mcp"],iQ=["mcp-server.cjs"];async function LM(){let t=process.platform==="win32",e=process.pid,r=[],n=[...jE,...iQ];try{if(t){let s=`powershell -NoProfile -NonInteractive -Command "Get-CimInstance Win32_Process -Filter '(${n.map(l=>`CommandLine LIKE '%${l}%'`).join(" OR ")}) AND ProcessId != ${e}' | Select-Object ProcessId, CommandLine, CreationDate | ConvertTo-Json"`,{stdout:o}=await NM(s,{timeout:Er.POWERSHELL_COMMAND,windowsHide:!0});if(!o.trim()||o.trim()==="null"){b.debug("SYSTEM","No orphaned claude-mem processes found (Windows)");return}let a=JSON.parse(o),c=Array.isArray(a)?a:[a],u=Date.now();for(let l of c){let d=l.ProcessId;if(!Number.isInteger(d)||d<=0||d===e)continue;let p=l.CommandLine||"";if(jE.some(m=>p.includes(m)))r.push(d),b.debug("SYSTEM","Found orphaned process (aggressive)",{pid:d,commandLine:p.substring(0,80)});else{let m=l.CreationDate?.match(/\/Date\((\d+)\)\//);if(m){let h=parseInt(m[1],10),g=(u-h)/(1e3*60);g>=MM&&(r.push(d),b.debug("SYSTEM","Found orphaned process (age-gated)",{pid:d,ageMinutes:Math.round(g)}))}}}}else{let i=n.join("|"),{stdout:s}=await NM(`ps -eo pid,etime,command | grep -E "${i}" | grep -v grep || true`);if(!s.trim()){b.debug("SYSTEM","No orphaned claude-mem processes found (Unix)");return}let o=s.trim().split(` +`);for(let a of o){let c=a.trim().match(/^(\d+)\s+(\S+)\s+(.*)$/);if(!c)continue;let u=parseInt(c[1],10),l=c[2],d=c[3];if(!Number.isInteger(u)||u<=0||u===e)continue;if(jE.some(f=>d.includes(f)))r.push(u),b.debug("SYSTEM","Found orphaned process (aggressive)",{pid:u,command:d.substring(0,80)});else{let f=nQ(l);f>=MM&&(r.push(u),b.debug("SYSTEM","Found orphaned process (age-gated)",{pid:u,ageMinutes:f,command:d.substring(0,80)}))}}}}catch(i){b.error("SYSTEM","Failed to enumerate orphaned processes during aggressive cleanup",{},i);return}if(r.length!==0){if(b.info("SYSTEM","Aggressive startup cleanup: killing orphaned processes",{platform:t?"Windows":"Unix",count:r.length,pids:r}),t){for(let i of r)if(!(!Number.isInteger(i)||i<=0))try{(0,ks.execSync)(`taskkill /PID ${i} /T /F`,{timeout:Er.POWERSHELL_COMMAND,stdio:"ignore",windowsHide:!0})}catch(s){b.debug("SYSTEM","Failed to kill process, may have already exited",{pid:i},s)}}else for(let i of r)try{process.kill(i,"SIGKILL")}catch(s){b.debug("SYSTEM","Process already exited",{pid:i},s)}b.info("SYSTEM","Aggressive startup cleanup complete",{count:r.length})}}var sQ=".chroma-cleaned-v10.3";function UM(t){let e=t??LE,r=Fi.default.join(e,sQ),n=Fi.default.join(e,"chroma");if((0,zt.existsSync)(r)){b.debug("SYSTEM","Chroma migration marker exists, skipping wipe");return}b.warn("SYSTEM","Running one-time chroma data wipe (upgrade from pre-v10.3)",{chromaDir:n}),(0,zt.existsSync)(n)&&((0,zt.rmSync)(n,{recursive:!0,force:!0}),b.info("SYSTEM","Chroma data directory removed",{chromaDir:n})),(0,zt.mkdirSync)(e,{recursive:!0}),(0,zt.writeFileSync)(r,new Date().toISOString()),b.info("SYSTEM","Chroma migration marker written",{markerPath:r})}function FE(t,e,r={}){let n=process.platform==="win32";vt().assertCanSpawn("worker daemon");let i=Ui({...process.env,CLAUDE_MEM_WORKER_PORT:String(e),...r});if(n){let a=rQ();if(!a){b.error("SYSTEM","Failed to locate Bun runtime for Windows worker spawn");return}let c=`Start-Process -FilePath '${a.replace(/'/g,"''")}' -ArgumentList @('${t.replace(/'/g,"''")}','--daemon') -WindowStyle Hidden`,u=Buffer.from(c,"utf16le").toString("base64");try{return(0,ks.execSync)(`powershell -NoProfile -EncodedCommand ${u}`,{stdio:"ignore",windowsHide:!0,env:i}),0}catch(l){b.error("SYSTEM","Failed to spawn worker daemon on Windows",{runtimePath:a},l);return}}let s="/usr/bin/setsid";if((0,zt.existsSync)(s)){let a=(0,ks.spawn)(s,[process.execPath,t,"--daemon"],{detached:!0,stdio:"ignore",env:i});return a.pid===void 0?void 0:(a.unref(),a.pid)}let o=(0,ks.spawn)(process.execPath,[t,"--daemon"],{detached:!0,stdio:"ignore",env:i});if(o.pid!==void 0)return o.unref(),o.pid}function FM(t){if(t===0)return!0;if(!Number.isInteger(t)||t<0)return!1;try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function qM(t=15e3){try{let e=(0,zt.statSync)(qi);return Date.now()-e.mtimeMssetTimeout(s,500))}return!1}function Yo(t,e=3e4){return WM(t,"/api/health",e,"Service not ready yet, will retry")}function VM(t,e=3e4){return WM(t,"/api/readiness",e,"Worker not ready yet, will retry")}async function og(t,e=1e4){let r=Date.now();for(;Date.now()-rsetTimeout(n,500))}return!1}async function ag(t){try{let e=await qE(t,"/api/admin/shutdown","POST");return e.ok?!0:(b.warn("SYSTEM","Shutdown request returned error",{status:e.statusCode}),!1)}catch(e){return e instanceof Error&&e.message?.includes("ECONNREFUSED")?(b.debug("SYSTEM","Worker already stopped",{},e),!1):(b.error("SYSTEM","Shutdown request failed unexpectedly",{},e),!1)}}function oQ(){try{let t=BM.default.join(Ss,"package.json");return JSON.parse((0,GM.readFileSync)(t,"utf-8")).version}catch(t){let e=t.code;if(e==="ENOENT"||e==="EBUSY")return b.debug("SYSTEM","Could not read plugin version (shutdown race)",{code:e}),"unknown";throw t}}async function aQ(t){try{let e=await qE(t,"/api/version");return e.ok?JSON.parse(e.body).version:null}catch{return b.debug("SYSTEM","Could not fetch worker version",{}),null}}async function KM(t){let e=oQ(),r=await aQ(t);return!r||e==="unknown"?{matches:!0,pluginVersion:e,workerVersion:r}:{matches:e===r,pluginVersion:e,workerVersion:r}}se();async function JM(t){b.info("SYSTEM","Shutdown initiated"),t.server&&(await cQ(t.server),b.info("SYSTEM","HTTP server closed")),await t.sessionManager.shutdownAll(),t.mcpClient&&(await t.mcpClient.close(),b.info("SYSTEM","MCP client closed")),t.chromaMcpManager&&(b.info("SHUTDOWN","Stopping Chroma MCP connection..."),await t.chromaMcpManager.stop(),b.info("SHUTDOWN","Chroma MCP connection stopped")),t.dbManager&&await t.dbManager.close(),await TM(),b.info("SYSTEM","Worker shutdown complete")}async function cQ(t){t.closeAllConnections(),process.platform==="win32"&&await new Promise(e=>setTimeout(e,500)),await new Promise((e,r)=>{t.close(n=>n?r(n):e())}),process.platform==="win32"&&(await new Promise(e=>setTimeout(e,500)),b.info("SYSTEM","Waited for Windows port cleanup"))}var u6=Me(hv(),1),VT=Me(require("fs"),1),wp=Me(require("path"),1);var J2=["search","context","summarize","import","export"],X2=["workflow","search_params","examples","all"];se();var BT=Me(hv(),1),n6=Me(r6(),1),i6=Me(require("path"),1);jt();se();function GT(t){let e=[];e.push(BT.default.json({limit:"50mb"})),e.push((0,n6.default)({origin:(i,s)=>{!i||i.startsWith("http://localhost:")||i.startsWith("http://127.0.0.1:")?s(null,!0):s(new Error("CORS not allowed"))},methods:["GET","HEAD","POST","PUT","PATCH","DELETE"],allowedHeaders:["Content-Type","Authorization","X-Requested-With"],credentials:!1})),e.push((i,s,o)=>{let c=[".html",".js",".css",".svg",".png",".jpg",".jpeg",".webp",".woff",".woff2",".ttf",".eot"].some(m=>i.path.endsWith(m)),u=i.path==="/api/logs";if(i.path.startsWith("/health")||i.path==="/"||c||u)return o();let l=Date.now(),d=`${i.method}-${Date.now()}`,p=t(i.method,i.path,i.body);b.debug("HTTP",`\u2192 ${i.method} ${i.path}`,{requestId:d},p);let f=s.send.bind(s);s.send=function(m){let h=Date.now()-l;return b.debug("HTTP",`\u2190 ${s.statusCode} ${i.path}`,{requestId:d,duration:`${h}ms`}),f(m)},o()});let r=dn(),n=i6.default.join(r,"plugin","ui");return e.push(BT.default.static(n)),e}function xp(t,e,r){let n=t.ip||t.connection.remoteAddress||"";if(!(n==="127.0.0.1"||n==="::1"||n==="::ffff:127.0.0.1"||n==="localhost")){b.warn("SECURITY","Admin endpoint access denied - not localhost",{endpoint:t.path,clientIp:n,method:t.method}),e.status(403).json({error:"Forbidden",message:"Admin endpoints are only accessible from localhost"});return}r()}function WT(t,e,r){if(!r||Object.keys(r).length===0||e.includes("/init"))return"";if(e.includes("/observations")){let n=r.tool_name||"?",i=r.tool_input;return`tool=${b.formatTool(n,i)}`}return e.includes("/summarize")?"requesting summary":""}se();var iu=class extends Error{constructor(r,n=500,i,s){super(r);this.statusCode=n;this.code=i;this.details=s;this.name="AppError"}};function s6(t,e,r,n){let i={error:t,message:e};return r&&(i.code=r),n&&(i.details=n),i}var o6=(t,e,r,n)=>{let i=t instanceof iu?t.statusCode:500;b.error("HTTP",`Error handling ${e.method} ${e.path}`,{statusCode:i,error:t.message,code:t instanceof iu?t.code:void 0},t);let s=s6(t.name||"Error",t.message,t instanceof iu?t.code:void 0,t instanceof iu?t.details:void 0);r.status(i).json(s)};function a6(t,e){e.status(404).json(s6("NotFound",`Cannot ${t.method} ${t.path}`))}var c6="10.7.0",gv=class{app;server=null;options;startTime=Date.now();constructor(e){this.options=e,this.app=(0,u6.default)(),this.setupMiddleware(),this.setupCoreRoutes()}getHttpServer(){return this.server}async listen(e,r){return new Promise((n,i)=>{this.server=this.app.listen(e,r,()=>{b.info("SYSTEM","HTTP server started",{host:r,port:e,pid:process.pid}),n()}),this.server.on("error",i)})}async close(){this.server&&(this.server.closeAllConnections(),process.platform==="win32"&&await new Promise(e=>setTimeout(e,500)),await new Promise((e,r)=>{this.server.close(n=>n?r(n):e())}),process.platform==="win32"&&await new Promise(e=>setTimeout(e,500)),this.server=null,b.info("SYSTEM","HTTP server closed"))}registerRoutes(e){e.setupRoutes(this.app)}finalizeRoutes(){this.app.use(a6),this.app.use(o6)}setupMiddleware(){GT(WT).forEach(r=>this.app.use(r))}setupCoreRoutes(){this.app.get("/api/health",(e,r)=>{r.status(200).json({status:"ok",version:c6,workerPath:this.options.workerPath,uptime:Date.now()-this.startTime,managed:process.env.CLAUDE_MEM_MANAGED==="true",hasIpc:typeof process.send=="function",platform:process.platform,pid:process.pid,initialized:this.options.getInitializationComplete(),mcpReady:this.options.getMcpReady(),ai:this.options.getAiStatus()})}),this.app.get("/api/readiness",(e,r)=>{this.options.getInitializationComplete()?r.status(200).json({status:"ready",mcpReady:this.options.getMcpReady()}):r.status(503).json({status:"initializing",message:"Worker is still initializing, please retry"})}),this.app.get("/api/version",(e,r)=>{r.status(200).json({version:c6})}),this.app.get("/api/instructions",async(e,r)=>{let n=e.query.topic||"all",i=e.query.operation;if(n&&!X2.includes(n))return r.status(400).json({error:"Invalid topic"});try{let s;if(i){if(!J2.includes(i))return r.status(400).json({error:"Invalid operation"});let o=wp.default.resolve(__dirname,"../skills/mem-search/operations"),a=wp.default.resolve(o,`${i}.md`);if(!a.startsWith(o+wp.default.sep))return r.status(400).json({error:"Invalid request"});s=await VT.promises.readFile(a,"utf-8")}else{let o=wp.default.join(__dirname,"../skills/mem-search/SKILL.md"),a=await VT.promises.readFile(o,"utf-8");s=this.extractInstructionSection(a,n)}r.json({content:[{type:"text",text:s}]})}catch{r.status(404).json({error:"Instruction not found"})}}),this.app.post("/api/admin/restart",xp,async(e,r)=>{r.json({status:"restarting"}),process.platform==="win32"&&process.env.CLAUDE_MEM_MANAGED==="true"&&process.send?(b.info("SYSTEM","Sending restart request to wrapper"),process.send({type:"restart"})):setTimeout(async()=>{try{await this.options.onRestart()}finally{process.exit(0)}},100)}),this.app.post("/api/admin/shutdown",xp,async(e,r)=>{r.json({status:"shutting_down"}),process.platform==="win32"&&process.env.CLAUDE_MEM_MANAGED==="true"&&process.send?(b.info("SYSTEM","Sending shutdown request to wrapper"),process.send({type:"shutdown"})):setTimeout(async()=>{try{await this.options.onShutdown()}finally{process.exit(0)}},100)}),this.app.get("/api/admin/doctor",xp,(e,r)=>{let o=vt().getRegistry().getAll().map(m=>({id:m.id,pid:m.pid,type:m.type,status:$n(m.pid)?"alive":"dead",startedAt:m.startedAt})),a=o.filter(m=>m.status==="dead").map(m=>m.pid),c=!Object.keys(process.env).some(m=>TE.has(m)||kE.some(h=>m.startsWith(h))),u=Date.now()-this.startTime,l=Math.floor(u/1e3),d=Math.floor(l/3600),p=Math.floor(l%3600/60),f=d>0?`${d}h ${p}m`:`${p}m`;r.json({supervisor:{running:!0,pid:process.pid,uptime:f},processes:o,health:{deadProcessPids:a,envClean:c}})})}extractInstructionSection(e,r){let n={workflow:this.extractBetween(e,"## The Workflow","## Search Parameters"),search_params:this.extractBetween(e,"## Search Parameters","## Examples"),examples:this.extractBetween(e,"## Examples","## Why This Workflow"),all:e};return n[r]||n.all}extractBetween(e,r,n){let i=e.indexOf(r),s=e.indexOf(n);return i===-1?e:s===-1?e.substring(i):e.substring(i,s).trim()}};var It=Me(require("path"),1),kp=require("os"),Kt=require("fs"),p6=require("child_process"),f6=require("util");se();Dr();jt();var Vn=require("fs"),Ep=require("path");se();function l6(t){try{return(0,Vn.existsSync)(t)?JSON.parse((0,Vn.readFileSync)(t,"utf-8")):{}}catch(e){return b.error("CONFIG","Failed to read Cursor registry, using empty registry",{file:t,error:e instanceof Error?e.message:String(e)}),{}}}function d6(t,e){let r=(0,Ep.join)(t,"..");(0,Vn.mkdirSync)(r,{recursive:!0}),(0,Vn.writeFileSync)(t,JSON.stringify(e,null,2))}function KT(t,e){let r=(0,Ep.join)(t,".cursor","rules"),n=(0,Ep.join)(r,"claude-mem-context.mdc"),i=`${n}.tmp`;(0,Vn.mkdirSync)(r,{recursive:!0});let s=`--- alwaysApply: true description: "Claude-mem context from past sessions (auto-updated)" --- @@ -993,7 +993,7 @@ Examples: claude-mem cursor status # Check if hooks are installed For more info: https://docs.claude-mem.ai/cursor - `),0}}var vv=Me(require("path"),1),_6=require("os"),ir=require("fs");ne();var yv=vv.default.join((0,_6.homedir)(),".gemini"),gi=vv.default.join(yv,"settings.json"),hi=vv.default.join(yv,"GEMINI.md"),Tp="claude-mem",mue=1e4,su={SessionStart:"context",BeforeAgent:"user-message",AfterAgent:"observation",BeforeTool:"observation",AfterTool:"observation",PreCompress:"summarize",Notification:"observation",SessionEnd:"session-complete"};function hue(t,e,r){let n=su[r];if(!n)throw new Error(`Unknown Gemini CLI event: ${r}`);let i=t.replace(/\\/g,"\\\\"),s=e.replace(/\\/g,"\\\\");return`"${i}" "${s}" hook gemini-cli ${n}`}function gue(t){return{matcher:"*",hooks:[{name:Tp,type:"command",command:t,timeout:mue}]}}function QT(){if(!(0,ir.existsSync)(gi))return{};try{let t=(0,ir.readFileSync)(gi,"utf-8");return JSON.parse(t)}catch{return b.warn("GEMINI",`Failed to parse ${gi}, treating as empty`,{}),{}}}function b6(t){(0,ir.mkdirSync)(yv,{recursive:!0}),(0,ir.writeFileSync)(gi,JSON.stringify(t,null,2)+` + `),0}}var vv=Me(require("path"),1),_6=require("os"),ir=require("fs");var yv=vv.default.join((0,_6.homedir)(),".gemini"),gi=vv.default.join(yv,"settings.json"),hi=vv.default.join(yv,"GEMINI.md"),Tp="claude-mem",mue=1e4,su={SessionStart:"context",BeforeAgent:"user-message",AfterAgent:"observation",BeforeTool:"observation",AfterTool:"observation",PreCompress:"summarize",Notification:"observation",SessionEnd:"session-complete"};function hue(t,e,r){let n=su[r];if(!n)throw new Error(`Unknown Gemini CLI event: ${r}`);let i=t.replace(/\\/g,"\\\\"),s=e.replace(/\\/g,"\\\\");return`"${i}" "${s}" hook gemini-cli ${n}`}function gue(t){return{matcher:"*",hooks:[{name:Tp,type:"command",command:t,timeout:mue}]}}function QT(){if(!(0,ir.existsSync)(gi))return{};let t=(0,ir.readFileSync)(gi,"utf-8");try{return JSON.parse(t)}catch{throw new Error(`Corrupt JSON in ${gi}, refusing to overwrite user settings`)}}function b6(t){(0,ir.mkdirSync)(yv,{recursive:!0}),(0,ir.writeFileSync)(gi,JSON.stringify(t,null,2)+` `)}function vue(t,e){let r={...t};r.hooks||(r.hooks={});for(let[n,i]of Object.entries(e)){let s=r.hooks[n]??[];for(let o of i){let a=s.findIndex(c=>c.hooks.some(u=>u.name===Tp));if(a>=0){let c=s[a],u=c.hooks.findIndex(l=>l.name===Tp);u>=0?c.hooks[u]=o.hooks[0]:c.hooks.push(o.hooks[0])}else s.push(o)}r.hooks[n]=s}return r}function yue(){let t="",r=`${t} # Memory Context from Past Sessions @@ -1022,14 +1022,15 @@ Context Injection: `),0}catch(r){return console.error(` Installation failed: ${r.message}`),1}}function bue(){console.log(` Uninstalling Claude-Mem Gemini CLI hooks... -`);try{if(!(0,ir.existsSync)(gi))return console.log(" No Gemini CLI settings found \u2014 nothing to uninstall."),0;let t=QT();if(!t.hooks)return console.log(" No hooks found in Gemini CLI settings \u2014 nothing to uninstall."),0;let e=0;for(let[r,n]of Object.entries(t.hooks)){let i=n.filter(s=>!s.hooks.some(o=>o.name===Tp));i.length0?t.hooks[r]=i:delete t.hooks[r]}if(Object.keys(t.hooks).length===0&&delete t.hooks,b6(t),console.log(` Removed ${e} claude-mem hook group(s) from ${gi}`),(0,ir.existsSync)(hi)){let r=(0,ir.readFileSync)(hi,"utf-8"),n=/\n?[\s\S]*?<\/claude-mem-context>\n?/;n.test(r)&&(r=r.replace(n,""),(0,ir.writeFileSync)(hi,r),console.log(` Removed context section from ${hi}`))}return console.log(` +`);try{if(!(0,ir.existsSync)(gi))return console.log(" No Gemini CLI settings found \u2014 nothing to uninstall."),0;let t=QT();if(!t.hooks)return console.log(" No hooks found in Gemini CLI settings \u2014 nothing to uninstall."),0;let e=0;for(let[r,n]of Object.entries(t.hooks)){let i=n.map(s=>{let o=s.hooks.filter(a=>a.name!==Tp);return e+=s.hooks.length-o.length,{...s,hooks:o}}).filter(s=>s.hooks.length>0);i.length>0?t.hooks[r]=i:delete t.hooks[r]}if(Object.keys(t.hooks).length===0&&delete t.hooks,b6(t),console.log(` Removed ${e} claude-mem hook(s) from ${gi}`),(0,ir.existsSync)(hi)){let r=(0,ir.readFileSync)(hi,"utf-8"),n=/\n?[\s\S]*?<\/claude-mem-context>\n?/;n.test(r)&&(r=r.replace(n,""),(0,ir.writeFileSync)(hi,r),console.log(` Removed context section from ${hi}`))}return console.log(` Uninstallation complete! `),console.log("Restart Gemini CLI to apply changes."),0}catch(t){return console.error(` Uninstallation failed: ${t.message}`),1}}function Sue(){if(console.log(` Claude-Mem Gemini CLI Hooks Status `),!(0,ir.existsSync)(gi))return console.log("Gemini CLI settings: Not found"),console.log(` Expected at: ${gi} `),console.log(`No hooks installed. Run: claude-mem install --ide gemini-cli -`),0;let t=QT();if(!t.hooks)return console.log(`Gemini CLI settings: Found, but no hooks configured +`),0;let t;try{t=QT()}catch(r){return console.log(`Gemini CLI settings: ${r.message} +`),0}if(!t.hooks)return console.log(`Gemini CLI settings: Found, but no hooks configured `),console.log(`No hooks installed. Run: claude-mem install --ide gemini-cli `),0;let e=[];for(let[r,n]of Object.entries(t.hooks))n.some(s=>s.hooks.some(o=>o.name===Tp))&&e.push(r);if(e.length===0)return console.log(`Gemini CLI settings: Found, but no claude-mem hooks `),console.log(`Run: claude-mem install --ide gemini-cli @@ -1049,7 +1050,7 @@ Examples: claude-mem gemini-cli uninstall # Remove hooks For more info: https://docs.claude-mem.ai/usage/gemini-provider - `),0}}ng();var w6=require("bun:sqlite");jt();ne();e$();var _v=class{db;constructor(e){e||(Mr(ur),e=Dd),this.db=new w6.Database(e),this.db.run("PRAGMA journal_mode = WAL"),this.ensureFTSTables()}ensureFTSTables(){if(!this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name LIKE '%_fts'").all().some(n=>n.name==="observations_fts"||n.name==="session_summaries_fts")){if(!this.isFts5Available()){b.warn("DB","FTS5 not available on this platform \u2014 skipping FTS table creation (search uses ChromaDB)");return}b.info("DB","Creating FTS5 tables");try{this.db.run(` + `),0}}ng();var w6=require("bun:sqlite");jt();se();e$();var _v=class{db;constructor(e){e||(Mr(ur),e=Dd),this.db=new w6.Database(e),this.db.run("PRAGMA journal_mode = WAL"),this.ensureFTSTables()}ensureFTSTables(){if(!this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name LIKE '%_fts'").all().some(n=>n.name==="observations_fts"||n.name==="session_summaries_fts")){if(!this.isFts5Available()){b.warn("DB","FTS5 not available on this platform \u2014 skipping FTS table creation (search uses ChromaDB)");return}b.info("DB","Creating FTS5 tables");try{this.db.run(` CREATE VIRTUAL TABLE IF NOT EXISTS observations_fts USING fts5( title, subtitle, @@ -1173,13 +1174,13 @@ For more info: https://docs.claude-mem.ai/usage/gemini-provider FROM user_prompts WHERE content_session_id = ? ORDER BY prompt_number ASC - `).all(e)}close(){this.db.close()}};rr();jt();ne();var bv=class{sessionStore=null;sessionSearch=null;chromaSync=null;async initialize(){this.sessionStore=new Es,this.sessionSearch=new _v,Ee.loadFromFile(qt).CLAUDE_MEM_CHROMA_ENABLED!=="false"?this.chromaSync=new Cc("claude-mem"):b.info("DB","Chroma disabled via CLAUDE_MEM_CHROMA_ENABLED=false, using SQLite-only search"),b.info("DB","Database initialized")}async close(){this.chromaSync&&(await this.chromaSync.close(),this.chromaSync=null),this.sessionStore&&(this.sessionStore.close(),this.sessionStore=null),this.sessionSearch&&(this.sessionSearch.close(),this.sessionSearch=null),b.info("DB","Database closed")}getSessionStore(){if(!this.sessionStore)throw new Error("Database not initialized");return this.sessionStore}getSessionSearch(){if(!this.sessionSearch)throw new Error("Database not initialized");return this.sessionSearch}getChromaSync(){return this.chromaSync}getSessionById(e){let r=this.getSessionStore().getSessionById(e);if(!r)throw new Error(`Session ${e} not found`);return r}};var P6=require("events");ne();ha();ne();var Sv=180*1e3,xv=class{constructor(e,r){this.store=e;this.events=r}async*createIterator(e){let{sessionDbId:r,signal:n,onIdleTimeout:i}=e,s=Date.now();for(;!n.aborted;)try{let o=this.store.claimNextMessage(r);if(o)s=Date.now(),yield this.toPendingMessageWithId(o);else if(!await this.waitForMessage(n,Sv)&&!n.aborted){let c=Date.now()-s;if(c>=Sv){b.info("SESSION","Idle timeout reached, triggering abort to kill subprocess",{sessionDbId:r,idleDurationMs:c,thresholdMs:Sv}),i?.();return}s=Date.now()}}catch(o){if(n.aborted)return;b.error("SESSION","Error in queue processor loop",{sessionDbId:r},o),await new Promise(a=>setTimeout(a,1e3))}}toPendingMessageWithId(e){return{...this.store.toPendingMessage(e),_persistentId:e.id,_originalTimestamp:e.created_at_epoch}}waitForMessage(e,r=Sv){return new Promise(n=>{let i,s=()=>{c(),n(!0)},o=()=>{c(),n(!1)},a=()=>{c(),n(!1)},c=()=>{i!==void 0&&clearTimeout(i),this.events.off("message",s),e.removeEventListener("abort",o)};this.events.once("message",s),e.addEventListener("abort",o,{once:!0}),i=setTimeout(a,r)})}};var Rp=require("child_process"),T6=require("util");ne();var $6=(0,T6.promisify)(Rp.exec);function wue(){return vt().getRegistry().getAll().filter(t=>t.type==="sdk").map(t=>{let e=vt().getRegistry().getRuntimeProcess(t.id);return e?{pid:t.pid,sessionDbId:Number(t.sessionId),spawnedAt:Date.parse(t.startedAt),process:e}:null}).filter(t=>t!==null)}function Eue(t,e,r){vt().registerProcess(`sdk:${e}:${t}`,{pid:t,type:"sdk",sessionId:e,startedAt:new Date().toISOString()},r),b.info("PROCESS",`Registered PID ${t} for session ${e}`,{pid:t,sessionDbId:e})}function wv(t){for(let e of vt().getRegistry().getByPid(t))e.type==="sdk"&&vt().unregisterProcess(e.id);b.debug("PROCESS",`Unregistered PID ${t}`,{pid:t}),I6()}function go(t){let e=wue().filter(r=>r.sessionDbId===t);return e.length>1&&b.warn("PROCESS",`Multiple processes found for session ${t}`,{count:e.length,pids:e.map(r=>r.pid)}),e[0]}function E6(){return vt().getRegistry().getAll().filter(t=>t.type==="sdk").length}var Ip=[];function I6(){let t=Ip.shift();t&&t()}var k6=10;async function R6(t,e=6e4){let r=E6();if(r>=k6)throw new Error(`Hard cap exceeded: ${r} processes in registry (cap=${k6}). Refusing to spawn more.`);if(!(r{let s=setTimeout(()=>{let a=Ip.indexOf(o);a>=0&&Ip.splice(a,1),i(new Error(`Timed out waiting for agent pool slot after ${e}ms`))},e),o=()=>{clearTimeout(s),E6(){n.once("exit",()=>c())}),s=new Promise(c=>{setTimeout(c,e)});if(await Promise.race([i,s]),n.exitCode!==null){wv(r);return}b.warn("PROCESS",`PID ${r} did not exit after ${e}ms, sending SIGKILL`,{pid:r,timeoutMs:e});try{n.kill("SIGKILL")}catch{}let o=new Promise(c=>{n.once("exit",()=>c())}),a=new Promise(c=>{setTimeout(c,1e3)});await Promise.race([o,a]),wv(r)}async function kue(){if(process.platform==="win32")return 0;let t=process.pid,e=0;try{let{stdout:r}=await $6('ps -eo pid,ppid,%cpu,etime,comm 2>/dev/null | grep "claude$" || true');for(let n of r.trim().split(` + `).all(e)}close(){this.db.close()}};rr();jt();se();var bv=class{sessionStore=null;sessionSearch=null;chromaSync=null;async initialize(){this.sessionStore=new Es,this.sessionSearch=new _v,Ee.loadFromFile(qt).CLAUDE_MEM_CHROMA_ENABLED!=="false"?this.chromaSync=new Cc("claude-mem"):b.info("DB","Chroma disabled via CLAUDE_MEM_CHROMA_ENABLED=false, using SQLite-only search"),b.info("DB","Database initialized")}async close(){this.chromaSync&&(await this.chromaSync.close(),this.chromaSync=null),this.sessionStore&&(this.sessionStore.close(),this.sessionStore=null),this.sessionSearch&&(this.sessionSearch.close(),this.sessionSearch=null),b.info("DB","Database closed")}getSessionStore(){if(!this.sessionStore)throw new Error("Database not initialized");return this.sessionStore}getSessionSearch(){if(!this.sessionSearch)throw new Error("Database not initialized");return this.sessionSearch}getChromaSync(){return this.chromaSync}getSessionById(e){let r=this.getSessionStore().getSessionById(e);if(!r)throw new Error(`Session ${e} not found`);return r}};var P6=require("events");se();ha();se();var Sv=180*1e3,xv=class{constructor(e,r){this.store=e;this.events=r}async*createIterator(e){let{sessionDbId:r,signal:n,onIdleTimeout:i}=e,s=Date.now();for(;!n.aborted;)try{let o=this.store.claimNextMessage(r);if(o)s=Date.now(),yield this.toPendingMessageWithId(o);else if(!await this.waitForMessage(n,Sv)&&!n.aborted){let c=Date.now()-s;if(c>=Sv){b.info("SESSION","Idle timeout reached, triggering abort to kill subprocess",{sessionDbId:r,idleDurationMs:c,thresholdMs:Sv}),i?.();return}s=Date.now()}}catch(o){if(n.aborted)return;b.error("SESSION","Error in queue processor loop",{sessionDbId:r},o),await new Promise(a=>setTimeout(a,1e3))}}toPendingMessageWithId(e){return{...this.store.toPendingMessage(e),_persistentId:e.id,_originalTimestamp:e.created_at_epoch}}waitForMessage(e,r=Sv){return new Promise(n=>{let i,s=()=>{c(),n(!0)},o=()=>{c(),n(!1)},a=()=>{c(),n(!1)},c=()=>{i!==void 0&&clearTimeout(i),this.events.off("message",s),e.removeEventListener("abort",o)};this.events.once("message",s),e.addEventListener("abort",o,{once:!0}),i=setTimeout(a,r)})}};var Rp=require("child_process"),T6=require("util");se();var $6=(0,T6.promisify)(Rp.exec);function wue(){return vt().getRegistry().getAll().filter(t=>t.type==="sdk").map(t=>{let e=vt().getRegistry().getRuntimeProcess(t.id);return e?{pid:t.pid,sessionDbId:Number(t.sessionId),spawnedAt:Date.parse(t.startedAt),process:e}:null}).filter(t=>t!==null)}function Eue(t,e,r){vt().registerProcess(`sdk:${e}:${t}`,{pid:t,type:"sdk",sessionId:e,startedAt:new Date().toISOString()},r),b.info("PROCESS",`Registered PID ${t} for session ${e}`,{pid:t,sessionDbId:e})}function wv(t){for(let e of vt().getRegistry().getByPid(t))e.type==="sdk"&&vt().unregisterProcess(e.id);b.debug("PROCESS",`Unregistered PID ${t}`,{pid:t}),I6()}function go(t){let e=wue().filter(r=>r.sessionDbId===t);return e.length>1&&b.warn("PROCESS",`Multiple processes found for session ${t}`,{count:e.length,pids:e.map(r=>r.pid)}),e[0]}function E6(){return vt().getRegistry().getAll().filter(t=>t.type==="sdk").length}var Ip=[];function I6(){let t=Ip.shift();t&&t()}var k6=10;async function R6(t,e=6e4){let r=E6();if(r>=k6)throw new Error(`Hard cap exceeded: ${r} processes in registry (cap=${k6}). Refusing to spawn more.`);if(!(r{let s=setTimeout(()=>{let a=Ip.indexOf(o);a>=0&&Ip.splice(a,1),i(new Error(`Timed out waiting for agent pool slot after ${e}ms`))},e),o=()=>{clearTimeout(s),E6(){n.once("exit",()=>c())}),s=new Promise(c=>{setTimeout(c,e)});if(await Promise.race([i,s]),n.exitCode!==null){wv(r);return}b.warn("PROCESS",`PID ${r} did not exit after ${e}ms, sending SIGKILL`,{pid:r,timeoutMs:e});try{n.kill("SIGKILL")}catch{}let o=new Promise(c=>{n.once("exit",()=>c())}),a=new Promise(c=>{setTimeout(c,1e3)});await Promise.race([o,a]),wv(r)}async function kue(){if(process.platform==="win32")return 0;let t=process.pid,e=0;try{let{stdout:r}=await $6('ps -eo pid,ppid,%cpu,etime,comm 2>/dev/null | grep "claude$" || true');for(let n of r.trim().split(` `)){if(!n)continue;let i=n.trim().split(/\s+/);if(i.length<5)continue;let[s,o,a,c]=i,u=parseInt(s,10),l=parseInt(o,10),d=parseFloat(a);if(l!==t||d>0)continue;let p=0,f=c.match(/^(\d+)-(\d+):(\d+):(\d+)$/),m=c.match(/^(\d+):(\d+):(\d+)$/),h=c.match(/^(\d+):(\d+)$/);if(f?p=parseInt(f[1],10)*24*60+parseInt(f[2],10)*60+parseInt(f[3],10):m?p=parseInt(m[1],10)*60+parseInt(m[2],10):h&&(p=parseInt(h[1],10)),p>=1){b.info("PROCESS",`Killing idle daemon child PID ${u} (idle ${p}m)`,{pid:u,minutes:p});try{process.kill(u,"SIGKILL"),e++}catch{}}}}catch{}return e}async function Tue(){if(process.platform==="win32")return 0;try{let{stdout:t}=await $6('ps -eo pid,ppid,args 2>/dev/null | grep -E "claude.*haiku|claude.*output-format" | grep -v grep'),e=0;for(let r of t.trim().split(` -`)){if(!r)continue;let n=r.trim().match(/^(\d+)\s+(\d+)/);if(n&&parseInt(n[2])===1){let i=parseInt(n[1]);b.warn("PROCESS",`Killing system orphan PID ${i}`,{pid:i});try{process.kill(i,"SIGKILL"),e++}catch{}}}return e}catch{return 0}}async function $ue(t){let e=0;for(let r of vt().getRegistry().getAll().filter(n=>n.type==="sdk")){let n=r.pid,i=Number(r.sessionId),s=vt().getRegistry().getRuntimeProcess(r.id);if(!t.has(i)){b.warn("PROCESS",`Killing orphan PID ${n} (session ${i} gone)`,{pid:n,sessionDbId:i});try{s?s.kill("SIGKILL"):process.kill(n,"SIGKILL"),e++}catch{}vt().unregisterProcess(r.id),I6()}}return e+=await Tue(),e+=await kue(),e}function O6(t){return e=>{vt().assertCanSpawn("claude sdk");let r=process.platform==="win32"&&e.command.endsWith(".cmd"),n=Ui(e.env??process.env),i=r?(0,Rp.spawn)("cmd.exe",["/d","/c",e.command,...e.args],{cwd:e.cwd,env:n,stdio:["pipe","pipe","pipe"],signal:e.signal,windowsHide:!0}):(0,Rp.spawn)(e.command,e.args,{cwd:e.cwd,env:n,stdio:["pipe","pipe","pipe"],signal:e.signal,windowsHide:!0});return i.stderr&&i.stderr.on("data",s=>{b.debug("SDK_SPAWN",`[session-${t}] stderr: ${s.toString().trim()}`)}),i.pid&&(Eue(i.pid,t,i),i.on("exit",(s,o)=>{s!==0&&b.warn("SDK_SPAWN",`[session-${t}] Claude process exited`,{code:s,signal:o,pid:i.pid}),i.pid&&wv(i.pid)})),{stdin:i.stdin,stdout:i.stdout,stderr:i.stderr,get killed(){return i.killed},get exitCode(){return i.exitCode},kill:i.kill.bind(i),on:i.on.bind(i),once:i.once.bind(i),off:i.off.bind(i)}}}function C6(t,e=30*1e3){let r=setInterval(async()=>{try{let n=t(),i=await $ue(n);i>0&&b.info("PROCESS",`Reaper cleaned up ${i} orphaned processes`,{killed:i})}catch(n){b.error("PROCESS","Reaper error",{},n)}},e);return()=>clearInterval(r)}var Ev=class t{dbManager;sessions=new Map;sessionQueues=new Map;onSessionDeletedCallback;pendingStore=null;constructor(e){this.dbManager=e}getPendingStore(){if(!this.pendingStore){let e=this.dbManager.getSessionStore();this.pendingStore=new $p(e.db,3)}return this.pendingStore}setOnSessionDeleted(e){this.onSessionDeletedCallback=e}initializeSession(e,r,n){b.debug("SESSION","initializeSession called",{sessionDbId:e,promptNumber:n,has_currentUserPrompt:!!r});let i=this.sessions.get(e);if(i){b.debug("SESSION","Returning cached session",{sessionDbId:e,contentSessionId:i.contentSessionId,lastPromptNumber:i.lastPromptNumber});let c=this.dbManager.getSessionById(e);return c.project&&c.project!==i.project&&(b.debug("SESSION","Updating project from database",{sessionDbId:e,oldProject:i.project,newProject:c.project}),i.project=c.project),r?(b.debug("SESSION","Updating userPrompt for continuation",{sessionDbId:e,promptNumber:n,oldPrompt:i.userPrompt.substring(0,80),newPrompt:r.substring(0,80)}),i.userPrompt=r,i.lastPromptNumber=n||i.lastPromptNumber):b.debug("SESSION","No currentUserPrompt provided for existing session",{sessionDbId:e,promptNumber:n,usingCachedPrompt:i.userPrompt.substring(0,80)}),i}let s=this.dbManager.getSessionById(e);b.debug("SESSION","Fetched session from database",{sessionDbId:e,content_session_id:s.content_session_id,memory_session_id:s.memory_session_id}),s.memory_session_id&&b.warn("SESSION","Discarding stale memory_session_id from previous worker instance (Issue #817)",{sessionDbId:e,staleMemorySessionId:s.memory_session_id,reason:"SDK context lost on worker restart - will capture new ID"});let o=r||s.user_prompt;r?b.debug("SESSION","Initializing session with fresh userPrompt",{sessionDbId:e,promptNumber:n,userPrompt:r.substring(0,80)}):b.debug("SESSION","No currentUserPrompt provided for new session, using database",{sessionDbId:e,promptNumber:n,dbPrompt:s.user_prompt.substring(0,80)}),i={sessionDbId:e,contentSessionId:s.content_session_id,memorySessionId:null,project:s.project,userPrompt:o,pendingMessages:[],abortController:new AbortController,generatorPromise:null,lastPromptNumber:n||this.dbManager.getSessionStore().getPromptNumberFromUserPrompts(s.content_session_id),startTime:Date.now(),cumulativeInputTokens:0,cumulativeOutputTokens:0,earliestPendingTimestamp:null,conversationHistory:[],currentProvider:null,consecutiveRestarts:0,processingMessageIds:[],lastGeneratorActivity:Date.now()},b.debug("SESSION","Creating new session object (memorySessionId cleared to prevent stale resume)",{sessionDbId:e,contentSessionId:s.content_session_id,dbMemorySessionId:s.memory_session_id||"(none in DB)",memorySessionId:"(cleared - will capture fresh from SDK)",lastPromptNumber:n||this.dbManager.getSessionStore().getPromptNumberFromUserPrompts(s.content_session_id)}),this.sessions.set(e,i);let a=new P6.EventEmitter;return this.sessionQueues.set(e,a),b.info("SESSION","Session initialized",{sessionId:e,project:i.project,contentSessionId:i.contentSessionId,queueDepth:0,hasGenerator:!1}),i}getSession(e){return this.sessions.get(e)}queueObservation(e,r){let n=this.sessions.get(e);n||(n=this.initializeSession(e));let i={type:"observation",tool_name:r.tool_name,tool_input:r.tool_input,tool_response:r.tool_response,prompt_number:r.prompt_number,cwd:r.cwd};try{let o=this.getPendingStore().enqueue(e,n.contentSessionId,i),a=this.getPendingStore().getPendingCount(e),c=b.formatTool(r.tool_name,r.tool_input);b.info("QUEUE",`ENQUEUED | sessionDbId=${e} | messageId=${o} | type=observation | tool=${c} | depth=${a}`,{sessionId:e})}catch(o){throw b.error("SESSION","Failed to persist observation to DB",{sessionId:e,tool:r.tool_name},o),o}this.sessionQueues.get(e)?.emit("message")}queueSummarize(e,r){let n=this.sessions.get(e);n||(n=this.initializeSession(e));let i={type:"summarize",last_assistant_message:r};try{let o=this.getPendingStore().enqueue(e,n.contentSessionId,i),a=this.getPendingStore().getPendingCount(e);b.info("QUEUE",`ENQUEUED | sessionDbId=${e} | messageId=${o} | type=summarize | depth=${a}`,{sessionId:e})}catch(o){throw b.error("SESSION","Failed to persist summarize to DB",{sessionId:e},o),o}this.sessionQueues.get(e)?.emit("message")}async deleteSession(e){let r=this.sessions.get(e);if(!r)return;let n=Date.now()-r.startTime;if(r.abortController.abort(),r.generatorPromise){let s=r.generatorPromise.catch(()=>{b.debug("SYSTEM","Generator already failed, cleaning up",{sessionId:r.sessionDbId})}),o=new Promise(a=>{AbortSignal.timeout(3e4).addEventListener("abort",()=>a(),{once:!0})});await Promise.race([s,o]).then(()=>{},()=>{b.warn("SESSION","Generator did not exit within 30s after abort, forcing cleanup (#1099)",{sessionDbId:e})})}let i=go(e);i&&i.process.exitCode===null&&(b.debug("SESSION",`Waiting for subprocess PID ${i.pid} to exit`,{sessionId:e,pid:i.pid}),await vo(i,5e3));try{await vt().getRegistry().reapSession(e)}catch(s){b.warn("SESSION","Supervisor reapSession failed (non-blocking)",{sessionId:e},s)}this.sessions.delete(e),this.sessionQueues.delete(e),b.info("SESSION","Session deleted",{sessionId:e,duration:`${(n/1e3).toFixed(1)}s`,project:r.project}),this.onSessionDeletedCallback&&this.onSessionDeletedCallback()}removeSessionImmediate(e){let r=this.sessions.get(e);r&&(this.sessions.delete(e),this.sessionQueues.delete(e),b.info("SESSION","Session removed from active sessions",{sessionId:e,project:r.project}),this.onSessionDeletedCallback&&this.onSessionDeletedCallback())}static MAX_SESSION_IDLE_MS=900*1e3;async reapStaleSessions(){let e=Date.now(),r=[];for(let[n,i]of this.sessions){if(i.generatorPromise||this.getPendingStore().getPendingCount(n)>0)continue;e-i.startTime>t.MAX_SESSION_IDLE_MS&&r.push(n)}for(let n of r)b.warn("SESSION",`Reaping stale session ${n} (no activity for >${Math.round(t.MAX_SESSION_IDLE_MS/6e4)}m)`,{sessionDbId:n}),await this.deleteSession(n);return r.length}async shutdownAll(){let e=Array.from(this.sessions.keys());await Promise.all(e.map(r=>this.deleteSession(r)))}hasPendingMessages(){return this.getTotalQueueDepth()>0}getActiveSessionCount(){return this.sessions.size}getTotalQueueDepth(){let e=0;for(let r of this.sessions.values())e+=this.getPendingStore().getPendingCount(r.sessionDbId);return e}getTotalActiveWork(){return this.getTotalQueueDepth()}isAnySessionProcessing(){return this.getTotalQueueDepth()>0}async*getMessageIterator(e){let r=this.sessions.get(e);r||(r=this.initializeSession(e));let n=this.sessionQueues.get(e);if(!n)throw new Error(`No emitter for session ${e}`);let i=new xv(this.getPendingStore(),n);for await(let s of i.createIterator({sessionDbId:e,signal:r.abortController.signal,onIdleTimeout:()=>{b.info("SESSION","Triggering abort due to idle timeout to kill subprocess",{sessionDbId:e}),r.idleTimedOut=!0,r.abortController.abort()}}))r.earliestPendingTimestamp===null?r.earliestPendingTimestamp=s._originalTimestamp:r.earliestPendingTimestamp=Math.min(r.earliestPendingTimestamp,s._originalTimestamp),r.lastGeneratorActivity=Date.now(),yield s}getPendingMessageStore(){return this.getPendingStore()}};ne();var kv=class{sseClients=new Set;addClient(e){this.sseClients.add(e),b.debug("WORKER","Client connected",{total:this.sseClients.size}),e.on("close",()=>{this.removeClient(e)}),this.sendToClient(e,{type:"connected",timestamp:Date.now()})}removeClient(e){this.sseClients.delete(e),b.debug("WORKER","Client disconnected",{total:this.sseClients.size})}broadcast(e){if(this.sseClients.size===0){b.debug("WORKER","SSE broadcast skipped (no clients)",{eventType:e.type});return}let r={...e,timestamp:Date.now()},n=`data: ${JSON.stringify(r)} +`)){if(!r)continue;let n=r.trim().match(/^(\d+)\s+(\d+)/);if(n&&parseInt(n[2])===1){let i=parseInt(n[1]);b.warn("PROCESS",`Killing system orphan PID ${i}`,{pid:i});try{process.kill(i,"SIGKILL"),e++}catch{}}}return e}catch{return 0}}async function $ue(t){let e=0;for(let r of vt().getRegistry().getAll().filter(n=>n.type==="sdk")){let n=r.pid,i=Number(r.sessionId),s=vt().getRegistry().getRuntimeProcess(r.id);if(!t.has(i)){b.warn("PROCESS",`Killing orphan PID ${n} (session ${i} gone)`,{pid:n,sessionDbId:i});try{s?s.kill("SIGKILL"):process.kill(n,"SIGKILL"),e++}catch{}vt().unregisterProcess(r.id),I6()}}return e+=await Tue(),e+=await kue(),e}function O6(t){return e=>{vt().assertCanSpawn("claude sdk");let r=process.platform==="win32"&&e.command.endsWith(".cmd"),n=Ui(e.env??process.env),i=r?(0,Rp.spawn)("cmd.exe",["/d","/c",e.command,...e.args],{cwd:e.cwd,env:n,stdio:["pipe","pipe","pipe"],signal:e.signal,windowsHide:!0}):(0,Rp.spawn)(e.command,e.args,{cwd:e.cwd,env:n,stdio:["pipe","pipe","pipe"],signal:e.signal,windowsHide:!0});return i.stderr&&i.stderr.on("data",s=>{b.debug("SDK_SPAWN",`[session-${t}] stderr: ${s.toString().trim()}`)}),i.pid&&(Eue(i.pid,t,i),i.on("exit",(s,o)=>{s!==0&&b.warn("SDK_SPAWN",`[session-${t}] Claude process exited`,{code:s,signal:o,pid:i.pid}),i.pid&&wv(i.pid)})),{stdin:i.stdin,stdout:i.stdout,stderr:i.stderr,get killed(){return i.killed},get exitCode(){return i.exitCode},kill:i.kill.bind(i),on:i.on.bind(i),once:i.once.bind(i),off:i.off.bind(i)}}}function C6(t,e=30*1e3){let r=setInterval(async()=>{try{let n=t(),i=await $ue(n);i>0&&b.info("PROCESS",`Reaper cleaned up ${i} orphaned processes`,{killed:i})}catch(n){b.error("PROCESS","Reaper error",{},n)}},e);return()=>clearInterval(r)}var Ev=class t{dbManager;sessions=new Map;sessionQueues=new Map;onSessionDeletedCallback;pendingStore=null;constructor(e){this.dbManager=e}getPendingStore(){if(!this.pendingStore){let e=this.dbManager.getSessionStore();this.pendingStore=new $p(e.db,3)}return this.pendingStore}setOnSessionDeleted(e){this.onSessionDeletedCallback=e}initializeSession(e,r,n){b.debug("SESSION","initializeSession called",{sessionDbId:e,promptNumber:n,has_currentUserPrompt:!!r});let i=this.sessions.get(e);if(i){b.debug("SESSION","Returning cached session",{sessionDbId:e,contentSessionId:i.contentSessionId,lastPromptNumber:i.lastPromptNumber});let c=this.dbManager.getSessionById(e);return c.project&&c.project!==i.project&&(b.debug("SESSION","Updating project from database",{sessionDbId:e,oldProject:i.project,newProject:c.project}),i.project=c.project),r?(b.debug("SESSION","Updating userPrompt for continuation",{sessionDbId:e,promptNumber:n,oldPrompt:i.userPrompt.substring(0,80),newPrompt:r.substring(0,80)}),i.userPrompt=r,i.lastPromptNumber=n||i.lastPromptNumber):b.debug("SESSION","No currentUserPrompt provided for existing session",{sessionDbId:e,promptNumber:n,usingCachedPrompt:i.userPrompt.substring(0,80)}),i}let s=this.dbManager.getSessionById(e);b.debug("SESSION","Fetched session from database",{sessionDbId:e,content_session_id:s.content_session_id,memory_session_id:s.memory_session_id}),s.memory_session_id&&b.warn("SESSION","Discarding stale memory_session_id from previous worker instance (Issue #817)",{sessionDbId:e,staleMemorySessionId:s.memory_session_id,reason:"SDK context lost on worker restart - will capture new ID"});let o=r||s.user_prompt;r?b.debug("SESSION","Initializing session with fresh userPrompt",{sessionDbId:e,promptNumber:n,userPrompt:r.substring(0,80)}):b.debug("SESSION","No currentUserPrompt provided for new session, using database",{sessionDbId:e,promptNumber:n,dbPrompt:s.user_prompt.substring(0,80)}),i={sessionDbId:e,contentSessionId:s.content_session_id,memorySessionId:null,project:s.project,userPrompt:o,pendingMessages:[],abortController:new AbortController,generatorPromise:null,lastPromptNumber:n||this.dbManager.getSessionStore().getPromptNumberFromUserPrompts(s.content_session_id),startTime:Date.now(),cumulativeInputTokens:0,cumulativeOutputTokens:0,earliestPendingTimestamp:null,conversationHistory:[],currentProvider:null,consecutiveRestarts:0,processingMessageIds:[],lastGeneratorActivity:Date.now()},b.debug("SESSION","Creating new session object (memorySessionId cleared to prevent stale resume)",{sessionDbId:e,contentSessionId:s.content_session_id,dbMemorySessionId:s.memory_session_id||"(none in DB)",memorySessionId:"(cleared - will capture fresh from SDK)",lastPromptNumber:n||this.dbManager.getSessionStore().getPromptNumberFromUserPrompts(s.content_session_id)}),this.sessions.set(e,i);let a=new P6.EventEmitter;return this.sessionQueues.set(e,a),b.info("SESSION","Session initialized",{sessionId:e,project:i.project,contentSessionId:i.contentSessionId,queueDepth:0,hasGenerator:!1}),i}getSession(e){return this.sessions.get(e)}queueObservation(e,r){let n=this.sessions.get(e);n||(n=this.initializeSession(e));let i={type:"observation",tool_name:r.tool_name,tool_input:r.tool_input,tool_response:r.tool_response,prompt_number:r.prompt_number,cwd:r.cwd};try{let o=this.getPendingStore().enqueue(e,n.contentSessionId,i),a=this.getPendingStore().getPendingCount(e),c=b.formatTool(r.tool_name,r.tool_input);b.info("QUEUE",`ENQUEUED | sessionDbId=${e} | messageId=${o} | type=observation | tool=${c} | depth=${a}`,{sessionId:e})}catch(o){throw b.error("SESSION","Failed to persist observation to DB",{sessionId:e,tool:r.tool_name},o),o}this.sessionQueues.get(e)?.emit("message")}queueSummarize(e,r){let n=this.sessions.get(e);n||(n=this.initializeSession(e));let i={type:"summarize",last_assistant_message:r};try{let o=this.getPendingStore().enqueue(e,n.contentSessionId,i),a=this.getPendingStore().getPendingCount(e);b.info("QUEUE",`ENQUEUED | sessionDbId=${e} | messageId=${o} | type=summarize | depth=${a}`,{sessionId:e})}catch(o){throw b.error("SESSION","Failed to persist summarize to DB",{sessionId:e},o),o}this.sessionQueues.get(e)?.emit("message")}async deleteSession(e){let r=this.sessions.get(e);if(!r)return;let n=Date.now()-r.startTime;if(r.abortController.abort(),r.generatorPromise){let s=r.generatorPromise.catch(()=>{b.debug("SYSTEM","Generator already failed, cleaning up",{sessionId:r.sessionDbId})}),o=new Promise(a=>{AbortSignal.timeout(3e4).addEventListener("abort",()=>a(),{once:!0})});await Promise.race([s,o]).then(()=>{},()=>{b.warn("SESSION","Generator did not exit within 30s after abort, forcing cleanup (#1099)",{sessionDbId:e})})}let i=go(e);i&&i.process.exitCode===null&&(b.debug("SESSION",`Waiting for subprocess PID ${i.pid} to exit`,{sessionId:e,pid:i.pid}),await vo(i,5e3));try{await vt().getRegistry().reapSession(e)}catch(s){b.warn("SESSION","Supervisor reapSession failed (non-blocking)",{sessionId:e},s)}this.sessions.delete(e),this.sessionQueues.delete(e),b.info("SESSION","Session deleted",{sessionId:e,duration:`${(n/1e3).toFixed(1)}s`,project:r.project}),this.onSessionDeletedCallback&&this.onSessionDeletedCallback()}removeSessionImmediate(e){let r=this.sessions.get(e);r&&(this.sessions.delete(e),this.sessionQueues.delete(e),b.info("SESSION","Session removed from active sessions",{sessionId:e,project:r.project}),this.onSessionDeletedCallback&&this.onSessionDeletedCallback())}static MAX_SESSION_IDLE_MS=900*1e3;async reapStaleSessions(){let e=Date.now(),r=[];for(let[n,i]of this.sessions){if(i.generatorPromise||this.getPendingStore().getPendingCount(n)>0)continue;e-i.startTime>t.MAX_SESSION_IDLE_MS&&r.push(n)}for(let n of r)b.warn("SESSION",`Reaping stale session ${n} (no activity for >${Math.round(t.MAX_SESSION_IDLE_MS/6e4)}m)`,{sessionDbId:n}),await this.deleteSession(n);return r.length}async shutdownAll(){let e=Array.from(this.sessions.keys());await Promise.all(e.map(r=>this.deleteSession(r)))}hasPendingMessages(){return this.getTotalQueueDepth()>0}getActiveSessionCount(){return this.sessions.size}getTotalQueueDepth(){let e=0;for(let r of this.sessions.values())e+=this.getPendingStore().getPendingCount(r.sessionDbId);return e}getTotalActiveWork(){return this.getTotalQueueDepth()}isAnySessionProcessing(){return this.getTotalQueueDepth()>0}async*getMessageIterator(e){let r=this.sessions.get(e);r||(r=this.initializeSession(e));let n=this.sessionQueues.get(e);if(!n)throw new Error(`No emitter for session ${e}`);let i=new xv(this.getPendingStore(),n);for await(let s of i.createIterator({sessionDbId:e,signal:r.abortController.signal,onIdleTimeout:()=>{b.info("SESSION","Triggering abort due to idle timeout to kill subprocess",{sessionDbId:e}),r.idleTimedOut=!0,r.abortController.abort()}}))r.earliestPendingTimestamp===null?r.earliestPendingTimestamp=s._originalTimestamp:r.earliestPendingTimestamp=Math.min(r.earliestPendingTimestamp,s._originalTimestamp),r.lastGeneratorActivity=Date.now(),yield s}getPendingMessageStore(){return this.getPendingStore()}};se();var kv=class{sseClients=new Set;addClient(e){this.sseClients.add(e),b.debug("WORKER","Client connected",{total:this.sseClients.size}),e.on("close",()=>{this.removeClient(e)}),this.sendToClient(e,{type:"connected",timestamp:Date.now()})}removeClient(e){this.sseClients.delete(e),b.debug("WORKER","Client disconnected",{total:this.sseClients.size})}broadcast(e){if(this.sseClients.size===0){b.debug("WORKER","SSE broadcast skipped (no clients)",{eventType:e.type});return}let r={...e,timestamp:Date.now()},n=`data: ${JSON.stringify(r)} `;b.debug("WORKER","SSE broadcast sent",{eventType:e.type,clients:this.sseClients.size});for(let i of this.sseClients)i.write(n)}getClientCount(){return this.sseClients.size}sendToClient(e,r){let n=`data: ${JSON.stringify(r)} -`;e.write(n)}};var X$=require("child_process"),p9=require("os"),f9=Me(require("path"),1);ne();ne();function au(t,e,r,n){return`${n.prompts.system_identity} +`;e.write(n)}};var X$=require("child_process"),p9=require("os"),f9=Me(require("path"),1);se();se();function au(t,e,r,n){return`${n.prompts.system_identity} ${r} @@ -1319,7 +1320,7 @@ ${n.prompts.format_examples} ${n.prompts.footer} -${n.prompts.header_memory_continued}`}rr();jt();Qr();var t$=["429","500","502","503","ECONNREFUSED","ETIMEDOUT","fetch failed"];ne();ne();Qr();function N6(t,e){let r=[],n=/([\s\S]*?)<\/observation>/g,i;for(;(i=n.exec(t))!==null;){let s=i[1],o=Ji(s,"type"),a=Ji(s,"title"),c=Ji(s,"subtitle"),u=Ji(s,"narrative"),l=$v(s,"facts","fact"),d=$v(s,"concepts","concept"),p=$v(s,"files_read","file"),f=$v(s,"files_modified","file"),h=He.getInstance().getActiveMode().observation_types.map(_=>_.id),g=h[0],v=g;o?h.includes(o.trim())?v=o.trim():b.error("PARSER",`Invalid observation type: ${o}, using "${g}"`,{correlationId:e}):b.error("PARSER",`Observation missing type field, using "${g}"`,{correlationId:e});let S=d.filter(_=>_!==v);S.length!==d.length&&b.error("PARSER","Removed observation type from concepts array",{correlationId:e,type:v,originalConcepts:d,cleanedConcepts:S}),r.push({type:v,title:a,subtitle:c,facts:l,narrative:u,concepts:S,files_read:p,files_modified:f})}return r}function M6(t,e){let n=//.exec(t);if(n)return b.info("PARSER","Summary skipped",{sessionId:e,reason:n[1]}),null;let s=/([\s\S]*?)<\/summary>/.exec(t);if(!s)return//.test(t)&&b.warn("PARSER","Summary response contained tags instead of \u2014 prompt conditioning may need strengthening",{sessionId:e}),null;let o=s[1],a=Ji(o,"request"),c=Ji(o,"investigated"),u=Ji(o,"learned"),l=Ji(o,"completed"),d=Ji(o,"next_steps"),p=Ji(o,"notes");return{request:a,investigated:c,learned:u,completed:l,next_steps:d,notes:p}}function Ji(t,e){let n=new RegExp(`<${e}>([\\s\\S]*?)`).exec(t);if(!n)return null;let i=n[1].trim();return i===""?null:i}function $v(t,e,r){let n=[],s=new RegExp(`<${e}>([\\s\\S]*?)`).exec(t);if(!s)return n;let o=s[1],a=new RegExp(`<${r}>([\\s\\S]*?)`,"g"),c;for(;(c=a.exec(o))!==null;){let u=c[1].trim();u&&n.push(u)}return n}var yi=require("fs"),Zt=Me(require("path"),1),j6=Me(require("os"),1);ne();ga();rr();Dr();var Iue=Zt.default.join(j6.default.homedir(),".claude-mem","settings.json");function Rue(t){let e=t.split(Zt.default.sep).filter(r=>r&&r!=="."&&r!=="..");for(let r=1;r([\s\S]*?)<\/observation>/g,i;for(;(i=n.exec(t))!==null;){let s=i[1],o=Ji(s,"type"),a=Ji(s,"title"),c=Ji(s,"subtitle"),u=Ji(s,"narrative"),l=$v(s,"facts","fact"),d=$v(s,"concepts","concept"),p=$v(s,"files_read","file"),f=$v(s,"files_modified","file"),h=He.getInstance().getActiveMode().observation_types.map(_=>_.id),g=h[0],v=g;o?h.includes(o.trim())?v=o.trim():b.error("PARSER",`Invalid observation type: ${o}, using "${g}"`,{correlationId:e}):b.error("PARSER",`Observation missing type field, using "${g}"`,{correlationId:e});let S=d.filter(_=>_!==v);S.length!==d.length&&b.error("PARSER","Removed observation type from concepts array",{correlationId:e,type:v,originalConcepts:d,cleanedConcepts:S}),r.push({type:v,title:a,subtitle:c,facts:l,narrative:u,concepts:S,files_read:p,files_modified:f})}return r}function M6(t,e){let n=//.exec(t);if(n)return b.info("PARSER","Summary skipped",{sessionId:e,reason:n[1]}),null;let s=/([\s\S]*?)<\/summary>/.exec(t);if(!s)return//.test(t)&&b.warn("PARSER","Summary response contained tags instead of \u2014 prompt conditioning may need strengthening",{sessionId:e}),null;let o=s[1],a=Ji(o,"request"),c=Ji(o,"investigated"),u=Ji(o,"learned"),l=Ji(o,"completed"),d=Ji(o,"next_steps"),p=Ji(o,"notes");return{request:a,investigated:c,learned:u,completed:l,next_steps:d,notes:p}}function Ji(t,e){let n=new RegExp(`<${e}>([\\s\\S]*?)`).exec(t);if(!n)return null;let i=n[1].trim();return i===""?null:i}function $v(t,e,r){let n=[],s=new RegExp(`<${e}>([\\s\\S]*?)`).exec(t);if(!s)return n;let o=s[1],a=new RegExp(`<${r}>([\\s\\S]*?)`,"g"),c;for(;(c=a.exec(o))!==null;){let u=c[1].trim();u&&n.push(u)}return n}var yi=require("fs"),Zt=Me(require("path"),1),j6=Me(require("os"),1);se();ga();rr();Dr();var Iue=Zt.default.join(j6.default.homedir(),".claude-mem","settings.json");function Rue(t){let e=t.split(Zt.default.sep).filter(r=>r&&r!=="."&&r!=="..");for(let r=1;r_.assign((0,i._)`${y}[${x}]`,w))}function m(_,y,x,w=o.Correct){let E=w===o.Correct?i.operators.EQ:i.operators.NEQ,T;switch(_){case"null":return(0,i._)`${y} ${E} null`;case"array":T=(0,i._)`Array.isArray(${y})`;break;case"object":T=(0,i._)`${y} && typeof ${y} == "object" && !Array.isArray(${y})`;break;case"integer":T=I((0,i._)`!(${y} % 1) && !isNaN(${y})`);break;case"number":T=I();break;default:return(0,i._)`typeof ${y} ${E} ${_}`}return w===o.Correct?T:(0,i.not)(T);function I(A=i.nil){return(0,i.and)((0,i._)`typeof ${y} == "number"`,A,x?(0,i._)`isFinite(${y})`:i.nil)}}t.checkDataType=m;function h(_,y,x,w){if(_.length===1)return m(_[0],y,x,w);let E,T=(0,s.toHash)(_);if(T.array&&T.object){let I=(0,i._)`typeof ${y} != "object"`;E=T.null?I:(0,i._)`!${y} || ${I}`,delete T.null,delete T.array,delete T.object}else E=i.nil;T.number&&delete T.integer;for(let I in T)E=(0,i.and)(E,m(I,y,x,w));return E}t.checkDataTypes=h;var g={message:({schema:_})=>`must be ${_}`,params:({schema:_,schemaValue:y})=>typeof _=="string"?(0,i._)`{type: ${_}}`:(0,i._)`{type: ${y}}`};function v(_){let y=S(_);(0,n.reportError)(y,g)}t.reportTypeError=v;function S(_){let{gen:y,data:x,schema:w}=_,E=(0,s.schemaRefOrVal)(_,w,"type");return{gen:y,keyword:"type",data:x,schema:w.type,schemaCode:E,schemaValue:E,parentSchema:w,params:{},it:_}}}),Gue=re(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.assignDefaults=void 0;var e=Ze(),r=at();function n(s,o){let{properties:a,items:c}=s.schema;if(o==="object"&&a)for(let u in a)i(s,u,a[u].default);else o==="array"&&Array.isArray(c)&&c.forEach((u,l)=>i(s,l,u.default))}t.assignDefaults=n;function i(s,o,a){let{gen:c,compositeRule:u,data:l,opts:d}=s;if(a===void 0)return;let p=(0,e._)`${l}${(0,e.getProperty)(o)}`;if(u){(0,r.checkStrictMode)(s,`default is ignored for: ${p}`);return}let f=(0,e._)`${p} === undefined`;d.useDefaults==="empty"&&(f=(0,e._)`${f} || ${p} === null || ${p} === ""`),c.if(f,(0,e._)`${p} = ${(0,e.stringify)(a)}`)}}),wi=re(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.validateUnion=t.validateArray=t.usePattern=t.callValidateCode=t.schemaProperties=t.allSchemaProperties=t.noPropertyInData=t.propertyInData=t.isOwnProperty=t.hasPropFunc=t.reportMissingProp=t.checkMissingProp=t.checkReportMissingProp=void 0;var e=Ze(),r=at(),n=xo(),i=at();function s(_,y){let{gen:x,data:w,it:E}=_;x.if(d(x,w,y,E.opts.ownProperties),()=>{_.setParams({missingProperty:(0,e._)`${y}`},!0),_.error()})}t.checkReportMissingProp=s;function o({gen:_,data:y,it:{opts:x}},w,E){return(0,e.or)(...w.map(T=>(0,e.and)(d(_,y,T,x.ownProperties),(0,e._)`${E} = ${T}`)))}t.checkMissingProp=o;function a(_,y){_.setParams({missingProperty:y},!0),_.error()}t.reportMissingProp=a;function c(_){return _.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,e._)`Object.prototype.hasOwnProperty`})}t.hasPropFunc=c;function u(_,y,x){return(0,e._)`${c(_)}.call(${y}, ${x})`}t.isOwnProperty=u;function l(_,y,x,w){let E=(0,e._)`${y}${(0,e.getProperty)(x)} !== undefined`;return w?(0,e._)`${E} && ${u(_,y,x)}`:E}t.propertyInData=l;function d(_,y,x,w){let E=(0,e._)`${y}${(0,e.getProperty)(x)} === undefined`;return w?(0,e.or)(E,(0,e.not)(u(_,y,x))):E}t.noPropertyInData=d;function p(_){return _?Object.keys(_).filter(y=>y!=="__proto__"):[]}t.allSchemaProperties=p;function f(_,y){return p(y).filter(x=>!(0,r.alwaysValidSchema)(_,y[x]))}t.schemaProperties=f;function m({schemaCode:_,data:y,it:{gen:x,topSchemaRef:w,schemaPath:E,errorPath:T},it:I},A,N,U){let V=U?(0,e._)`${_}, ${y}, ${w}${E}`:y,j=[[n.default.instancePath,(0,e.strConcat)(n.default.instancePath,T)],[n.default.parentData,I.parentData],[n.default.parentDataProperty,I.parentDataProperty],[n.default.rootData,n.default.rootData]];I.opts.dynamicRef&&j.push([n.default.dynamicAnchors,n.default.dynamicAnchors]);let ae=(0,e._)`${V}, ${x.object(...j)}`;return N!==e.nil?(0,e._)`${A}.call(${N}, ${ae})`:(0,e._)`${A}(${ae})`}t.callValidateCode=m;var h=(0,e._)`new RegExp`;function g({gen:_,it:{opts:y}},x){let w=y.unicodeRegExp?"u":"",{regExp:E}=y.code,T=E(x,w);return _.scopeValue("pattern",{key:T.toString(),ref:T,code:(0,e._)`${E.code==="new RegExp"?h:(0,i.useFunc)(_,E)}(${x}, ${w})`})}t.usePattern=g;function v(_){let{gen:y,data:x,keyword:w,it:E}=_,T=y.name("valid");if(E.allErrors){let A=y.let("valid",!0);return I(()=>y.assign(A,!1)),A}return y.var(T,!0),I(()=>y.break()),T;function I(A){let N=y.const("len",(0,e._)`${x}.length`);y.forRange("i",0,N,U=>{_.subschema({keyword:w,dataProp:U,dataPropType:r.Type.Num},T),y.if((0,e.not)(T),A)})}}t.validateArray=v;function S(_){let{gen:y,schema:x,keyword:w,it:E}=_;if(!Array.isArray(x))throw new Error("ajv implementation error");if(x.some(N=>(0,r.alwaysValidSchema)(E,N))&&!E.opts.unevaluated)return;let I=y.let("valid",!1),A=y.name("_valid");y.block(()=>x.forEach((N,U)=>{let V=_.subschema({keyword:w,schemaProp:U,compositeRule:!0},A);y.assign(I,(0,e._)`${I} || ${A}`),_.mergeValidEvaluated(V,A)||y.if((0,e.not)(I))})),_.result(I,()=>_.reset(),()=>_.error(!0))}t.validateUnion=S}),Wue=re(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.validateKeywordUsage=t.validSchemaType=t.funcKeywordCode=t.macroKeywordCode=void 0;var e=Ze(),r=xo(),n=wi(),i=Hv();function s(f,m){let{gen:h,keyword:g,schema:v,parentSchema:S,it:_}=f,y=m.macro.call(_.self,v,S,_),x=l(h,g,y);_.opts.validateSchema!==!1&&_.self.validateSchema(y,!0);let w=h.name("valid");f.subschema({schema:y,schemaPath:e.nil,errSchemaPath:`${_.errSchemaPath}/${g}`,topSchemaRef:x,compositeRule:!0},w),f.pass(w,()=>f.error(!0))}t.macroKeywordCode=s;function o(f,m){var h;let{gen:g,keyword:v,schema:S,parentSchema:_,$data:y,it:x}=f;u(x,m);let w=!y&&m.compile?m.compile.call(x.self,S,_,x):m.validate,E=l(g,v,w),T=g.let("valid");f.block$data(T,I),f.ok((h=m.valid)!==null&&h!==void 0?h:T);function I(){if(m.errors===!1)U(),m.modifying&&a(f),V(()=>f.error());else{let j=m.async?A():N();m.modifying&&a(f),V(()=>c(f,j))}}function A(){let j=g.let("ruleErrs",null);return g.try(()=>U((0,e._)`await `),ae=>g.assign(T,!1).if((0,e._)`${ae} instanceof ${x.ValidationError}`,()=>g.assign(j,(0,e._)`${ae}.errors`),()=>g.throw(ae))),j}function N(){let j=(0,e._)`${E}.errors`;return g.assign(j,null),U(e.nil),j}function U(j=m.async?(0,e._)`await `:e.nil){let ae=x.opts.passContext?r.default.this:r.default.self,Ne=!("compile"in m&&!y||m.schema===!1);g.assign(T,(0,e._)`${j}${(0,n.callValidateCode)(f,E,ae,Ne)}`,m.modifying)}function V(j){var ae;g.if((0,e.not)((ae=m.valid)!==null&&ae!==void 0?ae:T),j)}}t.funcKeywordCode=o;function a(f){let{gen:m,data:h,it:g}=f;m.if(g.parentData,()=>m.assign(h,(0,e._)`${g.parentData}[${g.parentDataProperty}]`))}function c(f,m){let{gen:h}=f;h.if((0,e._)`Array.isArray(${m})`,()=>{h.assign(r.default.vErrors,(0,e._)`${r.default.vErrors} === null ? ${m} : ${r.default.vErrors}.concat(${m})`).assign(r.default.errors,(0,e._)`${r.default.vErrors}.length`),(0,i.extendErrors)(f)},()=>f.error())}function u({schemaEnv:f},m){if(m.async&&!f.$async)throw new Error("async keyword in sync schema")}function l(f,m,h){if(h===void 0)throw new Error(`keyword "${m}" failed to compile`);return f.scopeValue("keyword",typeof h=="function"?{ref:h}:{ref:h,code:(0,e.stringify)(h)})}function d(f,m,h=!1){return!m.length||m.some(g=>g==="array"?Array.isArray(f):g==="object"?f&&typeof f=="object"&&!Array.isArray(f):typeof f==g||h&&typeof f>"u")}t.validSchemaType=d;function p({schema:f,opts:m,self:h,errSchemaPath:g},v,S){if(Array.isArray(v.keyword)?!v.keyword.includes(S):v.keyword!==S)throw new Error("ajv implementation error");let _=v.dependencies;if(_?.some(y=>!Object.prototype.hasOwnProperty.call(f,y)))throw new Error(`parent schema must have dependencies of ${S}: ${_.join(",")}`);if(v.validateSchema&&!v.validateSchema(f[S])){let x=`keyword "${S}" value is invalid at path "${g}": `+h.errorsText(v.validateSchema.errors);if(m.validateSchema==="log")h.logger.error(x);else throw new Error(x)}}t.validateKeywordUsage=p}),Vue=re(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.extendSubschemaMode=t.extendSubschemaData=t.getSubschema=void 0;var e=Ze(),r=at();function n(o,{keyword:a,schemaProp:c,schema:u,schemaPath:l,errSchemaPath:d,topSchemaRef:p}){if(a!==void 0&&u!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(a!==void 0){let f=o.schema[a];return c===void 0?{schema:f,schemaPath:(0,e._)`${o.schemaPath}${(0,e.getProperty)(a)}`,errSchemaPath:`${o.errSchemaPath}/${a}`}:{schema:f[c],schemaPath:(0,e._)`${o.schemaPath}${(0,e.getProperty)(a)}${(0,e.getProperty)(c)}`,errSchemaPath:`${o.errSchemaPath}/${a}/${(0,r.escapeFragment)(c)}`}}if(u!==void 0){if(l===void 0||d===void 0||p===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:u,schemaPath:l,topSchemaRef:p,errSchemaPath:d}}throw new Error('either "keyword" or "schema" must be passed')}t.getSubschema=n;function i(o,a,{dataProp:c,dataPropType:u,data:l,dataTypes:d,propertyName:p}){if(l!==void 0&&c!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:f}=a;if(c!==void 0){let{errorPath:h,dataPathArr:g,opts:v}=a,S=f.let("data",(0,e._)`${a.data}${(0,e.getProperty)(c)}`,!0);m(S),o.errorPath=(0,e.str)`${h}${(0,r.getErrorPath)(c,u,v.jsPropertySyntax)}`,o.parentDataProperty=(0,e._)`${c}`,o.dataPathArr=[...g,o.parentDataProperty]}if(l!==void 0){let h=l instanceof e.Name?l:f.let("data",l,!0);m(h),p!==void 0&&(o.propertyName=p)}d&&(o.dataTypes=d);function m(h){o.data=h,o.dataLevel=a.dataLevel+1,o.dataTypes=[],a.definedProperties=new Set,o.parentData=a.data,o.dataNames=[...a.dataNames,h]}}t.extendSubschemaData=i;function s(o,{jtdDiscriminator:a,jtdMetadata:c,compositeRule:u,createErrors:l,allErrors:d}){u!==void 0&&(o.compositeRule=u),l!==void 0&&(o.createErrors=l),d!==void 0&&(o.allErrors=d),o.jtdDiscriminator=a,o.jtdMetadata=c}t.extendSubschemaMode=s}),bF=re((t,e)=>{e.exports=function r(n,i){if(n===i)return!0;if(n&&i&&typeof n=="object"&&typeof i=="object"){if(n.constructor!==i.constructor)return!1;var s,o,a;if(Array.isArray(n)){if(s=n.length,s!=i.length)return!1;for(o=s;o--!==0;)if(!r(n[o],i[o]))return!1;return!0}if(n.constructor===RegExp)return n.source===i.source&&n.flags===i.flags;if(n.valueOf!==Object.prototype.valueOf)return n.valueOf()===i.valueOf();if(n.toString!==Object.prototype.toString)return n.toString()===i.toString();if(a=Object.keys(n),s=a.length,s!==Object.keys(i).length)return!1;for(o=s;o--!==0;)if(!Object.prototype.hasOwnProperty.call(i,a[o]))return!1;for(o=s;o--!==0;){var c=a[o];if(!r(n[c],i[c]))return!1}return!0}return n!==n&&i!==i}}),Kue=re((t,e)=>{var r=e.exports=function(s,o,a){typeof o=="function"&&(a=o,o={}),a=o.cb||a;var c=typeof a=="function"?a:a.pre||function(){},u=a.post||function(){};n(o,c,u,s,"",s)};r.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},r.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},r.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},r.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function n(s,o,a,c,u,l,d,p,f,m){if(c&&typeof c=="object"&&!Array.isArray(c)){o(c,u,l,d,p,f,m);for(var h in c){var g=c[h];if(Array.isArray(g)){if(h in r.arrayKeywords)for(var v=0;v{Object.defineProperty(t,"__esModule",{value:!0}),t.getSchemaRefs=t.resolveUrl=t.normalizeId=t._getFullPath=t.getFullPath=t.inlineRef=void 0;var e=at(),r=bF(),n=Kue(),i=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function s(g,v=!0){return typeof g=="boolean"?!0:v===!0?!a(g):v?c(g)<=v:!1}t.inlineRef=s;var o=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function a(g){for(let v in g){if(o.has(v))return!0;let S=g[v];if(Array.isArray(S)&&S.some(a)||typeof S=="object"&&a(S))return!0}return!1}function c(g){let v=0;for(let S in g){if(S==="$ref")return 1/0;if(v++,!i.has(S)&&(typeof g[S]=="object"&&(0,e.eachItem)(g[S],_=>v+=c(_)),v===1/0))return 1/0}return v}function u(g,v="",S){S!==!1&&(v=p(v));let _=g.parse(v);return l(g,_)}t.getFullPath=u;function l(g,v){return g.serialize(v).split("#")[0]+"#"}t._getFullPath=l;var d=/#\/?$/;function p(g){return g?g.replace(d,""):""}t.normalizeId=p;function f(g,v,S){return S=p(S),g.resolve(v,S)}t.resolveUrl=f;var m=/^[a-z_][-a-z0-9._]*$/i;function h(g,v){if(typeof g=="boolean")return{};let{schemaId:S,uriResolver:_}=this.opts,y=p(g[S]||v),x={"":y},w=u(_,y,!1),E={},T=new Set;return n(g,{allKeys:!0},(N,U,V,j)=>{if(j===void 0)return;let ae=w+U,Ne=x[j];typeof N[S]=="string"&&(Ne=ze.call(this,N[S])),Et.call(this,N.$anchor),Et.call(this,N.$dynamicAnchor),x[U]=Ne;function ze(Ge){let K=this.opts.uriResolver.resolve;if(Ge=p(Ne?K(Ne,Ge):Ge),T.has(Ge))throw A(Ge);T.add(Ge);let C=this.refs[Ge];return typeof C=="string"&&(C=this.refs[C]),typeof C=="object"?I(N,C.schema,Ge):Ge!==p(ae)&&(Ge[0]==="#"?(I(N,E[Ge],Ge),E[Ge]=N):this.refs[Ge]=ae),Ge}function Et(Ge){if(typeof Ge=="string"){if(!m.test(Ge))throw new Error(`invalid anchor "${Ge}"`);ze.call(this,`#${Ge}`)}}}),E;function I(N,U,V){if(U!==void 0&&!r(N,U))throw A(V)}function A(N){return new Error(`reference "${N}" resolves to more than one schema`)}}t.getSchemaRefs=h}),Bv=re(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getData=t.KeywordCxt=t.validateFunctionCode=void 0;var e=Bue(),r=Dv(),n=_F(),i=Dv(),s=Gue(),o=Wue(),a=Vue(),c=Ze(),u=xo(),l=Zv(),d=at(),p=Hv();function f(P){if(w(P)&&(T(P),x(P))){v(P);return}m(P,()=>(0,e.topBoolOrEmptySchema)(P))}t.validateFunctionCode=f;function m({gen:P,validateName:D,schema:Z,schemaEnv:J,opts:ue},We){ue.code.es5?P.func(D,(0,c._)`${u.default.data}, ${u.default.valCxt}`,J.$async,()=>{P.code((0,c._)`"use strict"; ${_(Z,ue)}`),g(P,ue),P.code(We)}):P.func(D,(0,c._)`${u.default.data}, ${h(ue)}`,J.$async,()=>P.code(_(Z,ue)).code(We))}function h(P){return(0,c._)`{${u.default.instancePath}="", ${u.default.parentData}, ${u.default.parentDataProperty}, ${u.default.rootData}=${u.default.data}${P.dynamicRef?(0,c._)`, ${u.default.dynamicAnchors}={}`:c.nil}}={}`}function g(P,D){P.if(u.default.valCxt,()=>{P.var(u.default.instancePath,(0,c._)`${u.default.valCxt}.${u.default.instancePath}`),P.var(u.default.parentData,(0,c._)`${u.default.valCxt}.${u.default.parentData}`),P.var(u.default.parentDataProperty,(0,c._)`${u.default.valCxt}.${u.default.parentDataProperty}`),P.var(u.default.rootData,(0,c._)`${u.default.valCxt}.${u.default.rootData}`),D.dynamicRef&&P.var(u.default.dynamicAnchors,(0,c._)`${u.default.valCxt}.${u.default.dynamicAnchors}`)},()=>{P.var(u.default.instancePath,(0,c._)`""`),P.var(u.default.parentData,(0,c._)`undefined`),P.var(u.default.parentDataProperty,(0,c._)`undefined`),P.var(u.default.rootData,u.default.data),D.dynamicRef&&P.var(u.default.dynamicAnchors,(0,c._)`{}`)})}function v(P){let{schema:D,opts:Z,gen:J}=P;m(P,()=>{Z.$comment&&D.$comment&&j(P),N(P),J.let(u.default.vErrors,null),J.let(u.default.errors,0),Z.unevaluated&&S(P),I(P),ae(P)})}function S(P){let{gen:D,validateName:Z}=P;P.evaluated=D.const("evaluated",(0,c._)`${Z}.evaluated`),D.if((0,c._)`${P.evaluated}.dynamicProps`,()=>D.assign((0,c._)`${P.evaluated}.props`,(0,c._)`undefined`)),D.if((0,c._)`${P.evaluated}.dynamicItems`,()=>D.assign((0,c._)`${P.evaluated}.items`,(0,c._)`undefined`))}function _(P,D){let Z=typeof P=="object"&&P[D.schemaId];return Z&&(D.code.source||D.code.process)?(0,c._)`/*# sourceURL=${Z} */`:c.nil}function y(P,D){if(w(P)&&(T(P),x(P))){E(P,D);return}(0,e.boolOrEmptySchema)(P,D)}function x({schema:P,self:D}){if(typeof P=="boolean")return!P;for(let Z in P)if(D.RULES.all[Z])return!0;return!1}function w(P){return typeof P.schema!="boolean"}function E(P,D){let{schema:Z,gen:J,opts:ue}=P;ue.$comment&&Z.$comment&&j(P),U(P),V(P);let We=J.const("_errs",u.default.errors);I(P,We),J.var(D,(0,c._)`${We} === ${u.default.errors}`)}function T(P){(0,d.checkUnknownRules)(P),A(P)}function I(P,D){if(P.opts.jtd)return ze(P,[],!1,D);let Z=(0,r.getSchemaTypes)(P.schema),J=(0,r.coerceAndCheckDataType)(P,Z);ze(P,Z,!J,D)}function A(P){let{schema:D,errSchemaPath:Z,opts:J,self:ue}=P;D.$ref&&J.ignoreKeywordsWithRef&&(0,d.schemaHasRulesButRef)(D,ue.RULES)&&ue.logger.warn(`$ref: keywords ignored in schema at path "${Z}"`)}function N(P){let{schema:D,opts:Z}=P;D.default!==void 0&&Z.useDefaults&&Z.strictSchema&&(0,d.checkStrictMode)(P,"default is ignored in the schema root")}function U(P){let D=P.schema[P.opts.schemaId];D&&(P.baseId=(0,l.resolveUrl)(P.opts.uriResolver,P.baseId,D))}function V(P){if(P.schema.$async&&!P.schemaEnv.$async)throw new Error("async schema in sync schema")}function j({gen:P,schemaEnv:D,schema:Z,errSchemaPath:J,opts:ue}){let We=Z.$comment;if(ue.$comment===!0)P.code((0,c._)`${u.default.self}.logger.log(${We})`);else if(typeof ue.$comment=="function"){let gr=(0,c.str)`${J}/$comment`,ri=P.scopeValue("root",{ref:D.root});P.code((0,c._)`${u.default.self}.opts.$comment(${We}, ${gr}, ${ri}.schema)`)}}function ae(P){let{gen:D,schemaEnv:Z,validateName:J,ValidationError:ue,opts:We}=P;Z.$async?D.if((0,c._)`${u.default.errors} === 0`,()=>D.return(u.default.data),()=>D.throw((0,c._)`new ${ue}(${u.default.vErrors})`)):(D.assign((0,c._)`${J}.errors`,u.default.vErrors),We.unevaluated&&Ne(P),D.return((0,c._)`${u.default.errors} === 0`))}function Ne({gen:P,evaluated:D,props:Z,items:J}){Z instanceof c.Name&&P.assign((0,c._)`${D}.props`,Z),J instanceof c.Name&&P.assign((0,c._)`${D}.items`,J)}function ze(P,D,Z,J){let{gen:ue,schema:We,data:gr,allErrors:ri,opts:nn,self:sn}=P,{RULES:vr}=sn;if(We.$ref&&(nn.ignoreKeywordsWithRef||!(0,d.schemaHasRulesButRef)(We,vr))){ue.block(()=>ce(P,"$ref",vr.all.$ref.definition));return}nn.jtd||Ge(P,D),ue.block(()=>{for(let Nn of vr.rules)Na(Nn);Na(vr.post)});function Na(Nn){(0,n.shouldUseGroup)(We,Nn)&&(Nn.type?(ue.if((0,i.checkDataType)(Nn.type,gr,nn.strictNumbers)),Et(P,Nn),D.length===1&&D[0]===Nn.type&&Z&&(ue.else(),(0,i.reportTypeError)(P)),ue.endIf()):Et(P,Nn),ri||ue.if((0,c._)`${u.default.errors} === ${J||0}`))}}function Et(P,D){let{gen:Z,schema:J,opts:{useDefaults:ue}}=P;ue&&(0,s.assignDefaults)(P,D.type),Z.block(()=>{for(let We of D.rules)(0,n.shouldUseRule)(J,We)&&ce(P,We.keyword,We.definition,D.type)})}function Ge(P,D){P.schemaEnv.meta||!P.opts.strictTypes||(K(P,D),P.opts.allowUnionTypes||C(P,D),H(P,P.dataTypes))}function K(P,D){if(D.length){if(!P.dataTypes.length){P.dataTypes=D;return}D.forEach(Z=>{k(P.dataTypes,Z)||F(P,`type "${Z}" not allowed by context "${P.dataTypes.join(",")}"`)}),R(P,D)}}function C(P,D){D.length>1&&!(D.length===2&&D.includes("null"))&&F(P,"use allowUnionTypes to allow union type keyword")}function H(P,D){let Z=P.self.RULES.all;for(let J in Z){let ue=Z[J];if(typeof ue=="object"&&(0,n.shouldUseRule)(P.schema,ue)){let{type:We}=ue.definition;We.length&&!We.some(gr=>M(D,gr))&&F(P,`missing type "${We.join(",")}" for keyword "${J}"`)}}}function M(P,D){return P.includes(D)||D==="number"&&P.includes("integer")}function k(P,D){return P.includes(D)||D==="integer"&&P.includes("number")}function R(P,D){let Z=[];for(let J of P.dataTypes)k(D,J)?Z.push(J):D.includes("integer")&&J==="number"&&Z.push("integer");P.dataTypes=Z}function F(P,D){let Z=P.schemaEnv.baseId+P.errSchemaPath;D+=` at "${Z}" (strictTypes)`,(0,d.checkStrictMode)(P,D,P.opts.strictTypes)}class le{constructor(D,Z,J){if((0,o.validateKeywordUsage)(D,Z,J),this.gen=D.gen,this.allErrors=D.allErrors,this.keyword=J,this.data=D.data,this.schema=D.schema[J],this.$data=Z.$data&&D.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,d.schemaRefOrVal)(D,this.schema,J,this.$data),this.schemaType=Z.schemaType,this.parentSchema=D.schema,this.params={},this.it=D,this.def=Z,this.$data)this.schemaCode=D.gen.const("vSchema",Ft(this.$data,D));else if(this.schemaCode=this.schemaValue,!(0,o.validSchemaType)(this.schema,Z.schemaType,Z.allowUndefined))throw new Error(`${J} value must be ${JSON.stringify(Z.schemaType)}`);("code"in Z?Z.trackErrors:Z.errors!==!1)&&(this.errsCount=D.gen.const("_errs",u.default.errors))}result(D,Z,J){this.failResult((0,c.not)(D),Z,J)}failResult(D,Z,J){this.gen.if(D),J?J():this.error(),Z?(this.gen.else(),Z(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(D,Z){this.failResult((0,c.not)(D),void 0,Z)}fail(D){if(D===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(D),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(D){if(!this.$data)return this.fail(D);let{schemaCode:Z}=this;this.fail((0,c._)`${Z} !== undefined && (${(0,c.or)(this.invalid$data(),D)})`)}error(D,Z,J){if(Z){this.setParams(Z),this._error(D,J),this.setParams({});return}this._error(D,J)}_error(D,Z){(D?p.reportExtraError:p.reportError)(this,this.def.error,Z)}$dataError(){(0,p.reportError)(this,this.def.$dataError||p.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,p.resetErrorsCount)(this.gen,this.errsCount)}ok(D){this.allErrors||this.gen.if(D)}setParams(D,Z){Z?Object.assign(this.params,D):this.params=D}block$data(D,Z,J=c.nil){this.gen.block(()=>{this.check$data(D,J),Z()})}check$data(D=c.nil,Z=c.nil){if(!this.$data)return;let{gen:J,schemaCode:ue,schemaType:We,def:gr}=this;J.if((0,c.or)((0,c._)`${ue} === undefined`,Z)),D!==c.nil&&J.assign(D,!0),(We.length||gr.validateSchema)&&(J.elseIf(this.invalid$data()),this.$dataError(),D!==c.nil&&J.assign(D,!1)),J.else()}invalid$data(){let{gen:D,schemaCode:Z,schemaType:J,def:ue,it:We}=this;return(0,c.or)(gr(),ri());function gr(){if(J.length){if(!(Z instanceof c.Name))throw new Error("ajv implementation error");let nn=Array.isArray(J)?J:[J];return(0,c._)`${(0,i.checkDataTypes)(nn,Z,We.opts.strictNumbers,i.DataType.Wrong)}`}return c.nil}function ri(){if(ue.validateSchema){let nn=D.scopeValue("validate$data",{ref:ue.validateSchema});return(0,c._)`!${nn}(${Z})`}return c.nil}}subschema(D,Z){let J=(0,a.getSubschema)(this.it,D);(0,a.extendSubschemaData)(J,this.it,D),(0,a.extendSubschemaMode)(J,D);let ue={...this.it,...J,items:void 0,props:void 0};return y(ue,Z),ue}mergeEvaluated(D,Z){let{it:J,gen:ue}=this;J.opts.unevaluated&&(J.props!==!0&&D.props!==void 0&&(J.props=d.mergeEvaluated.props(ue,D.props,J.props,Z)),J.items!==!0&&D.items!==void 0&&(J.items=d.mergeEvaluated.items(ue,D.items,J.items,Z)))}mergeValidEvaluated(D,Z){let{it:J,gen:ue}=this;if(J.opts.unevaluated&&(J.props!==!0||J.items!==!0))return ue.if(Z,()=>this.mergeEvaluated(D,c.Name)),!0}}t.KeywordCxt=le;function ce(P,D,Z,J){let ue=new le(P,Z,D);"code"in Z?Z.code(ue,J):ue.$data&&Z.validate?(0,o.funcKeywordCode)(ue,Z):"macro"in Z?(0,o.macroKeywordCode)(ue,Z):(Z.compile||Z.validate)&&(0,o.funcKeywordCode)(ue,Z)}var Qe=/^\/(?:[^~]|~0|~1)*$/,Xe=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Ft(P,{dataLevel:D,dataNames:Z,dataPathArr:J}){let ue,We;if(P==="")return u.default.rootData;if(P[0]==="/"){if(!Qe.test(P))throw new Error(`Invalid JSON-pointer: ${P}`);ue=P,We=u.default.rootData}else{let sn=Xe.exec(P);if(!sn)throw new Error(`Invalid JSON-pointer: ${P}`);let vr=+sn[1];if(ue=sn[2],ue==="#"){if(vr>=D)throw new Error(nn("property/index",vr));return J[D-vr]}if(vr>D)throw new Error(nn("data",vr));if(We=Z[D-vr],!ue)return We}let gr=We,ri=ue.split("/");for(let sn of ri)sn&&(We=(0,c._)`${We}${(0,c.getProperty)((0,d.unescapeJsonPointer)(sn))}`,gr=(0,c._)`${gr} && ${We}`);return gr;function nn(sn,vr){return`Cannot access ${sn} ${vr} levels up, current level is ${D}`}}t.getData=Ft}),A$=re(t=>{Object.defineProperty(t,"__esModule",{value:!0});class e extends Error{constructor(n){super("validation failed"),this.errors=n,this.ajv=this.validation=!0}}t.default=e}),Gv=re(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Zv();class r extends Error{constructor(i,s,o,a){super(a||`can't resolve reference ${o} from id ${s}`),this.missingRef=(0,e.resolveUrl)(i,s,o),this.missingSchema=(0,e.normalizeId)((0,e.getFullPath)(i,this.missingRef))}}t.default=r}),N$=re(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.resolveSchema=t.getCompilingSchema=t.resolveRef=t.compileSchema=t.SchemaEnv=void 0;var e=Ze(),r=A$(),n=xo(),i=Zv(),s=at(),o=Bv();class a{constructor(S){var _;this.refs={},this.dynamicAnchors={};let y;typeof S.schema=="object"&&(y=S.schema),this.schema=S.schema,this.schemaId=S.schemaId,this.root=S.root||this,this.baseId=(_=S.baseId)!==null&&_!==void 0?_:(0,i.normalizeId)(y?.[S.schemaId||"$id"]),this.schemaPath=S.schemaPath,this.localRefs=S.localRefs,this.meta=S.meta,this.$async=y?.$async,this.refs={}}}t.SchemaEnv=a;function c(v){let S=d.call(this,v);if(S)return S;let _=(0,i.getFullPath)(this.opts.uriResolver,v.root.baseId),{es5:y,lines:x}=this.opts.code,{ownProperties:w}=this.opts,E=new e.CodeGen(this.scope,{es5:y,lines:x,ownProperties:w}),T;v.$async&&(T=E.scopeValue("Error",{ref:r.default,code:(0,e._)`require("ajv/dist/runtime/validation_error").default`}));let I=E.scopeName("validate");v.validateName=I;let A={gen:E,allErrors:this.opts.allErrors,data:n.default.data,parentData:n.default.parentData,parentDataProperty:n.default.parentDataProperty,dataNames:[n.default.data],dataPathArr:[e.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:E.scopeValue("schema",this.opts.code.source===!0?{ref:v.schema,code:(0,e.stringify)(v.schema)}:{ref:v.schema}),validateName:I,ValidationError:T,schema:v.schema,schemaEnv:v,rootId:_,baseId:v.baseId||_,schemaPath:e.nil,errSchemaPath:v.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,e._)`""`,opts:this.opts,self:this},N;try{this._compilations.add(v),(0,o.validateFunctionCode)(A),E.optimize(this.opts.code.optimize);let U=E.toString();N=`${E.scopeRefs(n.default.scope)}return ${U}`,this.opts.code.process&&(N=this.opts.code.process(N,v));let j=new Function(`${n.default.self}`,`${n.default.scope}`,N)(this,this.scope.get());if(this.scope.value(I,{ref:j}),j.errors=null,j.schema=v.schema,j.schemaEnv=v,v.$async&&(j.$async=!0),this.opts.code.source===!0&&(j.source={validateName:I,validateCode:U,scopeValues:E._values}),this.opts.unevaluated){let{props:ae,items:Ne}=A;j.evaluated={props:ae instanceof e.Name?void 0:ae,items:Ne instanceof e.Name?void 0:Ne,dynamicProps:ae instanceof e.Name,dynamicItems:Ne instanceof e.Name},j.source&&(j.source.evaluated=(0,e.stringify)(j.evaluated))}return v.validate=j,v}catch(U){throw delete v.validate,delete v.validateName,N&&this.logger.error("Error compiling schema, function code:",N),U}finally{this._compilations.delete(v)}}t.compileSchema=c;function u(v,S,_){var y;_=(0,i.resolveUrl)(this.opts.uriResolver,S,_);let x=v.refs[_];if(x)return x;let w=f.call(this,v,_);if(w===void 0){let E=(y=v.localRefs)===null||y===void 0?void 0:y[_],{schemaId:T}=this.opts;E&&(w=new a({schema:E,schemaId:T,root:v,baseId:S}))}if(w!==void 0)return v.refs[_]=l.call(this,w)}t.resolveRef=u;function l(v){return(0,i.inlineRef)(v.schema,this.opts.inlineRefs)?v.schema:v.validate?v:c.call(this,v)}function d(v){for(let S of this._compilations)if(p(S,v))return S}t.getCompilingSchema=d;function p(v,S){return v.schema===S.schema&&v.root===S.root&&v.baseId===S.baseId}function f(v,S){let _;for(;typeof(_=this.refs[S])=="string";)S=_;return _||this.schemas[S]||m.call(this,v,S)}function m(v,S){let _=this.opts.uriResolver.parse(S),y=(0,i._getFullPath)(this.opts.uriResolver,_),x=(0,i.getFullPath)(this.opts.uriResolver,v.baseId,void 0);if(Object.keys(v.schema).length>0&&y===x)return g.call(this,_,v);let w=(0,i.normalizeId)(y),E=this.refs[w]||this.schemas[w];if(typeof E=="string"){let T=m.call(this,v,E);return typeof T?.schema!="object"?void 0:g.call(this,_,T)}if(typeof E?.schema=="object"){if(E.validate||c.call(this,E),w===(0,i.normalizeId)(S)){let{schema:T}=E,{schemaId:I}=this.opts,A=T[I];return A&&(x=(0,i.resolveUrl)(this.opts.uriResolver,x,A)),new a({schema:T,schemaId:I,root:v,baseId:x})}return g.call(this,_,E)}}t.resolveSchema=m;var h=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function g(v,{baseId:S,schema:_,root:y}){var x;if(((x=v.fragment)===null||x===void 0?void 0:x[0])!=="/")return;for(let T of v.fragment.slice(1).split("/")){if(typeof _=="boolean")return;let I=_[(0,s.unescapeFragment)(T)];if(I===void 0)return;_=I;let A=typeof _=="object"&&_[this.opts.schemaId];!h.has(T)&&A&&(S=(0,i.resolveUrl)(this.opts.uriResolver,S,A))}let w;if(typeof _!="boolean"&&_.$ref&&!(0,s.schemaHasRulesButRef)(_,this.RULES)){let T=(0,i.resolveUrl)(this.opts.uriResolver,S,_.$ref);w=m.call(this,y,T)}let{schemaId:E}=this.opts;if(w=w||new a({schema:_,schemaId:E,root:y,baseId:S}),w.schema!==w.root.schema)return w}}),Jue=re((t,e)=>{e.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}}),Xue=re((t,e)=>{var r={0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,a:10,A:10,b:11,B:11,c:12,C:12,d:13,D:13,e:14,E:14,f:15,F:15};e.exports={HEX:r}}),Yue=re((t,e)=>{var{HEX:r}=Xue(),n=/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u;function i(v){if(u(v,".")<3)return{host:v,isIPV4:!1};let S=v.match(n)||[],[_]=S;return _?{host:c(_,"."),isIPV4:!0}:{host:v,isIPV4:!1}}function s(v,S=!1){let _="",y=!0;for(let x of v){if(r[x]===void 0)return;x!=="0"&&y===!0&&(y=!1),y||(_+=x)}return S&&_.length===0&&(_="0"),_}function o(v){let S=0,_={error:!1,address:"",zone:""},y=[],x=[],w=!1,E=!1,T=!1;function I(){if(x.length){if(w===!1){let A=s(x);if(A!==void 0)y.push(A);else return _.error=!0,!1}x.length=0}return!0}for(let A=0;A7){_.error=!0;break}A-1>=0&&v[A-1]===":"&&(E=!0);continue}else if(N==="%"){if(!I())break;w=!0}else{x.push(N);continue}}return x.length&&(w?_.zone=x.join(""):T?y.push(x.join("")):y.push(s(x))),_.address=y.join(""),_}function a(v){if(u(v,":")<2)return{host:v,isIPV6:!1};let S=o(v);if(S.error)return{host:v,isIPV6:!1};{let _=S.address,y=S.address;return S.zone&&(_+="%"+S.zone,y+="%25"+S.zone),{host:_,escapedHost:y,isIPV6:!0}}}function c(v,S){let _="",y=!0,x=v.length;for(let w=0;w{var r=/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu,n=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu;function i(y){return typeof y.secure=="boolean"?y.secure:String(y.scheme).toLowerCase()==="wss"}function s(y){return y.host||(y.error=y.error||"HTTP URIs must have a host."),y}function o(y){let x=String(y.scheme).toLowerCase()==="https";return(y.port===(x?443:80)||y.port==="")&&(y.port=void 0),y.path||(y.path="/"),y}function a(y){return y.secure=i(y),y.resourceName=(y.path||"/")+(y.query?"?"+y.query:""),y.path=void 0,y.query=void 0,y}function c(y){if((y.port===(i(y)?443:80)||y.port==="")&&(y.port=void 0),typeof y.secure=="boolean"&&(y.scheme=y.secure?"wss":"ws",y.secure=void 0),y.resourceName){let[x,w]=y.resourceName.split("?");y.path=x&&x!=="/"?x:void 0,y.query=w,y.resourceName=void 0}return y.fragment=void 0,y}function u(y,x){if(!y.path)return y.error="URN can not be parsed",y;let w=y.path.match(n);if(w){let E=x.scheme||y.scheme||"urn";y.nid=w[1].toLowerCase(),y.nss=w[2];let T=`${E}:${x.nid||y.nid}`,I=_[T];y.path=void 0,I&&(y=I.parse(y,x))}else y.error=y.error||"URN can not be parsed.";return y}function l(y,x){let w=x.scheme||y.scheme||"urn",E=y.nid.toLowerCase(),T=`${w}:${x.nid||E}`,I=_[T];I&&(y=I.serialize(y,x));let A=y,N=y.nss;return A.path=`${E||x.nid}:${N}`,x.skipEscape=!0,A}function d(y,x){let w=y;return w.uuid=w.nss,w.nss=void 0,!x.tolerant&&(!w.uuid||!r.test(w.uuid))&&(w.error=w.error||"UUID is not valid."),w}function p(y){let x=y;return x.nss=(y.uuid||"").toLowerCase(),x}var f={scheme:"http",domainHost:!0,parse:s,serialize:o},m={scheme:"https",domainHost:f.domainHost,parse:s,serialize:o},h={scheme:"ws",domainHost:!0,parse:a,serialize:c},g={scheme:"wss",domainHost:h.domainHost,parse:h.parse,serialize:h.serialize},v={scheme:"urn",parse:u,serialize:l,skipNormalize:!0},S={scheme:"urn:uuid",parse:d,serialize:p,skipNormalize:!0},_={http:f,https:m,ws:h,wss:g,urn:v,"urn:uuid":S};e.exports=_}),ele=re((t,e)=>{var{normalizeIPv6:r,normalizeIPv4:n,removeDotSegments:i,recomposeAuthority:s,normalizeComponentEncoding:o}=Yue(),a=Que();function c(S,_){return typeof S=="string"?S=p(g(S,_),_):typeof S=="object"&&(S=g(p(S,_),_)),S}function u(S,_,y){let x=Object.assign({scheme:"null"},y),w=l(g(S,x),g(_,x),x,!0);return p(w,{...x,skipEscape:!0})}function l(S,_,y,x){let w={};return x||(S=g(p(S,y),y),_=g(p(_,y),y)),y=y||{},!y.tolerant&&_.scheme?(w.scheme=_.scheme,w.userinfo=_.userinfo,w.host=_.host,w.port=_.port,w.path=i(_.path||""),w.query=_.query):(_.userinfo!==void 0||_.host!==void 0||_.port!==void 0?(w.userinfo=_.userinfo,w.host=_.host,w.port=_.port,w.path=i(_.path||""),w.query=_.query):(_.path?(_.path.charAt(0)==="/"?w.path=i(_.path):((S.userinfo!==void 0||S.host!==void 0||S.port!==void 0)&&!S.path?w.path="/"+_.path:S.path?w.path=S.path.slice(0,S.path.lastIndexOf("/")+1)+_.path:w.path=_.path,w.path=i(w.path)),w.query=_.query):(w.path=S.path,_.query!==void 0?w.query=_.query:w.query=S.query),w.userinfo=S.userinfo,w.host=S.host,w.port=S.port),w.scheme=S.scheme),w.fragment=_.fragment,w}function d(S,_,y){return typeof S=="string"?(S=unescape(S),S=p(o(g(S,y),!0),{...y,skipEscape:!0})):typeof S=="object"&&(S=p(o(S,!0),{...y,skipEscape:!0})),typeof _=="string"?(_=unescape(_),_=p(o(g(_,y),!0),{...y,skipEscape:!0})):typeof _=="object"&&(_=p(o(_,!0),{...y,skipEscape:!0})),S.toLowerCase()===_.toLowerCase()}function p(S,_){let y={host:S.host,scheme:S.scheme,userinfo:S.userinfo,port:S.port,path:S.path,query:S.query,nid:S.nid,nss:S.nss,uuid:S.uuid,fragment:S.fragment,reference:S.reference,resourceName:S.resourceName,secure:S.secure,error:""},x=Object.assign({},_),w=[],E=a[(x.scheme||y.scheme||"").toLowerCase()];E&&E.serialize&&E.serialize(y,x),y.path!==void 0&&(x.skipEscape?y.path=unescape(y.path):(y.path=escape(y.path),y.scheme!==void 0&&(y.path=y.path.split("%3A").join(":")))),x.reference!=="suffix"&&y.scheme&&w.push(y.scheme,":");let T=s(y);if(T!==void 0&&(x.reference!=="suffix"&&w.push("//"),w.push(T),y.path&&y.path.charAt(0)!=="/"&&w.push("/")),y.path!==void 0){let I=y.path;!x.absolutePath&&(!E||!E.absolutePath)&&(I=i(I)),T===void 0&&(I=I.replace(/^\/\//u,"/%2F")),w.push(I)}return y.query!==void 0&&w.push("?",y.query),y.fragment!==void 0&&w.push("#",y.fragment),w.join("")}var f=Array.from({length:127},(S,_)=>/[^!"$&'()*+,\-.;=_`a-z{}~]/u.test(String.fromCharCode(_)));function m(S){let _=0;for(let y=0,x=S.length;y126||f[_])return!0;return!1}var h=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function g(S,_){let y=Object.assign({},_),x={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},w=S.indexOf("%")!==-1,E=!1;y.reference==="suffix"&&(S=(y.scheme?y.scheme+":":"")+"//"+S);let T=S.match(h);if(T){if(x.scheme=T[1],x.userinfo=T[3],x.host=T[4],x.port=parseInt(T[5],10),x.path=T[6]||"",x.query=T[7],x.fragment=T[8],isNaN(x.port)&&(x.port=T[5]),x.host){let A=n(x.host);if(A.isIPV4===!1){let N=r(A.host);x.host=N.host.toLowerCase(),E=N.isIPV6}else x.host=A.host,E=!0}x.scheme===void 0&&x.userinfo===void 0&&x.host===void 0&&x.port===void 0&&x.query===void 0&&!x.path?x.reference="same-document":x.scheme===void 0?x.reference="relative":x.fragment===void 0?x.reference="absolute":x.reference="uri",y.reference&&y.reference!=="suffix"&&y.reference!==x.reference&&(x.error=x.error||"URI is not a "+y.reference+" reference.");let I=a[(y.scheme||x.scheme||"").toLowerCase()];if(!y.unicodeSupport&&(!I||!I.unicodeSupport)&&x.host&&(y.domainHost||I&&I.domainHost)&&E===!1&&m(x.host))try{x.host=URL.domainToASCII(x.host.toLowerCase())}catch(A){x.error=x.error||"Host's domain name can not be converted to ASCII: "+A}(!I||I&&!I.skipNormalize)&&(w&&x.scheme!==void 0&&(x.scheme=unescape(x.scheme)),w&&x.host!==void 0&&(x.host=unescape(x.host)),x.path&&(x.path=escape(unescape(x.path))),x.fragment&&(x.fragment=encodeURI(decodeURIComponent(x.fragment)))),I&&I.parse&&I.parse(x,y)}else x.error=x.error||"URI can not be parsed.";return x}var v={SCHEMES:a,normalize:c,resolve:u,resolveComponents:l,equal:d,serialize:p,parse:g};e.exports=v,e.exports.default=v,e.exports.fastUri=v}),tle=re(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=ele();e.code='require("ajv/dist/runtime/uri").default',t.default=e}),rle=re(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CodeGen=t.Name=t.nil=t.stringify=t.str=t._=t.KeywordCxt=void 0;var e=Bv();Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return e.KeywordCxt}});var r=Ze();Object.defineProperty(t,"_",{enumerable:!0,get:function(){return r._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return r.Name}}),Object.defineProperty(t,"CodeGen",{enumerable:!0,get:function(){return r.CodeGen}});var n=A$(),i=Gv(),s=yF(),o=N$(),a=Ze(),c=Zv(),u=Dv(),l=at(),d=Jue(),p=tle(),f=(K,C)=>new RegExp(K,C);f.code="new RegExp";var m=["removeAdditional","useDefaults","coerceTypes"],h=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),g={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},v={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},S=200;function _(K){var C,H,M,k,R,F,le,ce,Qe,Xe,Ft,P,D,Z,J,ue,We,gr,ri,nn,sn,vr,Na,Nn,p_;let Yu=K.strict,f_=(C=K.code)===null||C===void 0?void 0:C.optimize,YI=f_===!0||f_===void 0?1:f_||0,QI=(M=(H=K.code)===null||H===void 0?void 0:H.regExp)!==null&&M!==void 0?M:f,tH=(k=K.uriResolver)!==null&&k!==void 0?k:p.default;return{strictSchema:(F=(R=K.strictSchema)!==null&&R!==void 0?R:Yu)!==null&&F!==void 0?F:!0,strictNumbers:(ce=(le=K.strictNumbers)!==null&&le!==void 0?le:Yu)!==null&&ce!==void 0?ce:!0,strictTypes:(Xe=(Qe=K.strictTypes)!==null&&Qe!==void 0?Qe:Yu)!==null&&Xe!==void 0?Xe:"log",strictTuples:(P=(Ft=K.strictTuples)!==null&&Ft!==void 0?Ft:Yu)!==null&&P!==void 0?P:"log",strictRequired:(Z=(D=K.strictRequired)!==null&&D!==void 0?D:Yu)!==null&&Z!==void 0?Z:!1,code:K.code?{...K.code,optimize:YI,regExp:QI}:{optimize:YI,regExp:QI},loopRequired:(J=K.loopRequired)!==null&&J!==void 0?J:S,loopEnum:(ue=K.loopEnum)!==null&&ue!==void 0?ue:S,meta:(We=K.meta)!==null&&We!==void 0?We:!0,messages:(gr=K.messages)!==null&&gr!==void 0?gr:!0,inlineRefs:(ri=K.inlineRefs)!==null&&ri!==void 0?ri:!0,schemaId:(nn=K.schemaId)!==null&&nn!==void 0?nn:"$id",addUsedSchema:(sn=K.addUsedSchema)!==null&&sn!==void 0?sn:!0,validateSchema:(vr=K.validateSchema)!==null&&vr!==void 0?vr:!0,validateFormats:(Na=K.validateFormats)!==null&&Na!==void 0?Na:!0,unicodeRegExp:(Nn=K.unicodeRegExp)!==null&&Nn!==void 0?Nn:!0,int32range:(p_=K.int32range)!==null&&p_!==void 0?p_:!0,uriResolver:tH}}class y{constructor(C={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,C=this.opts={...C,..._(C)};let{es5:H,lines:M}=this.opts.code;this.scope=new a.ValueScope({scope:{},prefixes:h,es5:H,lines:M}),this.logger=U(C.logger);let k=C.validateFormats;C.validateFormats=!1,this.RULES=(0,s.getRules)(),x.call(this,g,C,"NOT SUPPORTED"),x.call(this,v,C,"DEPRECATED","warn"),this._metaOpts=A.call(this),C.formats&&T.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),C.keywords&&I.call(this,C.keywords),typeof C.meta=="object"&&this.addMetaSchema(C.meta),E.call(this),C.validateFormats=k}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:C,meta:H,schemaId:M}=this.opts,k=d;M==="id"&&(k={...d},k.id=k.$id,delete k.$id),H&&C&&this.addMetaSchema(k,k[M],!1)}defaultMeta(){let{meta:C,schemaId:H}=this.opts;return this.opts.defaultMeta=typeof C=="object"?C[H]||C:void 0}validate(C,H){let M;if(typeof C=="string"){if(M=this.getSchema(C),!M)throw new Error(`no schema with key or ref "${C}"`)}else M=this.compile(C);let k=M(H);return"$async"in M||(this.errors=M.errors),k}compile(C,H){let M=this._addSchema(C,H);return M.validate||this._compileSchemaEnv(M)}compileAsync(C,H){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:M}=this.opts;return k.call(this,C,H);async function k(Xe,Ft){await R.call(this,Xe.$schema);let P=this._addSchema(Xe,Ft);return P.validate||F.call(this,P)}async function R(Xe){Xe&&!this.getSchema(Xe)&&await k.call(this,{$ref:Xe},!0)}async function F(Xe){try{return this._compileSchemaEnv(Xe)}catch(Ft){if(!(Ft instanceof i.default))throw Ft;return le.call(this,Ft),await ce.call(this,Ft.missingSchema),F.call(this,Xe)}}function le({missingSchema:Xe,missingRef:Ft}){if(this.refs[Xe])throw new Error(`AnySchema ${Xe} is loaded but ${Ft} cannot be resolved`)}async function ce(Xe){let Ft=await Qe.call(this,Xe);this.refs[Xe]||await R.call(this,Ft.$schema),this.refs[Xe]||this.addSchema(Ft,Xe,H)}async function Qe(Xe){let Ft=this._loading[Xe];if(Ft)return Ft;try{return await(this._loading[Xe]=M(Xe))}finally{delete this._loading[Xe]}}}addSchema(C,H,M,k=this.opts.validateSchema){if(Array.isArray(C)){for(let F of C)this.addSchema(F,void 0,M,k);return this}let R;if(typeof C=="object"){let{schemaId:F}=this.opts;if(R=C[F],R!==void 0&&typeof R!="string")throw new Error(`schema ${F} must be string`)}return H=(0,c.normalizeId)(H||R),this._checkUnique(H),this.schemas[H]=this._addSchema(C,M,H,k,!0),this}addMetaSchema(C,H,M=this.opts.validateSchema){return this.addSchema(C,H,!0,M),this}validateSchema(C,H){if(typeof C=="boolean")return!0;let M;if(M=C.$schema,M!==void 0&&typeof M!="string")throw new Error("$schema must be a string");if(M=M||this.opts.defaultMeta||this.defaultMeta(),!M)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let k=this.validate(M,C);if(!k&&H){let R="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(R);else throw new Error(R)}return k}getSchema(C){let H;for(;typeof(H=w.call(this,C))=="string";)C=H;if(H===void 0){let{schemaId:M}=this.opts,k=new o.SchemaEnv({schema:{},schemaId:M});if(H=o.resolveSchema.call(this,k,C),!H)return;this.refs[C]=H}return H.validate||this._compileSchemaEnv(H)}removeSchema(C){if(C instanceof RegExp)return this._removeAllSchemas(this.schemas,C),this._removeAllSchemas(this.refs,C),this;switch(typeof C){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let H=w.call(this,C);return typeof H=="object"&&this._cache.delete(H.schema),delete this.schemas[C],delete this.refs[C],this}case"object":{let H=C;this._cache.delete(H);let M=C[this.opts.schemaId];return M&&(M=(0,c.normalizeId)(M),delete this.schemas[M],delete this.refs[M]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(C){for(let H of C)this.addKeyword(H);return this}addKeyword(C,H){let M;if(typeof C=="string")M=C,typeof H=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),H.keyword=M);else if(typeof C=="object"&&H===void 0){if(H=C,M=H.keyword,Array.isArray(M)&&!M.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(j.call(this,M,H),!H)return(0,l.eachItem)(M,R=>ae.call(this,R)),this;ze.call(this,H);let k={...H,type:(0,u.getJSONTypes)(H.type),schemaType:(0,u.getJSONTypes)(H.schemaType)};return(0,l.eachItem)(M,k.type.length===0?R=>ae.call(this,R,k):R=>k.type.forEach(F=>ae.call(this,R,k,F))),this}getKeyword(C){let H=this.RULES.all[C];return typeof H=="object"?H.definition:!!H}removeKeyword(C){let{RULES:H}=this;delete H.keywords[C],delete H.all[C];for(let M of H.rules){let k=M.rules.findIndex(R=>R.keyword===C);k>=0&&M.rules.splice(k,1)}return this}addFormat(C,H){return typeof H=="string"&&(H=new RegExp(H)),this.formats[C]=H,this}errorsText(C=this.errors,{separator:H=", ",dataVar:M="data"}={}){return!C||C.length===0?"No errors":C.map(k=>`${M}${k.instancePath} ${k.message}`).reduce((k,R)=>k+H+R)}$dataMetaSchema(C,H){let M=this.RULES.all;C=JSON.parse(JSON.stringify(C));for(let k of H){let R=k.split("/").slice(1),F=C;for(let le of R)F=F[le];for(let le in M){let ce=M[le];if(typeof ce!="object")continue;let{$data:Qe}=ce.definition,Xe=F[le];Qe&&Xe&&(F[le]=Ge(Xe))}}return C}_removeAllSchemas(C,H){for(let M in C){let k=C[M];(!H||H.test(M))&&(typeof k=="string"?delete C[M]:k&&!k.meta&&(this._cache.delete(k.schema),delete C[M]))}}_addSchema(C,H,M,k=this.opts.validateSchema,R=this.opts.addUsedSchema){let F,{schemaId:le}=this.opts;if(typeof C=="object")F=C[le];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof C!="boolean")throw new Error("schema must be object or boolean")}let ce=this._cache.get(C);if(ce!==void 0)return ce;M=(0,c.normalizeId)(F||M);let Qe=c.getSchemaRefs.call(this,C,M);return ce=new o.SchemaEnv({schema:C,schemaId:le,meta:H,baseId:M,localRefs:Qe}),this._cache.set(ce.schema,ce),R&&!M.startsWith("#")&&(M&&this._checkUnique(M),this.refs[M]=ce),k&&this.validateSchema(C,!0),ce}_checkUnique(C){if(this.schemas[C]||this.refs[C])throw new Error(`schema with key or id "${C}" already exists`)}_compileSchemaEnv(C){if(C.meta?this._compileMetaSchema(C):o.compileSchema.call(this,C),!C.validate)throw new Error("ajv implementation error");return C.validate}_compileMetaSchema(C){let H=this.opts;this.opts=this._metaOpts;try{o.compileSchema.call(this,C)}finally{this.opts=H}}}y.ValidationError=n.default,y.MissingRefError=i.default,t.default=y;function x(K,C,H,M="error"){for(let k in K){let R=k;R in C&&this.logger[M](`${H}: option ${k}. ${K[R]}`)}}function w(K){return K=(0,c.normalizeId)(K),this.schemas[K]||this.refs[K]}function E(){let K=this.opts.schemas;if(K)if(Array.isArray(K))this.addSchema(K);else for(let C in K)this.addSchema(K[C],C)}function T(){for(let K in this.opts.formats){let C=this.opts.formats[K];C&&this.addFormat(K,C)}}function I(K){if(Array.isArray(K)){this.addVocabulary(K);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let C in K){let H=K[C];H.keyword||(H.keyword=C),this.addKeyword(H)}}function A(){let K={...this.opts};for(let C of m)delete K[C];return K}var N={log(){},warn(){},error(){}};function U(K){if(K===!1)return N;if(K===void 0)return console;if(K.log&&K.warn&&K.error)return K;throw new Error("logger must implement log, warn and error methods")}var V=/^[a-z_$][a-z0-9_$:-]*$/i;function j(K,C){let{RULES:H}=this;if((0,l.eachItem)(K,M=>{if(H.keywords[M])throw new Error(`Keyword ${M} is already defined`);if(!V.test(M))throw new Error(`Keyword ${M} has invalid name`)}),!!C&&C.$data&&!("code"in C||"validate"in C))throw new Error('$data keyword must have "code" or "validate" function')}function ae(K,C,H){var M;let k=C?.post;if(H&&k)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:R}=this,F=k?R.post:R.rules.find(({type:ce})=>ce===H);if(F||(F={type:H,rules:[]},R.rules.push(F)),R.keywords[K]=!0,!C)return;let le={keyword:K,definition:{...C,type:(0,u.getJSONTypes)(C.type),schemaType:(0,u.getJSONTypes)(C.schemaType)}};C.before?Ne.call(this,F,le,C.before):F.rules.push(le),R.all[K]=le,(M=C.implements)===null||M===void 0||M.forEach(ce=>this.addKeyword(ce))}function Ne(K,C,H){let M=K.rules.findIndex(k=>k.keyword===H);M>=0?K.rules.splice(M,0,C):(K.rules.push(C),this.logger.warn(`rule ${H} is not defined`))}function ze(K){let{metaSchema:C}=K;C!==void 0&&(K.$data&&this.opts.$data&&(C=Ge(C)),K.validateSchema=this.compile(C,!0))}var Et={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Ge(K){return{anyOf:[K,Et]}}}),nle=re(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};t.default=e}),ile=re(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.callRef=t.getValidate=void 0;var e=Gv(),r=wi(),n=Ze(),i=xo(),s=N$(),o=at(),a={keyword:"$ref",schemaType:"string",code(l){let{gen:d,schema:p,it:f}=l,{baseId:m,schemaEnv:h,validateName:g,opts:v,self:S}=f,{root:_}=h;if((p==="#"||p==="#/")&&m===_.baseId)return x();let y=s.resolveRef.call(S,_,m,p);if(y===void 0)throw new e.default(f.opts.uriResolver,m,p);if(y instanceof s.SchemaEnv)return w(y);return E(y);function x(){if(h===_)return u(l,g,h,h.$async);let T=d.scopeValue("root",{ref:_});return u(l,(0,n._)`${T}.validate`,_,_.$async)}function w(T){let I=c(l,T);u(l,I,T,T.$async)}function E(T){let I=d.scopeValue("schema",v.code.source===!0?{ref:T,code:(0,n.stringify)(T)}:{ref:T}),A=d.name("valid"),N=l.subschema({schema:T,dataTypes:[],schemaPath:n.nil,topSchemaRef:I,errSchemaPath:p},A);l.mergeEvaluated(N),l.ok(A)}}};function c(l,d){let{gen:p}=l;return d.validate?p.scopeValue("validate",{ref:d.validate}):(0,n._)`${p.scopeValue("wrapper",{ref:d})}.validate`}t.getValidate=c;function u(l,d,p,f){let{gen:m,it:h}=l,{allErrors:g,schemaEnv:v,opts:S}=h,_=S.passContext?i.default.this:n.nil;f?y():x();function y(){if(!v.$async)throw new Error("async schema referenced by sync schema");let T=m.let("valid");m.try(()=>{m.code((0,n._)`await ${(0,r.callValidateCode)(l,d,_)}`),E(d),g||m.assign(T,!0)},I=>{m.if((0,n._)`!(${I} instanceof ${h.ValidationError})`,()=>m.throw(I)),w(I),g||m.assign(T,!1)}),l.ok(T)}function x(){l.result((0,r.callValidateCode)(l,d,_),()=>E(d),()=>w(d))}function w(T){let I=(0,n._)`${T}.errors`;m.assign(i.default.vErrors,(0,n._)`${i.default.vErrors} === null ? ${I} : ${i.default.vErrors}.concat(${I})`),m.assign(i.default.errors,(0,n._)`${i.default.vErrors}.length`)}function E(T){var I;if(!h.opts.unevaluated)return;let A=(I=p?.validate)===null||I===void 0?void 0:I.evaluated;if(h.props!==!0)if(A&&!A.dynamicProps)A.props!==void 0&&(h.props=o.mergeEvaluated.props(m,A.props,h.props));else{let N=m.var("props",(0,n._)`${T}.evaluated.props`);h.props=o.mergeEvaluated.props(m,N,h.props,n.Name)}if(h.items!==!0)if(A&&!A.dynamicItems)A.items!==void 0&&(h.items=o.mergeEvaluated.items(m,A.items,h.items));else{let N=m.var("items",(0,n._)`${T}.evaluated.items`);h.items=o.mergeEvaluated.items(m,N,h.items,n.Name)}}}t.callRef=u,t.default=a}),sle=re(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=nle(),r=ile(),n=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",e.default,r.default];t.default=n}),ole=re(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Ze(),r=e.operators,n={maximum:{okStr:"<=",ok:r.LTE,fail:r.GT},minimum:{okStr:">=",ok:r.GTE,fail:r.LT},exclusiveMaximum:{okStr:"<",ok:r.LT,fail:r.GTE},exclusiveMinimum:{okStr:">",ok:r.GT,fail:r.LTE}},i={message:({keyword:o,schemaCode:a})=>(0,e.str)`must be ${n[o].okStr} ${a}`,params:({keyword:o,schemaCode:a})=>(0,e._)`{comparison: ${n[o].okStr}, limit: ${a}}`},s={keyword:Object.keys(n),type:"number",schemaType:"number",$data:!0,error:i,code(o){let{keyword:a,data:c,schemaCode:u}=o;o.fail$data((0,e._)`${c} ${n[a].fail} ${u} || isNaN(${c})`)}};t.default=s}),ale=re(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Ze(),r={message:({schemaCode:i})=>(0,e.str)`must be multiple of ${i}`,params:({schemaCode:i})=>(0,e._)`{multipleOf: ${i}}`},n={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:r,code(i){let{gen:s,data:o,schemaCode:a,it:c}=i,u=c.opts.multipleOfPrecision,l=s.let("res"),d=u?(0,e._)`Math.abs(Math.round(${l}) - ${l}) > 1e-${u}`:(0,e._)`${l} !== parseInt(${l})`;i.fail$data((0,e._)`(${a} === 0 || (${l} = ${o}/${a}, ${d}))`)}};t.default=n}),cle=re(t=>{Object.defineProperty(t,"__esModule",{value:!0});function e(r){let n=r.length,i=0,s=0,o;for(;s=55296&&o<=56319&&s{Object.defineProperty(t,"__esModule",{value:!0});var e=Ze(),r=at(),n=cle(),i={message({keyword:o,schemaCode:a}){let c=o==="maxLength"?"more":"fewer";return(0,e.str)`must NOT have ${c} than ${a} characters`},params:({schemaCode:o})=>(0,e._)`{limit: ${o}}`},s={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:i,code(o){let{keyword:a,data:c,schemaCode:u,it:l}=o,d=a==="maxLength"?e.operators.GT:e.operators.LT,p=l.opts.unicode===!1?(0,e._)`${c}.length`:(0,e._)`${(0,r.useFunc)(o.gen,n.default)}(${c})`;o.fail$data((0,e._)`${p} ${d} ${u}`)}};t.default=s}),lle=re(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=wi(),r=Ze(),n={message:({schemaCode:s})=>(0,r.str)`must match pattern "${s}"`,params:({schemaCode:s})=>(0,r._)`{pattern: ${s}}`},i={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:n,code(s){let{data:o,$data:a,schema:c,schemaCode:u,it:l}=s,d=l.opts.unicodeRegExp?"u":"",p=a?(0,r._)`(new RegExp(${u}, ${d}))`:(0,e.usePattern)(s,c);s.fail$data((0,r._)`!${p}.test(${o})`)}};t.default=i}),dle=re(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Ze(),r={message({keyword:i,schemaCode:s}){let o=i==="maxProperties"?"more":"fewer";return(0,e.str)`must NOT have ${o} than ${s} properties`},params:({schemaCode:i})=>(0,e._)`{limit: ${i}}`},n={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:r,code(i){let{keyword:s,data:o,schemaCode:a}=i,c=s==="maxProperties"?e.operators.GT:e.operators.LT;i.fail$data((0,e._)`Object.keys(${o}).length ${c} ${a}`)}};t.default=n}),ple=re(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=wi(),r=Ze(),n=at(),i={message:({params:{missingProperty:o}})=>(0,r.str)`must have required property '${o}'`,params:({params:{missingProperty:o}})=>(0,r._)`{missingProperty: ${o}}`},s={keyword:"required",type:"object",schemaType:"array",$data:!0,error:i,code(o){let{gen:a,schema:c,schemaCode:u,data:l,$data:d,it:p}=o,{opts:f}=p;if(!d&&c.length===0)return;let m=c.length>=f.loopRequired;if(p.allErrors?h():g(),f.strictRequired){let _=o.parentSchema.properties,{definedProperties:y}=o.it;for(let x of c)if(_?.[x]===void 0&&!y.has(x)){let w=p.schemaEnv.baseId+p.errSchemaPath,E=`required property "${x}" is not defined at "${w}" (strictRequired)`;(0,n.checkStrictMode)(p,E,p.opts.strictRequired)}}function h(){if(m||d)o.block$data(r.nil,v);else for(let _ of c)(0,e.checkReportMissingProp)(o,_)}function g(){let _=a.let("missing");if(m||d){let y=a.let("valid",!0);o.block$data(y,()=>S(_,y)),o.ok(y)}else a.if((0,e.checkMissingProp)(o,c,_)),(0,e.reportMissingProp)(o,_),a.else()}function v(){a.forOf("prop",u,_=>{o.setParams({missingProperty:_}),a.if((0,e.noPropertyInData)(a,l,_,f.ownProperties),()=>o.error())})}function S(_,y){o.setParams({missingProperty:_}),a.forOf(_,u,()=>{a.assign(y,(0,e.propertyInData)(a,l,_,f.ownProperties)),a.if((0,r.not)(y),()=>{o.error(),a.break()})},r.nil)}}};t.default=s}),fle=re(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Ze(),r={message({keyword:i,schemaCode:s}){let o=i==="maxItems"?"more":"fewer";return(0,e.str)`must NOT have ${o} than ${s} items`},params:({schemaCode:i})=>(0,e._)`{limit: ${i}}`},n={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:r,code(i){let{keyword:s,data:o,schemaCode:a}=i,c=s==="maxItems"?e.operators.GT:e.operators.LT;i.fail$data((0,e._)`${o}.length ${c} ${a}`)}};t.default=n}),M$=re(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=bF();e.code='require("ajv/dist/runtime/equal").default',t.default=e}),mle=re(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Dv(),r=Ze(),n=at(),i=M$(),s={message:({params:{i:a,j:c}})=>(0,r.str)`must NOT have duplicate items (items ## ${c} and ${a} are identical)`,params:({params:{i:a,j:c}})=>(0,r._)`{i: ${a}, j: ${c}}`},o={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:s,code(a){let{gen:c,data:u,$data:l,schema:d,parentSchema:p,schemaCode:f,it:m}=a;if(!l&&!d)return;let h=c.let("valid"),g=p.items?(0,e.getSchemaTypes)(p.items):[];a.block$data(h,v,(0,r._)`${f} === false`),a.ok(h);function v(){let x=c.let("i",(0,r._)`${u}.length`),w=c.let("j");a.setParams({i:x,j:w}),c.assign(h,!0),c.if((0,r._)`${x} > 1`,()=>(S()?_:y)(x,w))}function S(){return g.length>0&&!g.some(x=>x==="object"||x==="array")}function _(x,w){let E=c.name("item"),T=(0,e.checkDataTypes)(g,E,m.opts.strictNumbers,e.DataType.Wrong),I=c.const("indices",(0,r._)`{}`);c.for((0,r._)`;${x}--;`,()=>{c.let(E,(0,r._)`${u}[${x}]`),c.if(T,(0,r._)`continue`),g.length>1&&c.if((0,r._)`typeof ${E} == "string"`,(0,r._)`${E} += "_"`),c.if((0,r._)`typeof ${I}[${E}] == "number"`,()=>{c.assign(w,(0,r._)`${I}[${E}]`),a.error(),c.assign(h,!1).break()}).code((0,r._)`${I}[${E}] = ${x}`)})}function y(x,w){let E=(0,n.useFunc)(c,i.default),T=c.name("outer");c.label(T).for((0,r._)`;${x}--;`,()=>c.for((0,r._)`${w} = ${x}; ${w}--;`,()=>c.if((0,r._)`${E}(${u}[${x}], ${u}[${w}])`,()=>{a.error(),c.assign(h,!1).break(T)})))}}};t.default=o}),hle=re(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Ze(),r=at(),n=M$(),i={message:"must be equal to constant",params:({schemaCode:o})=>(0,e._)`{allowedValue: ${o}}`},s={keyword:"const",$data:!0,error:i,code(o){let{gen:a,data:c,$data:u,schemaCode:l,schema:d}=o;u||d&&typeof d=="object"?o.fail$data((0,e._)`!${(0,r.useFunc)(a,n.default)}(${c}, ${l})`):o.fail((0,e._)`${d} !== ${c}`)}};t.default=s}),gle=re(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Ze(),r=at(),n=M$(),i={message:"must be equal to one of the allowed values",params:({schemaCode:o})=>(0,e._)`{allowedValues: ${o}}`},s={keyword:"enum",schemaType:"array",$data:!0,error:i,code(o){let{gen:a,data:c,$data:u,schema:l,schemaCode:d,it:p}=o;if(!u&&l.length===0)throw new Error("enum must have non-empty array");let f=l.length>=p.opts.loopEnum,m,h=()=>m??(m=(0,r.useFunc)(a,n.default)),g;if(f||u)g=a.let("valid"),o.block$data(g,v);else{if(!Array.isArray(l))throw new Error("ajv implementation error");let _=a.const("vSchema",d);g=(0,e.or)(...l.map((y,x)=>S(_,x)))}o.pass(g);function v(){a.assign(g,!1),a.forOf("v",d,_=>a.if((0,e._)`${h()}(${c}, ${_})`,()=>a.assign(g,!0).break()))}function S(_,y){let x=l[y];return typeof x=="object"&&x!==null?(0,e._)`${h()}(${c}, ${_}[${y}])`:(0,e._)`${c} === ${x}`}}};t.default=s}),vle=re(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=ole(),r=ale(),n=ule(),i=lle(),s=dle(),o=ple(),a=fle(),c=mle(),u=hle(),l=gle(),d=[e.default,r.default,n.default,i.default,s.default,o.default,a.default,c.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},u.default,l.default];t.default=d}),SF=re(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.validateAdditionalItems=void 0;var e=Ze(),r=at(),n={message:({params:{len:o}})=>(0,e.str)`must NOT have more than ${o} items`,params:({params:{len:o}})=>(0,e._)`{limit: ${o}}`},i={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:n,code(o){let{parentSchema:a,it:c}=o,{items:u}=a;if(!Array.isArray(u)){(0,r.checkStrictMode)(c,'"additionalItems" is ignored when "items" is not an array of schemas');return}s(o,u)}};function s(o,a){let{gen:c,schema:u,data:l,keyword:d,it:p}=o;p.items=!0;let f=c.const("len",(0,e._)`${l}.length`);if(u===!1)o.setParams({len:a.length}),o.pass((0,e._)`${f} <= ${a.length}`);else if(typeof u=="object"&&!(0,r.alwaysValidSchema)(p,u)){let h=c.var("valid",(0,e._)`${f} <= ${a.length}`);c.if((0,e.not)(h),()=>m(h)),o.ok(h)}function m(h){c.forRange("i",a.length,f,g=>{o.subschema({keyword:d,dataProp:g,dataPropType:r.Type.Num},h),p.allErrors||c.if((0,e.not)(h),()=>c.break())})}}t.validateAdditionalItems=s,t.default=i}),xF=re(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.validateTuple=void 0;var e=Ze(),r=at(),n=wi(),i={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(o){let{schema:a,it:c}=o;if(Array.isArray(a))return s(o,"additionalItems",a);c.items=!0,!(0,r.alwaysValidSchema)(c,a)&&o.ok((0,n.validateArray)(o))}};function s(o,a,c=o.schema){let{gen:u,parentSchema:l,data:d,keyword:p,it:f}=o;g(l),f.opts.unevaluated&&c.length&&f.items!==!0&&(f.items=r.mergeEvaluated.items(u,c.length,f.items));let m=u.name("valid"),h=u.const("len",(0,e._)`${d}.length`);c.forEach((v,S)=>{(0,r.alwaysValidSchema)(f,v)||(u.if((0,e._)`${h} > ${S}`,()=>o.subschema({keyword:p,schemaProp:S,dataProp:S},m)),o.ok(m))});function g(v){let{opts:S,errSchemaPath:_}=f,y=c.length,x=y===v.minItems&&(y===v.maxItems||v[a]===!1);if(S.strictTuples&&!x){let w=`"${p}" is ${y}-tuple, but minItems or maxItems/${a} are not specified or different at path "${_}"`;(0,r.checkStrictMode)(f,w,S.strictTuples)}}}t.validateTuple=s,t.default=i}),yle=re(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=xF(),r={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:n=>(0,e.validateTuple)(n,"items")};t.default=r}),_le=re(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Ze(),r=at(),n=wi(),i=SF(),s={message:({params:{len:a}})=>(0,e.str)`must NOT have more than ${a} items`,params:({params:{len:a}})=>(0,e._)`{limit: ${a}}`},o={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:s,code(a){let{schema:c,parentSchema:u,it:l}=a,{prefixItems:d}=u;l.items=!0,!(0,r.alwaysValidSchema)(l,c)&&(d?(0,i.validateAdditionalItems)(a,d):a.ok((0,n.validateArray)(a)))}};t.default=o}),ble=re(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Ze(),r=at(),n={message:({params:{min:s,max:o}})=>o===void 0?(0,e.str)`must contain at least ${s} valid item(s)`:(0,e.str)`must contain at least ${s} and no more than ${o} valid item(s)`,params:({params:{min:s,max:o}})=>o===void 0?(0,e._)`{minContains: ${s}}`:(0,e._)`{minContains: ${s}, maxContains: ${o}}`},i={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:n,code(s){let{gen:o,schema:a,parentSchema:c,data:u,it:l}=s,d,p,{minContains:f,maxContains:m}=c;l.opts.next?(d=f===void 0?1:f,p=m):d=1;let h=o.const("len",(0,e._)`${u}.length`);if(s.setParams({min:d,max:p}),p===void 0&&d===0){(0,r.checkStrictMode)(l,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(p!==void 0&&d>p){(0,r.checkStrictMode)(l,'"minContains" > "maxContains" is always invalid'),s.fail();return}if((0,r.alwaysValidSchema)(l,a)){let y=(0,e._)`${h} >= ${d}`;p!==void 0&&(y=(0,e._)`${y} && ${h} <= ${p}`),s.pass(y);return}l.items=!0;let g=o.name("valid");p===void 0&&d===1?S(g,()=>o.if(g,()=>o.break())):d===0?(o.let(g,!0),p!==void 0&&o.if((0,e._)`${u}.length > 0`,v)):(o.let(g,!1),v()),s.result(g,()=>s.reset());function v(){let y=o.name("_valid"),x=o.let("count",0);S(y,()=>o.if(y,()=>_(x)))}function S(y,x){o.forRange("i",0,h,w=>{s.subschema({keyword:"contains",dataProp:w,dataPropType:r.Type.Num,compositeRule:!0},y),x()})}function _(y){o.code((0,e._)`${y}++`),p===void 0?o.if((0,e._)`${y} >= ${d}`,()=>o.assign(g,!0).break()):(o.if((0,e._)`${y} > ${p}`,()=>o.assign(g,!1).break()),d===1?o.assign(g,!0):o.if((0,e._)`${y} >= ${d}`,()=>o.assign(g,!0)))}}};t.default=i}),Sle=re(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.validateSchemaDeps=t.validatePropertyDeps=t.error=void 0;var e=Ze(),r=at(),n=wi();t.error={message:({params:{property:c,depsCount:u,deps:l}})=>{let d=u===1?"property":"properties";return(0,e.str)`must have ${d} ${l} when property ${c} is present`},params:({params:{property:c,depsCount:u,deps:l,missingProperty:d}})=>(0,e._)`{property: ${c}, missingProperty: ${d}, depsCount: ${u}, - deps: ${l}}`};var i={keyword:"dependencies",type:"object",schemaType:"object",error:t.error,code(c){let[u,l]=s(c);o(c,u),a(c,l)}};function s({schema:c}){let u={},l={};for(let d in c){if(d==="__proto__")continue;let p=Array.isArray(c[d])?u:l;p[d]=c[d]}return[u,l]}function o(c,u=c.schema){let{gen:l,data:d,it:p}=c;if(Object.keys(u).length===0)return;let f=l.let("missing");for(let m in u){let h=u[m];if(h.length===0)continue;let g=(0,n.propertyInData)(l,d,m,p.opts.ownProperties);c.setParams({property:m,depsCount:h.length,deps:h.join(", ")}),p.allErrors?l.if(g,()=>{for(let v of h)(0,n.checkReportMissingProp)(c,v)}):(l.if((0,e._)`${g} && (${(0,n.checkMissingProp)(c,h,f)})`),(0,n.reportMissingProp)(c,f),l.else())}}t.validatePropertyDeps=o;function a(c,u=c.schema){let{gen:l,data:d,keyword:p,it:f}=c,m=l.name("valid");for(let h in u)(0,r.alwaysValidSchema)(f,u[h])||(l.if((0,n.propertyInData)(l,d,h,f.opts.ownProperties),()=>{let g=c.subschema({keyword:p,schemaProp:h},m);c.mergeValidEvaluated(g,m)},()=>l.var(m,!0)),c.ok(m))}t.validateSchemaDeps=a,t.default=i}),xle=re(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Ze(),r=at(),n={message:"property name must be valid",params:({params:s})=>(0,e._)`{propertyName: ${s.propertyName}}`},i={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:n,code(s){let{gen:o,schema:a,data:c,it:u}=s;if((0,r.alwaysValidSchema)(u,a))return;let l=o.name("valid");o.forIn("key",c,d=>{s.setParams({propertyName:d}),s.subschema({keyword:"propertyNames",data:d,dataTypes:["string"],propertyName:d,compositeRule:!0},l),o.if((0,e.not)(l),()=>{s.error(!0),u.allErrors||o.break()})}),s.ok(l)}};t.default=i}),wF=re(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=wi(),r=Ze(),n=xo(),i=at(),s={message:"must NOT have additional properties",params:({params:a})=>(0,r._)`{additionalProperty: ${a.additionalProperty}}`},o={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:s,code(a){let{gen:c,schema:u,parentSchema:l,data:d,errsCount:p,it:f}=a;if(!p)throw new Error("ajv implementation error");let{allErrors:m,opts:h}=f;if(f.props=!0,h.removeAdditional!=="all"&&(0,i.alwaysValidSchema)(f,u))return;let g=(0,e.allSchemaProperties)(l.properties),v=(0,e.allSchemaProperties)(l.patternProperties);S(),a.ok((0,r._)`${p} === ${n.default.errors}`);function S(){c.forIn("key",d,E=>{!g.length&&!v.length?x(E):c.if(_(E),()=>x(E))})}function _(E){let T;if(g.length>8){let I=(0,i.schemaRefOrVal)(f,l.properties,"properties");T=(0,e.isOwnProperty)(c,I,E)}else g.length?T=(0,r.or)(...g.map(I=>(0,r._)`${E} === ${I}`)):T=r.nil;return v.length&&(T=(0,r.or)(T,...v.map(I=>(0,r._)`${(0,e.usePattern)(a,I)}.test(${E})`))),(0,r.not)(T)}function y(E){c.code((0,r._)`delete ${d}[${E}]`)}function x(E){if(h.removeAdditional==="all"||h.removeAdditional&&u===!1){y(E);return}if(u===!1){a.setParams({additionalProperty:E}),a.error(),m||c.break();return}if(typeof u=="object"&&!(0,i.alwaysValidSchema)(f,u)){let T=c.name("valid");h.removeAdditional==="failing"?(w(E,T,!1),c.if((0,r.not)(T),()=>{a.reset(),y(E)})):(w(E,T),m||c.if((0,r.not)(T),()=>c.break()))}}function w(E,T,I){let A={keyword:"additionalProperties",dataProp:E,dataPropType:i.Type.Str};I===!1&&Object.assign(A,{compositeRule:!0,createErrors:!1,allErrors:!1}),a.subschema(A,T)}}};t.default=o}),wle=re(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Bv(),r=wi(),n=at(),i=wF(),s={keyword:"properties",type:"object",schemaType:"object",code(o){let{gen:a,schema:c,parentSchema:u,data:l,it:d}=o;d.opts.removeAdditional==="all"&&u.additionalProperties===void 0&&i.default.code(new e.KeywordCxt(d,i.default,"additionalProperties"));let p=(0,r.allSchemaProperties)(c);for(let v of p)d.definedProperties.add(v);d.opts.unevaluated&&p.length&&d.props!==!0&&(d.props=n.mergeEvaluated.props(a,(0,n.toHash)(p),d.props));let f=p.filter(v=>!(0,n.alwaysValidSchema)(d,c[v]));if(f.length===0)return;let m=a.name("valid");for(let v of f)h(v)?g(v):(a.if((0,r.propertyInData)(a,l,v,d.opts.ownProperties)),g(v),d.allErrors||a.else().var(m,!0),a.endIf()),o.it.definedProperties.add(v),o.ok(m);function h(v){return d.opts.useDefaults&&!d.compositeRule&&c[v].default!==void 0}function g(v){o.subschema({keyword:"properties",schemaProp:v,dataProp:v},m)}}};t.default=s}),Ele=re(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=wi(),r=Ze(),n=at(),i=at(),s={keyword:"patternProperties",type:"object",schemaType:"object",code(o){let{gen:a,schema:c,data:u,parentSchema:l,it:d}=o,{opts:p}=d,f=(0,e.allSchemaProperties)(c),m=f.filter(x=>(0,n.alwaysValidSchema)(d,c[x]));if(f.length===0||m.length===f.length&&(!d.opts.unevaluated||d.props===!0))return;let h=p.strictSchema&&!p.allowMatchingProperties&&l.properties,g=a.name("valid");d.props!==!0&&!(d.props instanceof r.Name)&&(d.props=(0,i.evaluatedPropsToName)(a,d.props));let{props:v}=d;S();function S(){for(let x of f)h&&_(x),d.allErrors?y(x):(a.var(g,!0),y(x),a.if(g))}function _(x){for(let w in h)new RegExp(x).test(w)&&(0,n.checkStrictMode)(d,`property ${w} matches pattern ${x} (use allowMatchingProperties)`)}function y(x){a.forIn("key",u,w=>{a.if((0,r._)`${(0,e.usePattern)(o,x)}.test(${w})`,()=>{let E=m.includes(x);E||o.subschema({keyword:"patternProperties",schemaProp:x,dataProp:w,dataPropType:i.Type.Str},g),d.opts.unevaluated&&v!==!0?a.assign((0,r._)`${v}[${w}]`,!0):!E&&!d.allErrors&&a.if((0,r.not)(g),()=>a.break())})})}}};t.default=s}),kle=re(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=at(),r={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(n){let{gen:i,schema:s,it:o}=n;if((0,e.alwaysValidSchema)(o,s)){n.fail();return}let a=i.name("valid");n.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},a),n.failResult(a,()=>n.reset(),()=>n.error())},error:{message:"must NOT be valid"}};t.default=r}),Tle=re(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=wi(),r={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:e.validateUnion,error:{message:"must match a schema in anyOf"}};t.default=r}),$le=re(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Ze(),r=at(),n={message:"must match exactly one schema in oneOf",params:({params:s})=>(0,e._)`{passingSchemas: ${s.passing}}`},i={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:n,code(s){let{gen:o,schema:a,parentSchema:c,it:u}=s;if(!Array.isArray(a))throw new Error("ajv implementation error");if(u.opts.discriminator&&c.discriminator)return;let l=a,d=o.let("valid",!1),p=o.let("passing",null),f=o.name("_valid");s.setParams({passing:p}),o.block(m),s.result(d,()=>s.reset(),()=>s.error(!0));function m(){l.forEach((h,g)=>{let v;(0,r.alwaysValidSchema)(u,h)?o.var(f,!0):v=s.subschema({keyword:"oneOf",schemaProp:g,compositeRule:!0},f),g>0&&o.if((0,e._)`${f} && ${d}`).assign(d,!1).assign(p,(0,e._)`[${p}, ${g}]`).else(),o.if(f,()=>{o.assign(d,!0),o.assign(p,g),v&&s.mergeEvaluated(v,e.Name)})})}}};t.default=i}),Ile=re(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=at(),r={keyword:"allOf",schemaType:"array",code(n){let{gen:i,schema:s,it:o}=n;if(!Array.isArray(s))throw new Error("ajv implementation error");let a=i.name("valid");s.forEach((c,u)=>{if((0,e.alwaysValidSchema)(o,c))return;let l=n.subschema({keyword:"allOf",schemaProp:u},a);n.ok(a),n.mergeEvaluated(l)})}};t.default=r}),Rle=re(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Ze(),r=at(),n={message:({params:o})=>(0,e.str)`must match "${o.ifClause}" schema`,params:({params:o})=>(0,e._)`{failingKeyword: ${o.ifClause}}`},i={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:n,code(o){let{gen:a,parentSchema:c,it:u}=o;c.then===void 0&&c.else===void 0&&(0,r.checkStrictMode)(u,'"if" without "then" and "else" is ignored');let l=s(u,"then"),d=s(u,"else");if(!l&&!d)return;let p=a.let("valid",!0),f=a.name("_valid");if(m(),o.reset(),l&&d){let g=a.let("ifClause");o.setParams({ifClause:g}),a.if(f,h("then",g),h("else",g))}else l?a.if(f,h("then")):a.if((0,e.not)(f),h("else"));o.pass(p,()=>o.error(!0));function m(){let g=o.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},f);o.mergeEvaluated(g)}function h(g,v){return()=>{let S=o.subschema({keyword:g},f);a.assign(p,f),o.mergeValidEvaluated(S,p),v?a.assign(v,(0,e._)`${g}`):o.setParams({ifClause:g})}}}};function s(o,a){let c=o.schema[a];return c!==void 0&&!(0,r.alwaysValidSchema)(o,c)}t.default=i}),Ole=re(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=at(),r={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:n,parentSchema:i,it:s}){i.if===void 0&&(0,e.checkStrictMode)(s,`"${n}" without "if" is ignored`)}};t.default=r}),Cle=re(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=SF(),r=yle(),n=xF(),i=_le(),s=ble(),o=Sle(),a=xle(),c=wF(),u=wle(),l=Ele(),d=kle(),p=Tle(),f=$le(),m=Ile(),h=Rle(),g=Ole();function v(S=!1){let _=[d.default,p.default,f.default,m.default,h.default,g.default,a.default,c.default,o.default,u.default,l.default];return S?_.push(r.default,i.default):_.push(e.default,n.default),_.push(s.default),_}t.default=v}),Ple=re(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Ze(),r={message:({schemaCode:i})=>(0,e.str)`must match format "${i}"`,params:({schemaCode:i})=>(0,e._)`{format: ${i}}`},n={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:r,code(i,s){let{gen:o,data:a,$data:c,schema:u,schemaCode:l,it:d}=i,{opts:p,errSchemaPath:f,schemaEnv:m,self:h}=d;if(!p.validateFormats)return;c?g():v();function g(){let S=o.scopeValue("formats",{ref:h.formats,code:p.code.formats}),_=o.const("fDef",(0,e._)`${S}[${l}]`),y=o.let("fType"),x=o.let("format");o.if((0,e._)`typeof ${_} == "object" && !(${_} instanceof RegExp)`,()=>o.assign(y,(0,e._)`${_}.type || "string"`).assign(x,(0,e._)`${_}.validate`),()=>o.assign(y,(0,e._)`"string"`).assign(x,_)),i.fail$data((0,e.or)(w(),E()));function w(){return p.strictSchema===!1?e.nil:(0,e._)`${l} && !${x}`}function E(){let T=m.$async?(0,e._)`(${_}.async ? await ${x}(${a}) : ${x}(${a}))`:(0,e._)`${x}(${a})`,I=(0,e._)`(typeof ${x} == "function" ? ${T} : ${x}.test(${a}))`;return(0,e._)`${x} && ${x} !== true && ${y} === ${s} && !${I}`}}function v(){let S=h.formats[u];if(!S){w();return}if(S===!0)return;let[_,y,x]=E(S);_===s&&i.pass(T());function w(){if(p.strictSchema===!1){h.logger.warn(I());return}throw new Error(I());function I(){return`unknown format "${u}" ignored in schema at path "${f}"`}}function E(I){let A=I instanceof RegExp?(0,e.regexpCode)(I):p.code.formats?(0,e._)`${p.code.formats}${(0,e.getProperty)(u)}`:void 0,N=o.scopeValue("formats",{key:u,ref:I,code:A});return typeof I=="object"&&!(I instanceof RegExp)?[I.type||"string",I.validate,(0,e._)`${N}.validate`]:["string",I,N]}function T(){if(typeof S=="object"&&!(S instanceof RegExp)&&S.async){if(!m.$async)throw new Error("async format in sync schema");return(0,e._)`await ${x}(${a})`}return typeof y=="function"?(0,e._)`${x}(${a})`:(0,e._)`${x}.test(${a})`}}}};t.default=n}),Ale=re(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Ple(),r=[e.default];t.default=r}),Nle=re(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.contentVocabulary=t.metadataVocabulary=void 0,t.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],t.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]}),Mle=re(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=sle(),r=vle(),n=Cle(),i=Ale(),s=Nle(),o=[e.default,r.default,(0,n.default)(),i.default,s.metadataVocabulary,s.contentVocabulary];t.default=o}),Dle=re(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DiscrError=void 0;var e;(function(r){r.Tag="tag",r.Mapping="mapping"})(e||(t.DiscrError=e={}))}),jle=re(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Ze(),r=Dle(),n=N$(),i=Gv(),s=at(),o={message:({params:{discrError:c,tagName:u}})=>c===r.DiscrError.Tag?`tag "${u}" must be string`:`value of tag "${u}" must be in oneOf`,params:({params:{discrError:c,tag:u,tagName:l}})=>(0,e._)`{error: ${c}, tag: ${l}, tagValue: ${u}}`},a={keyword:"discriminator",type:"object",schemaType:"object",error:o,code(c){let{gen:u,data:l,schema:d,parentSchema:p,it:f}=c,{oneOf:m}=p;if(!f.opts.discriminator)throw new Error("discriminator: requires discriminator option");let h=d.propertyName;if(typeof h!="string")throw new Error("discriminator: requires propertyName");if(d.mapping)throw new Error("discriminator: mapping is not supported");if(!m)throw new Error("discriminator: requires oneOf keyword");let g=u.let("valid",!1),v=u.const("tag",(0,e._)`${l}${(0,e.getProperty)(h)}`);u.if((0,e._)`typeof ${v} == "string"`,()=>S(),()=>c.error(!1,{discrError:r.DiscrError.Tag,tag:v,tagName:h})),c.ok(g);function S(){let x=y();u.if(!1);for(let w in x)u.elseIf((0,e._)`${v} === ${w}`),u.assign(g,_(x[w]));u.else(),c.error(!1,{discrError:r.DiscrError.Mapping,tag:v,tagName:h}),u.endIf()}function _(x){let w=u.name("valid"),E=c.subschema({keyword:"oneOf",schemaProp:x},w);return c.mergeEvaluated(E,e.Name),w}function y(){var x;let w={},E=I(p),T=!0;for(let U=0;U{e.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}}),EF=re((t,e)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MissingRefError=t.ValidationError=t.CodeGen=t.Name=t.nil=t.stringify=t.str=t._=t.KeywordCxt=t.Ajv=void 0;var r=rle(),n=Mle(),i=jle(),s=zle(),o=["/properties"],a="http://json-schema.org/draft-07/schema";class c extends r.default{_addVocabularies(){super._addVocabularies(),n.default.forEach(m=>this.addVocabulary(m)),this.opts.discriminator&&this.addKeyword(i.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let m=this.opts.$data?this.$dataMetaSchema(s,o):s;this.addMetaSchema(m,a,!1),this.refs["http://json-schema.org/schema"]=a}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(a)?a:void 0)}}t.Ajv=c,e.exports=t=c,e.exports.Ajv=c,Object.defineProperty(t,"__esModule",{value:!0}),t.default=c;var u=Bv();Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return u.KeywordCxt}});var l=Ze();Object.defineProperty(t,"_",{enumerable:!0,get:function(){return l._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return l.str}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return l.stringify}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return l.nil}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return l.Name}}),Object.defineProperty(t,"CodeGen",{enumerable:!0,get:function(){return l.CodeGen}});var d=A$();Object.defineProperty(t,"ValidationError",{enumerable:!0,get:function(){return d.default}});var p=Gv();Object.defineProperty(t,"MissingRefError",{enumerable:!0,get:function(){return p.default}})}),Lle=re(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.formatNames=t.fastFormats=t.fullFormats=void 0;function e(N,U){return{validate:N,compare:U}}t.fullFormats={date:e(s,o),time:e(c(!0),u),"date-time":e(p(!0),f),"iso-time":e(c(),l),"iso-date-time":e(p(),m),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:v,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:A,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:_,int32:{type:"number",validate:w},int64:{type:"number",validate:E},float:{type:"number",validate:T},double:{type:"number",validate:T},password:!0,binary:!0},t.fastFormats={...t.fullFormats,date:e(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,o),time:e(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,u),"date-time":e(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,f),"iso-time":e(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,l),"iso-date-time":e(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,m),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i},t.formatNames=Object.keys(t.fullFormats);function r(N){return N%4===0&&(N%100!==0||N%400===0)}var n=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,i=[0,31,28,31,30,31,30,31,31,30,31,30,31];function s(N){let U=n.exec(N);if(!U)return!1;let V=+U[1],j=+U[2],ae=+U[3];return j>=1&&j<=12&&ae>=1&&ae<=(j===2&&r(V)?29:i[j])}function o(N,U){if(N&&U)return N>U?1:N23||C>59||N&&!Et)return!1;if(ae<=23&&Ne<=59&&ze<60)return!0;let H=Ne-C*Ge,M=ae-K*Ge-(H<0?1:0);return(M===23||M===-1)&&(H===59||H===-1)&&ze<61}}function u(N,U){if(!(N&&U))return;let V=new Date("2020-01-01T"+N).valueOf(),j=new Date("2020-01-01T"+U).valueOf();if(V&&j)return V-j}function l(N,U){if(!(N&&U))return;let V=a.exec(N),j=a.exec(U);if(V&&j)return N=V[1]+V[2]+V[3],U=j[1]+j[2]+j[3],N>U?1:N=y}function E(N){return Number.isInteger(N)}function T(){return!0}var I=/[^\\]\\Z/;function A(N){if(I.test(N))return!1;try{return new RegExp(N),!0}catch{return!1}}}),Ule=re(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.formatLimitDefinition=void 0;var e=EF(),r=Ze(),n=r.operators,i={formatMaximum:{okStr:"<=",ok:n.LTE,fail:n.GT},formatMinimum:{okStr:">=",ok:n.GTE,fail:n.LT},formatExclusiveMaximum:{okStr:"<",ok:n.LT,fail:n.GTE},formatExclusiveMinimum:{okStr:">",ok:n.GT,fail:n.LTE}},s={message:({keyword:a,schemaCode:c})=>(0,r.str)`should be ${i[a].okStr} ${c}`,params:({keyword:a,schemaCode:c})=>(0,r._)`{comparison: ${i[a].okStr}, limit: ${c}}`};t.formatLimitDefinition={keyword:Object.keys(i),type:"string",schemaType:"string",$data:!0,error:s,code(a){let{gen:c,data:u,schemaCode:l,keyword:d,it:p}=a,{opts:f,self:m}=p;if(!f.validateFormats)return;let h=new e.KeywordCxt(p,m.RULES.all.format.definition,"format");h.$data?g():v();function g(){let _=c.scopeValue("formats",{ref:m.formats,code:f.code.formats}),y=c.const("fmt",(0,r._)`${_}[${h.schemaCode}]`);a.fail$data((0,r.or)((0,r._)`typeof ${y} != "object"`,(0,r._)`${y} instanceof RegExp`,(0,r._)`typeof ${y}.compare != "function"`,S(y)))}function v(){let _=h.schema,y=m.formats[_];if(!y||y===!0)return;if(typeof y!="object"||y instanceof RegExp||typeof y.compare!="function")throw new Error(`"${d}": format "${_}" does not define "compare" function`);let x=c.scopeValue("formats",{key:_,ref:y,code:f.code.formats?(0,r._)`${f.code.formats}${(0,r.getProperty)(_)}`:void 0});a.fail$data(S(x))}function S(_){return(0,r._)`${_}.compare(${u}, ${l}) ${i[d].fail} 0`}},dependencies:["format"]};var o=a=>(a.addKeyword(t.formatLimitDefinition),a);t.default=o}),Fle=re((t,e)=>{Object.defineProperty(t,"__esModule",{value:!0});var r=Lle(),n=Ule(),i=Ze(),s=new i.Name("fullFormats"),o=new i.Name("fastFormats"),a=(u,l={keywords:!0})=>{if(Array.isArray(l))return c(u,l,r.fullFormats,s),u;let[d,p]=l.mode==="fast"?[r.fastFormats,o]:[r.fullFormats,s],f=l.formats||r.formatNames;return c(u,f,d,p),l.keywords&&(0,n.default)(u),u};a.get=(u,l="full")=>{let p=(l==="fast"?r.fastFormats:r.fullFormats)[u];if(!p)throw new Error(`Unknown format "${u}"`);return p};function c(u,l,d,p){var f,m;(f=(m=u.opts.code).formats)!==null&&f!==void 0||(m.formats=(0,i._)`require("ajv-formats/dist/formats").${p}`);for(let h of l)u.addFormat(h,d[h])}e.exports=t=a,Object.defineProperty(t,"__esModule",{value:!0}),t.default=a}),qle=50;function $F(t=qle){let e=new AbortController;return(0,TF.setMaxListeners)(t,e.signal),e}var Hle=typeof global=="object"&&global&&global.Object===Object&&global,Zle=Hle,Ble=typeof self=="object"&&self&&self.Object===Object&&self,Gle=Zle||Ble||Function("return this")(),D$=Gle,Wle=D$.Symbol,jv=Wle,CF=Object.prototype,Vle=CF.hasOwnProperty,Kle=CF.toString,Ap=jv?jv.toStringTag:void 0;function Jle(t){var e=Vle.call(t,Ap),r=t[Ap];try{t[Ap]=void 0;var n=!0}catch{}var i=Kle.call(t);return n&&(e?t[Ap]=r:delete t[Ap]),i}var Xle=Jle,Yle=Object.prototype,Qle=Yle.toString;function ede(t){return Qle.call(t)}var tde=ede,rde="[object Null]",nde="[object Undefined]",U6=jv?jv.toStringTag:void 0;function ide(t){return t==null?t===void 0?nde:rde:U6&&U6 in Object(t)?Xle(t):tde(t)}var sde=ide;function ode(t){var e=typeof t;return t!=null&&(e=="object"||e=="function")}var PF=ode,ade="[object AsyncFunction]",cde="[object Function]",ude="[object GeneratorFunction]",lde="[object Proxy]";function dde(t){if(!PF(t))return!1;var e=sde(t);return e==cde||e==ude||e==ade||e==lde}var pde=dde,fde=D$["__core-js_shared__"],a$=fde,F6=(function(){var t=/[^.]+$/.exec(a$&&a$.keys&&a$.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""})();function mde(t){return!!F6&&F6 in t}var hde=mde,gde=Function.prototype,vde=gde.toString;function yde(t){if(t!=null){try{return vde.call(t)}catch{}try{return t+""}catch{}}return""}var _de=yde,bde=/[\\^$.*+?()[\]{}|]/g,Sde=/^\[object .+?Constructor\]$/,xde=Function.prototype,wde=Object.prototype,Ede=xde.toString,kde=wde.hasOwnProperty,Tde=RegExp("^"+Ede.call(kde).replace(bde,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function $de(t){if(!PF(t)||hde(t))return!1;var e=pde(t)?Tde:Sde;return e.test(_de(t))}var Ide=$de;function Rde(t,e){return t?.[e]}var Ode=Rde;function Cde(t,e){var r=Ode(t,e);return Ide(r)?r:void 0}var AF=Cde,Pde=AF(Object,"create"),Dp=Pde;function Ade(){this.__data__=Dp?Dp(null):{},this.size=0}var Nde=Ade;function Mde(t){var e=this.has(t)&&delete this.__data__[t];return this.size-=e?1:0,e}var Dde=Mde,jde="__lodash_hash_undefined__",zde=Object.prototype,Lde=zde.hasOwnProperty;function Ude(t){var e=this.__data__;if(Dp){var r=e[t];return r===jde?void 0:r}return Lde.call(e,t)?e[t]:void 0}var Fde=Ude,qde=Object.prototype,Hde=qde.hasOwnProperty;function Zde(t){var e=this.__data__;return Dp?e[t]!==void 0:Hde.call(e,t)}var Bde=Zde,Gde="__lodash_hash_undefined__";function Wde(t,e){var r=this.__data__;return this.size+=this.has(t)?0:1,r[t]=Dp&&e===void 0?Gde:e,this}var Vde=Wde;function Ru(t){var e=-1,r=t==null?0:t.length;for(this.clear();++e-1}var ape=ope;function cpe(t,e){var r=this.__data__,n=Wv(r,t);return n<0?(++this.size,r.push([t,e])):r[n][1]=e,this}var upe=cpe;function Ou(t){var e=-1,r=t==null?0:t.length;for(this.clear();++e{if(!t||t.trim()==="")return null;let e=t.split(",").map(s=>s.trim()).filter(Boolean);if(e.length===0)return null;let r=e.some(s=>s.startsWith("!")),n=e.some(s=>!s.startsWith("!"));if(r&&n)return null;let i=e.map(s=>s.replace(/^!/,"").toLowerCase());return{include:r?[]:i,exclude:r?i:[],isExclusive:r}});function Rpe(t){let e=[],r=t.match(/^MCP server ["']([^"']+)["']/);if(r&&r[1])e.push("mcp"),e.push(r[1].toLowerCase());else{let s=t.match(/^([^:[]+):/);s&&s[1]&&e.push(s[1].trim().toLowerCase())}let n=t.match(/^\[([^\]]+)]/);n&&n[1]&&e.push(n[1].trim().toLowerCase()),t.toLowerCase().includes("statsig event:")&&e.push("statsig");let i=t.match(/:\s*([^:]+?)(?:\s+(?:type|mode|status|event))?:/);if(i&&i[1]){let s=i[1].trim().toLowerCase();s.length<30&&!s.includes(" ")&&e.push(s)}return Array.from(new Set(e))}function Ope(t,e){return e?t.length===0?!1:e.isExclusive?!t.some(r=>e.exclude.includes(r)):t.some(r=>e.include.includes(r)):!0}function Cpe(t,e){if(!e)return!0;let r=Rpe(t);return Ope(r,e)}function jF(){return process.env.CLAUDE_CONFIG_DIR??(0,MF.join)((0,DF.homedir)(),".claude")}function Z6(t){if(!t)return!1;if(typeof t=="boolean")return t;let e=t.toLowerCase().trim();return["1","true","yes","on"].includes(e)}var c$=15e4,Rv=3e4;function FF(t){return{name:t,default:Rv,validate:e=>{if(!e)return{effective:Rv,status:"valid"};let r=parseInt(e,10);return isNaN(r)||r<=0?{effective:Rv,status:"invalid",message:`Invalid value "${e}" (using default: ${Rv})`}:r>c$?{effective:c$,status:"capped",message:`Capped from ${r} to ${c$}`}:{effective:r,status:"valid"}}}}var Ppe=FF("BASH_MAX_OUTPUT_LENGTH"),mDe=FF("TASK_MAX_OUTPUT_LENGTH"),Ape={name:"CLAUDE_CODE_MAX_OUTPUT_TOKENS",default:32e3,validate:t=>{if(!t)return{effective:32e3,status:"valid"};let n=parseInt(t,10);return isNaN(n)||n<=0?{effective:32e3,status:"invalid",message:`Invalid value "${t}" (using default: 32000)`}:n>64e3?{effective:64e3,status:"capped",message:`Capped from ${n} to 64000`}:{effective:n,status:"valid"}}};function Npe(){let t="";return typeof process<"u"&&typeof process.cwd=="function"&&(t=(0,LF.realpathSync)((0,zF.cwd)())),{originalCwd:t,totalCostUSD:0,totalAPIDuration:0,totalAPIDurationWithoutRetries:0,totalToolDuration:0,startTime:Date.now(),lastInteractionTime:Date.now(),totalLinesAdded:0,totalLinesRemoved:0,hasUnknownModelCost:!1,cwd:t,modelUsage:{},mainLoopModelOverride:void 0,initialMainLoopModel:null,modelStrings:null,isInteractive:!1,clientType:"cli",sessionIngressToken:void 0,oauthTokenFromFd:void 0,apiKeyFromFd:void 0,flagSettingsPath:void 0,allowedSettingSources:["userSettings","projectSettings","localSettings","flagSettings","policySettings"],meter:null,sessionCounter:null,locCounter:null,prCounter:null,commitCounter:null,costCounter:null,tokenCounter:null,codeEditToolDecisionCounter:null,activeTimeCounter:null,sessionId:(0,UF.randomUUID)(),loggerProvider:null,eventLogger:null,meterProvider:null,tracerProvider:null,agentColorMap:new Map,agentColorIndex:0,envVarValidators:[Ppe,Ape],lastAPIRequest:null,inMemoryErrorLog:[],inlinePlugins:[],sessionBypassPermissionsMode:!1,sessionPersistenceDisabled:!1,hasExitedPlanMode:!1,needsPlanModeExitAttachment:!1,hasExitedDelegateMode:!1,needsDelegateModeExitAttachment:!1,lspRecommendationShownThisSession:!1,initJsonSchema:null,registeredHooks:null,planSlugCache:new Map,teleportedSessionInfo:null,invokedSkills:new Map,slowOperations:[],sdkBetas:void 0}}var Mpe=Npe();function Dpe(){return Mpe.sessionId}function jpe({writeFn:t,flushIntervalMs:e=1e3,maxBufferSize:r=100,immediateMode:n=!1}){let i=[],s=null;function o(){s&&(clearTimeout(s),s=null)}function a(){i.length!==0&&(t(i.join("")),i=[],o())}function c(){s||(s=setTimeout(a,e))}return{write(u){if(n){t(u);return}i.push(u),c(),i.length>=r&&a()},flush:a,dispose(){a()}}}var B6=new Set;function zpe(t){return B6.add(t),()=>B6.delete(t)}var qF=1/0;function Lpe(t){return t===null?"null":t===void 0?"undefined":Array.isArray(t)?`Array[${t.length}]`:typeof t=="object"?`Object{${Object.keys(t).length} keys}`:typeof t=="string"?`string(${t.length} chars)`:typeof t}function HF(t,e){let r=performance.now();try{return e()}finally{let n=performance.now()-r;n>qF&&(Ps(`[SLOW OPERATION DETECTED] ${t} (${n.toFixed(1)}ms)`),void 0)}}function Xi(t,e,r){let n=Lpe(t);return HF(`JSON.stringify(${n})`,()=>JSON.stringify(t,e,r))}var ZF=(t,e)=>{let r=typeof t=="string"?t.length:0;return HF(`JSON.parse(${r} chars)`,()=>JSON.parse(t,e))},Upe=Jp(()=>Z6(process.env.DEBUG)||Z6(process.env.DEBUG_SDK)||process.argv.includes("--debug")||process.argv.includes("-d")||BF()||process.argv.some(t=>t.startsWith("--debug="))),Fpe=Jp(()=>{let t=process.argv.find(r=>r.startsWith("--debug="));if(!t)return null;let e=t.substring(8);return Ipe(e)}),BF=Jp(()=>process.argv.includes("--debug-to-stderr")||process.argv.includes("-d2e"));function qpe(t){if(typeof process>"u"||typeof process.versions>"u"||typeof process.versions.node>"u")return!1;let e=Fpe();return Cpe(t,e)}var Hpe=!1,Ov=null;function Zpe(){return Ov||(Ov=jpe({writeFn:t=>{let e=GF();As().existsSync((0,_a.dirname)(e))||As().mkdirSync((0,_a.dirname)(e)),As().appendFileSync(e,t),Bpe()},flushIntervalMs:1e3,maxBufferSize:100,immediateMode:Upe()}),zpe(async()=>Ov?.dispose())),Ov}function Ps(t,{level:e}={level:"debug"}){if(!qpe(t))return;Hpe&&t.includes(` + deps: ${l}}`};var i={keyword:"dependencies",type:"object",schemaType:"object",error:t.error,code(c){let[u,l]=s(c);o(c,u),a(c,l)}};function s({schema:c}){let u={},l={};for(let d in c){if(d==="__proto__")continue;let p=Array.isArray(c[d])?u:l;p[d]=c[d]}return[u,l]}function o(c,u=c.schema){let{gen:l,data:d,it:p}=c;if(Object.keys(u).length===0)return;let f=l.let("missing");for(let m in u){let h=u[m];if(h.length===0)continue;let g=(0,n.propertyInData)(l,d,m,p.opts.ownProperties);c.setParams({property:m,depsCount:h.length,deps:h.join(", ")}),p.allErrors?l.if(g,()=>{for(let v of h)(0,n.checkReportMissingProp)(c,v)}):(l.if((0,e._)`${g} && (${(0,n.checkMissingProp)(c,h,f)})`),(0,n.reportMissingProp)(c,f),l.else())}}t.validatePropertyDeps=o;function a(c,u=c.schema){let{gen:l,data:d,keyword:p,it:f}=c,m=l.name("valid");for(let h in u)(0,r.alwaysValidSchema)(f,u[h])||(l.if((0,n.propertyInData)(l,d,h,f.opts.ownProperties),()=>{let g=c.subschema({keyword:p,schemaProp:h},m);c.mergeValidEvaluated(g,m)},()=>l.var(m,!0)),c.ok(m))}t.validateSchemaDeps=a,t.default=i}),xle=re(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Ze(),r=at(),n={message:"property name must be valid",params:({params:s})=>(0,e._)`{propertyName: ${s.propertyName}}`},i={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:n,code(s){let{gen:o,schema:a,data:c,it:u}=s;if((0,r.alwaysValidSchema)(u,a))return;let l=o.name("valid");o.forIn("key",c,d=>{s.setParams({propertyName:d}),s.subschema({keyword:"propertyNames",data:d,dataTypes:["string"],propertyName:d,compositeRule:!0},l),o.if((0,e.not)(l),()=>{s.error(!0),u.allErrors||o.break()})}),s.ok(l)}};t.default=i}),wF=re(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=wi(),r=Ze(),n=xo(),i=at(),s={message:"must NOT have additional properties",params:({params:a})=>(0,r._)`{additionalProperty: ${a.additionalProperty}}`},o={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:s,code(a){let{gen:c,schema:u,parentSchema:l,data:d,errsCount:p,it:f}=a;if(!p)throw new Error("ajv implementation error");let{allErrors:m,opts:h}=f;if(f.props=!0,h.removeAdditional!=="all"&&(0,i.alwaysValidSchema)(f,u))return;let g=(0,e.allSchemaProperties)(l.properties),v=(0,e.allSchemaProperties)(l.patternProperties);S(),a.ok((0,r._)`${p} === ${n.default.errors}`);function S(){c.forIn("key",d,E=>{!g.length&&!v.length?x(E):c.if(_(E),()=>x(E))})}function _(E){let T;if(g.length>8){let I=(0,i.schemaRefOrVal)(f,l.properties,"properties");T=(0,e.isOwnProperty)(c,I,E)}else g.length?T=(0,r.or)(...g.map(I=>(0,r._)`${E} === ${I}`)):T=r.nil;return v.length&&(T=(0,r.or)(T,...v.map(I=>(0,r._)`${(0,e.usePattern)(a,I)}.test(${E})`))),(0,r.not)(T)}function y(E){c.code((0,r._)`delete ${d}[${E}]`)}function x(E){if(h.removeAdditional==="all"||h.removeAdditional&&u===!1){y(E);return}if(u===!1){a.setParams({additionalProperty:E}),a.error(),m||c.break();return}if(typeof u=="object"&&!(0,i.alwaysValidSchema)(f,u)){let T=c.name("valid");h.removeAdditional==="failing"?(w(E,T,!1),c.if((0,r.not)(T),()=>{a.reset(),y(E)})):(w(E,T),m||c.if((0,r.not)(T),()=>c.break()))}}function w(E,T,I){let A={keyword:"additionalProperties",dataProp:E,dataPropType:i.Type.Str};I===!1&&Object.assign(A,{compositeRule:!0,createErrors:!1,allErrors:!1}),a.subschema(A,T)}}};t.default=o}),wle=re(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Bv(),r=wi(),n=at(),i=wF(),s={keyword:"properties",type:"object",schemaType:"object",code(o){let{gen:a,schema:c,parentSchema:u,data:l,it:d}=o;d.opts.removeAdditional==="all"&&u.additionalProperties===void 0&&i.default.code(new e.KeywordCxt(d,i.default,"additionalProperties"));let p=(0,r.allSchemaProperties)(c);for(let v of p)d.definedProperties.add(v);d.opts.unevaluated&&p.length&&d.props!==!0&&(d.props=n.mergeEvaluated.props(a,(0,n.toHash)(p),d.props));let f=p.filter(v=>!(0,n.alwaysValidSchema)(d,c[v]));if(f.length===0)return;let m=a.name("valid");for(let v of f)h(v)?g(v):(a.if((0,r.propertyInData)(a,l,v,d.opts.ownProperties)),g(v),d.allErrors||a.else().var(m,!0),a.endIf()),o.it.definedProperties.add(v),o.ok(m);function h(v){return d.opts.useDefaults&&!d.compositeRule&&c[v].default!==void 0}function g(v){o.subschema({keyword:"properties",schemaProp:v,dataProp:v},m)}}};t.default=s}),Ele=re(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=wi(),r=Ze(),n=at(),i=at(),s={keyword:"patternProperties",type:"object",schemaType:"object",code(o){let{gen:a,schema:c,data:u,parentSchema:l,it:d}=o,{opts:p}=d,f=(0,e.allSchemaProperties)(c),m=f.filter(x=>(0,n.alwaysValidSchema)(d,c[x]));if(f.length===0||m.length===f.length&&(!d.opts.unevaluated||d.props===!0))return;let h=p.strictSchema&&!p.allowMatchingProperties&&l.properties,g=a.name("valid");d.props!==!0&&!(d.props instanceof r.Name)&&(d.props=(0,i.evaluatedPropsToName)(a,d.props));let{props:v}=d;S();function S(){for(let x of f)h&&_(x),d.allErrors?y(x):(a.var(g,!0),y(x),a.if(g))}function _(x){for(let w in h)new RegExp(x).test(w)&&(0,n.checkStrictMode)(d,`property ${w} matches pattern ${x} (use allowMatchingProperties)`)}function y(x){a.forIn("key",u,w=>{a.if((0,r._)`${(0,e.usePattern)(o,x)}.test(${w})`,()=>{let E=m.includes(x);E||o.subschema({keyword:"patternProperties",schemaProp:x,dataProp:w,dataPropType:i.Type.Str},g),d.opts.unevaluated&&v!==!0?a.assign((0,r._)`${v}[${w}]`,!0):!E&&!d.allErrors&&a.if((0,r.not)(g),()=>a.break())})})}}};t.default=s}),kle=re(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=at(),r={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(n){let{gen:i,schema:s,it:o}=n;if((0,e.alwaysValidSchema)(o,s)){n.fail();return}let a=i.name("valid");n.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},a),n.failResult(a,()=>n.reset(),()=>n.error())},error:{message:"must NOT be valid"}};t.default=r}),Tle=re(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=wi(),r={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:e.validateUnion,error:{message:"must match a schema in anyOf"}};t.default=r}),$le=re(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Ze(),r=at(),n={message:"must match exactly one schema in oneOf",params:({params:s})=>(0,e._)`{passingSchemas: ${s.passing}}`},i={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:n,code(s){let{gen:o,schema:a,parentSchema:c,it:u}=s;if(!Array.isArray(a))throw new Error("ajv implementation error");if(u.opts.discriminator&&c.discriminator)return;let l=a,d=o.let("valid",!1),p=o.let("passing",null),f=o.name("_valid");s.setParams({passing:p}),o.block(m),s.result(d,()=>s.reset(),()=>s.error(!0));function m(){l.forEach((h,g)=>{let v;(0,r.alwaysValidSchema)(u,h)?o.var(f,!0):v=s.subschema({keyword:"oneOf",schemaProp:g,compositeRule:!0},f),g>0&&o.if((0,e._)`${f} && ${d}`).assign(d,!1).assign(p,(0,e._)`[${p}, ${g}]`).else(),o.if(f,()=>{o.assign(d,!0),o.assign(p,g),v&&s.mergeEvaluated(v,e.Name)})})}}};t.default=i}),Ile=re(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=at(),r={keyword:"allOf",schemaType:"array",code(n){let{gen:i,schema:s,it:o}=n;if(!Array.isArray(s))throw new Error("ajv implementation error");let a=i.name("valid");s.forEach((c,u)=>{if((0,e.alwaysValidSchema)(o,c))return;let l=n.subschema({keyword:"allOf",schemaProp:u},a);n.ok(a),n.mergeEvaluated(l)})}};t.default=r}),Rle=re(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Ze(),r=at(),n={message:({params:o})=>(0,e.str)`must match "${o.ifClause}" schema`,params:({params:o})=>(0,e._)`{failingKeyword: ${o.ifClause}}`},i={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:n,code(o){let{gen:a,parentSchema:c,it:u}=o;c.then===void 0&&c.else===void 0&&(0,r.checkStrictMode)(u,'"if" without "then" and "else" is ignored');let l=s(u,"then"),d=s(u,"else");if(!l&&!d)return;let p=a.let("valid",!0),f=a.name("_valid");if(m(),o.reset(),l&&d){let g=a.let("ifClause");o.setParams({ifClause:g}),a.if(f,h("then",g),h("else",g))}else l?a.if(f,h("then")):a.if((0,e.not)(f),h("else"));o.pass(p,()=>o.error(!0));function m(){let g=o.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},f);o.mergeEvaluated(g)}function h(g,v){return()=>{let S=o.subschema({keyword:g},f);a.assign(p,f),o.mergeValidEvaluated(S,p),v?a.assign(v,(0,e._)`${g}`):o.setParams({ifClause:g})}}}};function s(o,a){let c=o.schema[a];return c!==void 0&&!(0,r.alwaysValidSchema)(o,c)}t.default=i}),Ole=re(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=at(),r={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:n,parentSchema:i,it:s}){i.if===void 0&&(0,e.checkStrictMode)(s,`"${n}" without "if" is ignored`)}};t.default=r}),Cle=re(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=SF(),r=yle(),n=xF(),i=_le(),s=ble(),o=Sle(),a=xle(),c=wF(),u=wle(),l=Ele(),d=kle(),p=Tle(),f=$le(),m=Ile(),h=Rle(),g=Ole();function v(S=!1){let _=[d.default,p.default,f.default,m.default,h.default,g.default,a.default,c.default,o.default,u.default,l.default];return S?_.push(r.default,i.default):_.push(e.default,n.default),_.push(s.default),_}t.default=v}),Ple=re(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Ze(),r={message:({schemaCode:i})=>(0,e.str)`must match format "${i}"`,params:({schemaCode:i})=>(0,e._)`{format: ${i}}`},n={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:r,code(i,s){let{gen:o,data:a,$data:c,schema:u,schemaCode:l,it:d}=i,{opts:p,errSchemaPath:f,schemaEnv:m,self:h}=d;if(!p.validateFormats)return;c?g():v();function g(){let S=o.scopeValue("formats",{ref:h.formats,code:p.code.formats}),_=o.const("fDef",(0,e._)`${S}[${l}]`),y=o.let("fType"),x=o.let("format");o.if((0,e._)`typeof ${_} == "object" && !(${_} instanceof RegExp)`,()=>o.assign(y,(0,e._)`${_}.type || "string"`).assign(x,(0,e._)`${_}.validate`),()=>o.assign(y,(0,e._)`"string"`).assign(x,_)),i.fail$data((0,e.or)(w(),E()));function w(){return p.strictSchema===!1?e.nil:(0,e._)`${l} && !${x}`}function E(){let T=m.$async?(0,e._)`(${_}.async ? await ${x}(${a}) : ${x}(${a}))`:(0,e._)`${x}(${a})`,I=(0,e._)`(typeof ${x} == "function" ? ${T} : ${x}.test(${a}))`;return(0,e._)`${x} && ${x} !== true && ${y} === ${s} && !${I}`}}function v(){let S=h.formats[u];if(!S){w();return}if(S===!0)return;let[_,y,x]=E(S);_===s&&i.pass(T());function w(){if(p.strictSchema===!1){h.logger.warn(I());return}throw new Error(I());function I(){return`unknown format "${u}" ignored in schema at path "${f}"`}}function E(I){let A=I instanceof RegExp?(0,e.regexpCode)(I):p.code.formats?(0,e._)`${p.code.formats}${(0,e.getProperty)(u)}`:void 0,N=o.scopeValue("formats",{key:u,ref:I,code:A});return typeof I=="object"&&!(I instanceof RegExp)?[I.type||"string",I.validate,(0,e._)`${N}.validate`]:["string",I,N]}function T(){if(typeof S=="object"&&!(S instanceof RegExp)&&S.async){if(!m.$async)throw new Error("async format in sync schema");return(0,e._)`await ${x}(${a})`}return typeof y=="function"?(0,e._)`${x}(${a})`:(0,e._)`${x}.test(${a})`}}}};t.default=n}),Ale=re(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Ple(),r=[e.default];t.default=r}),Nle=re(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.contentVocabulary=t.metadataVocabulary=void 0,t.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],t.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]}),Mle=re(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=sle(),r=vle(),n=Cle(),i=Ale(),s=Nle(),o=[e.default,r.default,(0,n.default)(),i.default,s.metadataVocabulary,s.contentVocabulary];t.default=o}),Dle=re(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DiscrError=void 0;var e;(function(r){r.Tag="tag",r.Mapping="mapping"})(e||(t.DiscrError=e={}))}),jle=re(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Ze(),r=Dle(),n=N$(),i=Gv(),s=at(),o={message:({params:{discrError:c,tagName:u}})=>c===r.DiscrError.Tag?`tag "${u}" must be string`:`value of tag "${u}" must be in oneOf`,params:({params:{discrError:c,tag:u,tagName:l}})=>(0,e._)`{error: ${c}, tag: ${l}, tagValue: ${u}}`},a={keyword:"discriminator",type:"object",schemaType:"object",error:o,code(c){let{gen:u,data:l,schema:d,parentSchema:p,it:f}=c,{oneOf:m}=p;if(!f.opts.discriminator)throw new Error("discriminator: requires discriminator option");let h=d.propertyName;if(typeof h!="string")throw new Error("discriminator: requires propertyName");if(d.mapping)throw new Error("discriminator: mapping is not supported");if(!m)throw new Error("discriminator: requires oneOf keyword");let g=u.let("valid",!1),v=u.const("tag",(0,e._)`${l}${(0,e.getProperty)(h)}`);u.if((0,e._)`typeof ${v} == "string"`,()=>S(),()=>c.error(!1,{discrError:r.DiscrError.Tag,tag:v,tagName:h})),c.ok(g);function S(){let x=y();u.if(!1);for(let w in x)u.elseIf((0,e._)`${v} === ${w}`),u.assign(g,_(x[w]));u.else(),c.error(!1,{discrError:r.DiscrError.Mapping,tag:v,tagName:h}),u.endIf()}function _(x){let w=u.name("valid"),E=c.subschema({keyword:"oneOf",schemaProp:x},w);return c.mergeEvaluated(E,e.Name),w}function y(){var x;let w={},E=I(p),T=!0;for(let U=0;U{e.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}}),EF=re((t,e)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MissingRefError=t.ValidationError=t.CodeGen=t.Name=t.nil=t.stringify=t.str=t._=t.KeywordCxt=t.Ajv=void 0;var r=rle(),n=Mle(),i=jle(),s=zle(),o=["/properties"],a="http://json-schema.org/draft-07/schema";class c extends r.default{_addVocabularies(){super._addVocabularies(),n.default.forEach(m=>this.addVocabulary(m)),this.opts.discriminator&&this.addKeyword(i.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let m=this.opts.$data?this.$dataMetaSchema(s,o):s;this.addMetaSchema(m,a,!1),this.refs["http://json-schema.org/schema"]=a}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(a)?a:void 0)}}t.Ajv=c,e.exports=t=c,e.exports.Ajv=c,Object.defineProperty(t,"__esModule",{value:!0}),t.default=c;var u=Bv();Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return u.KeywordCxt}});var l=Ze();Object.defineProperty(t,"_",{enumerable:!0,get:function(){return l._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return l.str}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return l.stringify}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return l.nil}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return l.Name}}),Object.defineProperty(t,"CodeGen",{enumerable:!0,get:function(){return l.CodeGen}});var d=A$();Object.defineProperty(t,"ValidationError",{enumerable:!0,get:function(){return d.default}});var p=Gv();Object.defineProperty(t,"MissingRefError",{enumerable:!0,get:function(){return p.default}})}),Lle=re(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.formatNames=t.fastFormats=t.fullFormats=void 0;function e(N,U){return{validate:N,compare:U}}t.fullFormats={date:e(s,o),time:e(c(!0),u),"date-time":e(p(!0),f),"iso-time":e(c(),l),"iso-date-time":e(p(),m),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:v,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:A,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:_,int32:{type:"number",validate:w},int64:{type:"number",validate:E},float:{type:"number",validate:T},double:{type:"number",validate:T},password:!0,binary:!0},t.fastFormats={...t.fullFormats,date:e(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,o),time:e(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,u),"date-time":e(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,f),"iso-time":e(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,l),"iso-date-time":e(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,m),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i},t.formatNames=Object.keys(t.fullFormats);function r(N){return N%4===0&&(N%100!==0||N%400===0)}var n=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,i=[0,31,28,31,30,31,30,31,31,30,31,30,31];function s(N){let U=n.exec(N);if(!U)return!1;let V=+U[1],j=+U[2],ae=+U[3];return j>=1&&j<=12&&ae>=1&&ae<=(j===2&&r(V)?29:i[j])}function o(N,U){if(N&&U)return N>U?1:N23||C>59||N&&!Et)return!1;if(ae<=23&&Ne<=59&&ze<60)return!0;let H=Ne-C*Ge,M=ae-K*Ge-(H<0?1:0);return(M===23||M===-1)&&(H===59||H===-1)&&ze<61}}function u(N,U){if(!(N&&U))return;let V=new Date("2020-01-01T"+N).valueOf(),j=new Date("2020-01-01T"+U).valueOf();if(V&&j)return V-j}function l(N,U){if(!(N&&U))return;let V=a.exec(N),j=a.exec(U);if(V&&j)return N=V[1]+V[2]+V[3],U=j[1]+j[2]+j[3],N>U?1:N=y}function E(N){return Number.isInteger(N)}function T(){return!0}var I=/[^\\]\\Z/;function A(N){if(I.test(N))return!1;try{return new RegExp(N),!0}catch{return!1}}}),Ule=re(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.formatLimitDefinition=void 0;var e=EF(),r=Ze(),n=r.operators,i={formatMaximum:{okStr:"<=",ok:n.LTE,fail:n.GT},formatMinimum:{okStr:">=",ok:n.GTE,fail:n.LT},formatExclusiveMaximum:{okStr:"<",ok:n.LT,fail:n.GTE},formatExclusiveMinimum:{okStr:">",ok:n.GT,fail:n.LTE}},s={message:({keyword:a,schemaCode:c})=>(0,r.str)`should be ${i[a].okStr} ${c}`,params:({keyword:a,schemaCode:c})=>(0,r._)`{comparison: ${i[a].okStr}, limit: ${c}}`};t.formatLimitDefinition={keyword:Object.keys(i),type:"string",schemaType:"string",$data:!0,error:s,code(a){let{gen:c,data:u,schemaCode:l,keyword:d,it:p}=a,{opts:f,self:m}=p;if(!f.validateFormats)return;let h=new e.KeywordCxt(p,m.RULES.all.format.definition,"format");h.$data?g():v();function g(){let _=c.scopeValue("formats",{ref:m.formats,code:f.code.formats}),y=c.const("fmt",(0,r._)`${_}[${h.schemaCode}]`);a.fail$data((0,r.or)((0,r._)`typeof ${y} != "object"`,(0,r._)`${y} instanceof RegExp`,(0,r._)`typeof ${y}.compare != "function"`,S(y)))}function v(){let _=h.schema,y=m.formats[_];if(!y||y===!0)return;if(typeof y!="object"||y instanceof RegExp||typeof y.compare!="function")throw new Error(`"${d}": format "${_}" does not define "compare" function`);let x=c.scopeValue("formats",{key:_,ref:y,code:f.code.formats?(0,r._)`${f.code.formats}${(0,r.getProperty)(_)}`:void 0});a.fail$data(S(x))}function S(_){return(0,r._)`${_}.compare(${u}, ${l}) ${i[d].fail} 0`}},dependencies:["format"]};var o=a=>(a.addKeyword(t.formatLimitDefinition),a);t.default=o}),Fle=re((t,e)=>{Object.defineProperty(t,"__esModule",{value:!0});var r=Lle(),n=Ule(),i=Ze(),s=new i.Name("fullFormats"),o=new i.Name("fastFormats"),a=(u,l={keywords:!0})=>{if(Array.isArray(l))return c(u,l,r.fullFormats,s),u;let[d,p]=l.mode==="fast"?[r.fastFormats,o]:[r.fullFormats,s],f=l.formats||r.formatNames;return c(u,f,d,p),l.keywords&&(0,n.default)(u),u};a.get=(u,l="full")=>{let p=(l==="fast"?r.fastFormats:r.fullFormats)[u];if(!p)throw new Error(`Unknown format "${u}"`);return p};function c(u,l,d,p){var f,m;(f=(m=u.opts.code).formats)!==null&&f!==void 0||(m.formats=(0,i._)`require("ajv-formats/dist/formats").${p}`);for(let h of l)u.addFormat(h,d[h])}e.exports=t=a,Object.defineProperty(t,"__esModule",{value:!0}),t.default=a}),qle=50;function $F(t=qle){let e=new AbortController;return(0,TF.setMaxListeners)(t,e.signal),e}var Hle=typeof global=="object"&&global&&global.Object===Object&&global,Zle=Hle,Ble=typeof self=="object"&&self&&self.Object===Object&&self,Gle=Zle||Ble||Function("return this")(),D$=Gle,Wle=D$.Symbol,jv=Wle,CF=Object.prototype,Vle=CF.hasOwnProperty,Kle=CF.toString,Ap=jv?jv.toStringTag:void 0;function Jle(t){var e=Vle.call(t,Ap),r=t[Ap];try{t[Ap]=void 0;var n=!0}catch{}var i=Kle.call(t);return n&&(e?t[Ap]=r:delete t[Ap]),i}var Xle=Jle,Yle=Object.prototype,Qle=Yle.toString;function ede(t){return Qle.call(t)}var tde=ede,rde="[object Null]",nde="[object Undefined]",U6=jv?jv.toStringTag:void 0;function ide(t){return t==null?t===void 0?nde:rde:U6&&U6 in Object(t)?Xle(t):tde(t)}var sde=ide;function ode(t){var e=typeof t;return t!=null&&(e=="object"||e=="function")}var PF=ode,ade="[object AsyncFunction]",cde="[object Function]",ude="[object GeneratorFunction]",lde="[object Proxy]";function dde(t){if(!PF(t))return!1;var e=sde(t);return e==cde||e==ude||e==ade||e==lde}var pde=dde,fde=D$["__core-js_shared__"],a$=fde,F6=(function(){var t=/[^.]+$/.exec(a$&&a$.keys&&a$.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""})();function mde(t){return!!F6&&F6 in t}var hde=mde,gde=Function.prototype,vde=gde.toString;function yde(t){if(t!=null){try{return vde.call(t)}catch{}try{return t+""}catch{}}return""}var _de=yde,bde=/[\\^$.*+?()[\]{}|]/g,Sde=/^\[object .+?Constructor\]$/,xde=Function.prototype,wde=Object.prototype,Ede=xde.toString,kde=wde.hasOwnProperty,Tde=RegExp("^"+Ede.call(kde).replace(bde,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function $de(t){if(!PF(t)||hde(t))return!1;var e=pde(t)?Tde:Sde;return e.test(_de(t))}var Ide=$de;function Rde(t,e){return t?.[e]}var Ode=Rde;function Cde(t,e){var r=Ode(t,e);return Ide(r)?r:void 0}var AF=Cde,Pde=AF(Object,"create"),Dp=Pde;function Ade(){this.__data__=Dp?Dp(null):{},this.size=0}var Nde=Ade;function Mde(t){var e=this.has(t)&&delete this.__data__[t];return this.size-=e?1:0,e}var Dde=Mde,jde="__lodash_hash_undefined__",zde=Object.prototype,Lde=zde.hasOwnProperty;function Ude(t){var e=this.__data__;if(Dp){var r=e[t];return r===jde?void 0:r}return Lde.call(e,t)?e[t]:void 0}var Fde=Ude,qde=Object.prototype,Hde=qde.hasOwnProperty;function Zde(t){var e=this.__data__;return Dp?e[t]!==void 0:Hde.call(e,t)}var Bde=Zde,Gde="__lodash_hash_undefined__";function Wde(t,e){var r=this.__data__;return this.size+=this.has(t)?0:1,r[t]=Dp&&e===void 0?Gde:e,this}var Vde=Wde;function Ru(t){var e=-1,r=t==null?0:t.length;for(this.clear();++e-1}var ape=ope;function cpe(t,e){var r=this.__data__,n=Wv(r,t);return n<0?(++this.size,r.push([t,e])):r[n][1]=e,this}var upe=cpe;function Ou(t){var e=-1,r=t==null?0:t.length;for(this.clear();++e{if(!t||t.trim()==="")return null;let e=t.split(",").map(s=>s.trim()).filter(Boolean);if(e.length===0)return null;let r=e.some(s=>s.startsWith("!")),n=e.some(s=>!s.startsWith("!"));if(r&&n)return null;let i=e.map(s=>s.replace(/^!/,"").toLowerCase());return{include:r?[]:i,exclude:r?i:[],isExclusive:r}});function Rpe(t){let e=[],r=t.match(/^MCP server ["']([^"']+)["']/);if(r&&r[1])e.push("mcp"),e.push(r[1].toLowerCase());else{let s=t.match(/^([^:[]+):/);s&&s[1]&&e.push(s[1].trim().toLowerCase())}let n=t.match(/^\[([^\]]+)]/);n&&n[1]&&e.push(n[1].trim().toLowerCase()),t.toLowerCase().includes("statsig event:")&&e.push("statsig");let i=t.match(/:\s*([^:]+?)(?:\s+(?:type|mode|status|event))?:/);if(i&&i[1]){let s=i[1].trim().toLowerCase();s.length<30&&!s.includes(" ")&&e.push(s)}return Array.from(new Set(e))}function Ope(t,e){return e?t.length===0?!1:e.isExclusive?!t.some(r=>e.exclude.includes(r)):t.some(r=>e.include.includes(r)):!0}function Cpe(t,e){if(!e)return!0;let r=Rpe(t);return Ope(r,e)}function jF(){return process.env.CLAUDE_CONFIG_DIR??(0,MF.join)((0,DF.homedir)(),".claude")}function Z6(t){if(!t)return!1;if(typeof t=="boolean")return t;let e=t.toLowerCase().trim();return["1","true","yes","on"].includes(e)}var c$=15e4,Rv=3e4;function FF(t){return{name:t,default:Rv,validate:e=>{if(!e)return{effective:Rv,status:"valid"};let r=parseInt(e,10);return isNaN(r)||r<=0?{effective:Rv,status:"invalid",message:`Invalid value "${e}" (using default: ${Rv})`}:r>c$?{effective:c$,status:"capped",message:`Capped from ${r} to ${c$}`}:{effective:r,status:"valid"}}}}var Ppe=FF("BASH_MAX_OUTPUT_LENGTH"),fDe=FF("TASK_MAX_OUTPUT_LENGTH"),Ape={name:"CLAUDE_CODE_MAX_OUTPUT_TOKENS",default:32e3,validate:t=>{if(!t)return{effective:32e3,status:"valid"};let n=parseInt(t,10);return isNaN(n)||n<=0?{effective:32e3,status:"invalid",message:`Invalid value "${t}" (using default: 32000)`}:n>64e3?{effective:64e3,status:"capped",message:`Capped from ${n} to 64000`}:{effective:n,status:"valid"}}};function Npe(){let t="";return typeof process<"u"&&typeof process.cwd=="function"&&(t=(0,LF.realpathSync)((0,zF.cwd)())),{originalCwd:t,totalCostUSD:0,totalAPIDuration:0,totalAPIDurationWithoutRetries:0,totalToolDuration:0,startTime:Date.now(),lastInteractionTime:Date.now(),totalLinesAdded:0,totalLinesRemoved:0,hasUnknownModelCost:!1,cwd:t,modelUsage:{},mainLoopModelOverride:void 0,initialMainLoopModel:null,modelStrings:null,isInteractive:!1,clientType:"cli",sessionIngressToken:void 0,oauthTokenFromFd:void 0,apiKeyFromFd:void 0,flagSettingsPath:void 0,allowedSettingSources:["userSettings","projectSettings","localSettings","flagSettings","policySettings"],meter:null,sessionCounter:null,locCounter:null,prCounter:null,commitCounter:null,costCounter:null,tokenCounter:null,codeEditToolDecisionCounter:null,activeTimeCounter:null,sessionId:(0,UF.randomUUID)(),loggerProvider:null,eventLogger:null,meterProvider:null,tracerProvider:null,agentColorMap:new Map,agentColorIndex:0,envVarValidators:[Ppe,Ape],lastAPIRequest:null,inMemoryErrorLog:[],inlinePlugins:[],sessionBypassPermissionsMode:!1,sessionPersistenceDisabled:!1,hasExitedPlanMode:!1,needsPlanModeExitAttachment:!1,hasExitedDelegateMode:!1,needsDelegateModeExitAttachment:!1,lspRecommendationShownThisSession:!1,initJsonSchema:null,registeredHooks:null,planSlugCache:new Map,teleportedSessionInfo:null,invokedSkills:new Map,slowOperations:[],sdkBetas:void 0}}var Mpe=Npe();function Dpe(){return Mpe.sessionId}function jpe({writeFn:t,flushIntervalMs:e=1e3,maxBufferSize:r=100,immediateMode:n=!1}){let i=[],s=null;function o(){s&&(clearTimeout(s),s=null)}function a(){i.length!==0&&(t(i.join("")),i=[],o())}function c(){s||(s=setTimeout(a,e))}return{write(u){if(n){t(u);return}i.push(u),c(),i.length>=r&&a()},flush:a,dispose(){a()}}}var B6=new Set;function zpe(t){return B6.add(t),()=>B6.delete(t)}var qF=1/0;function Lpe(t){return t===null?"null":t===void 0?"undefined":Array.isArray(t)?`Array[${t.length}]`:typeof t=="object"?`Object{${Object.keys(t).length} keys}`:typeof t=="string"?`string(${t.length} chars)`:typeof t}function HF(t,e){let r=performance.now();try{return e()}finally{let n=performance.now()-r;n>qF&&(Ps(`[SLOW OPERATION DETECTED] ${t} (${n.toFixed(1)}ms)`),void 0)}}function Xi(t,e,r){let n=Lpe(t);return HF(`JSON.stringify(${n})`,()=>JSON.stringify(t,e,r))}var ZF=(t,e)=>{let r=typeof t=="string"?t.length:0;return HF(`JSON.parse(${r} chars)`,()=>JSON.parse(t,e))},Upe=Jp(()=>Z6(process.env.DEBUG)||Z6(process.env.DEBUG_SDK)||process.argv.includes("--debug")||process.argv.includes("-d")||BF()||process.argv.some(t=>t.startsWith("--debug="))),Fpe=Jp(()=>{let t=process.argv.find(r=>r.startsWith("--debug="));if(!t)return null;let e=t.substring(8);return Ipe(e)}),BF=Jp(()=>process.argv.includes("--debug-to-stderr")||process.argv.includes("-d2e"));function qpe(t){if(typeof process>"u"||typeof process.versions>"u"||typeof process.versions.node>"u")return!1;let e=Fpe();return Cpe(t,e)}var Hpe=!1,Ov=null;function Zpe(){return Ov||(Ov=jpe({writeFn:t=>{let e=GF();As().existsSync((0,_a.dirname)(e))||As().mkdirSync((0,_a.dirname)(e)),As().appendFileSync(e,t),Bpe()},flushIntervalMs:1e3,maxBufferSize:100,immediateMode:Upe()}),zpe(async()=>Ov?.dispose())),Ov}function Ps(t,{level:e}={level:"debug"}){if(!qpe(t))return;Hpe&&t.includes(` `)&&(t=Xi(t));let n=`${new Date().toISOString()} [${e.toUpperCase()}] ${t.trim()} `;if(BF()){$pe(n);return}Zpe().write(n)}function GF(){return process.env.CLAUDE_CODE_DEBUG_LOGS_DIR??(0,_a.join)(jF(),"debug",`${Dpe()}.txt`)}var Bpe=Jp(()=>{if(process.argv[2]!=="--ripgrep")try{let t=GF(),e=(0,_a.dirname)(t),r=(0,_a.join)(e,"latest");if(As().existsSync(e)||As().mkdirSync(e),As().existsSync(r))try{As().unlinkSync(r)}catch{}As().symlinkSync(t,r)}catch{}});function er(t,e){let r=performance.now();try{return e()}finally{let n=performance.now()-r;n>qF&&(Ps(`[SLOW OPERATION DETECTED] fs.${t} (${n.toFixed(1)}ms)`),`${t}`,void 0)}}var Gpe={cwd(){return process.cwd()},existsSync(t){return er(`existsSync(${t})`,()=>$e.existsSync(t))},async stat(t){return(0,OF.stat)(t)},statSync(t){return er(`statSync(${t})`,()=>$e.statSync(t))},lstatSync(t){return er(`lstatSync(${t})`,()=>$e.lstatSync(t))},readFileSync(t,e){return er(`readFileSync(${t})`,()=>$e.readFileSync(t,{encoding:e.encoding}))},readFileBytesSync(t){return er(`readFileBytesSync(${t})`,()=>$e.readFileSync(t))},readSync(t,e){return er(`readSync(${t}, ${e.length} bytes)`,()=>{let r;try{r=$e.openSync(t,"r");let n=Buffer.alloc(e.length),i=$e.readSync(r,n,0,e.length,0);return{buffer:n,bytesRead:i}}finally{r&&$e.closeSync(r)}})},appendFileSync(t,e,r){return er(`appendFileSync(${t}, ${e.length} chars)`,()=>{if(!$e.existsSync(t)&&r?.mode!==void 0){let n=$e.openSync(t,"a",r.mode);try{$e.appendFileSync(n,e)}finally{$e.closeSync(n)}}else $e.appendFileSync(t,e)})},copyFileSync(t,e){return er(`copyFileSync(${t} \u2192 ${e})`,()=>$e.copyFileSync(t,e))},unlinkSync(t){return er(`unlinkSync(${t})`,()=>$e.unlinkSync(t))},renameSync(t,e){return er(`renameSync(${t} \u2192 ${e})`,()=>$e.renameSync(t,e))},linkSync(t,e){return er(`linkSync(${t} \u2192 ${e})`,()=>$e.linkSync(t,e))},symlinkSync(t,e){return er(`symlinkSync(${t} \u2192 ${e})`,()=>$e.symlinkSync(t,e))},readlinkSync(t){return er(`readlinkSync(${t})`,()=>$e.readlinkSync(t))},realpathSync(t){return er(`realpathSync(${t})`,()=>$e.realpathSync(t))},mkdirSync(t,e){return er(`mkdirSync(${t})`,()=>{if(!$e.existsSync(t)){let r={recursive:!0};e?.mode!==void 0&&(r.mode=e.mode),$e.mkdirSync(t,r)}})},readdirSync(t){return er(`readdirSync(${t})`,()=>$e.readdirSync(t,{withFileTypes:!0}))},readdirStringSync(t){return er(`readdirStringSync(${t})`,()=>$e.readdirSync(t))},isDirEmptySync(t){return er(`isDirEmptySync(${t})`,()=>this.readdirSync(t).length===0)},rmdirSync(t){return er(`rmdirSync(${t})`,()=>$e.rmdirSync(t))},rmSync(t,e){return er(`rmSync(${t})`,()=>$e.rmSync(t,e))},createWriteStream(t){return $e.createWriteStream(t)}},Wpe=Gpe;function As(){return Wpe}var ya=class extends Error{};function WF(){return process.versions.bun!==void 0}var Cv=null,G6=!1;function Vpe(){if(G6)return Cv;if(G6=!0,!process.env.DEBUG_CLAUDE_AGENT_SDK)return null;let t=(0,m$.join)(jF(),"debug");return Cv=(0,m$.join)(t,`sdk-${(0,VF.randomUUID)()}.txt`),(0,Pu.existsSync)(t)||(0,Pu.mkdirSync)(t,{recursive:!0}),process.stderr.write(`SDK debug logs: ${Cv} `),Cv}function va(t){let e=Vpe();if(!e)return;let n=`${new Date().toISOString()} ${t} @@ -1345,7 +1346,7 @@ ${n}`}function Cue(t,e){let r=Zt.default.resolve(t);if(r.includes("/.git/")||r.i `))}finally{this.cancelControllers.delete(e.request_id)}}handleControlCancelRequest(e){let r=this.cancelControllers.get(e.request_id);r&&(r.abort(),this.cancelControllers.delete(e.request_id))}async processControlRequest(e,r){if(e.request.subtype==="can_use_tool"){if(!this.canUseTool)throw new Error("canUseTool callback is not provided.");return{...await this.canUseTool(e.request.tool_name,e.request.input,{signal:r,suggestions:e.request.permission_suggestions,blockedPath:e.request.blocked_path,decisionReason:e.request.decision_reason,toolUseID:e.request.tool_use_id,agentID:e.request.agent_id}),toolUseID:e.request.tool_use_id}}else{if(e.request.subtype==="hook_callback")return await this.handleHookCallbacks(e.request.callback_id,e.request.input,e.request.tool_use_id,r);if(e.request.subtype==="mcp_message"){let n=e.request,i=this.sdkMcpTransports.get(n.server_name);if(!i)throw new Error(`SDK MCP server not found: ${n.server_name}`);return"method"in n.message&&"id"in n.message&&n.message.id!==null?{mcp_response:await this.handleMcpControlRequest(n.server_name,n,i)}:(i.onmessage&&i.onmessage(n.message),{mcp_response:{jsonrpc:"2.0",result:{},id:0}})}}throw new Error("Unsupported control request subtype: "+e.request.subtype)}async*readSdkMessages(){for await(let e of this.inputStream)yield e}async initialize(){let e;if(this.hooks){e={};for(let[s,o]of Object.entries(this.hooks))o.length>0&&(e[s]=o.map(a=>{let c=[];for(let u of a.hooks){let l=`hook_${this.nextCallbackId++}`;this.hookCallbacks.set(l,u),c.push(l)}return{matcher:a.matcher,hookCallbackIds:c,timeout:a.timeout}}))}let r=this.sdkMcpTransports.size>0?Array.from(this.sdkMcpTransports.keys()):void 0,n={subtype:"initialize",hooks:e,sdkMcpServers:r,jsonSchema:this.jsonSchema,systemPrompt:this.initConfig?.systemPrompt,appendSystemPrompt:this.initConfig?.appendSystemPrompt,agents:this.initConfig?.agents};return(await this.request(n)).response}async interrupt(){await this.request({subtype:"interrupt"})}async setPermissionMode(e){await this.request({subtype:"set_permission_mode",mode:e})}async setModel(e){await this.request({subtype:"set_model",model:e})}async setMaxThinkingTokens(e){await this.request({subtype:"set_max_thinking_tokens",max_thinking_tokens:e})}async rewindFiles(e,r){return(await this.request({subtype:"rewind_files",user_message_id:e,dry_run:r?.dryRun})).response}async processPendingPermissionRequests(e){for(let r of e)r.request.subtype==="can_use_tool"&&this.handleControlRequest(r).catch(()=>{})}request(e){let r=Math.random().toString(36).substring(2,15),n={request_id:r,type:"control_request",request:e};return new Promise((i,s)=>{this.pendingControlResponses.set(r,o=>{o.subtype==="success"?i(o):(s(new Error(o.error)),o.pending_permission_requests&&this.processPendingPermissionRequests(o.pending_permission_requests))}),Promise.resolve(this.transport.write(Xi(n)+` `))})}async supportedCommands(){return(await this.initialization).commands}async supportedModels(){return(await this.initialization).models}async mcpServerStatus(){return(await this.request({subtype:"mcp_status"})).response.mcpServers}async setMcpServers(e){let r={},n={};for(let[c,u]of Object.entries(e))u.type==="sdk"&&"instance"in u?r[c]=u.instance:n[c]=u;let i=new Set(this.sdkMcpServerInstances.keys()),s=new Set(Object.keys(r));for(let c of i)s.has(c)||await this.disconnectSdkMcpServer(c);for(let[c,u]of Object.entries(r))i.has(c)||this.connectSdkMcpServer(c,u);let o={};for(let c of Object.keys(r))o[c]={type:"sdk",name:c};return(await this.request({subtype:"mcp_set_servers",servers:{...n,...o}})).response}async accountInfo(){return(await this.initialization).account}async streamInput(e){Ps("[Query.streamInput] Starting to process input stream");try{let r=0;for await(let n of e){if(r++,Ps(`[Query.streamInput] Processing message ${r}: ${n.type}`),this.abortController?.signal.aborted)break;await Promise.resolve(this.transport.write(Xi(n)+` `))}Ps(`[Query.streamInput] Finished processing ${r} messages from input stream`),r>0&&this.hasBidirectionalNeeds()&&(Ps("[Query.streamInput] Has bidirectional needs, waiting for first result"),await this.waitForFirstResult()),Ps("[Query] Calling transport.endInput() to close stdin to CLI process"),this.transport.endInput()}catch(r){if(!(r instanceof ya))throw r}}waitForFirstResult(){return this.firstResultReceived?(Ps("[Query.waitForFirstResult] Result already received, returning immediately"),Promise.resolve()):new Promise(e=>{if(this.abortController?.signal.aborted){e();return}this.abortController?.signal.addEventListener("abort",()=>e(),{once:!0}),this.firstResultReceivedResolve=e})}handleHookCallbacks(e,r,n,i){let s=this.hookCallbacks.get(e);if(!s)throw new Error(`No hook callback found for ID: ${e}`);return s(r,n,{signal:i})}connectSdkMcpServer(e,r){let n=new v$(i=>this.sendMcpServerMessageToCli(e,i));this.sdkMcpTransports.set(e,n),this.sdkMcpServerInstances.set(e,r),r.connect(n)}async disconnectSdkMcpServer(e){let r=this.sdkMcpTransports.get(e);r&&(await r.close(),this.sdkMcpTransports.delete(e)),this.sdkMcpServerInstances.delete(e)}sendMcpServerMessageToCli(e,r){if("id"in r&&r.id!==null&&r.id!==void 0){let i=`${e}:${r.id}`,s=this.pendingMcpResponses.get(i);if(s){s.resolve(r),this.pendingMcpResponses.delete(i);return}}let n={type:"control_request",request_id:(0,KF.randomUUID)(),request:{subtype:"mcp_message",server_name:e,message:r}};this.transport.write(Xi(n)+` -`)}handleMcpControlRequest(e,r,n){let i="id"in r.message?r.message.id:null,s=`${e}:${i}`;return new Promise((o,a)=>{let c=()=>{this.pendingMcpResponses.delete(s)},u=d=>{c(),o(d)},l=d=>{c(),a(d)};if(this.pendingMcpResponses.set(s,{resolve:u,reject:l}),n.onmessage)n.onmessage(r.message);else{c(),a(new Error("No message handler registered"));return}})}};var ot;(function(t){t.assertEqual=i=>{};function e(i){}t.assertIs=e;function r(i){throw new Error}t.assertNever=r,t.arrayToEnum=i=>{let s={};for(let o of i)s[o]=o;return s},t.getValidEnumValues=i=>{let s=t.objectKeys(i).filter(a=>typeof i[i[a]]!="number"),o={};for(let a of s)o[a]=i[a];return t.objectValues(o)},t.objectValues=i=>t.objectKeys(i).map(function(s){return i[s]}),t.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let s=[];for(let o in i)Object.prototype.hasOwnProperty.call(i,o)&&s.push(o);return s},t.find=(i,s)=>{for(let o of i)if(s(o))return o},t.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function n(i,s=" | "){return i.map(o=>typeof o=="string"?`'${o}'`:o).join(s)}t.joinValues=n,t.jsonStringifyReplacer=(i,s)=>typeof s=="bigint"?s.toString():s})(ot||(ot={}));var W6;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(W6||(W6={}));var oe=ot.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),yo=t=>{switch(typeof t){case"undefined":return oe.undefined;case"string":return oe.string;case"number":return Number.isNaN(t)?oe.nan:oe.number;case"boolean":return oe.boolean;case"function":return oe.function;case"bigint":return oe.bigint;case"symbol":return oe.symbol;case"object":return Array.isArray(t)?oe.array:t===null?oe.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?oe.promise:typeof Map<"u"&&t instanceof Map?oe.map:typeof Set<"u"&&t instanceof Set?oe.set:typeof Date<"u"&&t instanceof Date?oe.date:oe.object;default:return oe.unknown}},W=ot.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"]),Kn=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(s){return s.message},n={_errors:[]},i=s=>{for(let o of s.issues)if(o.code==="invalid_union")o.unionErrors.map(i);else if(o.code==="invalid_return_type")i(o.returnTypeError);else if(o.code==="invalid_arguments")i(o.argumentsError);else if(o.path.length===0)n._errors.push(r(o));else{let a=n,c=0;for(;cr.message){let r={},n=[];for(let i of this.issues)if(i.path.length>0){let s=i.path[0];r[s]=r[s]||[],r[s].push(e(i))}else n.push(e(i));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};Kn.create=t=>new Kn(t);var Xpe=(t,e)=>{let r;switch(t.code){case W.invalid_type:t.received===oe.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case W.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,ot.jsonStringifyReplacer)}`;break;case W.unrecognized_keys:r=`Unrecognized key(s) in object: ${ot.joinValues(t.keys,", ")}`;break;case W.invalid_union:r="Invalid input";break;case W.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${ot.joinValues(t.options)}`;break;case W.invalid_enum_value:r=`Invalid enum value. Expected ${ot.joinValues(t.options)}, received '${t.received}'`;break;case W.invalid_arguments:r="Invalid function arguments";break;case W.invalid_return_type:r="Invalid function return type";break;case W.invalid_date:r="Invalid date";break;case W.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:ot.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case W.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case W.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case W.custom:r="Invalid input";break;case W.invalid_intersection_types:r="Intersection results could not be merged";break;case W.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case W.not_finite:r="Number must be finite";break;default:r=e.defaultError,ot.assertNever(t)}return{message:r}},jp=Xpe,Ype=jp;function _$(){return Ype}var b$=t=>{let{data:e,path:r,errorMaps:n,issueData:i}=t,s=[...r,...i.path||[]],o={...i,path:s};if(i.message!==void 0)return{...i,path:s,message:i.message};let a="",c=n.filter(u=>!!u).slice().reverse();for(let u of c)a=u(o,{data:e,defaultError:a}).message;return{...i,path:s,message:a}};function te(t,e){let r=_$(),n=b$({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===jp?void 0:jp].filter(i=>!!i)});t.common.issues.push(n)}var en=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let i of r){if(i.status==="aborted")return ke;i.status==="dirty"&&e.dirty(),n.push(i.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let i of r){let s=await i.key,o=await i.value;n.push({key:s,value:o})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let i of r){let{key:s,value:o}=i;if(s.status==="aborted"||o.status==="aborted")return ke;s.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof o.value<"u"||i.alwaysSet)&&(n[s.value]=o.value)}return{status:e.value,value:n}}},ke=Object.freeze({status:"aborted"}),Np=t=>({status:"dirty",value:t}),gn=t=>({status:"valid",value:t}),V6=t=>t.status==="aborted",K6=t=>t.status==="dirty",hu=t=>t.status==="valid",zv=t=>typeof Promise<"u"&&t instanceof Promise,pe;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(pe||(pe={}));var Jn=class{constructor(e,r,n,i){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=i}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},J6=(t,e)=>{if(hu(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new Kn(t.common.issues);return this._error=r,this._error}}};function Ae(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:i}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:i}:{errorMap:(o,a)=>{let{message:c}=t;return o.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:o.code!=="invalid_type"?{message:a.defaultError}:{message:c??r??a.defaultError}},description:i}}var Be=class{get description(){return this._def.description}_getType(e){return yo(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:yo(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new en,ctx:{common:e.parent.common,data:e.data,parsedType:yo(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(zv(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:yo(e)},i=this._parseSync({data:e,path:n.path,parent:n});return J6(n,i)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:yo(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return hu(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>hu(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:yo(e)},i=this._parse({data:e,path:n.path,parent:n}),s=await(zv(i)?i:Promise.resolve(i));return J6(n,s)}refine(e,r){let n=i=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(i):r;return this._refinement((i,s)=>{let o=e(i),a=()=>s.addIssue({code:W.custom,...n(i)});return typeof Promise<"u"&&o instanceof Promise?o.then(c=>c?!0:(a(),!1)):o?!0:(a(),!1)})}refinement(e,r){return this._refinement((n,i)=>e(n)?!0:(i.addIssue(typeof r=="function"?r(n,i):r),!1))}_refinement(e){return new Si({schema:this,typeName:Te.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:r=>this["~validate"](r)}}optional(){return bi.create(this,this._def)}nullable(){return Ms.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return So.create(this)}promise(){return ba.create(this,this._def)}or(e){return _u.create([this,e],this._def)}and(e){return bu.create(this,e,this._def)}transform(e){return new Si({...Ae(this._def),schema:this,typeName:Te.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new ku({...Ae(this._def),innerType:this,defaultValue:r,typeName:Te.ZodDefault})}brand(){return new Lv({typeName:Te.ZodBranded,type:this,...Ae(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Tu({...Ae(this._def),innerType:this,catchValue:r,typeName:Te.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return Uv.create(this,e)}readonly(){return $u.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Qpe=/^c[^\s-]{8,}$/i,efe=/^[0-9a-z]+$/,tfe=/^[0-9A-HJKMNP-TV-Z]{26}$/i,rfe=/^[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,nfe=/^[a-z0-9_-]{21}$/i,ife=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,sfe=/^[-+]?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)?)??$/,ofe=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,afe="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",u$,cfe=/^(?:(?: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])$/,ufe=/^(?:(?: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])$/,lfe=/^(([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]))$/,dfe=/^(([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])$/,pfe=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,ffe=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,JF="((\\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])))",mfe=new RegExp(`^${JF}$`);function XF(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function hfe(t){return new RegExp(`^${XF(t)}$`)}function gfe(t){let e=`${JF}T${XF(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function vfe(t,e){return!!((e==="v4"||!e)&&cfe.test(t)||(e==="v6"||!e)&&lfe.test(t))}function yfe(t,e){if(!ife.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),i=JSON.parse(atob(n));return!(typeof i!="object"||i===null||"typ"in i&&i?.typ!=="JWT"||!i.alg||e&&i.alg!==e)}catch{return!1}}function _fe(t,e){return!!((e==="v4"||!e)&&ufe.test(t)||(e==="v6"||!e)&&dfe.test(t))}var gu=class t extends Be{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==oe.string){let s=this._getOrReturnCtx(e);return te(s,{code:W.invalid_type,expected:oe.string,received:s.parsedType}),ke}let n=new en,i;for(let s of this._def.checks)if(s.kind==="min")e.data.lengths.value&&(i=this._getOrReturnCtx(e,i),te(i,{code:W.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){let o=e.data.length>s.value,a=e.data.lengthe.test(i),{validation:r,code:W.invalid_string,...pe.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...pe.errToObj(e)})}url(e){return this._addCheck({kind:"url",...pe.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...pe.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...pe.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...pe.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...pe.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...pe.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...pe.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...pe.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...pe.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...pe.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...pe.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...pe.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,...pe.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,...pe.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...pe.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...pe.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...pe.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...pe.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...pe.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...pe.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...pe.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...pe.errToObj(r)})}nonempty(e){return this.min(1,pe.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...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 r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.valuenew gu({checks:[],typeName:Te.ZodString,coerce:t?.coerce??!1,...Ae(t)});function bfe(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,i=r>n?r:n,s=Number.parseInt(t.toFixed(i).replace(".","")),o=Number.parseInt(e.toFixed(i).replace(".",""));return s%o/10**i}var zp=class t extends Be{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)!==oe.number){let s=this._getOrReturnCtx(e);return te(s,{code:W.invalid_type,expected:oe.number,received:s.parsedType}),ke}let n,i=new en;for(let s of this._def.checks)s.kind==="int"?ot.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),te(n,{code:W.invalid_type,expected:"integer",received:"float",message:s.message}),i.dirty()):s.kind==="min"?(s.inclusive?e.datas.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),te(n,{code:W.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),i.dirty()):s.kind==="multipleOf"?bfe(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),te(n,{code:W.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),te(n,{code:W.not_finite,message:s.message}),i.dirty()):ot.assertNever(s);return{status:i.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,pe.toString(r))}gt(e,r){return this.setLimit("min",e,!1,pe.toString(r))}lte(e,r){return this.setLimit("max",e,!0,pe.toString(r))}lt(e,r){return this.setLimit("max",e,!1,pe.toString(r))}setLimit(e,r,n,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:pe.toString(i)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:pe.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:pe.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:pe.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:pe.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:pe.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:pe.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:pe.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:pe.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:pe.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.valuee.kind==="int"||e.kind==="multipleOf"&&ot.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.valuenew zp({checks:[],typeName:Te.ZodNumber,coerce:t?.coerce||!1,...Ae(t)});var Lp=class t extends Be{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)!==oe.bigint)return this._getInvalidInput(e);let n,i=new en;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?e.datas.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),te(n,{code:W.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),i.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),te(n,{code:W.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):ot.assertNever(s);return{status:i.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return te(r,{code:W.invalid_type,expected:oe.bigint,received:r.parsedType}),ke}gte(e,r){return this.setLimit("min",e,!0,pe.toString(r))}gt(e,r){return this.setLimit("min",e,!1,pe.toString(r))}lte(e,r){return this.setLimit("max",e,!0,pe.toString(r))}lt(e,r){return this.setLimit("max",e,!1,pe.toString(r))}setLimit(e,r,n,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:pe.toString(i)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:pe.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:pe.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:pe.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:pe.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:pe.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.valuenew Lp({checks:[],typeName:Te.ZodBigInt,coerce:t?.coerce??!1,...Ae(t)});var Up=class extends Be{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==oe.boolean){let n=this._getOrReturnCtx(e);return te(n,{code:W.invalid_type,expected:oe.boolean,received:n.parsedType}),ke}return gn(e.data)}};Up.create=t=>new Up({typeName:Te.ZodBoolean,coerce:t?.coerce||!1,...Ae(t)});var Fp=class t extends Be{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==oe.date){let s=this._getOrReturnCtx(e);return te(s,{code:W.invalid_type,expected:oe.date,received:s.parsedType}),ke}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return te(s,{code:W.invalid_date}),ke}let n=new en,i;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()s.value&&(i=this._getOrReturnCtx(e,i),te(i,{code:W.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):ot.assertNever(s);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:pe.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:pe.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.valuenew Fp({checks:[],coerce:t?.coerce||!1,typeName:Te.ZodDate,...Ae(t)});var qp=class extends Be{_parse(e){if(this._getType(e)!==oe.symbol){let n=this._getOrReturnCtx(e);return te(n,{code:W.invalid_type,expected:oe.symbol,received:n.parsedType}),ke}return gn(e.data)}};qp.create=t=>new qp({typeName:Te.ZodSymbol,...Ae(t)});var vu=class extends Be{_parse(e){if(this._getType(e)!==oe.undefined){let n=this._getOrReturnCtx(e);return te(n,{code:W.invalid_type,expected:oe.undefined,received:n.parsedType}),ke}return gn(e.data)}};vu.create=t=>new vu({typeName:Te.ZodUndefined,...Ae(t)});var yu=class extends Be{_parse(e){if(this._getType(e)!==oe.null){let n=this._getOrReturnCtx(e);return te(n,{code:W.invalid_type,expected:oe.null,received:n.parsedType}),ke}return gn(e.data)}};yu.create=t=>new yu({typeName:Te.ZodNull,...Ae(t)});var Hp=class extends Be{constructor(){super(...arguments),this._any=!0}_parse(e){return gn(e.data)}};Hp.create=t=>new Hp({typeName:Te.ZodAny,...Ae(t)});var bo=class extends Be{constructor(){super(...arguments),this._unknown=!0}_parse(e){return gn(e.data)}};bo.create=t=>new bo({typeName:Te.ZodUnknown,...Ae(t)});var Qi=class extends Be{_parse(e){let r=this._getOrReturnCtx(e);return te(r,{code:W.invalid_type,expected:oe.never,received:r.parsedType}),ke}};Qi.create=t=>new Qi({typeName:Te.ZodNever,...Ae(t)});var Zp=class extends Be{_parse(e){if(this._getType(e)!==oe.undefined){let n=this._getOrReturnCtx(e);return te(n,{code:W.invalid_type,expected:oe.void,received:n.parsedType}),ke}return gn(e.data)}};Zp.create=t=>new Zp({typeName:Te.ZodVoid,...Ae(t)});var So=class t extends Be{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),i=this._def;if(r.parsedType!==oe.array)return te(r,{code:W.invalid_type,expected:oe.array,received:r.parsedType}),ke;if(i.exactLength!==null){let o=r.data.length>i.exactLength.value,a=r.data.lengthi.maxLength.value&&(te(r,{code:W.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((o,a)=>i.type._parseAsync(new Jn(r,o,r.path,a)))).then(o=>en.mergeArray(n,o));let s=[...r.data].map((o,a)=>i.type._parseSync(new Jn(r,o,r.path,a)));return en.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:pe.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:pe.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:pe.toString(r)}})}nonempty(e){return this.min(1,e)}};So.create=(t,e)=>new So({type:t,minLength:null,maxLength:null,exactLength:null,typeName:Te.ZodArray,...Ae(e)});function pu(t){if(t instanceof On){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=bi.create(pu(n))}return new On({...t._def,shape:()=>e})}else return t instanceof So?new So({...t._def,type:pu(t.element)}):t instanceof bi?bi.create(pu(t.unwrap())):t instanceof Ms?Ms.create(pu(t.unwrap())):t instanceof Ns?Ns.create(t.items.map(e=>pu(e))):t}var On=class t extends Be{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(),r=ot.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==oe.object){let u=this._getOrReturnCtx(e);return te(u,{code:W.invalid_type,expected:oe.object,received:u.parsedType}),ke}let{status:n,ctx:i}=this._processInputParams(e),{shape:s,keys:o}=this._getCached(),a=[];if(!(this._def.catchall instanceof Qi&&this._def.unknownKeys==="strip"))for(let u in i.data)o.includes(u)||a.push(u);let c=[];for(let u of o){let l=s[u],d=i.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new Jn(i,d,i.path,u)),alwaysSet:u in i.data})}if(this._def.catchall instanceof Qi){let u=this._def.unknownKeys;if(u==="passthrough")for(let l of a)c.push({key:{status:"valid",value:l},value:{status:"valid",value:i.data[l]}});else if(u==="strict")a.length>0&&(te(i,{code:W.unrecognized_keys,keys:a}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let l of a){let d=i.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new Jn(i,d,i.path,l)),alwaysSet:l in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let u=[];for(let l of c){let d=await l.key,p=await l.value;u.push({key:d,value:p,alwaysSet:l.alwaysSet})}return u}).then(u=>en.mergeObjectSync(n,u)):en.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return pe.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let i=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:pe.errToObj(e).message??i}:{message:i}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Te.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let n of ot.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let n of ot.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return pu(this)}partial(e){let r={};for(let n of ot.objectKeys(this.shape)){let i=this.shape[n];e&&!e[n]?r[n]=i:r[n]=i.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of ot.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof bi;)s=s._def.innerType;r[n]=s}return new t({...this._def,shape:()=>r})}keyof(){return YF(ot.objectKeys(this.shape))}};On.create=(t,e)=>new On({shape:()=>t,unknownKeys:"strip",catchall:Qi.create(),typeName:Te.ZodObject,...Ae(e)});On.strictCreate=(t,e)=>new On({shape:()=>t,unknownKeys:"strict",catchall:Qi.create(),typeName:Te.ZodObject,...Ae(e)});On.lazycreate=(t,e)=>new On({shape:t,unknownKeys:"strip",catchall:Qi.create(),typeName:Te.ZodObject,...Ae(e)});var _u=class extends Be{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function i(s){for(let a of s)if(a.result.status==="valid")return a.result;for(let a of s)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let o=s.map(a=>new Kn(a.ctx.common.issues));return te(r,{code:W.invalid_union,unionErrors:o}),ke}if(r.common.async)return Promise.all(n.map(async s=>{let o={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:o}),ctx:o}})).then(i);{let s,o=[];for(let c of n){let u={...r,common:{...r.common,issues:[]},parent:null},l=c._parseSync({data:r.data,path:r.path,parent:u});if(l.status==="valid")return l;l.status==="dirty"&&!s&&(s={result:l,ctx:u}),u.common.issues.length&&o.push(u.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;let a=o.map(c=>new Kn(c));return te(r,{code:W.invalid_union,unionErrors:a}),ke}}get options(){return this._def.options}};_u.create=(t,e)=>new _u({options:t,typeName:Te.ZodUnion,...Ae(e)});var Cs=t=>t instanceof Su?Cs(t.schema):t instanceof Si?Cs(t.innerType()):t instanceof xu?[t.value]:t instanceof wu?t.options:t instanceof Eu?ot.objectValues(t.enum):t instanceof ku?Cs(t._def.innerType):t instanceof vu?[void 0]:t instanceof yu?[null]:t instanceof bi?[void 0,...Cs(t.unwrap())]:t instanceof Ms?[null,...Cs(t.unwrap())]:t instanceof Lv||t instanceof $u?Cs(t.unwrap()):t instanceof Tu?Cs(t._def.innerType):[],S$=class t extends Be{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==oe.object)return te(r,{code:W.invalid_type,expected:oe.object,received:r.parsedType}),ke;let n=this.discriminator,i=r.data[n],s=this.optionsMap.get(i);return s?r.common.async?s._parseAsync({data:r.data,path:r.path,parent:r}):s._parseSync({data:r.data,path:r.path,parent:r}):(te(r,{code:W.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),ke)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let i=new Map;for(let s of r){let o=Cs(s.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(i.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);i.set(a,s)}}return new t({typeName:Te.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:i,...Ae(n)})}};function x$(t,e){let r=yo(t),n=yo(e);if(t===e)return{valid:!0,data:t};if(r===oe.object&&n===oe.object){let i=ot.objectKeys(e),s=ot.objectKeys(t).filter(a=>i.indexOf(a)!==-1),o={...t,...e};for(let a of s){let c=x$(t[a],e[a]);if(!c.valid)return{valid:!1};o[a]=c.data}return{valid:!0,data:o}}else if(r===oe.array&&n===oe.array){if(t.length!==e.length)return{valid:!1};let i=[];for(let s=0;s{if(V6(s)||V6(o))return ke;let a=x$(s.value,o.value);return a.valid?((K6(s)||K6(o))&&r.dirty(),{status:r.value,value:a.data}):(te(n,{code:W.invalid_intersection_types}),ke)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([s,o])=>i(s,o)):i(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};bu.create=(t,e,r)=>new bu({left:t,right:e,typeName:Te.ZodIntersection,...Ae(r)});var Ns=class t extends Be{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==oe.array)return te(n,{code:W.invalid_type,expected:oe.array,received:n.parsedType}),ke;if(n.data.lengththis._def.items.length&&(te(n,{code:W.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let s=[...n.data].map((o,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new Jn(n,o,n.path,a)):null}).filter(o=>!!o);return n.common.async?Promise.all(s).then(o=>en.mergeArray(r,o)):en.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};Ns.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ns({items:t,typeName:Te.ZodTuple,rest:null,...Ae(e)})};var w$=class t extends Be{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==oe.object)return te(n,{code:W.invalid_type,expected:oe.object,received:n.parsedType}),ke;let i=[],s=this._def.keyType,o=this._def.valueType;for(let a in n.data)i.push({key:s._parse(new Jn(n,a,n.path,a)),value:o._parse(new Jn(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?en.mergeObjectAsync(r,i):en.mergeObjectSync(r,i)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof Be?new t({keyType:e,valueType:r,typeName:Te.ZodRecord,...Ae(n)}):new t({keyType:gu.create(),valueType:e,typeName:Te.ZodRecord,...Ae(r)})}},Bp=class extends Be{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==oe.map)return te(n,{code:W.invalid_type,expected:oe.map,received:n.parsedType}),ke;let i=this._def.keyType,s=this._def.valueType,o=[...n.data.entries()].map(([a,c],u)=>({key:i._parse(new Jn(n,a,n.path,[u,"key"])),value:s._parse(new Jn(n,c,n.path,[u,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of o){let u=await c.key,l=await c.value;if(u.status==="aborted"||l.status==="aborted")return ke;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let c of o){let u=c.key,l=c.value;if(u.status==="aborted"||l.status==="aborted")return ke;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}}}};Bp.create=(t,e,r)=>new Bp({valueType:e,keyType:t,typeName:Te.ZodMap,...Ae(r)});var Gp=class t extends Be{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==oe.set)return te(n,{code:W.invalid_type,expected:oe.set,received:n.parsedType}),ke;let i=this._def;i.minSize!==null&&n.data.sizei.maxSize.value&&(te(n,{code:W.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),r.dirty());let s=this._def.valueType;function o(c){let u=new Set;for(let l of c){if(l.status==="aborted")return ke;l.status==="dirty"&&r.dirty(),u.add(l.value)}return{status:r.value,value:u}}let a=[...n.data.values()].map((c,u)=>s._parse(new Jn(n,c,n.path,u)));return n.common.async?Promise.all(a).then(c=>o(c)):o(a)}min(e,r){return new t({...this._def,minSize:{value:e,message:pe.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:pe.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};Gp.create=(t,e)=>new Gp({valueType:t,minSize:null,maxSize:null,typeName:Te.ZodSet,...Ae(e)});var E$=class t extends Be{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==oe.function)return te(r,{code:W.invalid_type,expected:oe.function,received:r.parsedType}),ke;function n(a,c){return b$({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,_$(),jp].filter(u=>!!u),issueData:{code:W.invalid_arguments,argumentsError:c}})}function i(a,c){return b$({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,_$(),jp].filter(u=>!!u),issueData:{code:W.invalid_return_type,returnTypeError:c}})}let s={errorMap:r.common.contextualErrorMap},o=r.data;if(this._def.returns instanceof ba){let a=this;return gn(async function(...c){let u=new Kn([]),l=await a._def.args.parseAsync(c,s).catch(f=>{throw u.addIssue(n(c,f)),u}),d=await Reflect.apply(o,this,l);return await a._def.returns._def.type.parseAsync(d,s).catch(f=>{throw u.addIssue(i(d,f)),u})})}else{let a=this;return gn(function(...c){let u=a._def.args.safeParse(c,s);if(!u.success)throw new Kn([n(c,u.error)]);let l=Reflect.apply(o,this,u.data),d=a._def.returns.safeParse(l,s);if(!d.success)throw new Kn([i(l,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:Ns.create(e).rest(bo.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new t({args:e||Ns.create([]).rest(bo.create()),returns:r||bo.create(),typeName:Te.ZodFunction,...Ae(n)})}},Su=class extends Be{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};Su.create=(t,e)=>new Su({getter:t,typeName:Te.ZodLazy,...Ae(e)});var xu=class extends Be{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return te(r,{received:r.data,code:W.invalid_literal,expected:this._def.value}),ke}return{status:"valid",value:e.data}}get value(){return this._def.value}};xu.create=(t,e)=>new xu({value:t,typeName:Te.ZodLiteral,...Ae(e)});function YF(t,e){return new wu({values:t,typeName:Te.ZodEnum,...Ae(e)})}var wu=class t extends Be{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return te(r,{expected:ot.joinValues(n),received:r.parsedType,code:W.invalid_type}),ke}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return te(r,{received:r.data,code:W.invalid_enum_value,options:n}),ke}return gn(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};wu.create=YF;var Eu=class extends Be{_parse(e){let r=ot.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==oe.string&&n.parsedType!==oe.number){let i=ot.objectValues(r);return te(n,{expected:ot.joinValues(i),received:n.parsedType,code:W.invalid_type}),ke}if(this._cache||(this._cache=new Set(ot.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let i=ot.objectValues(r);return te(n,{received:n.data,code:W.invalid_enum_value,options:i}),ke}return gn(e.data)}get enum(){return this._def.values}};Eu.create=(t,e)=>new Eu({values:t,typeName:Te.ZodNativeEnum,...Ae(e)});var ba=class extends Be{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==oe.promise&&r.common.async===!1)return te(r,{code:W.invalid_type,expected:oe.promise,received:r.parsedType}),ke;let n=r.parsedType===oe.promise?r.data:Promise.resolve(r.data);return gn(n.then(i=>this._def.type.parseAsync(i,{path:r.path,errorMap:r.common.contextualErrorMap})))}};ba.create=(t,e)=>new ba({type:t,typeName:Te.ZodPromise,...Ae(e)});var Si=class extends Be{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Te.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),i=this._def.effect||null,s={addIssue:o=>{te(n,o),o.fatal?r.abort():r.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),i.type==="preprocess"){let o=i.transform(n.data,s);if(n.common.async)return Promise.resolve(o).then(async a=>{if(r.value==="aborted")return ke;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?ke:c.status==="dirty"||r.value==="dirty"?Np(c.value):c});{if(r.value==="aborted")return ke;let a=this._def.schema._parseSync({data:o,path:n.path,parent:n});return a.status==="aborted"?ke:a.status==="dirty"||r.value==="dirty"?Np(a.value):a}}if(i.type==="refinement"){let o=a=>{let c=i.refinement(a,s);if(n.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(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?ke:(a.status==="dirty"&&r.dirty(),o(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?ke:(a.status==="dirty"&&r.dirty(),o(a.value).then(()=>({status:r.value,value:a.value}))))}if(i.type==="transform")if(n.common.async===!1){let o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!hu(o))return ke;let a=i.transform(o.value,s);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>hu(o)?Promise.resolve(i.transform(o.value,s)).then(a=>({status:r.value,value:a})):ke);ot.assertNever(i)}};Si.create=(t,e,r)=>new Si({schema:t,typeName:Te.ZodEffects,effect:e,...Ae(r)});Si.createWithPreprocess=(t,e,r)=>new Si({schema:e,effect:{type:"preprocess",transform:t},typeName:Te.ZodEffects,...Ae(r)});var bi=class extends Be{_parse(e){return this._getType(e)===oe.undefined?gn(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};bi.create=(t,e)=>new bi({innerType:t,typeName:Te.ZodOptional,...Ae(e)});var Ms=class extends Be{_parse(e){return this._getType(e)===oe.null?gn(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Ms.create=(t,e)=>new Ms({innerType:t,typeName:Te.ZodNullable,...Ae(e)});var ku=class extends Be{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===oe.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};ku.create=(t,e)=>new ku({innerType:t,typeName:Te.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...Ae(e)});var Tu=class extends Be{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},i=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return zv(i)?i.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Kn(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Kn(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Tu.create=(t,e)=>new Tu({innerType:t,typeName:Te.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...Ae(e)});var Wp=class extends Be{_parse(e){if(this._getType(e)!==oe.nan){let n=this._getOrReturnCtx(e);return te(n,{code:W.invalid_type,expected:oe.nan,received:n.parsedType}),ke}return{status:"valid",value:e.data}}};Wp.create=t=>new Wp({typeName:Te.ZodNaN,...Ae(t)});var Lv=class extends Be{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},Uv=class t extends Be{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?ke:s.status==="dirty"?(r.dirty(),Np(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{let i=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?ke:i.status==="dirty"?(r.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:Te.ZodPipeline})}},$u=class extends Be{_parse(e){let r=this._def.innerType._parse(e),n=i=>(hu(i)&&(i.value=Object.freeze(i.value)),i);return zv(r)?r.then(i=>n(i)):n(r)}unwrap(){return this._def.innerType}};$u.create=(t,e)=>new $u({innerType:t,typeName:Te.ZodReadonly,...Ae(e)});var hDe={object:On.lazycreate},Te;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(Te||(Te={}));var gDe=gu.create,vDe=zp.create,yDe=Wp.create,_De=Lp.create,bDe=Up.create,SDe=Fp.create,xDe=qp.create,wDe=vu.create,EDe=yu.create,kDe=Hp.create,TDe=bo.create,$De=Qi.create,IDe=Zp.create,RDe=So.create,ODe=On.create,CDe=On.strictCreate,PDe=_u.create,ADe=S$.create,NDe=bu.create,MDe=Ns.create,DDe=w$.create,jDe=Bp.create,zDe=Gp.create,LDe=E$.create,UDe=Su.create,FDe=xu.create,qDe=wu.create,HDe=Eu.create,ZDe=ba.create,BDe=Si.create,GDe=bi.create,WDe=Ms.create,VDe=Si.createWithPreprocess,KDe=Uv.create,JDe=Object.freeze({status:"aborted"});function q(t,e,r){function n(a,c){var u;Object.defineProperty(a,"_zod",{value:a._zod??{},enumerable:!1}),(u=a._zod).traits??(u.traits=new Set),a._zod.traits.add(t),e(a,c);for(let l in o.prototype)l in a||Object.defineProperty(a,l,{value:o.prototype[l].bind(a)});a._zod.constr=o,a._zod.def=c}let i=r?.Parent??Object;class s extends i{}Object.defineProperty(s,"name",{value:t});function o(a){var c;let u=r?.Parent?new s:this;n(u,a),(c=u._zod).deferred??(c.deferred=[]);for(let l of u._zod.deferred)l();return u}return Object.defineProperty(o,"init",{value:n}),Object.defineProperty(o,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(o,"name",{value:t}),o}var Sa=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},k$={};function Ds(t){return t&&Object.assign(k$,t),k$}var At={};vF(At,{unwrapMessage:()=>Mp,stringifyPrimitive:()=>U$,required:()=>Lfe,randomString:()=>Ife,propertyKeyTypes:()=>nq,promiseAllObject:()=>$fe,primitiveTypes:()=>Cfe,prefixIssues:()=>_o,pick:()=>Nfe,partial:()=>zfe,optionalKeys:()=>iq,omit:()=>Mfe,numKeys:()=>Rfe,nullish:()=>Jv,normalizeParams:()=>Se,merge:()=>jfe,jsonStringifyReplacer:()=>eq,joinValues:()=>T$,issue:()=>oq,isPlainObject:()=>Kp,isObject:()=>Vp,getSizableOrigin:()=>Ufe,getParsedType:()=>Ofe,getLengthableOrigin:()=>Yv,getEnumValues:()=>QF,getElementAtPath:()=>Tfe,floatSafeRemainder:()=>tq,finalizeIssue:()=>js,extend:()=>Dfe,escapeRegex:()=>Au,esc:()=>fu,defineLazy:()=>Nt,createTransparentProxy:()=>Pfe,clone:()=>wo,cleanRegex:()=>Xv,cleanEnum:()=>Ffe,captureStackTrace:()=>L$,cached:()=>Kv,assignProp:()=>z$,assertNotEqual:()=>xfe,assertNever:()=>Efe,assertIs:()=>wfe,assertEqual:()=>Sfe,assert:()=>kfe,allowsEval:()=>rq,aborted:()=>mu,NUMBER_FORMAT_RANGES:()=>sq,Class:()=>$$,BIGINT_FORMAT_RANGES:()=>Afe});function Sfe(t){return t}function xfe(t){return t}function wfe(t){}function Efe(t){throw new Error}function kfe(t){}function QF(t){let e=Object.values(t).filter(n=>typeof n=="number");return Object.entries(t).filter(([n,i])=>e.indexOf(+n)===-1).map(([n,i])=>i)}function T$(t,e="|"){return t.map(r=>U$(r)).join(e)}function eq(t,e){return typeof e=="bigint"?e.toString():e}function Kv(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Jv(t){return t==null}function Xv(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function tq(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,i=r>n?r:n,s=Number.parseInt(t.toFixed(i).replace(".","")),o=Number.parseInt(e.toFixed(i).replace(".",""));return s%o/10**i}function Nt(t,e,r){Object.defineProperty(t,e,{get(){{let i=r();return t[e]=i,i}throw new Error("cached value already set")},set(i){Object.defineProperty(t,e,{value:i})},configurable:!0})}function z$(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Tfe(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function $fe(t){let e=Object.keys(t),r=e.map(n=>t[n]);return Promise.all(r).then(n=>{let i={};for(let s=0;s{};function Vp(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var rq=Kv(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});function Kp(t){if(Vp(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(Vp(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function Rfe(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}var Ofe=t=>{let e=typeof t;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(t)?"array":t===null?"null":t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?"promise":typeof Map<"u"&&t instanceof Map?"map":typeof Set<"u"&&t instanceof Set?"set":typeof Date<"u"&&t instanceof Date?"date":typeof File<"u"&&t instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},nq=new Set(["string","number","symbol"]),Cfe=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Au(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function wo(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function Se(t){let e=t;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 Pfe(t){let e;return new Proxy({},{get(r,n,i){return e??(e=t()),Reflect.get(e,n,i)},set(r,n,i,s){return e??(e=t()),Reflect.set(e,n,i,s)},has(r,n){return e??(e=t()),Reflect.has(e,n)},deleteProperty(r,n){return e??(e=t()),Reflect.deleteProperty(e,n)},ownKeys(r){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(r,n){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,n)},defineProperty(r,n,i){return e??(e=t()),Reflect.defineProperty(e,n,i)}})}function U$(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function iq(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}var sq={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]},Afe={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function Nfe(t,e){let r={},n=t._zod.def;for(let i in e){if(!(i in n.shape))throw new Error(`Unrecognized key: "${i}"`);e[i]&&(r[i]=n.shape[i])}return wo(t,{...t._zod.def,shape:r,checks:[]})}function Mfe(t,e){let r={...t._zod.def.shape},n=t._zod.def;for(let i in e){if(!(i in n.shape))throw new Error(`Unrecognized key: "${i}"`);e[i]&&delete r[i]}return wo(t,{...t._zod.def,shape:r,checks:[]})}function Dfe(t,e){if(!Kp(e))throw new Error("Invalid input to extend: expected a plain object");let r={...t._zod.def,get shape(){let n={...t._zod.def.shape,...e};return z$(this,"shape",n),n},checks:[]};return wo(t,r)}function jfe(t,e){return wo(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return z$(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function zfe(t,e,r){let n=e._zod.def.shape,i={...n};if(r)for(let s in r){if(!(s in n))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(i[s]=t?new t({type:"optional",innerType:n[s]}):n[s])}else for(let s in n)i[s]=t?new t({type:"optional",innerType:n[s]}):n[s];return wo(e,{...e._zod.def,shape:i,checks:[]})}function Lfe(t,e,r){let n=e._zod.def.shape,i={...n};if(r)for(let s in r){if(!(s in i))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(i[s]=new t({type:"nonoptional",innerType:n[s]}))}else for(let s in n)i[s]=new t({type:"nonoptional",innerType:n[s]});return wo(e,{...e._zod.def,shape:i,checks:[]})}function mu(t,e=0){for(let r=e;r{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function Mp(t){return typeof t=="string"?t:t?.message}function js(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let i=Mp(t.inst?._zod.def?.error?.(t))??Mp(e?.error?.(t))??Mp(r.customError?.(t))??Mp(r.localeError?.(t))??"Invalid input";n.message=i}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function Ufe(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function Yv(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function oq(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function Ffe(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var $$=class{constructor(...e){}},aq=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),Object.defineProperty(t,"message",{get(){return JSON.stringify(e,eq,2)},enumerable:!0})},cq=q("$ZodError",aq),uq=q("$ZodError",aq,{Parent:Error});function qfe(t,e=r=>r.message){let r={},n=[];for(let i of t.issues)i.path.length>0?(r[i.path[0]]=r[i.path[0]]||[],r[i.path[0]].push(e(i))):n.push(e(i));return{formErrors:n,fieldErrors:r}}function Hfe(t,e){let r=e||function(s){return s.message},n={_errors:[]},i=s=>{for(let o of s.issues)if(o.code==="invalid_union"&&o.errors.length)o.errors.map(a=>i({issues:a}));else if(o.code==="invalid_key")i({issues:o.issues});else if(o.code==="invalid_element")i({issues:o.issues});else if(o.path.length===0)n._errors.push(r(o));else{let a=n,c=0;for(;c(e,r,n,i)=>{let s=n?Object.assign(n,{async:!1}):{async:!1},o=e._zod.run({value:r,issues:[]},s);if(o instanceof Promise)throw new Sa;if(o.issues.length){let a=new(i?.Err??t)(o.issues.map(c=>js(c,s,Ds())));throw L$(a,i?.callee),a}return o.value};var Bfe=t=>async(e,r,n,i)=>{let s=n?Object.assign(n,{async:!0}):{async:!0},o=e._zod.run({value:r,issues:[]},s);if(o instanceof Promise&&(o=await o),o.issues.length){let a=new(i?.Err??t)(o.issues.map(c=>js(c,s,Ds())));throw L$(a,i?.callee),a}return o.value};var lq=t=>(e,r,n)=>{let i=n?{...n,async:!1}:{async:!1},s=e._zod.run({value:r,issues:[]},i);if(s instanceof Promise)throw new Sa;return s.issues.length?{success:!1,error:new(t??cq)(s.issues.map(o=>js(o,i,Ds())))}:{success:!0,data:s.value}},Gfe=lq(uq),dq=t=>async(e,r,n)=>{let i=n?Object.assign(n,{async:!0}):{async:!0},s=e._zod.run({value:r,issues:[]},i);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new t(s.issues.map(o=>js(o,i,Ds())))}:{success:!0,data:s.value}},Wfe=dq(uq),Vfe=/^[cC][^\s-]{8,}$/,Kfe=/^[0-9a-z]+$/,Jfe=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Xfe=/^[0-9a-vA-V]{20}$/,Yfe=/^[A-Za-z0-9]{27}$/,Qfe=/^[a-zA-Z0-9_-]{21}$/,eme=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,tme=/^([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})$/,X6=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[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)$/,rme=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,nme="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function ime(){return new RegExp(nme,"u")}var sme=/^(?:(?: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])$/,ome=/^(([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})$/,ame=/^((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])$/,cme=/^(([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])$/,ume=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,pq=/^[A-Za-z0-9_-]*$/,lme=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,dme=/^\+(?:[0-9]){6,14}[0-9]$/,fq="(?:(?:\\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])))",pme=new RegExp(`^${fq}$`);function mq(t){let e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function fme(t){return new RegExp(`^${mq(t)}$`)}function mme(t){let e=mq({precision:t.precision}),r=["Z"];t.local&&r.push(""),t.offset&&r.push("([+-]\\d{2}:\\d{2})");let n=`${e}(?:${r.join("|")})`;return new RegExp(`^${fq}T(?:${n})$`)}var hme=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},gme=/^\d+$/,vme=/^-?\d+(?:\.\d+)?/i,yme=/true|false/i,_me=/null/i,bme=/^[^A-Z]*$/,Sme=/^[^a-z]*$/,vn=q("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),hq={number:"number",bigint:"bigint",object:"date"},gq=q("$ZodCheckLessThan",(t,e)=>{vn.init(t,e);let r=hq[typeof e.value];t._zod.onattach.push(n=>{let i=n._zod.bag,s=(e.inclusive?i.maximum:i.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value{(e.inclusive?n.value<=e.value:n.value{vn.init(t,e);let r=hq[typeof e.value];t._zod.onattach.push(n=>{let i=n._zod.bag,s=(e.inclusive?i.minimum:i.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>s&&(e.inclusive?i.minimum=e.value:i.exclusiveMinimum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value>=e.value:n.value>e.value)||n.issues.push({origin:r,code:"too_small",minimum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),xme=q("$ZodCheckMultipleOf",(t,e)=>{vn.init(t,e),t._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=e.value)}),t._zod.check=r=>{if(typeof r.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%e.value===BigInt(0):tq(r.value,e.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:e.value,input:r.value,inst:t,continue:!e.abort})}}),wme=q("$ZodCheckNumberFormat",(t,e)=>{vn.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[i,s]=sq[e.format];t._zod.onattach.push(o=>{let a=o._zod.bag;a.format=e.format,a.minimum=i,a.maximum=s,r&&(a.pattern=gme)}),t._zod.check=o=>{let a=o.value;if(r){if(!Number.isInteger(a)){o.issues.push({expected:n,format:e.format,code:"invalid_type",input:a,inst:t});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:t,origin:n,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:t,origin:n,continue:!e.abort});return}}as&&o.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inst:t})}}),Eme=q("$ZodCheckMaxLength",(t,e)=>{vn.init(t,e),t._zod.when=r=>{let n=r.value;return!Jv(n)&&n.length!==void 0},t._zod.onattach.push(r=>{let n=r._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum{let n=r.value;if(n.length<=e.maximum)return;let s=Yv(n);r.issues.push({origin:s,code:"too_big",maximum:e.maximum,inclusive:!0,input:n,inst:t,continue:!e.abort})}}),kme=q("$ZodCheckMinLength",(t,e)=>{vn.init(t,e),t._zod.when=r=>{let n=r.value;return!Jv(n)&&n.length!==void 0},t._zod.onattach.push(r=>{let n=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>n&&(r._zod.bag.minimum=e.minimum)}),t._zod.check=r=>{let n=r.value;if(n.length>=e.minimum)return;let s=Yv(n);r.issues.push({origin:s,code:"too_small",minimum:e.minimum,inclusive:!0,input:n,inst:t,continue:!e.abort})}}),Tme=q("$ZodCheckLengthEquals",(t,e)=>{vn.init(t,e),t._zod.when=r=>{let n=r.value;return!Jv(n)&&n.length!==void 0},t._zod.onattach.push(r=>{let n=r._zod.bag;n.minimum=e.length,n.maximum=e.length,n.length=e.length}),t._zod.check=r=>{let n=r.value,i=n.length;if(i===e.length)return;let s=Yv(n),o=i>e.length;r.issues.push({origin:s,...o?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:r.value,inst:t,continue:!e.abort})}}),Qv=q("$ZodCheckStringFormat",(t,e)=>{var r,n;vn.init(t,e),t._zod.onattach.push(i=>{let s=i._zod.bag;s.format=e.format,e.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(e.pattern))}),e.pattern?(r=t._zod).check??(r.check=i=>{e.pattern.lastIndex=0,!e.pattern.test(i.value)&&i.issues.push({origin:"string",code:"invalid_format",format:e.format,input:i.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(n=t._zod).check??(n.check=()=>{})}),$me=q("$ZodCheckRegex",(t,e)=>{Qv.init(t,e),t._zod.check=r=>{e.pattern.lastIndex=0,!e.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),Ime=q("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=bme),Qv.init(t,e)}),Rme=q("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=Sme),Qv.init(t,e)}),Ome=q("$ZodCheckIncludes",(t,e)=>{vn.init(t,e);let r=Au(e.includes),n=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=n,t._zod.onattach.push(i=>{let s=i._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),t._zod.check=i=>{i.value.includes(e.includes,e.position)||i.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:i.value,inst:t,continue:!e.abort})}}),Cme=q("$ZodCheckStartsWith",(t,e)=>{vn.init(t,e);let r=new RegExp(`^${Au(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let i=n._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(r)}),t._zod.check=n=>{n.value.startsWith(e.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:n.value,inst:t,continue:!e.abort})}}),Pme=q("$ZodCheckEndsWith",(t,e)=>{vn.init(t,e);let r=new RegExp(`.*${Au(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let i=n._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(r)}),t._zod.check=n=>{n.value.endsWith(e.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:n.value,inst:t,continue:!e.abort})}}),Ame=q("$ZodCheckOverwrite",(t,e)=>{vn.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}}),I$=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 n=e.split(` +`)}handleMcpControlRequest(e,r,n){let i="id"in r.message?r.message.id:null,s=`${e}:${i}`;return new Promise((o,a)=>{let c=()=>{this.pendingMcpResponses.delete(s)},u=d=>{c(),o(d)},l=d=>{c(),a(d)};if(this.pendingMcpResponses.set(s,{resolve:u,reject:l}),n.onmessage)n.onmessage(r.message);else{c(),a(new Error("No message handler registered"));return}})}};var ot;(function(t){t.assertEqual=i=>{};function e(i){}t.assertIs=e;function r(i){throw new Error}t.assertNever=r,t.arrayToEnum=i=>{let s={};for(let o of i)s[o]=o;return s},t.getValidEnumValues=i=>{let s=t.objectKeys(i).filter(a=>typeof i[i[a]]!="number"),o={};for(let a of s)o[a]=i[a];return t.objectValues(o)},t.objectValues=i=>t.objectKeys(i).map(function(s){return i[s]}),t.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let s=[];for(let o in i)Object.prototype.hasOwnProperty.call(i,o)&&s.push(o);return s},t.find=(i,s)=>{for(let o of i)if(s(o))return o},t.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function n(i,s=" | "){return i.map(o=>typeof o=="string"?`'${o}'`:o).join(s)}t.joinValues=n,t.jsonStringifyReplacer=(i,s)=>typeof s=="bigint"?s.toString():s})(ot||(ot={}));var W6;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(W6||(W6={}));var oe=ot.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),yo=t=>{switch(typeof t){case"undefined":return oe.undefined;case"string":return oe.string;case"number":return Number.isNaN(t)?oe.nan:oe.number;case"boolean":return oe.boolean;case"function":return oe.function;case"bigint":return oe.bigint;case"symbol":return oe.symbol;case"object":return Array.isArray(t)?oe.array:t===null?oe.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?oe.promise:typeof Map<"u"&&t instanceof Map?oe.map:typeof Set<"u"&&t instanceof Set?oe.set:typeof Date<"u"&&t instanceof Date?oe.date:oe.object;default:return oe.unknown}},W=ot.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"]),Kn=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(s){return s.message},n={_errors:[]},i=s=>{for(let o of s.issues)if(o.code==="invalid_union")o.unionErrors.map(i);else if(o.code==="invalid_return_type")i(o.returnTypeError);else if(o.code==="invalid_arguments")i(o.argumentsError);else if(o.path.length===0)n._errors.push(r(o));else{let a=n,c=0;for(;cr.message){let r={},n=[];for(let i of this.issues)if(i.path.length>0){let s=i.path[0];r[s]=r[s]||[],r[s].push(e(i))}else n.push(e(i));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};Kn.create=t=>new Kn(t);var Xpe=(t,e)=>{let r;switch(t.code){case W.invalid_type:t.received===oe.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case W.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,ot.jsonStringifyReplacer)}`;break;case W.unrecognized_keys:r=`Unrecognized key(s) in object: ${ot.joinValues(t.keys,", ")}`;break;case W.invalid_union:r="Invalid input";break;case W.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${ot.joinValues(t.options)}`;break;case W.invalid_enum_value:r=`Invalid enum value. Expected ${ot.joinValues(t.options)}, received '${t.received}'`;break;case W.invalid_arguments:r="Invalid function arguments";break;case W.invalid_return_type:r="Invalid function return type";break;case W.invalid_date:r="Invalid date";break;case W.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:ot.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case W.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case W.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case W.custom:r="Invalid input";break;case W.invalid_intersection_types:r="Intersection results could not be merged";break;case W.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case W.not_finite:r="Number must be finite";break;default:r=e.defaultError,ot.assertNever(t)}return{message:r}},jp=Xpe,Ype=jp;function _$(){return Ype}var b$=t=>{let{data:e,path:r,errorMaps:n,issueData:i}=t,s=[...r,...i.path||[]],o={...i,path:s};if(i.message!==void 0)return{...i,path:s,message:i.message};let a="",c=n.filter(u=>!!u).slice().reverse();for(let u of c)a=u(o,{data:e,defaultError:a}).message;return{...i,path:s,message:a}};function te(t,e){let r=_$(),n=b$({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===jp?void 0:jp].filter(i=>!!i)});t.common.issues.push(n)}var en=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let i of r){if(i.status==="aborted")return ke;i.status==="dirty"&&e.dirty(),n.push(i.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let i of r){let s=await i.key,o=await i.value;n.push({key:s,value:o})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let i of r){let{key:s,value:o}=i;if(s.status==="aborted"||o.status==="aborted")return ke;s.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof o.value<"u"||i.alwaysSet)&&(n[s.value]=o.value)}return{status:e.value,value:n}}},ke=Object.freeze({status:"aborted"}),Np=t=>({status:"dirty",value:t}),gn=t=>({status:"valid",value:t}),V6=t=>t.status==="aborted",K6=t=>t.status==="dirty",hu=t=>t.status==="valid",zv=t=>typeof Promise<"u"&&t instanceof Promise,pe;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(pe||(pe={}));var Jn=class{constructor(e,r,n,i){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=i}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},J6=(t,e)=>{if(hu(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new Kn(t.common.issues);return this._error=r,this._error}}};function Ae(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:i}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:i}:{errorMap:(o,a)=>{let{message:c}=t;return o.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:o.code!=="invalid_type"?{message:a.defaultError}:{message:c??r??a.defaultError}},description:i}}var Be=class{get description(){return this._def.description}_getType(e){return yo(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:yo(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new en,ctx:{common:e.parent.common,data:e.data,parsedType:yo(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(zv(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:yo(e)},i=this._parseSync({data:e,path:n.path,parent:n});return J6(n,i)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:yo(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return hu(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>hu(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:yo(e)},i=this._parse({data:e,path:n.path,parent:n}),s=await(zv(i)?i:Promise.resolve(i));return J6(n,s)}refine(e,r){let n=i=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(i):r;return this._refinement((i,s)=>{let o=e(i),a=()=>s.addIssue({code:W.custom,...n(i)});return typeof Promise<"u"&&o instanceof Promise?o.then(c=>c?!0:(a(),!1)):o?!0:(a(),!1)})}refinement(e,r){return this._refinement((n,i)=>e(n)?!0:(i.addIssue(typeof r=="function"?r(n,i):r),!1))}_refinement(e){return new Si({schema:this,typeName:Te.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:r=>this["~validate"](r)}}optional(){return bi.create(this,this._def)}nullable(){return Ms.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return So.create(this)}promise(){return ba.create(this,this._def)}or(e){return _u.create([this,e],this._def)}and(e){return bu.create(this,e,this._def)}transform(e){return new Si({...Ae(this._def),schema:this,typeName:Te.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new ku({...Ae(this._def),innerType:this,defaultValue:r,typeName:Te.ZodDefault})}brand(){return new Lv({typeName:Te.ZodBranded,type:this,...Ae(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Tu({...Ae(this._def),innerType:this,catchValue:r,typeName:Te.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return Uv.create(this,e)}readonly(){return $u.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Qpe=/^c[^\s-]{8,}$/i,efe=/^[0-9a-z]+$/,tfe=/^[0-9A-HJKMNP-TV-Z]{26}$/i,rfe=/^[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,nfe=/^[a-z0-9_-]{21}$/i,ife=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,sfe=/^[-+]?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)?)??$/,ofe=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,afe="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",u$,cfe=/^(?:(?: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])$/,ufe=/^(?:(?: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])$/,lfe=/^(([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]))$/,dfe=/^(([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])$/,pfe=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,ffe=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,JF="((\\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])))",mfe=new RegExp(`^${JF}$`);function XF(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function hfe(t){return new RegExp(`^${XF(t)}$`)}function gfe(t){let e=`${JF}T${XF(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function vfe(t,e){return!!((e==="v4"||!e)&&cfe.test(t)||(e==="v6"||!e)&&lfe.test(t))}function yfe(t,e){if(!ife.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),i=JSON.parse(atob(n));return!(typeof i!="object"||i===null||"typ"in i&&i?.typ!=="JWT"||!i.alg||e&&i.alg!==e)}catch{return!1}}function _fe(t,e){return!!((e==="v4"||!e)&&ufe.test(t)||(e==="v6"||!e)&&dfe.test(t))}var gu=class t extends Be{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==oe.string){let s=this._getOrReturnCtx(e);return te(s,{code:W.invalid_type,expected:oe.string,received:s.parsedType}),ke}let n=new en,i;for(let s of this._def.checks)if(s.kind==="min")e.data.lengths.value&&(i=this._getOrReturnCtx(e,i),te(i,{code:W.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){let o=e.data.length>s.value,a=e.data.lengthe.test(i),{validation:r,code:W.invalid_string,...pe.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...pe.errToObj(e)})}url(e){return this._addCheck({kind:"url",...pe.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...pe.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...pe.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...pe.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...pe.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...pe.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...pe.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...pe.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...pe.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...pe.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...pe.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...pe.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,...pe.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,...pe.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...pe.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...pe.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...pe.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...pe.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...pe.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...pe.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...pe.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...pe.errToObj(r)})}nonempty(e){return this.min(1,pe.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...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 r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.valuenew gu({checks:[],typeName:Te.ZodString,coerce:t?.coerce??!1,...Ae(t)});function bfe(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,i=r>n?r:n,s=Number.parseInt(t.toFixed(i).replace(".","")),o=Number.parseInt(e.toFixed(i).replace(".",""));return s%o/10**i}var zp=class t extends Be{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)!==oe.number){let s=this._getOrReturnCtx(e);return te(s,{code:W.invalid_type,expected:oe.number,received:s.parsedType}),ke}let n,i=new en;for(let s of this._def.checks)s.kind==="int"?ot.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),te(n,{code:W.invalid_type,expected:"integer",received:"float",message:s.message}),i.dirty()):s.kind==="min"?(s.inclusive?e.datas.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),te(n,{code:W.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),i.dirty()):s.kind==="multipleOf"?bfe(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),te(n,{code:W.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),te(n,{code:W.not_finite,message:s.message}),i.dirty()):ot.assertNever(s);return{status:i.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,pe.toString(r))}gt(e,r){return this.setLimit("min",e,!1,pe.toString(r))}lte(e,r){return this.setLimit("max",e,!0,pe.toString(r))}lt(e,r){return this.setLimit("max",e,!1,pe.toString(r))}setLimit(e,r,n,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:pe.toString(i)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:pe.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:pe.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:pe.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:pe.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:pe.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:pe.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:pe.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:pe.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:pe.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.valuee.kind==="int"||e.kind==="multipleOf"&&ot.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.valuenew zp({checks:[],typeName:Te.ZodNumber,coerce:t?.coerce||!1,...Ae(t)});var Lp=class t extends Be{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)!==oe.bigint)return this._getInvalidInput(e);let n,i=new en;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?e.datas.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),te(n,{code:W.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),i.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),te(n,{code:W.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):ot.assertNever(s);return{status:i.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return te(r,{code:W.invalid_type,expected:oe.bigint,received:r.parsedType}),ke}gte(e,r){return this.setLimit("min",e,!0,pe.toString(r))}gt(e,r){return this.setLimit("min",e,!1,pe.toString(r))}lte(e,r){return this.setLimit("max",e,!0,pe.toString(r))}lt(e,r){return this.setLimit("max",e,!1,pe.toString(r))}setLimit(e,r,n,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:pe.toString(i)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:pe.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:pe.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:pe.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:pe.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:pe.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.valuenew Lp({checks:[],typeName:Te.ZodBigInt,coerce:t?.coerce??!1,...Ae(t)});var Up=class extends Be{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==oe.boolean){let n=this._getOrReturnCtx(e);return te(n,{code:W.invalid_type,expected:oe.boolean,received:n.parsedType}),ke}return gn(e.data)}};Up.create=t=>new Up({typeName:Te.ZodBoolean,coerce:t?.coerce||!1,...Ae(t)});var Fp=class t extends Be{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==oe.date){let s=this._getOrReturnCtx(e);return te(s,{code:W.invalid_type,expected:oe.date,received:s.parsedType}),ke}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return te(s,{code:W.invalid_date}),ke}let n=new en,i;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()s.value&&(i=this._getOrReturnCtx(e,i),te(i,{code:W.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):ot.assertNever(s);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:pe.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:pe.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.valuenew Fp({checks:[],coerce:t?.coerce||!1,typeName:Te.ZodDate,...Ae(t)});var qp=class extends Be{_parse(e){if(this._getType(e)!==oe.symbol){let n=this._getOrReturnCtx(e);return te(n,{code:W.invalid_type,expected:oe.symbol,received:n.parsedType}),ke}return gn(e.data)}};qp.create=t=>new qp({typeName:Te.ZodSymbol,...Ae(t)});var vu=class extends Be{_parse(e){if(this._getType(e)!==oe.undefined){let n=this._getOrReturnCtx(e);return te(n,{code:W.invalid_type,expected:oe.undefined,received:n.parsedType}),ke}return gn(e.data)}};vu.create=t=>new vu({typeName:Te.ZodUndefined,...Ae(t)});var yu=class extends Be{_parse(e){if(this._getType(e)!==oe.null){let n=this._getOrReturnCtx(e);return te(n,{code:W.invalid_type,expected:oe.null,received:n.parsedType}),ke}return gn(e.data)}};yu.create=t=>new yu({typeName:Te.ZodNull,...Ae(t)});var Hp=class extends Be{constructor(){super(...arguments),this._any=!0}_parse(e){return gn(e.data)}};Hp.create=t=>new Hp({typeName:Te.ZodAny,...Ae(t)});var bo=class extends Be{constructor(){super(...arguments),this._unknown=!0}_parse(e){return gn(e.data)}};bo.create=t=>new bo({typeName:Te.ZodUnknown,...Ae(t)});var Qi=class extends Be{_parse(e){let r=this._getOrReturnCtx(e);return te(r,{code:W.invalid_type,expected:oe.never,received:r.parsedType}),ke}};Qi.create=t=>new Qi({typeName:Te.ZodNever,...Ae(t)});var Zp=class extends Be{_parse(e){if(this._getType(e)!==oe.undefined){let n=this._getOrReturnCtx(e);return te(n,{code:W.invalid_type,expected:oe.void,received:n.parsedType}),ke}return gn(e.data)}};Zp.create=t=>new Zp({typeName:Te.ZodVoid,...Ae(t)});var So=class t extends Be{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),i=this._def;if(r.parsedType!==oe.array)return te(r,{code:W.invalid_type,expected:oe.array,received:r.parsedType}),ke;if(i.exactLength!==null){let o=r.data.length>i.exactLength.value,a=r.data.lengthi.maxLength.value&&(te(r,{code:W.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((o,a)=>i.type._parseAsync(new Jn(r,o,r.path,a)))).then(o=>en.mergeArray(n,o));let s=[...r.data].map((o,a)=>i.type._parseSync(new Jn(r,o,r.path,a)));return en.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:pe.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:pe.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:pe.toString(r)}})}nonempty(e){return this.min(1,e)}};So.create=(t,e)=>new So({type:t,minLength:null,maxLength:null,exactLength:null,typeName:Te.ZodArray,...Ae(e)});function pu(t){if(t instanceof On){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=bi.create(pu(n))}return new On({...t._def,shape:()=>e})}else return t instanceof So?new So({...t._def,type:pu(t.element)}):t instanceof bi?bi.create(pu(t.unwrap())):t instanceof Ms?Ms.create(pu(t.unwrap())):t instanceof Ns?Ns.create(t.items.map(e=>pu(e))):t}var On=class t extends Be{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(),r=ot.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==oe.object){let u=this._getOrReturnCtx(e);return te(u,{code:W.invalid_type,expected:oe.object,received:u.parsedType}),ke}let{status:n,ctx:i}=this._processInputParams(e),{shape:s,keys:o}=this._getCached(),a=[];if(!(this._def.catchall instanceof Qi&&this._def.unknownKeys==="strip"))for(let u in i.data)o.includes(u)||a.push(u);let c=[];for(let u of o){let l=s[u],d=i.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new Jn(i,d,i.path,u)),alwaysSet:u in i.data})}if(this._def.catchall instanceof Qi){let u=this._def.unknownKeys;if(u==="passthrough")for(let l of a)c.push({key:{status:"valid",value:l},value:{status:"valid",value:i.data[l]}});else if(u==="strict")a.length>0&&(te(i,{code:W.unrecognized_keys,keys:a}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let l of a){let d=i.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new Jn(i,d,i.path,l)),alwaysSet:l in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let u=[];for(let l of c){let d=await l.key,p=await l.value;u.push({key:d,value:p,alwaysSet:l.alwaysSet})}return u}).then(u=>en.mergeObjectSync(n,u)):en.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return pe.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let i=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:pe.errToObj(e).message??i}:{message:i}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Te.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let n of ot.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let n of ot.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return pu(this)}partial(e){let r={};for(let n of ot.objectKeys(this.shape)){let i=this.shape[n];e&&!e[n]?r[n]=i:r[n]=i.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of ot.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof bi;)s=s._def.innerType;r[n]=s}return new t({...this._def,shape:()=>r})}keyof(){return YF(ot.objectKeys(this.shape))}};On.create=(t,e)=>new On({shape:()=>t,unknownKeys:"strip",catchall:Qi.create(),typeName:Te.ZodObject,...Ae(e)});On.strictCreate=(t,e)=>new On({shape:()=>t,unknownKeys:"strict",catchall:Qi.create(),typeName:Te.ZodObject,...Ae(e)});On.lazycreate=(t,e)=>new On({shape:t,unknownKeys:"strip",catchall:Qi.create(),typeName:Te.ZodObject,...Ae(e)});var _u=class extends Be{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function i(s){for(let a of s)if(a.result.status==="valid")return a.result;for(let a of s)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let o=s.map(a=>new Kn(a.ctx.common.issues));return te(r,{code:W.invalid_union,unionErrors:o}),ke}if(r.common.async)return Promise.all(n.map(async s=>{let o={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:o}),ctx:o}})).then(i);{let s,o=[];for(let c of n){let u={...r,common:{...r.common,issues:[]},parent:null},l=c._parseSync({data:r.data,path:r.path,parent:u});if(l.status==="valid")return l;l.status==="dirty"&&!s&&(s={result:l,ctx:u}),u.common.issues.length&&o.push(u.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;let a=o.map(c=>new Kn(c));return te(r,{code:W.invalid_union,unionErrors:a}),ke}}get options(){return this._def.options}};_u.create=(t,e)=>new _u({options:t,typeName:Te.ZodUnion,...Ae(e)});var Cs=t=>t instanceof Su?Cs(t.schema):t instanceof Si?Cs(t.innerType()):t instanceof xu?[t.value]:t instanceof wu?t.options:t instanceof Eu?ot.objectValues(t.enum):t instanceof ku?Cs(t._def.innerType):t instanceof vu?[void 0]:t instanceof yu?[null]:t instanceof bi?[void 0,...Cs(t.unwrap())]:t instanceof Ms?[null,...Cs(t.unwrap())]:t instanceof Lv||t instanceof $u?Cs(t.unwrap()):t instanceof Tu?Cs(t._def.innerType):[],S$=class t extends Be{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==oe.object)return te(r,{code:W.invalid_type,expected:oe.object,received:r.parsedType}),ke;let n=this.discriminator,i=r.data[n],s=this.optionsMap.get(i);return s?r.common.async?s._parseAsync({data:r.data,path:r.path,parent:r}):s._parseSync({data:r.data,path:r.path,parent:r}):(te(r,{code:W.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),ke)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let i=new Map;for(let s of r){let o=Cs(s.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(i.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);i.set(a,s)}}return new t({typeName:Te.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:i,...Ae(n)})}};function x$(t,e){let r=yo(t),n=yo(e);if(t===e)return{valid:!0,data:t};if(r===oe.object&&n===oe.object){let i=ot.objectKeys(e),s=ot.objectKeys(t).filter(a=>i.indexOf(a)!==-1),o={...t,...e};for(let a of s){let c=x$(t[a],e[a]);if(!c.valid)return{valid:!1};o[a]=c.data}return{valid:!0,data:o}}else if(r===oe.array&&n===oe.array){if(t.length!==e.length)return{valid:!1};let i=[];for(let s=0;s{if(V6(s)||V6(o))return ke;let a=x$(s.value,o.value);return a.valid?((K6(s)||K6(o))&&r.dirty(),{status:r.value,value:a.data}):(te(n,{code:W.invalid_intersection_types}),ke)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([s,o])=>i(s,o)):i(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};bu.create=(t,e,r)=>new bu({left:t,right:e,typeName:Te.ZodIntersection,...Ae(r)});var Ns=class t extends Be{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==oe.array)return te(n,{code:W.invalid_type,expected:oe.array,received:n.parsedType}),ke;if(n.data.lengththis._def.items.length&&(te(n,{code:W.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let s=[...n.data].map((o,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new Jn(n,o,n.path,a)):null}).filter(o=>!!o);return n.common.async?Promise.all(s).then(o=>en.mergeArray(r,o)):en.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};Ns.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ns({items:t,typeName:Te.ZodTuple,rest:null,...Ae(e)})};var w$=class t extends Be{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==oe.object)return te(n,{code:W.invalid_type,expected:oe.object,received:n.parsedType}),ke;let i=[],s=this._def.keyType,o=this._def.valueType;for(let a in n.data)i.push({key:s._parse(new Jn(n,a,n.path,a)),value:o._parse(new Jn(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?en.mergeObjectAsync(r,i):en.mergeObjectSync(r,i)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof Be?new t({keyType:e,valueType:r,typeName:Te.ZodRecord,...Ae(n)}):new t({keyType:gu.create(),valueType:e,typeName:Te.ZodRecord,...Ae(r)})}},Bp=class extends Be{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==oe.map)return te(n,{code:W.invalid_type,expected:oe.map,received:n.parsedType}),ke;let i=this._def.keyType,s=this._def.valueType,o=[...n.data.entries()].map(([a,c],u)=>({key:i._parse(new Jn(n,a,n.path,[u,"key"])),value:s._parse(new Jn(n,c,n.path,[u,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of o){let u=await c.key,l=await c.value;if(u.status==="aborted"||l.status==="aborted")return ke;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let c of o){let u=c.key,l=c.value;if(u.status==="aborted"||l.status==="aborted")return ke;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}}}};Bp.create=(t,e,r)=>new Bp({valueType:e,keyType:t,typeName:Te.ZodMap,...Ae(r)});var Gp=class t extends Be{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==oe.set)return te(n,{code:W.invalid_type,expected:oe.set,received:n.parsedType}),ke;let i=this._def;i.minSize!==null&&n.data.sizei.maxSize.value&&(te(n,{code:W.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),r.dirty());let s=this._def.valueType;function o(c){let u=new Set;for(let l of c){if(l.status==="aborted")return ke;l.status==="dirty"&&r.dirty(),u.add(l.value)}return{status:r.value,value:u}}let a=[...n.data.values()].map((c,u)=>s._parse(new Jn(n,c,n.path,u)));return n.common.async?Promise.all(a).then(c=>o(c)):o(a)}min(e,r){return new t({...this._def,minSize:{value:e,message:pe.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:pe.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};Gp.create=(t,e)=>new Gp({valueType:t,minSize:null,maxSize:null,typeName:Te.ZodSet,...Ae(e)});var E$=class t extends Be{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==oe.function)return te(r,{code:W.invalid_type,expected:oe.function,received:r.parsedType}),ke;function n(a,c){return b$({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,_$(),jp].filter(u=>!!u),issueData:{code:W.invalid_arguments,argumentsError:c}})}function i(a,c){return b$({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,_$(),jp].filter(u=>!!u),issueData:{code:W.invalid_return_type,returnTypeError:c}})}let s={errorMap:r.common.contextualErrorMap},o=r.data;if(this._def.returns instanceof ba){let a=this;return gn(async function(...c){let u=new Kn([]),l=await a._def.args.parseAsync(c,s).catch(f=>{throw u.addIssue(n(c,f)),u}),d=await Reflect.apply(o,this,l);return await a._def.returns._def.type.parseAsync(d,s).catch(f=>{throw u.addIssue(i(d,f)),u})})}else{let a=this;return gn(function(...c){let u=a._def.args.safeParse(c,s);if(!u.success)throw new Kn([n(c,u.error)]);let l=Reflect.apply(o,this,u.data),d=a._def.returns.safeParse(l,s);if(!d.success)throw new Kn([i(l,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:Ns.create(e).rest(bo.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new t({args:e||Ns.create([]).rest(bo.create()),returns:r||bo.create(),typeName:Te.ZodFunction,...Ae(n)})}},Su=class extends Be{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};Su.create=(t,e)=>new Su({getter:t,typeName:Te.ZodLazy,...Ae(e)});var xu=class extends Be{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return te(r,{received:r.data,code:W.invalid_literal,expected:this._def.value}),ke}return{status:"valid",value:e.data}}get value(){return this._def.value}};xu.create=(t,e)=>new xu({value:t,typeName:Te.ZodLiteral,...Ae(e)});function YF(t,e){return new wu({values:t,typeName:Te.ZodEnum,...Ae(e)})}var wu=class t extends Be{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return te(r,{expected:ot.joinValues(n),received:r.parsedType,code:W.invalid_type}),ke}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return te(r,{received:r.data,code:W.invalid_enum_value,options:n}),ke}return gn(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};wu.create=YF;var Eu=class extends Be{_parse(e){let r=ot.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==oe.string&&n.parsedType!==oe.number){let i=ot.objectValues(r);return te(n,{expected:ot.joinValues(i),received:n.parsedType,code:W.invalid_type}),ke}if(this._cache||(this._cache=new Set(ot.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let i=ot.objectValues(r);return te(n,{received:n.data,code:W.invalid_enum_value,options:i}),ke}return gn(e.data)}get enum(){return this._def.values}};Eu.create=(t,e)=>new Eu({values:t,typeName:Te.ZodNativeEnum,...Ae(e)});var ba=class extends Be{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==oe.promise&&r.common.async===!1)return te(r,{code:W.invalid_type,expected:oe.promise,received:r.parsedType}),ke;let n=r.parsedType===oe.promise?r.data:Promise.resolve(r.data);return gn(n.then(i=>this._def.type.parseAsync(i,{path:r.path,errorMap:r.common.contextualErrorMap})))}};ba.create=(t,e)=>new ba({type:t,typeName:Te.ZodPromise,...Ae(e)});var Si=class extends Be{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Te.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),i=this._def.effect||null,s={addIssue:o=>{te(n,o),o.fatal?r.abort():r.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),i.type==="preprocess"){let o=i.transform(n.data,s);if(n.common.async)return Promise.resolve(o).then(async a=>{if(r.value==="aborted")return ke;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?ke:c.status==="dirty"||r.value==="dirty"?Np(c.value):c});{if(r.value==="aborted")return ke;let a=this._def.schema._parseSync({data:o,path:n.path,parent:n});return a.status==="aborted"?ke:a.status==="dirty"||r.value==="dirty"?Np(a.value):a}}if(i.type==="refinement"){let o=a=>{let c=i.refinement(a,s);if(n.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(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?ke:(a.status==="dirty"&&r.dirty(),o(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?ke:(a.status==="dirty"&&r.dirty(),o(a.value).then(()=>({status:r.value,value:a.value}))))}if(i.type==="transform")if(n.common.async===!1){let o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!hu(o))return ke;let a=i.transform(o.value,s);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>hu(o)?Promise.resolve(i.transform(o.value,s)).then(a=>({status:r.value,value:a})):ke);ot.assertNever(i)}};Si.create=(t,e,r)=>new Si({schema:t,typeName:Te.ZodEffects,effect:e,...Ae(r)});Si.createWithPreprocess=(t,e,r)=>new Si({schema:e,effect:{type:"preprocess",transform:t},typeName:Te.ZodEffects,...Ae(r)});var bi=class extends Be{_parse(e){return this._getType(e)===oe.undefined?gn(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};bi.create=(t,e)=>new bi({innerType:t,typeName:Te.ZodOptional,...Ae(e)});var Ms=class extends Be{_parse(e){return this._getType(e)===oe.null?gn(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Ms.create=(t,e)=>new Ms({innerType:t,typeName:Te.ZodNullable,...Ae(e)});var ku=class extends Be{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===oe.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};ku.create=(t,e)=>new ku({innerType:t,typeName:Te.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...Ae(e)});var Tu=class extends Be{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},i=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return zv(i)?i.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Kn(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Kn(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Tu.create=(t,e)=>new Tu({innerType:t,typeName:Te.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...Ae(e)});var Wp=class extends Be{_parse(e){if(this._getType(e)!==oe.nan){let n=this._getOrReturnCtx(e);return te(n,{code:W.invalid_type,expected:oe.nan,received:n.parsedType}),ke}return{status:"valid",value:e.data}}};Wp.create=t=>new Wp({typeName:Te.ZodNaN,...Ae(t)});var Lv=class extends Be{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},Uv=class t extends Be{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?ke:s.status==="dirty"?(r.dirty(),Np(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{let i=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?ke:i.status==="dirty"?(r.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:Te.ZodPipeline})}},$u=class extends Be{_parse(e){let r=this._def.innerType._parse(e),n=i=>(hu(i)&&(i.value=Object.freeze(i.value)),i);return zv(r)?r.then(i=>n(i)):n(r)}unwrap(){return this._def.innerType}};$u.create=(t,e)=>new $u({innerType:t,typeName:Te.ZodReadonly,...Ae(e)});var mDe={object:On.lazycreate},Te;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(Te||(Te={}));var hDe=gu.create,gDe=zp.create,vDe=Wp.create,yDe=Lp.create,_De=Up.create,bDe=Fp.create,SDe=qp.create,xDe=vu.create,wDe=yu.create,EDe=Hp.create,kDe=bo.create,TDe=Qi.create,$De=Zp.create,IDe=So.create,RDe=On.create,ODe=On.strictCreate,CDe=_u.create,PDe=S$.create,ADe=bu.create,NDe=Ns.create,MDe=w$.create,DDe=Bp.create,jDe=Gp.create,zDe=E$.create,LDe=Su.create,UDe=xu.create,FDe=wu.create,qDe=Eu.create,HDe=ba.create,ZDe=Si.create,BDe=bi.create,GDe=Ms.create,WDe=Si.createWithPreprocess,VDe=Uv.create,KDe=Object.freeze({status:"aborted"});function q(t,e,r){function n(a,c){var u;Object.defineProperty(a,"_zod",{value:a._zod??{},enumerable:!1}),(u=a._zod).traits??(u.traits=new Set),a._zod.traits.add(t),e(a,c);for(let l in o.prototype)l in a||Object.defineProperty(a,l,{value:o.prototype[l].bind(a)});a._zod.constr=o,a._zod.def=c}let i=r?.Parent??Object;class s extends i{}Object.defineProperty(s,"name",{value:t});function o(a){var c;let u=r?.Parent?new s:this;n(u,a),(c=u._zod).deferred??(c.deferred=[]);for(let l of u._zod.deferred)l();return u}return Object.defineProperty(o,"init",{value:n}),Object.defineProperty(o,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(o,"name",{value:t}),o}var Sa=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},k$={};function Ds(t){return t&&Object.assign(k$,t),k$}var At={};vF(At,{unwrapMessage:()=>Mp,stringifyPrimitive:()=>U$,required:()=>Lfe,randomString:()=>Ife,propertyKeyTypes:()=>nq,promiseAllObject:()=>$fe,primitiveTypes:()=>Cfe,prefixIssues:()=>_o,pick:()=>Nfe,partial:()=>zfe,optionalKeys:()=>iq,omit:()=>Mfe,numKeys:()=>Rfe,nullish:()=>Jv,normalizeParams:()=>Se,merge:()=>jfe,jsonStringifyReplacer:()=>eq,joinValues:()=>T$,issue:()=>oq,isPlainObject:()=>Kp,isObject:()=>Vp,getSizableOrigin:()=>Ufe,getParsedType:()=>Ofe,getLengthableOrigin:()=>Yv,getEnumValues:()=>QF,getElementAtPath:()=>Tfe,floatSafeRemainder:()=>tq,finalizeIssue:()=>js,extend:()=>Dfe,escapeRegex:()=>Au,esc:()=>fu,defineLazy:()=>Nt,createTransparentProxy:()=>Pfe,clone:()=>wo,cleanRegex:()=>Xv,cleanEnum:()=>Ffe,captureStackTrace:()=>L$,cached:()=>Kv,assignProp:()=>z$,assertNotEqual:()=>xfe,assertNever:()=>Efe,assertIs:()=>wfe,assertEqual:()=>Sfe,assert:()=>kfe,allowsEval:()=>rq,aborted:()=>mu,NUMBER_FORMAT_RANGES:()=>sq,Class:()=>$$,BIGINT_FORMAT_RANGES:()=>Afe});function Sfe(t){return t}function xfe(t){return t}function wfe(t){}function Efe(t){throw new Error}function kfe(t){}function QF(t){let e=Object.values(t).filter(n=>typeof n=="number");return Object.entries(t).filter(([n,i])=>e.indexOf(+n)===-1).map(([n,i])=>i)}function T$(t,e="|"){return t.map(r=>U$(r)).join(e)}function eq(t,e){return typeof e=="bigint"?e.toString():e}function Kv(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Jv(t){return t==null}function Xv(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function tq(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,i=r>n?r:n,s=Number.parseInt(t.toFixed(i).replace(".","")),o=Number.parseInt(e.toFixed(i).replace(".",""));return s%o/10**i}function Nt(t,e,r){Object.defineProperty(t,e,{get(){{let i=r();return t[e]=i,i}throw new Error("cached value already set")},set(i){Object.defineProperty(t,e,{value:i})},configurable:!0})}function z$(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Tfe(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function $fe(t){let e=Object.keys(t),r=e.map(n=>t[n]);return Promise.all(r).then(n=>{let i={};for(let s=0;s{};function Vp(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var rq=Kv(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});function Kp(t){if(Vp(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(Vp(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function Rfe(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}var Ofe=t=>{let e=typeof t;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(t)?"array":t===null?"null":t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?"promise":typeof Map<"u"&&t instanceof Map?"map":typeof Set<"u"&&t instanceof Set?"set":typeof Date<"u"&&t instanceof Date?"date":typeof File<"u"&&t instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},nq=new Set(["string","number","symbol"]),Cfe=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Au(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function wo(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function Se(t){let e=t;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 Pfe(t){let e;return new Proxy({},{get(r,n,i){return e??(e=t()),Reflect.get(e,n,i)},set(r,n,i,s){return e??(e=t()),Reflect.set(e,n,i,s)},has(r,n){return e??(e=t()),Reflect.has(e,n)},deleteProperty(r,n){return e??(e=t()),Reflect.deleteProperty(e,n)},ownKeys(r){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(r,n){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,n)},defineProperty(r,n,i){return e??(e=t()),Reflect.defineProperty(e,n,i)}})}function U$(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function iq(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}var sq={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]},Afe={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function Nfe(t,e){let r={},n=t._zod.def;for(let i in e){if(!(i in n.shape))throw new Error(`Unrecognized key: "${i}"`);e[i]&&(r[i]=n.shape[i])}return wo(t,{...t._zod.def,shape:r,checks:[]})}function Mfe(t,e){let r={...t._zod.def.shape},n=t._zod.def;for(let i in e){if(!(i in n.shape))throw new Error(`Unrecognized key: "${i}"`);e[i]&&delete r[i]}return wo(t,{...t._zod.def,shape:r,checks:[]})}function Dfe(t,e){if(!Kp(e))throw new Error("Invalid input to extend: expected a plain object");let r={...t._zod.def,get shape(){let n={...t._zod.def.shape,...e};return z$(this,"shape",n),n},checks:[]};return wo(t,r)}function jfe(t,e){return wo(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return z$(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function zfe(t,e,r){let n=e._zod.def.shape,i={...n};if(r)for(let s in r){if(!(s in n))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(i[s]=t?new t({type:"optional",innerType:n[s]}):n[s])}else for(let s in n)i[s]=t?new t({type:"optional",innerType:n[s]}):n[s];return wo(e,{...e._zod.def,shape:i,checks:[]})}function Lfe(t,e,r){let n=e._zod.def.shape,i={...n};if(r)for(let s in r){if(!(s in i))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(i[s]=new t({type:"nonoptional",innerType:n[s]}))}else for(let s in n)i[s]=new t({type:"nonoptional",innerType:n[s]});return wo(e,{...e._zod.def,shape:i,checks:[]})}function mu(t,e=0){for(let r=e;r{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function Mp(t){return typeof t=="string"?t:t?.message}function js(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let i=Mp(t.inst?._zod.def?.error?.(t))??Mp(e?.error?.(t))??Mp(r.customError?.(t))??Mp(r.localeError?.(t))??"Invalid input";n.message=i}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function Ufe(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function Yv(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function oq(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function Ffe(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var $$=class{constructor(...e){}},aq=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),Object.defineProperty(t,"message",{get(){return JSON.stringify(e,eq,2)},enumerable:!0})},cq=q("$ZodError",aq),uq=q("$ZodError",aq,{Parent:Error});function qfe(t,e=r=>r.message){let r={},n=[];for(let i of t.issues)i.path.length>0?(r[i.path[0]]=r[i.path[0]]||[],r[i.path[0]].push(e(i))):n.push(e(i));return{formErrors:n,fieldErrors:r}}function Hfe(t,e){let r=e||function(s){return s.message},n={_errors:[]},i=s=>{for(let o of s.issues)if(o.code==="invalid_union"&&o.errors.length)o.errors.map(a=>i({issues:a}));else if(o.code==="invalid_key")i({issues:o.issues});else if(o.code==="invalid_element")i({issues:o.issues});else if(o.path.length===0)n._errors.push(r(o));else{let a=n,c=0;for(;c(e,r,n,i)=>{let s=n?Object.assign(n,{async:!1}):{async:!1},o=e._zod.run({value:r,issues:[]},s);if(o instanceof Promise)throw new Sa;if(o.issues.length){let a=new(i?.Err??t)(o.issues.map(c=>js(c,s,Ds())));throw L$(a,i?.callee),a}return o.value};var Bfe=t=>async(e,r,n,i)=>{let s=n?Object.assign(n,{async:!0}):{async:!0},o=e._zod.run({value:r,issues:[]},s);if(o instanceof Promise&&(o=await o),o.issues.length){let a=new(i?.Err??t)(o.issues.map(c=>js(c,s,Ds())));throw L$(a,i?.callee),a}return o.value};var lq=t=>(e,r,n)=>{let i=n?{...n,async:!1}:{async:!1},s=e._zod.run({value:r,issues:[]},i);if(s instanceof Promise)throw new Sa;return s.issues.length?{success:!1,error:new(t??cq)(s.issues.map(o=>js(o,i,Ds())))}:{success:!0,data:s.value}},Gfe=lq(uq),dq=t=>async(e,r,n)=>{let i=n?Object.assign(n,{async:!0}):{async:!0},s=e._zod.run({value:r,issues:[]},i);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new t(s.issues.map(o=>js(o,i,Ds())))}:{success:!0,data:s.value}},Wfe=dq(uq),Vfe=/^[cC][^\s-]{8,}$/,Kfe=/^[0-9a-z]+$/,Jfe=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Xfe=/^[0-9a-vA-V]{20}$/,Yfe=/^[A-Za-z0-9]{27}$/,Qfe=/^[a-zA-Z0-9_-]{21}$/,eme=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,tme=/^([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})$/,X6=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[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)$/,rme=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,nme="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function ime(){return new RegExp(nme,"u")}var sme=/^(?:(?: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])$/,ome=/^(([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})$/,ame=/^((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])$/,cme=/^(([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])$/,ume=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,pq=/^[A-Za-z0-9_-]*$/,lme=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,dme=/^\+(?:[0-9]){6,14}[0-9]$/,fq="(?:(?:\\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])))",pme=new RegExp(`^${fq}$`);function mq(t){let e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function fme(t){return new RegExp(`^${mq(t)}$`)}function mme(t){let e=mq({precision:t.precision}),r=["Z"];t.local&&r.push(""),t.offset&&r.push("([+-]\\d{2}:\\d{2})");let n=`${e}(?:${r.join("|")})`;return new RegExp(`^${fq}T(?:${n})$`)}var hme=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},gme=/^\d+$/,vme=/^-?\d+(?:\.\d+)?/i,yme=/true|false/i,_me=/null/i,bme=/^[^A-Z]*$/,Sme=/^[^a-z]*$/,vn=q("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),hq={number:"number",bigint:"bigint",object:"date"},gq=q("$ZodCheckLessThan",(t,e)=>{vn.init(t,e);let r=hq[typeof e.value];t._zod.onattach.push(n=>{let i=n._zod.bag,s=(e.inclusive?i.maximum:i.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value{(e.inclusive?n.value<=e.value:n.value{vn.init(t,e);let r=hq[typeof e.value];t._zod.onattach.push(n=>{let i=n._zod.bag,s=(e.inclusive?i.minimum:i.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>s&&(e.inclusive?i.minimum=e.value:i.exclusiveMinimum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value>=e.value:n.value>e.value)||n.issues.push({origin:r,code:"too_small",minimum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),xme=q("$ZodCheckMultipleOf",(t,e)=>{vn.init(t,e),t._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=e.value)}),t._zod.check=r=>{if(typeof r.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%e.value===BigInt(0):tq(r.value,e.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:e.value,input:r.value,inst:t,continue:!e.abort})}}),wme=q("$ZodCheckNumberFormat",(t,e)=>{vn.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[i,s]=sq[e.format];t._zod.onattach.push(o=>{let a=o._zod.bag;a.format=e.format,a.minimum=i,a.maximum=s,r&&(a.pattern=gme)}),t._zod.check=o=>{let a=o.value;if(r){if(!Number.isInteger(a)){o.issues.push({expected:n,format:e.format,code:"invalid_type",input:a,inst:t});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:t,origin:n,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:t,origin:n,continue:!e.abort});return}}as&&o.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inst:t})}}),Eme=q("$ZodCheckMaxLength",(t,e)=>{vn.init(t,e),t._zod.when=r=>{let n=r.value;return!Jv(n)&&n.length!==void 0},t._zod.onattach.push(r=>{let n=r._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum{let n=r.value;if(n.length<=e.maximum)return;let s=Yv(n);r.issues.push({origin:s,code:"too_big",maximum:e.maximum,inclusive:!0,input:n,inst:t,continue:!e.abort})}}),kme=q("$ZodCheckMinLength",(t,e)=>{vn.init(t,e),t._zod.when=r=>{let n=r.value;return!Jv(n)&&n.length!==void 0},t._zod.onattach.push(r=>{let n=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>n&&(r._zod.bag.minimum=e.minimum)}),t._zod.check=r=>{let n=r.value;if(n.length>=e.minimum)return;let s=Yv(n);r.issues.push({origin:s,code:"too_small",minimum:e.minimum,inclusive:!0,input:n,inst:t,continue:!e.abort})}}),Tme=q("$ZodCheckLengthEquals",(t,e)=>{vn.init(t,e),t._zod.when=r=>{let n=r.value;return!Jv(n)&&n.length!==void 0},t._zod.onattach.push(r=>{let n=r._zod.bag;n.minimum=e.length,n.maximum=e.length,n.length=e.length}),t._zod.check=r=>{let n=r.value,i=n.length;if(i===e.length)return;let s=Yv(n),o=i>e.length;r.issues.push({origin:s,...o?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:r.value,inst:t,continue:!e.abort})}}),Qv=q("$ZodCheckStringFormat",(t,e)=>{var r,n;vn.init(t,e),t._zod.onattach.push(i=>{let s=i._zod.bag;s.format=e.format,e.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(e.pattern))}),e.pattern?(r=t._zod).check??(r.check=i=>{e.pattern.lastIndex=0,!e.pattern.test(i.value)&&i.issues.push({origin:"string",code:"invalid_format",format:e.format,input:i.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(n=t._zod).check??(n.check=()=>{})}),$me=q("$ZodCheckRegex",(t,e)=>{Qv.init(t,e),t._zod.check=r=>{e.pattern.lastIndex=0,!e.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),Ime=q("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=bme),Qv.init(t,e)}),Rme=q("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=Sme),Qv.init(t,e)}),Ome=q("$ZodCheckIncludes",(t,e)=>{vn.init(t,e);let r=Au(e.includes),n=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=n,t._zod.onattach.push(i=>{let s=i._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),t._zod.check=i=>{i.value.includes(e.includes,e.position)||i.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:i.value,inst:t,continue:!e.abort})}}),Cme=q("$ZodCheckStartsWith",(t,e)=>{vn.init(t,e);let r=new RegExp(`^${Au(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let i=n._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(r)}),t._zod.check=n=>{n.value.startsWith(e.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:n.value,inst:t,continue:!e.abort})}}),Pme=q("$ZodCheckEndsWith",(t,e)=>{vn.init(t,e);let r=new RegExp(`.*${Au(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let i=n._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(r)}),t._zod.check=n=>{n.value.endsWith(e.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:n.value,inst:t,continue:!e.abort})}}),Ame=q("$ZodCheckOverwrite",(t,e)=>{vn.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}}),I$=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 n=e.split(` `).filter(o=>o),i=Math.min(...n.map(o=>o.length-o.trimStart().length)),s=n.map(o=>o.slice(i)).map(o=>" ".repeat(this.indent*2)+o);for(let o of s)this.content.push(o)}compile(){let e=Function,r=this?.args,i=[...(this?.content??[""]).map(s=>` ${s}`)];return new e(...r,i.join(` `))}},Nme={major:4,minor:0,patch:0},Mt=q("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=Nme;let n=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&n.unshift(t);for(let i of n)for(let s of i._zod.onattach)s(t);if(n.length===0)(r=t._zod).deferred??(r.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let i=(s,o,a)=>{let c=mu(s),u;for(let l of o){if(l._zod.when){if(!l._zod.when(s))continue}else if(c)continue;let d=s.issues.length,p=l._zod.check(s);if(p instanceof Promise&&a?.async===!1)throw new Sa;if(u||p instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await p,s.issues.length!==d&&(c||(c=mu(s,d)))});else{if(s.issues.length===d)continue;c||(c=mu(s,d))}}return u?u.then(()=>s):s};t._zod.run=(s,o)=>{let a=t._zod.parse(s,o);if(a instanceof Promise){if(o.async===!1)throw new Sa;return a.then(c=>i(c,n,o))}return i(a,n,o)}}t["~standard"]={validate:i=>{try{let s=Gfe(t,i);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return Wfe(t,i).then(o=>o.success?{value:o.data}:{issues:o.error?.issues})}},vendor:"zod",version:1}}),F$=q("$ZodString",(t,e)=>{Mt.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??hme(t._zod.bag),t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:t}),r}}),Lt=q("$ZodStringFormat",(t,e)=>{Qv.init(t,e),F$.init(t,e)}),Mme=q("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=tme),Lt.init(t,e)}),Dme=q("$ZodUUID",(t,e)=>{if(e.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(n===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=X6(n))}else e.pattern??(e.pattern=X6());Lt.init(t,e)}),jme=q("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=rme),Lt.init(t,e)}),zme=q("$ZodURL",(t,e)=>{Lt.init(t,e),t._zod.check=r=>{try{let n=r.value,i=new URL(n),s=i.href;e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(i.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:lme.source,input:r.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(i.protocol.endsWith(":")?i.protocol.slice(0,-1):i.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:r.value,inst:t,continue:!e.abort})),!n.endsWith("/")&&s.endsWith("/")?r.value=s.slice(0,-1):r.value=s;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:t,continue:!e.abort})}}}),Lme=q("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=ime()),Lt.init(t,e)}),Ume=q("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=Qfe),Lt.init(t,e)}),Fme=q("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=Vfe),Lt.init(t,e)}),qme=q("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=Kfe),Lt.init(t,e)}),Hme=q("$ZodULID",(t,e)=>{e.pattern??(e.pattern=Jfe),Lt.init(t,e)}),Zme=q("$ZodXID",(t,e)=>{e.pattern??(e.pattern=Xfe),Lt.init(t,e)}),Bme=q("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=Yfe),Lt.init(t,e)}),Gme=q("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=mme(e)),Lt.init(t,e)}),Wme=q("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=pme),Lt.init(t,e)}),Vme=q("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=fme(e)),Lt.init(t,e)}),Kme=q("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=eme),Lt.init(t,e)}),Jme=q("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=sme),Lt.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),Xme=q("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=ome),Lt.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv6"}),t._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:t,continue:!e.abort})}}}),Yme=q("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=ame),Lt.init(t,e)}),Qme=q("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=cme),Lt.init(t,e),t._zod.check=r=>{let[n,i]=r.value.split("/");try{if(!i)throw new Error;let s=Number(i);if(`${s}`!==i)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:t,continue:!e.abort})}}});function yq(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}var ehe=q("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=ume),Lt.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),t._zod.check=r=>{yq(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});function the(t){if(!pq.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return yq(r)}var rhe=q("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=pq),Lt.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),t._zod.check=r=>{the(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),nhe=q("$ZodE164",(t,e)=>{e.pattern??(e.pattern=dme),Lt.init(t,e)});function ihe(t,e=null){try{let r=t.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let i=JSON.parse(atob(n));return!("typ"in i&&i?.typ!=="JWT"||!i.alg||e&&(!("alg"in i)||i.alg!==e))}catch{return!1}}var she=q("$ZodJWT",(t,e)=>{Lt.init(t,e),t._zod.check=r=>{ihe(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}}),_q=q("$ZodNumber",(t,e)=>{Mt.init(t,e),t._zod.pattern=t._zod.bag.pattern??vme,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=Number(r.value)}catch{}let i=r.value;if(typeof i=="number"&&!Number.isNaN(i)&&Number.isFinite(i))return r;let s=typeof i=="number"?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:i,inst:t,...s?{received:s}:{}}),r}}),ohe=q("$ZodNumber",(t,e)=>{wme.init(t,e),_q.init(t,e)}),ahe=q("$ZodBoolean",(t,e)=>{Mt.init(t,e),t._zod.pattern=yme,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=!!r.value}catch{}let i=r.value;return typeof i=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:t}),r}}),che=q("$ZodNull",(t,e)=>{Mt.init(t,e),t._zod.pattern=_me,t._zod.values=new Set([null]),t._zod.parse=(r,n)=>{let i=r.value;return i===null||r.issues.push({expected:"null",code:"invalid_type",input:i,inst:t}),r}}),uhe=q("$ZodUnknown",(t,e)=>{Mt.init(t,e),t._zod.parse=r=>r}),lhe=q("$ZodNever",(t,e)=>{Mt.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});function Y6(t,e,r){t.issues.length&&e.issues.push(..._o(r,t.issues)),e.value[r]=t.value}var dhe=q("$ZodArray",(t,e)=>{Mt.init(t,e),t._zod.parse=(r,n)=>{let i=r.value;if(!Array.isArray(i))return r.issues.push({expected:"array",code:"invalid_type",input:i,inst:t}),r;r.value=Array(i.length);let s=[];for(let o=0;oY6(u,r,o))):Y6(c,r,o)}return s.length?Promise.all(s).then(()=>r):r}});function Pv(t,e,r){t.issues.length&&e.issues.push(..._o(r,t.issues)),e.value[r]=t.value}function Q6(t,e,r,n){t.issues.length?n[r]===void 0?r in n?e.value[r]=void 0:e.value[r]=t.value:e.issues.push(..._o(r,t.issues)):t.value===void 0?r in n&&(e.value[r]=void 0):e.value[r]=t.value}var phe=q("$ZodObject",(t,e)=>{Mt.init(t,e);let r=Kv(()=>{let d=Object.keys(e.shape);for(let f of d)if(!(e.shape[f]instanceof Mt))throw new Error(`Invalid element at key "${f}": expected a Zod schema`);let p=iq(e.shape);return{shape:e.shape,keys:d,keySet:new Set(d),numKeys:d.length,optionalKeys:new Set(p)}});Nt(t._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 n=d=>{let p=new I$(["shape","payload","ctx"]),f=r.value,m=S=>{let _=fu(S);return`shape[${_}]._zod.run({ value: input[${_}], issues: [] }, ctx)`};p.write("const input = payload.value;");let h=Object.create(null),g=0;for(let S of f.keys)h[S]=`key_${g++}`;p.write("const newResult = {}");for(let S of f.keys)if(f.optionalKeys.has(S)){let _=h[S];p.write(`const ${_} = ${m(S)};`);let y=fu(S);p.write(` if (${_}.issues.length) { @@ -1370,12 +1371,12 @@ ${n}`}function Cue(t,e){let r=Zt.default.resolve(t);if(r.includes("/.git/")||r.i if (${_}.issues.length) payload.issues = payload.issues.concat(${_}.issues.map(iss => ({ ...iss, path: iss.path ? [${fu(S)}, ...iss.path] : [${fu(S)}] - })));`),p.write(`newResult[${fu(S)}] = ${_}.value`)}p.write("payload.value = newResult;"),p.write("return payload;");let v=p.compile();return(S,_)=>v(d,S,_)},i,s=Vp,o=!k$.jitless,c=o&&rq.value,u=e.catchall,l;t._zod.parse=(d,p)=>{l??(l=r.value);let f=d.value;if(!s(f))return d.issues.push({expected:"object",code:"invalid_type",input:f,inst:t}),d;let m=[];if(o&&c&&p?.async===!1&&p.jitless!==!0)i||(i=n(e.shape)),d=i(d,p);else{d.value={};let _=l.shape;for(let y of l.keys){let x=_[y],w=x._zod.run({value:f[y],issues:[]},p),E=x._zod.optin==="optional"&&x._zod.optout==="optional";w instanceof Promise?m.push(w.then(T=>E?Q6(T,d,y,f):Pv(T,d,y))):E?Q6(w,d,y,f):Pv(w,d,y)}}if(!u)return m.length?Promise.all(m).then(()=>d):d;let h=[],g=l.keySet,v=u._zod,S=v.def.type;for(let _ of Object.keys(f)){if(g.has(_))continue;if(S==="never"){h.push(_);continue}let y=v.run({value:f[_],issues:[]},p);y instanceof Promise?m.push(y.then(x=>Pv(x,d,_))):Pv(y,d,_)}return h.length&&d.issues.push({code:"unrecognized_keys",keys:h,input:f,inst:t}),m.length?Promise.all(m).then(()=>d):d}});function eF(t,e,r,n){for(let i of t)if(i.issues.length===0)return e.value=i.value,e;return e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(i=>i.issues.map(s=>js(s,n,Ds())))}),e}var bq=q("$ZodUnion",(t,e)=>{Mt.init(t,e),Nt(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),Nt(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),Nt(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),Nt(t._zod,"pattern",()=>{if(e.options.every(r=>r._zod.pattern)){let r=e.options.map(n=>n._zod.pattern);return new RegExp(`^(${r.map(n=>Xv(n.source)).join("|")})$`)}}),t._zod.parse=(r,n)=>{let i=!1,s=[];for(let o of e.options){let a=o._zod.run({value:r.value,issues:[]},n);if(a instanceof Promise)s.push(a),i=!0;else{if(a.issues.length===0)return a;s.push(a)}}return i?Promise.all(s).then(o=>eF(o,r,t,n)):eF(s,r,t,n)}}),fhe=q("$ZodDiscriminatedUnion",(t,e)=>{bq.init(t,e);let r=t._zod.parse;Nt(t._zod,"propValues",()=>{let i={};for(let s of e.options){let o=s._zod.propValues;if(!o||Object.keys(o).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(let[a,c]of Object.entries(o)){i[a]||(i[a]=new Set);for(let u of c)i[a].add(u)}}return i});let n=Kv(()=>{let i=e.options,s=new Map;for(let o of i){let a=o._zod.propValues[e.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(o)}"`);for(let c of a){if(s.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);s.set(c,o)}}return s});t._zod.parse=(i,s)=>{let o=i.value;if(!Vp(o))return i.issues.push({code:"invalid_type",expected:"object",input:o,inst:t}),i;let a=n.value.get(o?.[e.discriminator]);return a?a._zod.run(i,s):e.unionFallback?r(i,s):(i.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:o,path:[e.discriminator],inst:t}),i)}}),mhe=q("$ZodIntersection",(t,e)=>{Mt.init(t,e),t._zod.parse=(r,n)=>{let i=r.value,s=e.left._zod.run({value:i,issues:[]},n),o=e.right._zod.run({value:i,issues:[]},n);return s instanceof Promise||o instanceof Promise?Promise.all([s,o]).then(([c,u])=>tF(r,c,u)):tF(r,s,o)}});function R$(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(Kp(t)&&Kp(e)){let r=Object.keys(e),n=Object.keys(t).filter(s=>r.indexOf(s)!==-1),i={...t,...e};for(let s of n){let o=R$(t[s],e[s]);if(!o.valid)return{valid:!1,mergeErrorPath:[s,...o.mergeErrorPath]};i[s]=o.data}return{valid:!0,data:i}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n{Mt.init(t,e),t._zod.parse=(r,n)=>{let i=r.value;if(!Kp(i))return r.issues.push({expected:"record",code:"invalid_type",input:i,inst:t}),r;let s=[];if(e.keyType._zod.values){let o=e.keyType._zod.values;r.value={};for(let c of o)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){let u=e.valueType._zod.run({value:i[c],issues:[]},n);u instanceof Promise?s.push(u.then(l=>{l.issues.length&&r.issues.push(..._o(c,l.issues)),r.value[c]=l.value})):(u.issues.length&&r.issues.push(..._o(c,u.issues)),r.value[c]=u.value)}let a;for(let c in i)o.has(c)||(a=a??[],a.push(c));a&&a.length>0&&r.issues.push({code:"unrecognized_keys",input:i,inst:t,keys:a})}else{r.value={};for(let o of Reflect.ownKeys(i)){if(o==="__proto__")continue;let a=e.keyType._zod.run({value:o,issues:[]},n);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:a.issues.map(u=>js(u,n,Ds())),input:o,path:[o],inst:t}),r.value[a.value]=a.value;continue}let c=e.valueType._zod.run({value:i[o],issues:[]},n);c instanceof Promise?s.push(c.then(u=>{u.issues.length&&r.issues.push(..._o(o,u.issues)),r.value[a.value]=u.value})):(c.issues.length&&r.issues.push(..._o(o,c.issues)),r.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>r):r}}),ghe=q("$ZodEnum",(t,e)=>{Mt.init(t,e);let r=QF(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>nq.has(typeof n)).map(n=>typeof n=="string"?Au(n):n.toString()).join("|")})$`),t._zod.parse=(n,i)=>{let s=n.value;return t._zod.values.has(s)||n.issues.push({code:"invalid_value",values:r,input:s,inst:t}),n}}),vhe=q("$ZodLiteral",(t,e)=>{Mt.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?Au(r):r?r.toString():String(r)).join("|")})$`),t._zod.parse=(r,n)=>{let i=r.value;return t._zod.values.has(i)||r.issues.push({code:"invalid_value",values:e.values,input:i,inst:t}),r}}),yhe=q("$ZodTransform",(t,e)=>{Mt.init(t,e),t._zod.parse=(r,n)=>{let i=e.transform(r.value,r);if(n.async)return(i instanceof Promise?i:Promise.resolve(i)).then(o=>(r.value=o,r));if(i instanceof Promise)throw new Sa;return r.value=i,r}}),_he=q("$ZodOptional",(t,e)=>{Mt.init(t,e),t._zod.optin="optional",t._zod.optout="optional",Nt(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),Nt(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Xv(r.source)})?$`):void 0}),t._zod.parse=(r,n)=>e.innerType._zod.optin==="optional"?e.innerType._zod.run(r,n):r.value===void 0?r:e.innerType._zod.run(r,n)}),bhe=q("$ZodNullable",(t,e)=>{Mt.init(t,e),Nt(t._zod,"optin",()=>e.innerType._zod.optin),Nt(t._zod,"optout",()=>e.innerType._zod.optout),Nt(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Xv(r.source)}|null)$`):void 0}),Nt(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(r,n)=>r.value===null?r:e.innerType._zod.run(r,n)}),She=q("$ZodDefault",(t,e)=>{Mt.init(t,e),t._zod.optin="optional",Nt(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(r.value===void 0)return r.value=e.defaultValue,r;let i=e.innerType._zod.run(r,n);return i instanceof Promise?i.then(s=>rF(s,e)):rF(i,e)}});function rF(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}var xhe=q("$ZodPrefault",(t,e)=>{Mt.init(t,e),t._zod.optin="optional",Nt(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>(r.value===void 0&&(r.value=e.defaultValue),e.innerType._zod.run(r,n))}),whe=q("$ZodNonOptional",(t,e)=>{Mt.init(t,e),Nt(t._zod,"values",()=>{let r=e.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),t._zod.parse=(r,n)=>{let i=e.innerType._zod.run(r,n);return i instanceof Promise?i.then(s=>nF(s,t)):nF(i,t)}});function nF(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}var Ehe=q("$ZodCatch",(t,e)=>{Mt.init(t,e),t._zod.optin="optional",Nt(t._zod,"optout",()=>e.innerType._zod.optout),Nt(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{let i=e.innerType._zod.run(r,n);return i instanceof Promise?i.then(s=>(r.value=s.value,s.issues.length&&(r.value=e.catchValue({...r,error:{issues:s.issues.map(o=>js(o,n,Ds()))},input:r.value}),r.issues=[]),r)):(r.value=i.value,i.issues.length&&(r.value=e.catchValue({...r,error:{issues:i.issues.map(s=>js(s,n,Ds()))},input:r.value}),r.issues=[]),r)}}),khe=q("$ZodPipe",(t,e)=>{Mt.init(t,e),Nt(t._zod,"values",()=>e.in._zod.values),Nt(t._zod,"optin",()=>e.in._zod.optin),Nt(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(r,n)=>{let i=e.in._zod.run(r,n);return i instanceof Promise?i.then(s=>iF(s,e,n)):iF(i,e,n)}});function iF(t,e,r){return mu(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}var The=q("$ZodReadonly",(t,e)=>{Mt.init(t,e),Nt(t._zod,"propValues",()=>e.innerType._zod.propValues),Nt(t._zod,"values",()=>e.innerType._zod.values),Nt(t._zod,"optin",()=>e.innerType._zod.optin),Nt(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(r,n)=>{let i=e.innerType._zod.run(r,n);return i instanceof Promise?i.then(sF):sF(i)}});function sF(t){return t.value=Object.freeze(t.value),t}var $he=q("$ZodCustom",(t,e)=>{vn.init(t,e),Mt.init(t,e),t._zod.parse=(r,n)=>r,t._zod.check=r=>{let n=r.value,i=e.fn(n);if(i instanceof Promise)return i.then(s=>oF(s,r,n,t));oF(i,r,n,t)}});function oF(t,e,r,n){if(!t){let i={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(i.params=n._zod.def.params),e.issues.push(oq(i))}}var Ihe=t=>{let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"number";case"object":{if(Array.isArray(t))return"array";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},Rhe=()=>{let t={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function e(n){return t[n]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return n=>{switch(n.code){case"invalid_type":return`Invalid input: expected ${n.expected}, received ${Ihe(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${U$(n.values[0])}`:`Invalid option: expected one of ${T$(n.values,"|")}`;case"too_big":{let i=n.inclusive?"<=":"<",s=e(n.origin);return s?`Too big: expected ${n.origin??"value"} to have ${i}${n.maximum.toString()} ${s.unit??"elements"}`:`Too big: expected ${n.origin??"value"} to be ${i}${n.maximum.toString()}`}case"too_small":{let i=n.inclusive?">=":">",s=e(n.origin);return s?`Too small: expected ${n.origin} to have ${i}${n.minimum.toString()} ${s.unit}`:`Too small: expected ${n.origin} to be ${i}${n.minimum.toString()}`}case"invalid_format":{let i=n;return i.format==="starts_with"?`Invalid string: must start with "${i.prefix}"`:i.format==="ends_with"?`Invalid string: must end with "${i.suffix}"`:i.format==="includes"?`Invalid string: must include "${i.includes}"`:i.format==="regex"?`Invalid string: must match pattern ${i.pattern}`:`Invalid ${r[i.format]??n.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${n.divisor}`;case"unrecognized_keys":return`Unrecognized key${n.keys.length>1?"s":""}: ${T$(n.keys,", ")}`;case"invalid_key":return`Invalid key in ${n.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${n.origin}`;default:return"Invalid input"}}};function Ohe(){return{localeError:Rhe()}}var O$=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...r){let n=r[0];if(this._map.set(e,n),n&&typeof n=="object"&&"id"in n){if(this._idmap.has(n.id))throw new Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,e)}return this}remove(e){return this._map.delete(e),this}get(e){let r=e._zod.parent;if(r){let n={...this.get(r)??{}};return delete n.id,{...n,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}};function Che(){return new O$}var Av=Che();function Phe(t,e){return new t({type:"string",...Se(e)})}function Ahe(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...Se(e)})}function aF(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...Se(e)})}function Nhe(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...Se(e)})}function Mhe(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...Se(e)})}function Dhe(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...Se(e)})}function jhe(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...Se(e)})}function zhe(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...Se(e)})}function Lhe(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...Se(e)})}function Uhe(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...Se(e)})}function Fhe(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...Se(e)})}function qhe(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...Se(e)})}function Hhe(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...Se(e)})}function Zhe(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...Se(e)})}function Bhe(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...Se(e)})}function Ghe(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...Se(e)})}function Whe(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...Se(e)})}function Vhe(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...Se(e)})}function Khe(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...Se(e)})}function Jhe(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...Se(e)})}function Xhe(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...Se(e)})}function Yhe(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...Se(e)})}function Qhe(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...Se(e)})}function ege(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...Se(e)})}function tge(t,e){return new t({type:"string",format:"date",check:"string_format",...Se(e)})}function rge(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...Se(e)})}function nge(t,e){return new t({type:"string",format:"duration",check:"string_format",...Se(e)})}function ige(t,e){return new t({type:"number",checks:[],...Se(e)})}function sge(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...Se(e)})}function oge(t,e){return new t({type:"boolean",...Se(e)})}function age(t,e){return new t({type:"null",...Se(e)})}function cge(t){return new t({type:"unknown"})}function uge(t,e){return new t({type:"never",...Se(e)})}function cF(t,e){return new gq({check:"less_than",...Se(e),value:t,inclusive:!1})}function l$(t,e){return new gq({check:"less_than",...Se(e),value:t,inclusive:!0})}function uF(t,e){return new vq({check:"greater_than",...Se(e),value:t,inclusive:!1})}function d$(t,e){return new vq({check:"greater_than",...Se(e),value:t,inclusive:!0})}function lF(t,e){return new xme({check:"multiple_of",...Se(e),value:t})}function Sq(t,e){return new Eme({check:"max_length",...Se(e),maximum:t})}function Fv(t,e){return new kme({check:"min_length",...Se(e),minimum:t})}function xq(t,e){return new Tme({check:"length_equals",...Se(e),length:t})}function lge(t,e){return new $me({check:"string_format",format:"regex",...Se(e),pattern:t})}function dge(t){return new Ime({check:"string_format",format:"lowercase",...Se(t)})}function pge(t){return new Rme({check:"string_format",format:"uppercase",...Se(t)})}function fge(t,e){return new Ome({check:"string_format",format:"includes",...Se(e),includes:t})}function mge(t,e){return new Cme({check:"string_format",format:"starts_with",...Se(e),prefix:t})}function hge(t,e){return new Pme({check:"string_format",format:"ends_with",...Se(e),suffix:t})}function Xp(t){return new Ame({check:"overwrite",tx:t})}function gge(t){return Xp(e=>e.normalize(t))}function vge(){return Xp(t=>t.trim())}function yge(){return Xp(t=>t.toLowerCase())}function _ge(){return Xp(t=>t.toUpperCase())}function bge(t,e,r){return new t({type:"array",element:e,...Se(r)})}function Sge(t,e,r){let n=Se(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function xge(t,e,r){return new t({type:"custom",check:"custom",fn:e,...Se(r)})}var wq={};vF(wq,{time:()=>Rq,duration:()=>Cq,datetime:()=>kq,date:()=>$q,ZodISOTime:()=>Iq,ZodISODuration:()=>Oq,ZodISODateTime:()=>Eq,ZodISODate:()=>Tq});var Eq=q("ZodISODateTime",(t,e)=>{Gme.init(t,e),Gt.init(t,e)});function kq(t){return ege(Eq,t)}var Tq=q("ZodISODate",(t,e)=>{Wme.init(t,e),Gt.init(t,e)});function $q(t){return tge(Tq,t)}var Iq=q("ZodISOTime",(t,e)=>{Vme.init(t,e),Gt.init(t,e)});function Rq(t){return rge(Iq,t)}var Oq=q("ZodISODuration",(t,e)=>{Kme.init(t,e),Gt.init(t,e)});function Cq(t){return nge(Oq,t)}var Pq=(t,e)=>{cq.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>Hfe(t,r)},flatten:{value:r=>qfe(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},XDe=q("ZodError",Pq),ey=q("ZodError",Pq,{Parent:Error}),wge=Zfe(ey),Ege=Bfe(ey),kge=lq(ey),Tge=dq(ey),Bt=q("ZodType",(t,e)=>(Mt.init(t,e),t.def=e,Object.defineProperty(t,"_def",{value:e}),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>wo(t,r,n),t.brand=()=>t,t.register=(r,n)=>(r.add(t,n),t),t.parse=(r,n)=>wge(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>kge(t,r,n),t.parseAsync=async(r,n)=>Ege(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Tge(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(gve(r,n)),t.superRefine=r=>t.check(vve(r)),t.overwrite=r=>t.check(Xp(r)),t.optional=()=>he(t),t.nullable=()=>fF(t),t.nullish=()=>he(fF(t)),t.nonoptional=r=>cve(t,r),t.array=()=>rt(t),t.or=r=>Ut([t,r]),t.and=r=>q$(t,r),t.transform=r=>P$(t,Lq(r)),t.default=r=>sve(t,r),t.prefault=r=>ave(t,r),t.catch=r=>lve(t,r),t.pipe=r=>P$(t,r),t.readonly=()=>fve(t),t.describe=r=>{let n=t.clone();return Av.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return Av.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return Av.get(t);let n=t.clone();return Av.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),Aq=q("_ZodString",(t,e)=>{F$.init(t,e),Bt.init(t,e);let r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,t.regex=(...n)=>t.check(lge(...n)),t.includes=(...n)=>t.check(fge(...n)),t.startsWith=(...n)=>t.check(mge(...n)),t.endsWith=(...n)=>t.check(hge(...n)),t.min=(...n)=>t.check(Fv(...n)),t.max=(...n)=>t.check(Sq(...n)),t.length=(...n)=>t.check(xq(...n)),t.nonempty=(...n)=>t.check(Fv(1,...n)),t.lowercase=n=>t.check(dge(n)),t.uppercase=n=>t.check(pge(n)),t.trim=()=>t.check(vge()),t.normalize=(...n)=>t.check(gge(...n)),t.toLowerCase=()=>t.check(yge()),t.toUpperCase=()=>t.check(_ge())}),$ge=q("ZodString",(t,e)=>{F$.init(t,e),Aq.init(t,e),t.email=r=>t.check(Ahe(Ige,r)),t.url=r=>t.check(zhe(Rge,r)),t.jwt=r=>t.check(Qhe(Zge,r)),t.emoji=r=>t.check(Lhe(Oge,r)),t.guid=r=>t.check(aF(dF,r)),t.uuid=r=>t.check(Nhe(Nv,r)),t.uuidv4=r=>t.check(Mhe(Nv,r)),t.uuidv6=r=>t.check(Dhe(Nv,r)),t.uuidv7=r=>t.check(jhe(Nv,r)),t.nanoid=r=>t.check(Uhe(Cge,r)),t.guid=r=>t.check(aF(dF,r)),t.cuid=r=>t.check(Fhe(Pge,r)),t.cuid2=r=>t.check(qhe(Age,r)),t.ulid=r=>t.check(Hhe(Nge,r)),t.base64=r=>t.check(Jhe(Fge,r)),t.base64url=r=>t.check(Xhe(qge,r)),t.xid=r=>t.check(Zhe(Mge,r)),t.ksuid=r=>t.check(Bhe(Dge,r)),t.ipv4=r=>t.check(Ghe(jge,r)),t.ipv6=r=>t.check(Whe(zge,r)),t.cidrv4=r=>t.check(Vhe(Lge,r)),t.cidrv6=r=>t.check(Khe(Uge,r)),t.e164=r=>t.check(Yhe(Hge,r)),t.datetime=r=>t.check(kq(r)),t.date=r=>t.check($q(r)),t.time=r=>t.check(Rq(r)),t.duration=r=>t.check(Cq(r))});function L(t){return Phe($ge,t)}var Gt=q("ZodStringFormat",(t,e)=>{Lt.init(t,e),Aq.init(t,e)}),Ige=q("ZodEmail",(t,e)=>{jme.init(t,e),Gt.init(t,e)}),dF=q("ZodGUID",(t,e)=>{Mme.init(t,e),Gt.init(t,e)}),Nv=q("ZodUUID",(t,e)=>{Dme.init(t,e),Gt.init(t,e)}),Rge=q("ZodURL",(t,e)=>{zme.init(t,e),Gt.init(t,e)}),Oge=q("ZodEmoji",(t,e)=>{Lme.init(t,e),Gt.init(t,e)}),Cge=q("ZodNanoID",(t,e)=>{Ume.init(t,e),Gt.init(t,e)}),Pge=q("ZodCUID",(t,e)=>{Fme.init(t,e),Gt.init(t,e)}),Age=q("ZodCUID2",(t,e)=>{qme.init(t,e),Gt.init(t,e)}),Nge=q("ZodULID",(t,e)=>{Hme.init(t,e),Gt.init(t,e)}),Mge=q("ZodXID",(t,e)=>{Zme.init(t,e),Gt.init(t,e)}),Dge=q("ZodKSUID",(t,e)=>{Bme.init(t,e),Gt.init(t,e)}),jge=q("ZodIPv4",(t,e)=>{Jme.init(t,e),Gt.init(t,e)}),zge=q("ZodIPv6",(t,e)=>{Xme.init(t,e),Gt.init(t,e)}),Lge=q("ZodCIDRv4",(t,e)=>{Yme.init(t,e),Gt.init(t,e)}),Uge=q("ZodCIDRv6",(t,e)=>{Qme.init(t,e),Gt.init(t,e)}),Fge=q("ZodBase64",(t,e)=>{ehe.init(t,e),Gt.init(t,e)}),qge=q("ZodBase64URL",(t,e)=>{rhe.init(t,e),Gt.init(t,e)}),Hge=q("ZodE164",(t,e)=>{nhe.init(t,e),Gt.init(t,e)}),Zge=q("ZodJWT",(t,e)=>{she.init(t,e),Gt.init(t,e)}),Nq=q("ZodNumber",(t,e)=>{_q.init(t,e),Bt.init(t,e),t.gt=(n,i)=>t.check(uF(n,i)),t.gte=(n,i)=>t.check(d$(n,i)),t.min=(n,i)=>t.check(d$(n,i)),t.lt=(n,i)=>t.check(cF(n,i)),t.lte=(n,i)=>t.check(l$(n,i)),t.max=(n,i)=>t.check(l$(n,i)),t.int=n=>t.check(pF(n)),t.safe=n=>t.check(pF(n)),t.positive=n=>t.check(uF(0,n)),t.nonnegative=n=>t.check(d$(0,n)),t.negative=n=>t.check(cF(0,n)),t.nonpositive=n=>t.check(l$(0,n)),t.multipleOf=(n,i)=>t.check(lF(n,i)),t.step=(n,i)=>t.check(lF(n,i)),t.finite=()=>t;let r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});function Rt(t){return ige(Nq,t)}var Bge=q("ZodNumberFormat",(t,e)=>{ohe.init(t,e),Nq.init(t,e)});function pF(t){return sge(Bge,t)}var Gge=q("ZodBoolean",(t,e)=>{ahe.init(t,e),Bt.init(t,e)});function jr(t){return oge(Gge,t)}var Wge=q("ZodNull",(t,e)=>{che.init(t,e),Bt.init(t,e)});function Mq(t){return age(Wge,t)}var Vge=q("ZodUnknown",(t,e)=>{uhe.init(t,e),Bt.init(t,e)});function sr(){return cge(Vge)}var Kge=q("ZodNever",(t,e)=>{lhe.init(t,e),Bt.init(t,e)});function Jge(t){return uge(Kge,t)}var Xge=q("ZodArray",(t,e)=>{dhe.init(t,e),Bt.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(Fv(r,n)),t.nonempty=r=>t.check(Fv(1,r)),t.max=(r,n)=>t.check(Sq(r,n)),t.length=(r,n)=>t.check(xq(r,n)),t.unwrap=()=>t.element});function rt(t,e){return bge(Xge,t,e)}var Dq=q("ZodObject",(t,e)=>{phe.init(t,e),Bt.init(t,e),At.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>zr(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:sr()}),t.loose=()=>t.clone({...t._zod.def,catchall:sr()}),t.strict=()=>t.clone({...t._zod.def,catchall:Jge()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>At.extend(t,r),t.merge=r=>At.merge(t,r),t.pick=r=>At.pick(t,r),t.omit=r=>At.omit(t,r),t.partial=(...r)=>At.partial(Uq,t,r[0]),t.required=(...r)=>At.required(Fq,t,r[0])});function X(t,e){let r={type:"object",get shape(){return At.assignProp(this,"shape",{...t}),this.shape},...At.normalizeParams(e)};return new Dq(r)}function xi(t,e){return new Dq({type:"object",get shape(){return At.assignProp(this,"shape",{...t}),this.shape},catchall:sr(),...At.normalizeParams(e)})}var jq=q("ZodUnion",(t,e)=>{bq.init(t,e),Bt.init(t,e),t.options=e.options});function Ut(t,e){return new jq({type:"union",options:t,...At.normalizeParams(e)})}var Yge=q("ZodDiscriminatedUnion",(t,e)=>{jq.init(t,e),fhe.init(t,e)});function zq(t,e,r){return new Yge({type:"union",options:e,discriminator:t,...At.normalizeParams(r)})}var Qge=q("ZodIntersection",(t,e)=>{mhe.init(t,e),Bt.init(t,e)});function q$(t,e){return new Qge({type:"intersection",left:t,right:e})}var eve=q("ZodRecord",(t,e)=>{hhe.init(t,e),Bt.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});function or(t,e,r){return new eve({type:"record",keyType:t,valueType:e,...At.normalizeParams(r)})}var C$=q("ZodEnum",(t,e)=>{ghe.init(t,e),Bt.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(n,i)=>{let s={};for(let o of n)if(r.has(o))s[o]=e.entries[o];else throw new Error(`Key ${o} not found in enum`);return new C$({...e,checks:[],...At.normalizeParams(i),entries:s})},t.exclude=(n,i)=>{let s={...e.entries};for(let o of n)if(r.has(o))delete s[o];else throw new Error(`Key ${o} not found in enum`);return new C$({...e,checks:[],...At.normalizeParams(i),entries:s})}});function zr(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new C$({type:"enum",entries:r,...At.normalizeParams(e)})}var tve=q("ZodLiteral",(t,e)=>{vhe.init(t,e),Bt.init(t,e),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function ge(t,e){return new tve({type:"literal",values:Array.isArray(t)?t:[t],...At.normalizeParams(e)})}var rve=q("ZodTransform",(t,e)=>{yhe.init(t,e),Bt.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(At.issue(s,r.value,e));else{let o=s;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=t),o.continue??(o.continue=!0),r.issues.push(At.issue(o))}};let i=e.transform(r.value,r);return i instanceof Promise?i.then(s=>(r.value=s,r)):(r.value=i,r)}});function Lq(t){return new rve({type:"transform",transform:t})}var Uq=q("ZodOptional",(t,e)=>{_he.init(t,e),Bt.init(t,e),t.unwrap=()=>t._zod.def.innerType});function he(t){return new Uq({type:"optional",innerType:t})}var nve=q("ZodNullable",(t,e)=>{bhe.init(t,e),Bt.init(t,e),t.unwrap=()=>t._zod.def.innerType});function fF(t){return new nve({type:"nullable",innerType:t})}var ive=q("ZodDefault",(t,e)=>{She.init(t,e),Bt.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function sve(t,e){return new ive({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var ove=q("ZodPrefault",(t,e)=>{xhe.init(t,e),Bt.init(t,e),t.unwrap=()=>t._zod.def.innerType});function ave(t,e){return new ove({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var Fq=q("ZodNonOptional",(t,e)=>{whe.init(t,e),Bt.init(t,e),t.unwrap=()=>t._zod.def.innerType});function cve(t,e){return new Fq({type:"nonoptional",innerType:t,...At.normalizeParams(e)})}var uve=q("ZodCatch",(t,e)=>{Ehe.init(t,e),Bt.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function lve(t,e){return new uve({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var dve=q("ZodPipe",(t,e)=>{khe.init(t,e),Bt.init(t,e),t.in=e.in,t.out=e.out});function P$(t,e){return new dve({type:"pipe",in:t,out:e})}var pve=q("ZodReadonly",(t,e)=>{The.init(t,e),Bt.init(t,e)});function fve(t){return new pve({type:"readonly",innerType:t})}var qq=q("ZodCustom",(t,e)=>{$he.init(t,e),Bt.init(t,e)});function mve(t,e){let r=new vn({check:"custom",...At.normalizeParams(e)});return r._zod.check=t,r}function hve(t,e){return Sge(qq,t??(()=>!0),e)}function gve(t,e={}){return xge(qq,t,e)}function vve(t,e){let r=mve(n=>(n.addIssue=i=>{if(typeof i=="string")n.issues.push(At.issue(i,n.value,r._zod.def));else{let s=i;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=n.value),s.inst??(s.inst=r),s.continue??(s.continue=!r._zod.def.abort),n.issues.push(At.issue(s))}},t(n.value,n)),e);return r}function Hq(t,e){return P$(Lq(t),e)}Ds(Ohe());var H$="io.modelcontextprotocol/related-task",ty="2.0",Yi=hve(t=>t!==null&&(typeof t=="object"||typeof t=="function")),Zq=Ut([L(),Rt().int()]),Bq=L(),yve=xi({ttl:Ut([Rt(),Mq()]).optional(),pollInterval:Rt().optional()}),Z$=xi({taskId:L()}),_ve=xi({progressToken:Zq.optional(),[H$]:Z$.optional()}),yn=xi({task:yve.optional(),_meta:_ve.optional()}),Tr=X({method:L(),params:yn.optional()}),xa=xi({_meta:X({[H$]:he(Z$)}).passthrough().optional()}),Xn=X({method:L(),params:xa.optional()}),Lr=xi({_meta:xi({[H$]:Z$.optional()}).optional()}),ry=Ut([L(),Rt().int()]),bve=X({jsonrpc:ge(ty),id:ry,...Tr.shape}).strict();var Sve=X({jsonrpc:ge(ty),...Xn.shape}).strict();var xve=X({jsonrpc:ge(ty),id:ry,result:Lr}).strict();var mF;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(mF||(mF={}));var wve=X({jsonrpc:ge(ty),id:ry,error:X({code:Rt().int(),message:L(),data:he(sr())})}).strict();var YDe=Ut([bve,Sve,xve,wve]),Gq=Lr.strict(),Eve=xa.extend({requestId:ry,reason:L().optional()}),Wq=Xn.extend({method:ge("notifications/cancelled"),params:Eve}),kve=X({src:L(),mimeType:L().optional(),sizes:rt(L()).optional()}),Yp=X({icons:rt(kve).optional()}),Iu=X({name:L(),title:L().optional()}),Vq=Iu.extend({...Iu.shape,...Yp.shape,version:L(),websiteUrl:L().optional()}),Tve=q$(X({applyDefaults:jr().optional()}),or(L(),sr())),$ve=Hq(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,q$(X({form:Tve.optional(),url:Yi.optional()}),or(L(),sr()).optional())),Ive=X({list:he(X({}).passthrough()),cancel:he(X({}).passthrough()),requests:he(X({sampling:he(X({createMessage:he(X({}).passthrough())}).passthrough()),elicitation:he(X({create:he(X({}).passthrough())}).passthrough())}).passthrough())}).passthrough(),Rve=X({list:he(X({}).passthrough()),cancel:he(X({}).passthrough()),requests:he(X({tools:he(X({call:he(X({}).passthrough())}).passthrough())}).passthrough())}).passthrough(),Ove=X({experimental:or(L(),Yi).optional(),sampling:X({context:Yi.optional(),tools:Yi.optional()}).optional(),elicitation:$ve.optional(),roots:X({listChanged:jr().optional()}).optional(),tasks:he(Ive)}),Cve=yn.extend({protocolVersion:L(),capabilities:Ove,clientInfo:Vq}),Pve=Tr.extend({method:ge("initialize"),params:Cve}),Ave=X({experimental:or(L(),Yi).optional(),logging:Yi.optional(),completions:Yi.optional(),prompts:he(X({listChanged:he(jr())})),resources:X({subscribe:jr().optional(),listChanged:jr().optional()}).optional(),tools:X({listChanged:jr().optional()}).optional(),tasks:he(Rve)}).passthrough(),Nve=Lr.extend({protocolVersion:L(),capabilities:Ave,serverInfo:Vq,instructions:L().optional()}),Mve=Xn.extend({method:ge("notifications/initialized")}),Kq=Tr.extend({method:ge("ping")}),Dve=X({progress:Rt(),total:he(Rt()),message:he(L())}),jve=X({...xa.shape,...Dve.shape,progressToken:Zq}),Jq=Xn.extend({method:ge("notifications/progress"),params:jve}),zve=yn.extend({cursor:Bq.optional()}),Qp=Tr.extend({params:zve.optional()}),ef=Lr.extend({nextCursor:he(Bq)}),tf=X({taskId:L(),status:zr(["working","input_required","completed","failed","cancelled"]),ttl:Ut([Rt(),Mq()]),createdAt:L(),lastUpdatedAt:L(),pollInterval:he(Rt()),statusMessage:he(L())}),Xq=Lr.extend({task:tf}),Lve=xa.merge(tf),Yq=Xn.extend({method:ge("notifications/tasks/status"),params:Lve}),Qq=Tr.extend({method:ge("tasks/get"),params:yn.extend({taskId:L()})}),e9=Lr.merge(tf),t9=Tr.extend({method:ge("tasks/result"),params:yn.extend({taskId:L()})}),r9=Qp.extend({method:ge("tasks/list")}),n9=ef.extend({tasks:rt(tf)}),QDe=Tr.extend({method:ge("tasks/cancel"),params:yn.extend({taskId:L()})}),eje=Lr.merge(tf),i9=X({uri:L(),mimeType:he(L()),_meta:or(L(),sr()).optional()}),s9=i9.extend({text:L()}),B$=L().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),o9=i9.extend({blob:B$}),Nu=X({audience:rt(zr(["user","assistant"])).optional(),priority:Rt().min(0).max(1).optional(),lastModified:wq.datetime({offset:!0}).optional()}),a9=X({...Iu.shape,...Yp.shape,uri:L(),description:he(L()),mimeType:he(L()),annotations:Nu.optional(),_meta:he(xi({}))}),Uve=X({...Iu.shape,...Yp.shape,uriTemplate:L(),description:he(L()),mimeType:he(L()),annotations:Nu.optional(),_meta:he(xi({}))}),Fve=Qp.extend({method:ge("resources/list")}),qve=ef.extend({resources:rt(a9)}),Hve=Qp.extend({method:ge("resources/templates/list")}),Zve=ef.extend({resourceTemplates:rt(Uve)}),G$=yn.extend({uri:L()}),Bve=G$,Gve=Tr.extend({method:ge("resources/read"),params:Bve}),Wve=Lr.extend({contents:rt(Ut([s9,o9]))}),Vve=Xn.extend({method:ge("notifications/resources/list_changed")}),Kve=G$,Jve=Tr.extend({method:ge("resources/subscribe"),params:Kve}),Xve=G$,Yve=Tr.extend({method:ge("resources/unsubscribe"),params:Xve}),Qve=xa.extend({uri:L()}),eye=Xn.extend({method:ge("notifications/resources/updated"),params:Qve}),tye=X({name:L(),description:he(L()),required:he(jr())}),rye=X({...Iu.shape,...Yp.shape,description:he(L()),arguments:he(rt(tye)),_meta:he(xi({}))}),nye=Qp.extend({method:ge("prompts/list")}),iye=ef.extend({prompts:rt(rye)}),sye=yn.extend({name:L(),arguments:or(L(),L()).optional()}),oye=Tr.extend({method:ge("prompts/get"),params:sye}),W$=X({type:ge("text"),text:L(),annotations:Nu.optional(),_meta:or(L(),sr()).optional()}),V$=X({type:ge("image"),data:B$,mimeType:L(),annotations:Nu.optional(),_meta:or(L(),sr()).optional()}),K$=X({type:ge("audio"),data:B$,mimeType:L(),annotations:Nu.optional(),_meta:or(L(),sr()).optional()}),aye=X({type:ge("tool_use"),name:L(),id:L(),input:X({}).passthrough(),_meta:he(X({}).passthrough())}).passthrough(),cye=X({type:ge("resource"),resource:Ut([s9,o9]),annotations:Nu.optional(),_meta:or(L(),sr()).optional()}),uye=a9.extend({type:ge("resource_link")}),J$=Ut([W$,V$,K$,uye,cye]),lye=X({role:zr(["user","assistant"]),content:J$}),dye=Lr.extend({description:he(L()),messages:rt(lye)}),pye=Xn.extend({method:ge("notifications/prompts/list_changed")}),fye=X({title:L().optional(),readOnlyHint:jr().optional(),destructiveHint:jr().optional(),idempotentHint:jr().optional(),openWorldHint:jr().optional()}),mye=X({taskSupport:zr(["required","optional","forbidden"]).optional()}),c9=X({...Iu.shape,...Yp.shape,description:L().optional(),inputSchema:X({type:ge("object"),properties:or(L(),Yi).optional(),required:rt(L()).optional()}).catchall(sr()),outputSchema:X({type:ge("object"),properties:or(L(),Yi).optional(),required:rt(L()).optional()}).catchall(sr()).optional(),annotations:he(fye),execution:he(mye),_meta:or(L(),sr()).optional()}),hye=Qp.extend({method:ge("tools/list")}),gye=ef.extend({tools:rt(c9)}),u9=Lr.extend({content:rt(J$).default([]),structuredContent:or(L(),sr()).optional(),isError:he(jr())}),tje=u9.or(Lr.extend({toolResult:sr()})),vye=yn.extend({name:L(),arguments:he(or(L(),sr()))}),yye=Tr.extend({method:ge("tools/call"),params:vye}),_ye=Xn.extend({method:ge("notifications/tools/list_changed")}),l9=zr(["debug","info","notice","warning","error","critical","alert","emergency"]),bye=yn.extend({level:l9}),Sye=Tr.extend({method:ge("logging/setLevel"),params:bye}),xye=xa.extend({level:l9,logger:L().optional(),data:sr()}),wye=Xn.extend({method:ge("notifications/message"),params:xye}),Eye=X({name:L().optional()}),kye=X({hints:he(rt(Eye)),costPriority:he(Rt().min(0).max(1)),speedPriority:he(Rt().min(0).max(1)),intelligencePriority:he(Rt().min(0).max(1))}),Tye=X({mode:he(zr(["auto","required","none"]))}),$ye=X({type:ge("tool_result"),toolUseId:L().describe("The unique identifier for the corresponding tool call."),content:rt(J$).default([]),structuredContent:X({}).passthrough().optional(),isError:he(jr()),_meta:he(X({}).passthrough())}).passthrough(),Iye=zq("type",[W$,V$,K$]),qv=zq("type",[W$,V$,K$,aye,$ye]),Rye=X({role:zr(["user","assistant"]),content:Ut([qv,rt(qv)]),_meta:he(X({}).passthrough())}).passthrough(),Oye=yn.extend({messages:rt(Rye),modelPreferences:kye.optional(),systemPrompt:L().optional(),includeContext:zr(["none","thisServer","allServers"]).optional(),temperature:Rt().optional(),maxTokens:Rt().int(),stopSequences:rt(L()).optional(),metadata:Yi.optional(),tools:he(rt(c9)),toolChoice:he(Tye)}),Cye=Tr.extend({method:ge("sampling/createMessage"),params:Oye}),Pye=Lr.extend({model:L(),stopReason:he(zr(["endTurn","stopSequence","maxTokens"]).or(L())),role:zr(["user","assistant"]),content:Iye}),Aye=Lr.extend({model:L(),stopReason:he(zr(["endTurn","stopSequence","maxTokens","toolUse"]).or(L())),role:zr(["user","assistant"]),content:Ut([qv,rt(qv)])}),Nye=X({type:ge("boolean"),title:L().optional(),description:L().optional(),default:jr().optional()}),Mye=X({type:ge("string"),title:L().optional(),description:L().optional(),minLength:Rt().optional(),maxLength:Rt().optional(),format:zr(["email","uri","date","date-time"]).optional(),default:L().optional()}),Dye=X({type:zr(["number","integer"]),title:L().optional(),description:L().optional(),minimum:Rt().optional(),maximum:Rt().optional(),default:Rt().optional()}),jye=X({type:ge("string"),title:L().optional(),description:L().optional(),enum:rt(L()),default:L().optional()}),zye=X({type:ge("string"),title:L().optional(),description:L().optional(),oneOf:rt(X({const:L(),title:L()})),default:L().optional()}),Lye=X({type:ge("string"),title:L().optional(),description:L().optional(),enum:rt(L()),enumNames:rt(L()).optional(),default:L().optional()}),Uye=Ut([jye,zye]),Fye=X({type:ge("array"),title:L().optional(),description:L().optional(),minItems:Rt().optional(),maxItems:Rt().optional(),items:X({type:ge("string"),enum:rt(L())}),default:rt(L()).optional()}),qye=X({type:ge("array"),title:L().optional(),description:L().optional(),minItems:Rt().optional(),maxItems:Rt().optional(),items:X({anyOf:rt(X({const:L(),title:L()}))}),default:rt(L()).optional()}),Hye=Ut([Fye,qye]),Zye=Ut([Lye,Uye,Hye]),Bye=Ut([Zye,Nye,Mye,Dye]),Gye=yn.extend({mode:ge("form").optional(),message:L(),requestedSchema:X({type:ge("object"),properties:or(L(),Bye),required:rt(L()).optional()})}),Wye=yn.extend({mode:ge("url"),message:L(),elicitationId:L(),url:L().url()}),Vye=Ut([Gye,Wye]),Kye=Tr.extend({method:ge("elicitation/create"),params:Vye}),Jye=xa.extend({elicitationId:L()}),Xye=Xn.extend({method:ge("notifications/elicitation/complete"),params:Jye}),Yye=Lr.extend({action:zr(["accept","decline","cancel"]),content:Hq(t=>t===null?void 0:t,or(L(),Ut([L(),Rt(),jr(),rt(L())])).optional())}),Qye=X({type:ge("ref/resource"),uri:L()}),e_e=X({type:ge("ref/prompt"),name:L()}),t_e=yn.extend({ref:Ut([e_e,Qye]),argument:X({name:L(),value:L()}),context:X({arguments:or(L(),L()).optional()}).optional()}),r_e=Tr.extend({method:ge("completion/complete"),params:t_e});var n_e=Lr.extend({completion:xi({values:rt(L()).max(100),total:he(Rt().int()),hasMore:he(jr())})}),i_e=X({uri:L().startsWith("file://"),name:L().optional(),_meta:or(L(),sr()).optional()}),s_e=Tr.extend({method:ge("roots/list")}),o_e=Lr.extend({roots:rt(i_e)}),a_e=Xn.extend({method:ge("notifications/roots/list_changed")}),rje=Ut([Kq,Pve,r_e,Sye,oye,nye,Fve,Hve,Gve,Jve,Yve,yye,hye,Qq,t9,r9]),nje=Ut([Wq,Jq,Mve,a_e,Yq]),ije=Ut([Gq,Pye,Aye,Yye,o_e,e9,n9,Xq]),sje=Ut([Kq,Cye,Kye,s_e,Qq,t9,r9]),oje=Ut([Wq,Jq,wye,eye,Vve,_ye,pye,Yq,Xye]),aje=Ut([Gq,Nve,n_e,dye,iye,qve,Zve,Wve,u9,gye,e9,n9,Xq]);var cje=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");var uje=gF(EF(),1),lje=gF(Fle(),1);var hF;(function(t){t.Completable="McpCompletable"})(hF||(hF={}));function d9({prompt:t,options:e}){let{systemPrompt:r,settingSources:n,sandbox:i,...s}=e??{},o,a;r===void 0?o="":typeof r=="string"?o=r:r.type==="preset"&&(a=r.append);let c=s.pathToClaudeCodeExecutable;if(!c){let J=(0,kF.fileURLToPath)(c_e.url),ue=(0,f$.join)(J,"..");c=(0,f$.join)(ue,"cli.js")}process.env.CLAUDE_AGENT_SDK_VERSION="0.1.77";let{abortController:u=$F(),additionalDirectories:l=[],agents:d,allowedTools:p=[],betas:f,canUseTool:m,continue:h,cwd:g,disallowedTools:v=[],tools:S,env:_,executable:y=WF()?"bun":"node",executableArgs:x=[],extraArgs:w={},fallbackModel:E,enableFileCheckpointing:T,forkSession:I,hooks:A,includePartialMessages:N,persistSession:U,maxThinkingTokens:V,maxTurns:j,maxBudgetUsd:ae,mcpServers:Ne,model:ze,outputFormat:Et,permissionMode:Ge="default",allowDangerouslySkipPermissions:K=!1,permissionPromptToolName:C,plugins:H,resume:M,resumeSessionAt:k,stderr:R,strictMcpConfig:F}=s,le=Et?.type==="json_schema"?Et.schema:void 0,ce=_;if(ce||(ce={...process.env}),ce.CLAUDE_CODE_ENTRYPOINT||(ce.CLAUDE_CODE_ENTRYPOINT="sdk-ts"),T&&(ce.CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING="true"),!c)throw new Error("pathToClaudeCodeExecutable is required");let Qe={},Xe=new Map;if(Ne)for(let[J,ue]of Object.entries(Ne))ue.type==="sdk"&&"instance"in ue?(Xe.set(J,ue.instance),Qe[J]={type:"sdk",name:J}):Qe[J]=ue;let Ft=typeof t=="string",P=new h$({abortController:u,additionalDirectories:l,betas:f,cwd:g,executable:y,executableArgs:x,extraArgs:w,pathToClaudeCodeExecutable:c,env:ce,forkSession:I,stderr:R,maxThinkingTokens:V,maxTurns:j,maxBudgetUsd:ae,model:ze,fallbackModel:E,jsonSchema:le,permissionMode:Ge,allowDangerouslySkipPermissions:K,permissionPromptToolName:C,continueConversation:h,resume:M,resumeSessionAt:k,settingSources:n??[],allowedTools:p,disallowedTools:v,tools:S,mcpServers:Qe,strictMcpConfig:F,canUseTool:!!m,hooks:!!A,includePartialMessages:N,persistSession:U,plugins:H,sandbox:i,spawnClaudeCodeProcess:s.spawnClaudeCodeProcess}),D={systemPrompt:o,appendSystemPrompt:a,agents:d},Z=new y$(P,Ft,m,A,u,Xe,le,D);return typeof t=="string"?P.write(Xi({type:"user",session_id:"",message:{role:"user",content:[{type:"text",text:t}]},parent_tool_use_id:null})+` + })));`),p.write(`newResult[${fu(S)}] = ${_}.value`)}p.write("payload.value = newResult;"),p.write("return payload;");let v=p.compile();return(S,_)=>v(d,S,_)},i,s=Vp,o=!k$.jitless,c=o&&rq.value,u=e.catchall,l;t._zod.parse=(d,p)=>{l??(l=r.value);let f=d.value;if(!s(f))return d.issues.push({expected:"object",code:"invalid_type",input:f,inst:t}),d;let m=[];if(o&&c&&p?.async===!1&&p.jitless!==!0)i||(i=n(e.shape)),d=i(d,p);else{d.value={};let _=l.shape;for(let y of l.keys){let x=_[y],w=x._zod.run({value:f[y],issues:[]},p),E=x._zod.optin==="optional"&&x._zod.optout==="optional";w instanceof Promise?m.push(w.then(T=>E?Q6(T,d,y,f):Pv(T,d,y))):E?Q6(w,d,y,f):Pv(w,d,y)}}if(!u)return m.length?Promise.all(m).then(()=>d):d;let h=[],g=l.keySet,v=u._zod,S=v.def.type;for(let _ of Object.keys(f)){if(g.has(_))continue;if(S==="never"){h.push(_);continue}let y=v.run({value:f[_],issues:[]},p);y instanceof Promise?m.push(y.then(x=>Pv(x,d,_))):Pv(y,d,_)}return h.length&&d.issues.push({code:"unrecognized_keys",keys:h,input:f,inst:t}),m.length?Promise.all(m).then(()=>d):d}});function eF(t,e,r,n){for(let i of t)if(i.issues.length===0)return e.value=i.value,e;return e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(i=>i.issues.map(s=>js(s,n,Ds())))}),e}var bq=q("$ZodUnion",(t,e)=>{Mt.init(t,e),Nt(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),Nt(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),Nt(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),Nt(t._zod,"pattern",()=>{if(e.options.every(r=>r._zod.pattern)){let r=e.options.map(n=>n._zod.pattern);return new RegExp(`^(${r.map(n=>Xv(n.source)).join("|")})$`)}}),t._zod.parse=(r,n)=>{let i=!1,s=[];for(let o of e.options){let a=o._zod.run({value:r.value,issues:[]},n);if(a instanceof Promise)s.push(a),i=!0;else{if(a.issues.length===0)return a;s.push(a)}}return i?Promise.all(s).then(o=>eF(o,r,t,n)):eF(s,r,t,n)}}),fhe=q("$ZodDiscriminatedUnion",(t,e)=>{bq.init(t,e);let r=t._zod.parse;Nt(t._zod,"propValues",()=>{let i={};for(let s of e.options){let o=s._zod.propValues;if(!o||Object.keys(o).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(let[a,c]of Object.entries(o)){i[a]||(i[a]=new Set);for(let u of c)i[a].add(u)}}return i});let n=Kv(()=>{let i=e.options,s=new Map;for(let o of i){let a=o._zod.propValues[e.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(o)}"`);for(let c of a){if(s.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);s.set(c,o)}}return s});t._zod.parse=(i,s)=>{let o=i.value;if(!Vp(o))return i.issues.push({code:"invalid_type",expected:"object",input:o,inst:t}),i;let a=n.value.get(o?.[e.discriminator]);return a?a._zod.run(i,s):e.unionFallback?r(i,s):(i.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:o,path:[e.discriminator],inst:t}),i)}}),mhe=q("$ZodIntersection",(t,e)=>{Mt.init(t,e),t._zod.parse=(r,n)=>{let i=r.value,s=e.left._zod.run({value:i,issues:[]},n),o=e.right._zod.run({value:i,issues:[]},n);return s instanceof Promise||o instanceof Promise?Promise.all([s,o]).then(([c,u])=>tF(r,c,u)):tF(r,s,o)}});function R$(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(Kp(t)&&Kp(e)){let r=Object.keys(e),n=Object.keys(t).filter(s=>r.indexOf(s)!==-1),i={...t,...e};for(let s of n){let o=R$(t[s],e[s]);if(!o.valid)return{valid:!1,mergeErrorPath:[s,...o.mergeErrorPath]};i[s]=o.data}return{valid:!0,data:i}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n{Mt.init(t,e),t._zod.parse=(r,n)=>{let i=r.value;if(!Kp(i))return r.issues.push({expected:"record",code:"invalid_type",input:i,inst:t}),r;let s=[];if(e.keyType._zod.values){let o=e.keyType._zod.values;r.value={};for(let c of o)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){let u=e.valueType._zod.run({value:i[c],issues:[]},n);u instanceof Promise?s.push(u.then(l=>{l.issues.length&&r.issues.push(..._o(c,l.issues)),r.value[c]=l.value})):(u.issues.length&&r.issues.push(..._o(c,u.issues)),r.value[c]=u.value)}let a;for(let c in i)o.has(c)||(a=a??[],a.push(c));a&&a.length>0&&r.issues.push({code:"unrecognized_keys",input:i,inst:t,keys:a})}else{r.value={};for(let o of Reflect.ownKeys(i)){if(o==="__proto__")continue;let a=e.keyType._zod.run({value:o,issues:[]},n);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:a.issues.map(u=>js(u,n,Ds())),input:o,path:[o],inst:t}),r.value[a.value]=a.value;continue}let c=e.valueType._zod.run({value:i[o],issues:[]},n);c instanceof Promise?s.push(c.then(u=>{u.issues.length&&r.issues.push(..._o(o,u.issues)),r.value[a.value]=u.value})):(c.issues.length&&r.issues.push(..._o(o,c.issues)),r.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>r):r}}),ghe=q("$ZodEnum",(t,e)=>{Mt.init(t,e);let r=QF(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>nq.has(typeof n)).map(n=>typeof n=="string"?Au(n):n.toString()).join("|")})$`),t._zod.parse=(n,i)=>{let s=n.value;return t._zod.values.has(s)||n.issues.push({code:"invalid_value",values:r,input:s,inst:t}),n}}),vhe=q("$ZodLiteral",(t,e)=>{Mt.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?Au(r):r?r.toString():String(r)).join("|")})$`),t._zod.parse=(r,n)=>{let i=r.value;return t._zod.values.has(i)||r.issues.push({code:"invalid_value",values:e.values,input:i,inst:t}),r}}),yhe=q("$ZodTransform",(t,e)=>{Mt.init(t,e),t._zod.parse=(r,n)=>{let i=e.transform(r.value,r);if(n.async)return(i instanceof Promise?i:Promise.resolve(i)).then(o=>(r.value=o,r));if(i instanceof Promise)throw new Sa;return r.value=i,r}}),_he=q("$ZodOptional",(t,e)=>{Mt.init(t,e),t._zod.optin="optional",t._zod.optout="optional",Nt(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),Nt(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Xv(r.source)})?$`):void 0}),t._zod.parse=(r,n)=>e.innerType._zod.optin==="optional"?e.innerType._zod.run(r,n):r.value===void 0?r:e.innerType._zod.run(r,n)}),bhe=q("$ZodNullable",(t,e)=>{Mt.init(t,e),Nt(t._zod,"optin",()=>e.innerType._zod.optin),Nt(t._zod,"optout",()=>e.innerType._zod.optout),Nt(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Xv(r.source)}|null)$`):void 0}),Nt(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(r,n)=>r.value===null?r:e.innerType._zod.run(r,n)}),She=q("$ZodDefault",(t,e)=>{Mt.init(t,e),t._zod.optin="optional",Nt(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(r.value===void 0)return r.value=e.defaultValue,r;let i=e.innerType._zod.run(r,n);return i instanceof Promise?i.then(s=>rF(s,e)):rF(i,e)}});function rF(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}var xhe=q("$ZodPrefault",(t,e)=>{Mt.init(t,e),t._zod.optin="optional",Nt(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>(r.value===void 0&&(r.value=e.defaultValue),e.innerType._zod.run(r,n))}),whe=q("$ZodNonOptional",(t,e)=>{Mt.init(t,e),Nt(t._zod,"values",()=>{let r=e.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),t._zod.parse=(r,n)=>{let i=e.innerType._zod.run(r,n);return i instanceof Promise?i.then(s=>nF(s,t)):nF(i,t)}});function nF(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}var Ehe=q("$ZodCatch",(t,e)=>{Mt.init(t,e),t._zod.optin="optional",Nt(t._zod,"optout",()=>e.innerType._zod.optout),Nt(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{let i=e.innerType._zod.run(r,n);return i instanceof Promise?i.then(s=>(r.value=s.value,s.issues.length&&(r.value=e.catchValue({...r,error:{issues:s.issues.map(o=>js(o,n,Ds()))},input:r.value}),r.issues=[]),r)):(r.value=i.value,i.issues.length&&(r.value=e.catchValue({...r,error:{issues:i.issues.map(s=>js(s,n,Ds()))},input:r.value}),r.issues=[]),r)}}),khe=q("$ZodPipe",(t,e)=>{Mt.init(t,e),Nt(t._zod,"values",()=>e.in._zod.values),Nt(t._zod,"optin",()=>e.in._zod.optin),Nt(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(r,n)=>{let i=e.in._zod.run(r,n);return i instanceof Promise?i.then(s=>iF(s,e,n)):iF(i,e,n)}});function iF(t,e,r){return mu(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}var The=q("$ZodReadonly",(t,e)=>{Mt.init(t,e),Nt(t._zod,"propValues",()=>e.innerType._zod.propValues),Nt(t._zod,"values",()=>e.innerType._zod.values),Nt(t._zod,"optin",()=>e.innerType._zod.optin),Nt(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(r,n)=>{let i=e.innerType._zod.run(r,n);return i instanceof Promise?i.then(sF):sF(i)}});function sF(t){return t.value=Object.freeze(t.value),t}var $he=q("$ZodCustom",(t,e)=>{vn.init(t,e),Mt.init(t,e),t._zod.parse=(r,n)=>r,t._zod.check=r=>{let n=r.value,i=e.fn(n);if(i instanceof Promise)return i.then(s=>oF(s,r,n,t));oF(i,r,n,t)}});function oF(t,e,r,n){if(!t){let i={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(i.params=n._zod.def.params),e.issues.push(oq(i))}}var Ihe=t=>{let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"number";case"object":{if(Array.isArray(t))return"array";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},Rhe=()=>{let t={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function e(n){return t[n]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return n=>{switch(n.code){case"invalid_type":return`Invalid input: expected ${n.expected}, received ${Ihe(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${U$(n.values[0])}`:`Invalid option: expected one of ${T$(n.values,"|")}`;case"too_big":{let i=n.inclusive?"<=":"<",s=e(n.origin);return s?`Too big: expected ${n.origin??"value"} to have ${i}${n.maximum.toString()} ${s.unit??"elements"}`:`Too big: expected ${n.origin??"value"} to be ${i}${n.maximum.toString()}`}case"too_small":{let i=n.inclusive?">=":">",s=e(n.origin);return s?`Too small: expected ${n.origin} to have ${i}${n.minimum.toString()} ${s.unit}`:`Too small: expected ${n.origin} to be ${i}${n.minimum.toString()}`}case"invalid_format":{let i=n;return i.format==="starts_with"?`Invalid string: must start with "${i.prefix}"`:i.format==="ends_with"?`Invalid string: must end with "${i.suffix}"`:i.format==="includes"?`Invalid string: must include "${i.includes}"`:i.format==="regex"?`Invalid string: must match pattern ${i.pattern}`:`Invalid ${r[i.format]??n.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${n.divisor}`;case"unrecognized_keys":return`Unrecognized key${n.keys.length>1?"s":""}: ${T$(n.keys,", ")}`;case"invalid_key":return`Invalid key in ${n.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${n.origin}`;default:return"Invalid input"}}};function Ohe(){return{localeError:Rhe()}}var O$=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...r){let n=r[0];if(this._map.set(e,n),n&&typeof n=="object"&&"id"in n){if(this._idmap.has(n.id))throw new Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,e)}return this}remove(e){return this._map.delete(e),this}get(e){let r=e._zod.parent;if(r){let n={...this.get(r)??{}};return delete n.id,{...n,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}};function Che(){return new O$}var Av=Che();function Phe(t,e){return new t({type:"string",...Se(e)})}function Ahe(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...Se(e)})}function aF(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...Se(e)})}function Nhe(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...Se(e)})}function Mhe(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...Se(e)})}function Dhe(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...Se(e)})}function jhe(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...Se(e)})}function zhe(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...Se(e)})}function Lhe(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...Se(e)})}function Uhe(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...Se(e)})}function Fhe(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...Se(e)})}function qhe(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...Se(e)})}function Hhe(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...Se(e)})}function Zhe(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...Se(e)})}function Bhe(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...Se(e)})}function Ghe(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...Se(e)})}function Whe(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...Se(e)})}function Vhe(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...Se(e)})}function Khe(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...Se(e)})}function Jhe(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...Se(e)})}function Xhe(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...Se(e)})}function Yhe(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...Se(e)})}function Qhe(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...Se(e)})}function ege(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...Se(e)})}function tge(t,e){return new t({type:"string",format:"date",check:"string_format",...Se(e)})}function rge(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...Se(e)})}function nge(t,e){return new t({type:"string",format:"duration",check:"string_format",...Se(e)})}function ige(t,e){return new t({type:"number",checks:[],...Se(e)})}function sge(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...Se(e)})}function oge(t,e){return new t({type:"boolean",...Se(e)})}function age(t,e){return new t({type:"null",...Se(e)})}function cge(t){return new t({type:"unknown"})}function uge(t,e){return new t({type:"never",...Se(e)})}function cF(t,e){return new gq({check:"less_than",...Se(e),value:t,inclusive:!1})}function l$(t,e){return new gq({check:"less_than",...Se(e),value:t,inclusive:!0})}function uF(t,e){return new vq({check:"greater_than",...Se(e),value:t,inclusive:!1})}function d$(t,e){return new vq({check:"greater_than",...Se(e),value:t,inclusive:!0})}function lF(t,e){return new xme({check:"multiple_of",...Se(e),value:t})}function Sq(t,e){return new Eme({check:"max_length",...Se(e),maximum:t})}function Fv(t,e){return new kme({check:"min_length",...Se(e),minimum:t})}function xq(t,e){return new Tme({check:"length_equals",...Se(e),length:t})}function lge(t,e){return new $me({check:"string_format",format:"regex",...Se(e),pattern:t})}function dge(t){return new Ime({check:"string_format",format:"lowercase",...Se(t)})}function pge(t){return new Rme({check:"string_format",format:"uppercase",...Se(t)})}function fge(t,e){return new Ome({check:"string_format",format:"includes",...Se(e),includes:t})}function mge(t,e){return new Cme({check:"string_format",format:"starts_with",...Se(e),prefix:t})}function hge(t,e){return new Pme({check:"string_format",format:"ends_with",...Se(e),suffix:t})}function Xp(t){return new Ame({check:"overwrite",tx:t})}function gge(t){return Xp(e=>e.normalize(t))}function vge(){return Xp(t=>t.trim())}function yge(){return Xp(t=>t.toLowerCase())}function _ge(){return Xp(t=>t.toUpperCase())}function bge(t,e,r){return new t({type:"array",element:e,...Se(r)})}function Sge(t,e,r){let n=Se(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function xge(t,e,r){return new t({type:"custom",check:"custom",fn:e,...Se(r)})}var wq={};vF(wq,{time:()=>Rq,duration:()=>Cq,datetime:()=>kq,date:()=>$q,ZodISOTime:()=>Iq,ZodISODuration:()=>Oq,ZodISODateTime:()=>Eq,ZodISODate:()=>Tq});var Eq=q("ZodISODateTime",(t,e)=>{Gme.init(t,e),Gt.init(t,e)});function kq(t){return ege(Eq,t)}var Tq=q("ZodISODate",(t,e)=>{Wme.init(t,e),Gt.init(t,e)});function $q(t){return tge(Tq,t)}var Iq=q("ZodISOTime",(t,e)=>{Vme.init(t,e),Gt.init(t,e)});function Rq(t){return rge(Iq,t)}var Oq=q("ZodISODuration",(t,e)=>{Kme.init(t,e),Gt.init(t,e)});function Cq(t){return nge(Oq,t)}var Pq=(t,e)=>{cq.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>Hfe(t,r)},flatten:{value:r=>qfe(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},JDe=q("ZodError",Pq),ey=q("ZodError",Pq,{Parent:Error}),wge=Zfe(ey),Ege=Bfe(ey),kge=lq(ey),Tge=dq(ey),Bt=q("ZodType",(t,e)=>(Mt.init(t,e),t.def=e,Object.defineProperty(t,"_def",{value:e}),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>wo(t,r,n),t.brand=()=>t,t.register=(r,n)=>(r.add(t,n),t),t.parse=(r,n)=>wge(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>kge(t,r,n),t.parseAsync=async(r,n)=>Ege(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Tge(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(gve(r,n)),t.superRefine=r=>t.check(vve(r)),t.overwrite=r=>t.check(Xp(r)),t.optional=()=>he(t),t.nullable=()=>fF(t),t.nullish=()=>he(fF(t)),t.nonoptional=r=>cve(t,r),t.array=()=>rt(t),t.or=r=>Ut([t,r]),t.and=r=>q$(t,r),t.transform=r=>P$(t,Lq(r)),t.default=r=>sve(t,r),t.prefault=r=>ave(t,r),t.catch=r=>lve(t,r),t.pipe=r=>P$(t,r),t.readonly=()=>fve(t),t.describe=r=>{let n=t.clone();return Av.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return Av.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return Av.get(t);let n=t.clone();return Av.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),Aq=q("_ZodString",(t,e)=>{F$.init(t,e),Bt.init(t,e);let r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,t.regex=(...n)=>t.check(lge(...n)),t.includes=(...n)=>t.check(fge(...n)),t.startsWith=(...n)=>t.check(mge(...n)),t.endsWith=(...n)=>t.check(hge(...n)),t.min=(...n)=>t.check(Fv(...n)),t.max=(...n)=>t.check(Sq(...n)),t.length=(...n)=>t.check(xq(...n)),t.nonempty=(...n)=>t.check(Fv(1,...n)),t.lowercase=n=>t.check(dge(n)),t.uppercase=n=>t.check(pge(n)),t.trim=()=>t.check(vge()),t.normalize=(...n)=>t.check(gge(...n)),t.toLowerCase=()=>t.check(yge()),t.toUpperCase=()=>t.check(_ge())}),$ge=q("ZodString",(t,e)=>{F$.init(t,e),Aq.init(t,e),t.email=r=>t.check(Ahe(Ige,r)),t.url=r=>t.check(zhe(Rge,r)),t.jwt=r=>t.check(Qhe(Zge,r)),t.emoji=r=>t.check(Lhe(Oge,r)),t.guid=r=>t.check(aF(dF,r)),t.uuid=r=>t.check(Nhe(Nv,r)),t.uuidv4=r=>t.check(Mhe(Nv,r)),t.uuidv6=r=>t.check(Dhe(Nv,r)),t.uuidv7=r=>t.check(jhe(Nv,r)),t.nanoid=r=>t.check(Uhe(Cge,r)),t.guid=r=>t.check(aF(dF,r)),t.cuid=r=>t.check(Fhe(Pge,r)),t.cuid2=r=>t.check(qhe(Age,r)),t.ulid=r=>t.check(Hhe(Nge,r)),t.base64=r=>t.check(Jhe(Fge,r)),t.base64url=r=>t.check(Xhe(qge,r)),t.xid=r=>t.check(Zhe(Mge,r)),t.ksuid=r=>t.check(Bhe(Dge,r)),t.ipv4=r=>t.check(Ghe(jge,r)),t.ipv6=r=>t.check(Whe(zge,r)),t.cidrv4=r=>t.check(Vhe(Lge,r)),t.cidrv6=r=>t.check(Khe(Uge,r)),t.e164=r=>t.check(Yhe(Hge,r)),t.datetime=r=>t.check(kq(r)),t.date=r=>t.check($q(r)),t.time=r=>t.check(Rq(r)),t.duration=r=>t.check(Cq(r))});function L(t){return Phe($ge,t)}var Gt=q("ZodStringFormat",(t,e)=>{Lt.init(t,e),Aq.init(t,e)}),Ige=q("ZodEmail",(t,e)=>{jme.init(t,e),Gt.init(t,e)}),dF=q("ZodGUID",(t,e)=>{Mme.init(t,e),Gt.init(t,e)}),Nv=q("ZodUUID",(t,e)=>{Dme.init(t,e),Gt.init(t,e)}),Rge=q("ZodURL",(t,e)=>{zme.init(t,e),Gt.init(t,e)}),Oge=q("ZodEmoji",(t,e)=>{Lme.init(t,e),Gt.init(t,e)}),Cge=q("ZodNanoID",(t,e)=>{Ume.init(t,e),Gt.init(t,e)}),Pge=q("ZodCUID",(t,e)=>{Fme.init(t,e),Gt.init(t,e)}),Age=q("ZodCUID2",(t,e)=>{qme.init(t,e),Gt.init(t,e)}),Nge=q("ZodULID",(t,e)=>{Hme.init(t,e),Gt.init(t,e)}),Mge=q("ZodXID",(t,e)=>{Zme.init(t,e),Gt.init(t,e)}),Dge=q("ZodKSUID",(t,e)=>{Bme.init(t,e),Gt.init(t,e)}),jge=q("ZodIPv4",(t,e)=>{Jme.init(t,e),Gt.init(t,e)}),zge=q("ZodIPv6",(t,e)=>{Xme.init(t,e),Gt.init(t,e)}),Lge=q("ZodCIDRv4",(t,e)=>{Yme.init(t,e),Gt.init(t,e)}),Uge=q("ZodCIDRv6",(t,e)=>{Qme.init(t,e),Gt.init(t,e)}),Fge=q("ZodBase64",(t,e)=>{ehe.init(t,e),Gt.init(t,e)}),qge=q("ZodBase64URL",(t,e)=>{rhe.init(t,e),Gt.init(t,e)}),Hge=q("ZodE164",(t,e)=>{nhe.init(t,e),Gt.init(t,e)}),Zge=q("ZodJWT",(t,e)=>{she.init(t,e),Gt.init(t,e)}),Nq=q("ZodNumber",(t,e)=>{_q.init(t,e),Bt.init(t,e),t.gt=(n,i)=>t.check(uF(n,i)),t.gte=(n,i)=>t.check(d$(n,i)),t.min=(n,i)=>t.check(d$(n,i)),t.lt=(n,i)=>t.check(cF(n,i)),t.lte=(n,i)=>t.check(l$(n,i)),t.max=(n,i)=>t.check(l$(n,i)),t.int=n=>t.check(pF(n)),t.safe=n=>t.check(pF(n)),t.positive=n=>t.check(uF(0,n)),t.nonnegative=n=>t.check(d$(0,n)),t.negative=n=>t.check(cF(0,n)),t.nonpositive=n=>t.check(l$(0,n)),t.multipleOf=(n,i)=>t.check(lF(n,i)),t.step=(n,i)=>t.check(lF(n,i)),t.finite=()=>t;let r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});function Rt(t){return ige(Nq,t)}var Bge=q("ZodNumberFormat",(t,e)=>{ohe.init(t,e),Nq.init(t,e)});function pF(t){return sge(Bge,t)}var Gge=q("ZodBoolean",(t,e)=>{ahe.init(t,e),Bt.init(t,e)});function jr(t){return oge(Gge,t)}var Wge=q("ZodNull",(t,e)=>{che.init(t,e),Bt.init(t,e)});function Mq(t){return age(Wge,t)}var Vge=q("ZodUnknown",(t,e)=>{uhe.init(t,e),Bt.init(t,e)});function sr(){return cge(Vge)}var Kge=q("ZodNever",(t,e)=>{lhe.init(t,e),Bt.init(t,e)});function Jge(t){return uge(Kge,t)}var Xge=q("ZodArray",(t,e)=>{dhe.init(t,e),Bt.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(Fv(r,n)),t.nonempty=r=>t.check(Fv(1,r)),t.max=(r,n)=>t.check(Sq(r,n)),t.length=(r,n)=>t.check(xq(r,n)),t.unwrap=()=>t.element});function rt(t,e){return bge(Xge,t,e)}var Dq=q("ZodObject",(t,e)=>{phe.init(t,e),Bt.init(t,e),At.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>zr(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:sr()}),t.loose=()=>t.clone({...t._zod.def,catchall:sr()}),t.strict=()=>t.clone({...t._zod.def,catchall:Jge()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>At.extend(t,r),t.merge=r=>At.merge(t,r),t.pick=r=>At.pick(t,r),t.omit=r=>At.omit(t,r),t.partial=(...r)=>At.partial(Uq,t,r[0]),t.required=(...r)=>At.required(Fq,t,r[0])});function X(t,e){let r={type:"object",get shape(){return At.assignProp(this,"shape",{...t}),this.shape},...At.normalizeParams(e)};return new Dq(r)}function xi(t,e){return new Dq({type:"object",get shape(){return At.assignProp(this,"shape",{...t}),this.shape},catchall:sr(),...At.normalizeParams(e)})}var jq=q("ZodUnion",(t,e)=>{bq.init(t,e),Bt.init(t,e),t.options=e.options});function Ut(t,e){return new jq({type:"union",options:t,...At.normalizeParams(e)})}var Yge=q("ZodDiscriminatedUnion",(t,e)=>{jq.init(t,e),fhe.init(t,e)});function zq(t,e,r){return new Yge({type:"union",options:e,discriminator:t,...At.normalizeParams(r)})}var Qge=q("ZodIntersection",(t,e)=>{mhe.init(t,e),Bt.init(t,e)});function q$(t,e){return new Qge({type:"intersection",left:t,right:e})}var eve=q("ZodRecord",(t,e)=>{hhe.init(t,e),Bt.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});function or(t,e,r){return new eve({type:"record",keyType:t,valueType:e,...At.normalizeParams(r)})}var C$=q("ZodEnum",(t,e)=>{ghe.init(t,e),Bt.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(n,i)=>{let s={};for(let o of n)if(r.has(o))s[o]=e.entries[o];else throw new Error(`Key ${o} not found in enum`);return new C$({...e,checks:[],...At.normalizeParams(i),entries:s})},t.exclude=(n,i)=>{let s={...e.entries};for(let o of n)if(r.has(o))delete s[o];else throw new Error(`Key ${o} not found in enum`);return new C$({...e,checks:[],...At.normalizeParams(i),entries:s})}});function zr(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new C$({type:"enum",entries:r,...At.normalizeParams(e)})}var tve=q("ZodLiteral",(t,e)=>{vhe.init(t,e),Bt.init(t,e),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function ge(t,e){return new tve({type:"literal",values:Array.isArray(t)?t:[t],...At.normalizeParams(e)})}var rve=q("ZodTransform",(t,e)=>{yhe.init(t,e),Bt.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(At.issue(s,r.value,e));else{let o=s;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=t),o.continue??(o.continue=!0),r.issues.push(At.issue(o))}};let i=e.transform(r.value,r);return i instanceof Promise?i.then(s=>(r.value=s,r)):(r.value=i,r)}});function Lq(t){return new rve({type:"transform",transform:t})}var Uq=q("ZodOptional",(t,e)=>{_he.init(t,e),Bt.init(t,e),t.unwrap=()=>t._zod.def.innerType});function he(t){return new Uq({type:"optional",innerType:t})}var nve=q("ZodNullable",(t,e)=>{bhe.init(t,e),Bt.init(t,e),t.unwrap=()=>t._zod.def.innerType});function fF(t){return new nve({type:"nullable",innerType:t})}var ive=q("ZodDefault",(t,e)=>{She.init(t,e),Bt.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function sve(t,e){return new ive({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var ove=q("ZodPrefault",(t,e)=>{xhe.init(t,e),Bt.init(t,e),t.unwrap=()=>t._zod.def.innerType});function ave(t,e){return new ove({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var Fq=q("ZodNonOptional",(t,e)=>{whe.init(t,e),Bt.init(t,e),t.unwrap=()=>t._zod.def.innerType});function cve(t,e){return new Fq({type:"nonoptional",innerType:t,...At.normalizeParams(e)})}var uve=q("ZodCatch",(t,e)=>{Ehe.init(t,e),Bt.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function lve(t,e){return new uve({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var dve=q("ZodPipe",(t,e)=>{khe.init(t,e),Bt.init(t,e),t.in=e.in,t.out=e.out});function P$(t,e){return new dve({type:"pipe",in:t,out:e})}var pve=q("ZodReadonly",(t,e)=>{The.init(t,e),Bt.init(t,e)});function fve(t){return new pve({type:"readonly",innerType:t})}var qq=q("ZodCustom",(t,e)=>{$he.init(t,e),Bt.init(t,e)});function mve(t,e){let r=new vn({check:"custom",...At.normalizeParams(e)});return r._zod.check=t,r}function hve(t,e){return Sge(qq,t??(()=>!0),e)}function gve(t,e={}){return xge(qq,t,e)}function vve(t,e){let r=mve(n=>(n.addIssue=i=>{if(typeof i=="string")n.issues.push(At.issue(i,n.value,r._zod.def));else{let s=i;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=n.value),s.inst??(s.inst=r),s.continue??(s.continue=!r._zod.def.abort),n.issues.push(At.issue(s))}},t(n.value,n)),e);return r}function Hq(t,e){return P$(Lq(t),e)}Ds(Ohe());var H$="io.modelcontextprotocol/related-task",ty="2.0",Yi=hve(t=>t!==null&&(typeof t=="object"||typeof t=="function")),Zq=Ut([L(),Rt().int()]),Bq=L(),yve=xi({ttl:Ut([Rt(),Mq()]).optional(),pollInterval:Rt().optional()}),Z$=xi({taskId:L()}),_ve=xi({progressToken:Zq.optional(),[H$]:Z$.optional()}),yn=xi({task:yve.optional(),_meta:_ve.optional()}),Tr=X({method:L(),params:yn.optional()}),xa=xi({_meta:X({[H$]:he(Z$)}).passthrough().optional()}),Xn=X({method:L(),params:xa.optional()}),Lr=xi({_meta:xi({[H$]:Z$.optional()}).optional()}),ry=Ut([L(),Rt().int()]),bve=X({jsonrpc:ge(ty),id:ry,...Tr.shape}).strict();var Sve=X({jsonrpc:ge(ty),...Xn.shape}).strict();var xve=X({jsonrpc:ge(ty),id:ry,result:Lr}).strict();var mF;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(mF||(mF={}));var wve=X({jsonrpc:ge(ty),id:ry,error:X({code:Rt().int(),message:L(),data:he(sr())})}).strict();var XDe=Ut([bve,Sve,xve,wve]),Gq=Lr.strict(),Eve=xa.extend({requestId:ry,reason:L().optional()}),Wq=Xn.extend({method:ge("notifications/cancelled"),params:Eve}),kve=X({src:L(),mimeType:L().optional(),sizes:rt(L()).optional()}),Yp=X({icons:rt(kve).optional()}),Iu=X({name:L(),title:L().optional()}),Vq=Iu.extend({...Iu.shape,...Yp.shape,version:L(),websiteUrl:L().optional()}),Tve=q$(X({applyDefaults:jr().optional()}),or(L(),sr())),$ve=Hq(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,q$(X({form:Tve.optional(),url:Yi.optional()}),or(L(),sr()).optional())),Ive=X({list:he(X({}).passthrough()),cancel:he(X({}).passthrough()),requests:he(X({sampling:he(X({createMessage:he(X({}).passthrough())}).passthrough()),elicitation:he(X({create:he(X({}).passthrough())}).passthrough())}).passthrough())}).passthrough(),Rve=X({list:he(X({}).passthrough()),cancel:he(X({}).passthrough()),requests:he(X({tools:he(X({call:he(X({}).passthrough())}).passthrough())}).passthrough())}).passthrough(),Ove=X({experimental:or(L(),Yi).optional(),sampling:X({context:Yi.optional(),tools:Yi.optional()}).optional(),elicitation:$ve.optional(),roots:X({listChanged:jr().optional()}).optional(),tasks:he(Ive)}),Cve=yn.extend({protocolVersion:L(),capabilities:Ove,clientInfo:Vq}),Pve=Tr.extend({method:ge("initialize"),params:Cve}),Ave=X({experimental:or(L(),Yi).optional(),logging:Yi.optional(),completions:Yi.optional(),prompts:he(X({listChanged:he(jr())})),resources:X({subscribe:jr().optional(),listChanged:jr().optional()}).optional(),tools:X({listChanged:jr().optional()}).optional(),tasks:he(Rve)}).passthrough(),Nve=Lr.extend({protocolVersion:L(),capabilities:Ave,serverInfo:Vq,instructions:L().optional()}),Mve=Xn.extend({method:ge("notifications/initialized")}),Kq=Tr.extend({method:ge("ping")}),Dve=X({progress:Rt(),total:he(Rt()),message:he(L())}),jve=X({...xa.shape,...Dve.shape,progressToken:Zq}),Jq=Xn.extend({method:ge("notifications/progress"),params:jve}),zve=yn.extend({cursor:Bq.optional()}),Qp=Tr.extend({params:zve.optional()}),ef=Lr.extend({nextCursor:he(Bq)}),tf=X({taskId:L(),status:zr(["working","input_required","completed","failed","cancelled"]),ttl:Ut([Rt(),Mq()]),createdAt:L(),lastUpdatedAt:L(),pollInterval:he(Rt()),statusMessage:he(L())}),Xq=Lr.extend({task:tf}),Lve=xa.merge(tf),Yq=Xn.extend({method:ge("notifications/tasks/status"),params:Lve}),Qq=Tr.extend({method:ge("tasks/get"),params:yn.extend({taskId:L()})}),e9=Lr.merge(tf),t9=Tr.extend({method:ge("tasks/result"),params:yn.extend({taskId:L()})}),r9=Qp.extend({method:ge("tasks/list")}),n9=ef.extend({tasks:rt(tf)}),YDe=Tr.extend({method:ge("tasks/cancel"),params:yn.extend({taskId:L()})}),QDe=Lr.merge(tf),i9=X({uri:L(),mimeType:he(L()),_meta:or(L(),sr()).optional()}),s9=i9.extend({text:L()}),B$=L().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),o9=i9.extend({blob:B$}),Nu=X({audience:rt(zr(["user","assistant"])).optional(),priority:Rt().min(0).max(1).optional(),lastModified:wq.datetime({offset:!0}).optional()}),a9=X({...Iu.shape,...Yp.shape,uri:L(),description:he(L()),mimeType:he(L()),annotations:Nu.optional(),_meta:he(xi({}))}),Uve=X({...Iu.shape,...Yp.shape,uriTemplate:L(),description:he(L()),mimeType:he(L()),annotations:Nu.optional(),_meta:he(xi({}))}),Fve=Qp.extend({method:ge("resources/list")}),qve=ef.extend({resources:rt(a9)}),Hve=Qp.extend({method:ge("resources/templates/list")}),Zve=ef.extend({resourceTemplates:rt(Uve)}),G$=yn.extend({uri:L()}),Bve=G$,Gve=Tr.extend({method:ge("resources/read"),params:Bve}),Wve=Lr.extend({contents:rt(Ut([s9,o9]))}),Vve=Xn.extend({method:ge("notifications/resources/list_changed")}),Kve=G$,Jve=Tr.extend({method:ge("resources/subscribe"),params:Kve}),Xve=G$,Yve=Tr.extend({method:ge("resources/unsubscribe"),params:Xve}),Qve=xa.extend({uri:L()}),eye=Xn.extend({method:ge("notifications/resources/updated"),params:Qve}),tye=X({name:L(),description:he(L()),required:he(jr())}),rye=X({...Iu.shape,...Yp.shape,description:he(L()),arguments:he(rt(tye)),_meta:he(xi({}))}),nye=Qp.extend({method:ge("prompts/list")}),iye=ef.extend({prompts:rt(rye)}),sye=yn.extend({name:L(),arguments:or(L(),L()).optional()}),oye=Tr.extend({method:ge("prompts/get"),params:sye}),W$=X({type:ge("text"),text:L(),annotations:Nu.optional(),_meta:or(L(),sr()).optional()}),V$=X({type:ge("image"),data:B$,mimeType:L(),annotations:Nu.optional(),_meta:or(L(),sr()).optional()}),K$=X({type:ge("audio"),data:B$,mimeType:L(),annotations:Nu.optional(),_meta:or(L(),sr()).optional()}),aye=X({type:ge("tool_use"),name:L(),id:L(),input:X({}).passthrough(),_meta:he(X({}).passthrough())}).passthrough(),cye=X({type:ge("resource"),resource:Ut([s9,o9]),annotations:Nu.optional(),_meta:or(L(),sr()).optional()}),uye=a9.extend({type:ge("resource_link")}),J$=Ut([W$,V$,K$,uye,cye]),lye=X({role:zr(["user","assistant"]),content:J$}),dye=Lr.extend({description:he(L()),messages:rt(lye)}),pye=Xn.extend({method:ge("notifications/prompts/list_changed")}),fye=X({title:L().optional(),readOnlyHint:jr().optional(),destructiveHint:jr().optional(),idempotentHint:jr().optional(),openWorldHint:jr().optional()}),mye=X({taskSupport:zr(["required","optional","forbidden"]).optional()}),c9=X({...Iu.shape,...Yp.shape,description:L().optional(),inputSchema:X({type:ge("object"),properties:or(L(),Yi).optional(),required:rt(L()).optional()}).catchall(sr()),outputSchema:X({type:ge("object"),properties:or(L(),Yi).optional(),required:rt(L()).optional()}).catchall(sr()).optional(),annotations:he(fye),execution:he(mye),_meta:or(L(),sr()).optional()}),hye=Qp.extend({method:ge("tools/list")}),gye=ef.extend({tools:rt(c9)}),u9=Lr.extend({content:rt(J$).default([]),structuredContent:or(L(),sr()).optional(),isError:he(jr())}),eje=u9.or(Lr.extend({toolResult:sr()})),vye=yn.extend({name:L(),arguments:he(or(L(),sr()))}),yye=Tr.extend({method:ge("tools/call"),params:vye}),_ye=Xn.extend({method:ge("notifications/tools/list_changed")}),l9=zr(["debug","info","notice","warning","error","critical","alert","emergency"]),bye=yn.extend({level:l9}),Sye=Tr.extend({method:ge("logging/setLevel"),params:bye}),xye=xa.extend({level:l9,logger:L().optional(),data:sr()}),wye=Xn.extend({method:ge("notifications/message"),params:xye}),Eye=X({name:L().optional()}),kye=X({hints:he(rt(Eye)),costPriority:he(Rt().min(0).max(1)),speedPriority:he(Rt().min(0).max(1)),intelligencePriority:he(Rt().min(0).max(1))}),Tye=X({mode:he(zr(["auto","required","none"]))}),$ye=X({type:ge("tool_result"),toolUseId:L().describe("The unique identifier for the corresponding tool call."),content:rt(J$).default([]),structuredContent:X({}).passthrough().optional(),isError:he(jr()),_meta:he(X({}).passthrough())}).passthrough(),Iye=zq("type",[W$,V$,K$]),qv=zq("type",[W$,V$,K$,aye,$ye]),Rye=X({role:zr(["user","assistant"]),content:Ut([qv,rt(qv)]),_meta:he(X({}).passthrough())}).passthrough(),Oye=yn.extend({messages:rt(Rye),modelPreferences:kye.optional(),systemPrompt:L().optional(),includeContext:zr(["none","thisServer","allServers"]).optional(),temperature:Rt().optional(),maxTokens:Rt().int(),stopSequences:rt(L()).optional(),metadata:Yi.optional(),tools:he(rt(c9)),toolChoice:he(Tye)}),Cye=Tr.extend({method:ge("sampling/createMessage"),params:Oye}),Pye=Lr.extend({model:L(),stopReason:he(zr(["endTurn","stopSequence","maxTokens"]).or(L())),role:zr(["user","assistant"]),content:Iye}),Aye=Lr.extend({model:L(),stopReason:he(zr(["endTurn","stopSequence","maxTokens","toolUse"]).or(L())),role:zr(["user","assistant"]),content:Ut([qv,rt(qv)])}),Nye=X({type:ge("boolean"),title:L().optional(),description:L().optional(),default:jr().optional()}),Mye=X({type:ge("string"),title:L().optional(),description:L().optional(),minLength:Rt().optional(),maxLength:Rt().optional(),format:zr(["email","uri","date","date-time"]).optional(),default:L().optional()}),Dye=X({type:zr(["number","integer"]),title:L().optional(),description:L().optional(),minimum:Rt().optional(),maximum:Rt().optional(),default:Rt().optional()}),jye=X({type:ge("string"),title:L().optional(),description:L().optional(),enum:rt(L()),default:L().optional()}),zye=X({type:ge("string"),title:L().optional(),description:L().optional(),oneOf:rt(X({const:L(),title:L()})),default:L().optional()}),Lye=X({type:ge("string"),title:L().optional(),description:L().optional(),enum:rt(L()),enumNames:rt(L()).optional(),default:L().optional()}),Uye=Ut([jye,zye]),Fye=X({type:ge("array"),title:L().optional(),description:L().optional(),minItems:Rt().optional(),maxItems:Rt().optional(),items:X({type:ge("string"),enum:rt(L())}),default:rt(L()).optional()}),qye=X({type:ge("array"),title:L().optional(),description:L().optional(),minItems:Rt().optional(),maxItems:Rt().optional(),items:X({anyOf:rt(X({const:L(),title:L()}))}),default:rt(L()).optional()}),Hye=Ut([Fye,qye]),Zye=Ut([Lye,Uye,Hye]),Bye=Ut([Zye,Nye,Mye,Dye]),Gye=yn.extend({mode:ge("form").optional(),message:L(),requestedSchema:X({type:ge("object"),properties:or(L(),Bye),required:rt(L()).optional()})}),Wye=yn.extend({mode:ge("url"),message:L(),elicitationId:L(),url:L().url()}),Vye=Ut([Gye,Wye]),Kye=Tr.extend({method:ge("elicitation/create"),params:Vye}),Jye=xa.extend({elicitationId:L()}),Xye=Xn.extend({method:ge("notifications/elicitation/complete"),params:Jye}),Yye=Lr.extend({action:zr(["accept","decline","cancel"]),content:Hq(t=>t===null?void 0:t,or(L(),Ut([L(),Rt(),jr(),rt(L())])).optional())}),Qye=X({type:ge("ref/resource"),uri:L()}),e_e=X({type:ge("ref/prompt"),name:L()}),t_e=yn.extend({ref:Ut([e_e,Qye]),argument:X({name:L(),value:L()}),context:X({arguments:or(L(),L()).optional()}).optional()}),r_e=Tr.extend({method:ge("completion/complete"),params:t_e});var n_e=Lr.extend({completion:xi({values:rt(L()).max(100),total:he(Rt().int()),hasMore:he(jr())})}),i_e=X({uri:L().startsWith("file://"),name:L().optional(),_meta:or(L(),sr()).optional()}),s_e=Tr.extend({method:ge("roots/list")}),o_e=Lr.extend({roots:rt(i_e)}),a_e=Xn.extend({method:ge("notifications/roots/list_changed")}),tje=Ut([Kq,Pve,r_e,Sye,oye,nye,Fve,Hve,Gve,Jve,Yve,yye,hye,Qq,t9,r9]),rje=Ut([Wq,Jq,Mve,a_e,Yq]),nje=Ut([Gq,Pye,Aye,Yye,o_e,e9,n9,Xq]),ije=Ut([Kq,Cye,Kye,s_e,Qq,t9,r9]),sje=Ut([Wq,Jq,wye,eye,Vve,_ye,pye,Yq,Xye]),oje=Ut([Gq,Nve,n_e,dye,iye,qve,Zve,Wve,u9,gye,e9,n9,Xq]);var aje=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");var cje=gF(EF(),1),uje=gF(Fle(),1);var hF;(function(t){t.Completable="McpCompletable"})(hF||(hF={}));function d9({prompt:t,options:e}){let{systemPrompt:r,settingSources:n,sandbox:i,...s}=e??{},o,a;r===void 0?o="":typeof r=="string"?o=r:r.type==="preset"&&(a=r.append);let c=s.pathToClaudeCodeExecutable;if(!c){let J=(0,kF.fileURLToPath)(c_e.url),ue=(0,f$.join)(J,"..");c=(0,f$.join)(ue,"cli.js")}process.env.CLAUDE_AGENT_SDK_VERSION="0.1.77";let{abortController:u=$F(),additionalDirectories:l=[],agents:d,allowedTools:p=[],betas:f,canUseTool:m,continue:h,cwd:g,disallowedTools:v=[],tools:S,env:_,executable:y=WF()?"bun":"node",executableArgs:x=[],extraArgs:w={},fallbackModel:E,enableFileCheckpointing:T,forkSession:I,hooks:A,includePartialMessages:N,persistSession:U,maxThinkingTokens:V,maxTurns:j,maxBudgetUsd:ae,mcpServers:Ne,model:ze,outputFormat:Et,permissionMode:Ge="default",allowDangerouslySkipPermissions:K=!1,permissionPromptToolName:C,plugins:H,resume:M,resumeSessionAt:k,stderr:R,strictMcpConfig:F}=s,le=Et?.type==="json_schema"?Et.schema:void 0,ce=_;if(ce||(ce={...process.env}),ce.CLAUDE_CODE_ENTRYPOINT||(ce.CLAUDE_CODE_ENTRYPOINT="sdk-ts"),T&&(ce.CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING="true"),!c)throw new Error("pathToClaudeCodeExecutable is required");let Qe={},Xe=new Map;if(Ne)for(let[J,ue]of Object.entries(Ne))ue.type==="sdk"&&"instance"in ue?(Xe.set(J,ue.instance),Qe[J]={type:"sdk",name:J}):Qe[J]=ue;let Ft=typeof t=="string",P=new h$({abortController:u,additionalDirectories:l,betas:f,cwd:g,executable:y,executableArgs:x,extraArgs:w,pathToClaudeCodeExecutable:c,env:ce,forkSession:I,stderr:R,maxThinkingTokens:V,maxTurns:j,maxBudgetUsd:ae,model:ze,fallbackModel:E,jsonSchema:le,permissionMode:Ge,allowDangerouslySkipPermissions:K,permissionPromptToolName:C,continueConversation:h,resume:M,resumeSessionAt:k,settingSources:n??[],allowedTools:p,disallowedTools:v,tools:S,mcpServers:Qe,strictMcpConfig:F,canUseTool:!!m,hooks:!!A,includePartialMessages:N,persistSession:U,plugins:H,sandbox:i,spawnClaudeCodeProcess:s.spawnClaudeCodeProcess}),D={systemPrompt:o,appendSystemPrompt:a,agents:d},Z=new y$(P,Ft,m,A,u,Xe,le,D);return typeof t=="string"?P.write(Xi({type:"user",session_id:"",message:{role:"user",content:[{type:"text",text:t}]},parent_tool_use_id:null})+` `):Z.streamInput(t),Z}var ny=class{dbManager;sessionManager;constructor(e,r){this.dbManager=e,this.sessionManager=r}async startSession(e,r){let n={lastCwd:void 0},i=this.findClaudeExecutable(),s=this.getModelId(),o=["Bash","Read","Write","Edit","Grep","Glob","WebFetch","WebSearch","Task","NotebookEdit","AskUserQuestion","TodoWrite"],a=this.createMessageGenerator(e,n),c=!!e.memorySessionId,u=c&&e.lastPromptNumber>1&&!e.forceInit;e.forceInit&&(b.info("SDK","forceInit flag set, starting fresh SDK session",{sessionDbId:e.sessionDbId,previousMemorySessionId:e.memorySessionId}),e.forceInit=!1);let l=Ee.loadFromFile(qt),d=parseInt(l.CLAUDE_MEM_MAX_CONCURRENT_AGENTS,10)||2;await R6(d);let p=Ui(pM()),f=Xh();if(b.info("SDK","Starting SDK query",{sessionDbId:e.sessionDbId,contentSessionId:e.contentSessionId,memorySessionId:e.memorySessionId,hasRealMemorySessionId:c,shouldResume:u,resume_parameter:u?e.memorySessionId:"(none - fresh start)",lastPromptNumber:e.lastPromptNumber,authMethod:f}),e.lastPromptNumber>1)b.debug("SDK",`[ALIGNMENT] Resume Decision | contentSessionId=${e.contentSessionId} | memorySessionId=${e.memorySessionId} | prompt#=${e.lastPromptNumber} | hasRealMemorySessionId=${c} | shouldResume=${u} | resumeWith=${u?e.memorySessionId:"NONE"}`);else{let g=c;b.debug("SDK",`[ALIGNMENT] First Prompt (INIT) | contentSessionId=${e.contentSessionId} | prompt#=${e.lastPromptNumber} | hasStaleMemoryId=${g} | action=START_FRESH | Will capture new memorySessionId from SDK response`),g&&b.warn("SDK",`Skipping resume for INIT prompt despite existing memorySessionId=${e.memorySessionId} - SDK context was lost (worker restart or crash recovery)`)}Mr(Kh);let m=d9({prompt:a,options:{model:s,cwd:Kh,...u&&{resume:e.memorySessionId},disallowedTools:o,abortController:e.abortController,pathToClaudeCodeExecutable:i,spawnClaudeCodeProcess:O6(e.sessionDbId),env:p}});try{for await(let g of m){if(g.session_id&&g.session_id!==e.memorySessionId){let v=e.memorySessionId;e.memorySessionId=g.session_id,this.dbManager.getSessionStore().ensureMemorySessionIdRegistered(e.sessionDbId,g.session_id);let S=this.dbManager.getSessionStore().getSessionById(e.sessionDbId),_=S?.memory_session_id===g.session_id,y=v?`MEMORY_ID_CHANGED | sessionDbId=${e.sessionDbId} | from=${v} | to=${g.session_id} | dbVerified=${_}`:`MEMORY_ID_CAPTURED | sessionDbId=${e.sessionDbId} | memorySessionId=${g.session_id} | dbVerified=${_}`;b.info("SESSION",y,{sessionId:e.sessionDbId,memorySessionId:g.session_id,previousId:v}),_||b.error("SESSION",`MEMORY_ID_MISMATCH | sessionDbId=${e.sessionDbId} | expected=${g.session_id} | got=${S?.memory_session_id}`,{sessionId:e.sessionDbId}),b.debug("SDK",`[ALIGNMENT] ${v?"Updated":"Captured"} | contentSessionId=${e.contentSessionId} \u2192 memorySessionId=${g.session_id} | Future prompts will resume with this ID`)}if(g.type==="assistant"){let v=g.message.content,S=Array.isArray(v)?v.filter(T=>T.type==="text").map(T=>T.text).join(` `):typeof v=="string"?v:"";if(S.includes("prompt is too long")||S.includes("context window")){b.error("SDK","Context overflow detected - terminating session"),e.abortController.abort();return}let _=S.length,y=e.cumulativeInputTokens+e.cumulativeOutputTokens,x=g.message.usage;x&&(e.cumulativeInputTokens+=x.input_tokens||0,e.cumulativeOutputTokens+=x.output_tokens||0,x.cache_creation_input_tokens&&(e.cumulativeInputTokens+=x.cache_creation_input_tokens),b.debug("SDK","Token usage captured",{sessionId:e.sessionDbId,inputTokens:x.input_tokens,outputTokens:x.output_tokens,cacheCreation:x.cache_creation_input_tokens||0,cacheRead:x.cache_read_input_tokens||0,cumulativeInput:e.cumulativeInputTokens,cumulativeOutput:e.cumulativeOutputTokens}));let w=e.cumulativeInputTokens+e.cumulativeOutputTokens-y,E=e.earliestPendingTimestamp;if(_>0){let T=_>100?S.substring(0,100)+"...":S;b.dataOut("SDK",`Response received (${_} chars)`,{sessionId:e.sessionDbId,promptNumber:e.lastPromptNumber},T)}if(typeof S=="string"&&S.includes("Prompt is too long"))throw new Error("Claude session context overflow: prompt is too long");if(typeof S=="string"&&S.includes("Invalid API key"))throw new Error("Invalid API key: check your API key configuration in ~/.claude-mem/settings.json or ~/.claude-mem/.env");await _i(S,e,this.dbManager,this.sessionManager,r,w,E,"SDK",n.lastCwd)}g.type==="result"&&g.subtype}}finally{let g=go(e.sessionDbId);g&&g.process.exitCode===null&&await vo(g,5e3)}let h=Date.now()-e.startTime;b.success("SDK","Agent completed",{sessionId:e.sessionDbId,duration:`${(h/1e3).toFixed(1)}s`})}async*createMessageGenerator(e,r){let n=He.getInstance().getActiveMode(),i=e.lastPromptNumber===1;b.info("SDK","Creating message generator",{sessionDbId:e.sessionDbId,contentSessionId:e.contentSessionId,lastPromptNumber:e.lastPromptNumber,isInitPrompt:i,promptType:i?"INIT":"CONTINUATION"});let s=i?au(e.project,e.contentSessionId,e.userPrompt,n):lu(e.userPrompt,e.lastPromptNumber,e.contentSessionId,n);e.conversationHistory.push({role:"user",content:s}),yield{type:"user",message:{role:"user",content:s},session_id:e.contentSessionId,parent_tool_use_id:null,isSynthetic:!0};for await(let o of this.sessionManager.getMessageIterator(e.sessionDbId))if(e.processingMessageIds.push(o._persistentId),o.cwd&&(r.lastCwd=o.cwd),o.type==="observation"){o.prompt_number!==void 0&&(e.lastPromptNumber=o.prompt_number);let a=cu({id:0,tool_name:o.tool_name,tool_input:JSON.stringify(o.tool_input),tool_output:JSON.stringify(o.tool_response),created_at_epoch:Date.now(),cwd:o.cwd});e.conversationHistory.push({role:"user",content:a}),yield{type:"user",message:{role:"user",content:a},session_id:e.contentSessionId,parent_tool_use_id:null,isSynthetic:!0}}else if(o.type==="summarize"){let a=uu({id:e.sessionDbId,memory_session_id:e.memorySessionId,project:e.project,user_prompt:e.userPrompt,last_assistant_message:o.last_assistant_message||""},n);e.conversationHistory.push({role:"user",content:a}),yield{type:"user",message:{role:"user",content:a},session_id:e.contentSessionId,parent_tool_use_id:null,isSynthetic:!0}}}findClaudeExecutable(){let e=Ee.loadFromFile(qt);if(e.CLAUDE_CODE_PATH){let{existsSync:r}=require("fs");if(!r(e.CLAUDE_CODE_PATH))throw new Error(`CLAUDE_CODE_PATH is set to "${e.CLAUDE_CODE_PATH}" but the file does not exist.`);return e.CLAUDE_CODE_PATH}if(process.platform==="win32")try{return(0,X$.execSync)("where claude.cmd",{encoding:"utf8",windowsHide:!0,stdio:["ignore","pipe","ignore"]}),"claude.cmd"}catch{}try{let r=(0,X$.execSync)(process.platform==="win32"?"where claude":"which claude",{encoding:"utf8",windowsHide:!0,stdio:["ignore","pipe","ignore"]}).trim().split(` `)[0].trim();if(r)return r}catch(r){b.debug("SDK","Claude executable auto-detection failed",{},r)}throw new Error(`Claude executable not found. Please either: 1. Add "claude" to your system PATH, or -2. Set CLAUDE_CODE_PATH in ~/.claude-mem/settings.json`)}getModelId(){let e=f9.default.join((0,p9.homedir)(),".claude-mem","settings.json");return Ee.loadFromFile(e).CLAUDE_MEM_MODEL}};var sy=Me(require("path"),1),oy=require("os");ne();rr();Qr();var u_e="https://generativelanguage.googleapis.com/v1/models",l_e={"gemini-2.5-flash-lite":10,"gemini-2.5-flash":10,"gemini-2.5-pro":5,"gemini-2.0-flash":15,"gemini-2.0-flash-lite":30,"gemini-3-flash":10,"gemini-3-flash-preview":5},m9=0;async function d_e(t,e){if(!e)return;let r=l_e[t]||5,n=Math.ceil(6e4/r)+100,s=Date.now()-m9;if(ssetTimeout(a,o))}m9=Date.now()}var iy=class{dbManager;sessionManager;fallbackAgent=null;constructor(e,r){this.dbManager=e,this.sessionManager=r}setFallbackAgent(e){this.fallbackAgent=e}async startSession(e,r){try{let{apiKey:n,model:i,rateLimitingEnabled:s}=this.getGeminiConfig();if(!n)throw new Error("Gemini API key not configured. Set CLAUDE_MEM_GEMINI_API_KEY in settings or GEMINI_API_KEY environment variable.");if(!e.memorySessionId){let d=`gemini-${e.contentSessionId}-${Date.now()}`;e.memorySessionId=d,this.dbManager.getSessionStore().updateMemorySessionId(e.sessionDbId,d),b.info("SESSION",`MEMORY_ID_GENERATED | sessionDbId=${e.sessionDbId} | provider=Gemini`)}let o=He.getInstance().getActiveMode(),a=e.lastPromptNumber===1?au(e.project,e.contentSessionId,e.userPrompt,o):lu(e.userPrompt,e.lastPromptNumber,e.contentSessionId,o);e.conversationHistory.push({role:"user",content:a});let c=await this.queryGeminiMultiTurn(e.conversationHistory,n,i,s);if(c.content){e.conversationHistory.push({role:"assistant",content:c.content});let d=c.tokensUsed||0;e.cumulativeInputTokens+=Math.floor(d*.7),e.cumulativeOutputTokens+=Math.floor(d*.3),await _i(c.content,e,this.dbManager,this.sessionManager,r,d,null,"Gemini")}else b.error("SDK","Empty Gemini init response - session may lack context",{sessionId:e.sessionDbId,model:i});let u;for await(let d of this.sessionManager.getMessageIterator(e.sessionDbId)){e.processingMessageIds.push(d._persistentId),d.cwd&&(u=d.cwd);let p=e.earliestPendingTimestamp;if(d.type==="observation"){if(d.prompt_number!==void 0&&(e.lastPromptNumber=d.prompt_number),!e.memorySessionId)throw new Error("Cannot process observations: memorySessionId not yet captured. This session may need to be reinitialized.");let f=cu({id:0,tool_name:d.tool_name,tool_input:JSON.stringify(d.tool_input),tool_output:JSON.stringify(d.tool_response),created_at_epoch:p??Date.now(),cwd:d.cwd});e.conversationHistory.push({role:"user",content:f});let m=await this.queryGeminiMultiTurn(e.conversationHistory,n,i,s),h=0;m.content&&(e.conversationHistory.push({role:"assistant",content:m.content}),h=m.tokensUsed||0,e.cumulativeInputTokens+=Math.floor(h*.7),e.cumulativeOutputTokens+=Math.floor(h*.3)),m.content?await _i(m.content,e,this.dbManager,this.sessionManager,r,h,p,"Gemini",u):b.warn("SDK","Empty Gemini observation response, skipping processing to preserve message",{sessionId:e.sessionDbId,messageId:e.processingMessageIds[e.processingMessageIds.length-1]})}else if(d.type==="summarize"){if(!e.memorySessionId)throw new Error("Cannot process summary: memorySessionId not yet captured. This session may need to be reinitialized.");let f=uu({id:e.sessionDbId,memory_session_id:e.memorySessionId,project:e.project,user_prompt:e.userPrompt,last_assistant_message:d.last_assistant_message||""},o);e.conversationHistory.push({role:"user",content:f});let m=await this.queryGeminiMultiTurn(e.conversationHistory,n,i,s),h=0;m.content&&(e.conversationHistory.push({role:"assistant",content:m.content}),h=m.tokensUsed||0,e.cumulativeInputTokens+=Math.floor(h*.7),e.cumulativeOutputTokens+=Math.floor(h*.3)),m.content?await _i(m.content,e,this.dbManager,this.sessionManager,r,h,p,"Gemini",u):b.warn("SDK","Empty Gemini summary response, skipping processing to preserve message",{sessionId:e.sessionDbId,messageId:e.processingMessageIds[e.processingMessageIds.length-1]})}}let l=Date.now()-e.startTime;b.success("SDK","Gemini agent completed",{sessionId:e.sessionDbId,duration:`${(l/1e3).toFixed(1)}s`,historyLength:e.conversationHistory.length})}catch(n){if(Pp(n))throw b.warn("SDK","Gemini agent aborted",{sessionId:e.sessionDbId}),n;if(Cp(n)&&this.fallbackAgent)return b.warn("SDK","Gemini API failed, falling back to Claude SDK",{sessionDbId:e.sessionDbId,error:n instanceof Error?n.message:String(n),historyLength:e.conversationHistory.length}),this.fallbackAgent.startSession(e,r);throw b.failure("SDK","Gemini agent error",{sessionDbId:e.sessionDbId},n),n}}conversationToGeminiContents(e){return e.map(r=>({role:r.role==="assistant"?"model":"user",parts:[{text:r.content}]}))}async queryGeminiMultiTurn(e,r,n,i){let s=this.conversationToGeminiContents(e),o=e.reduce((p,f)=>p+f.content.length,0);b.debug("SDK",`Querying Gemini multi-turn (${n})`,{turns:e.length,totalChars:o});let a=`${u_e}/${n}:generateContent?key=${r}`;await d_e(n,i);let c=await fetch(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({contents:s,generationConfig:{temperature:.3,maxOutputTokens:4096}})});if(!c.ok){let p=await c.text();throw new Error(`Gemini API error: ${c.status} - ${p}`)}let u=await c.json();if(!u.candidates?.[0]?.content?.parts?.[0]?.text)return b.error("SDK","Empty response from Gemini"),{content:""};let l=u.candidates[0].content.parts[0].text,d=u.usageMetadata?.totalTokenCount;return{content:l,tokensUsed:d}}getGeminiConfig(){let e=sy.default.join((0,oy.homedir)(),".claude-mem","settings.json"),r=Ee.loadFromFile(e),n=r.CLAUDE_MEM_GEMINI_API_KEY||Rc("GEMINI_API_KEY")||"",i="gemini-2.5-flash",s=r.CLAUDE_MEM_GEMINI_MODEL||i,o=["gemini-2.5-flash-lite","gemini-2.5-flash","gemini-2.5-pro","gemini-2.0-flash","gemini-2.0-flash-lite","gemini-3-flash","gemini-3-flash-preview"],a;o.includes(s)?a=s:(b.warn("SDK",`Invalid Gemini model "${s}", falling back to ${i}`,{configured:s,validModels:o}),a=i);let c=r.CLAUDE_MEM_GEMINI_RATE_LIMITING_ENABLED!=="false";return{apiKey:n,model:a,rateLimitingEnabled:c}}};function wa(){let t=sy.default.join((0,oy.homedir)(),".claude-mem","settings.json");return!!(Ee.loadFromFile(t).CLAUDE_MEM_GEMINI_API_KEY||Rc("GEMINI_API_KEY"))}function Mu(){let t=sy.default.join((0,oy.homedir)(),".claude-mem","settings.json");return Ee.loadFromFile(t).CLAUDE_MEM_PROVIDER==="gemini"}rr();jt();ne();Qr();var p_e="https://openrouter.ai/api/v1/chat/completions",f_e=20,m_e=1e5,h_e=4,ay=class{dbManager;sessionManager;fallbackAgent=null;constructor(e,r){this.dbManager=e,this.sessionManager=r}setFallbackAgent(e){this.fallbackAgent=e}async startSession(e,r){try{let{apiKey:n,model:i,siteUrl:s,appName:o}=this.getOpenRouterConfig();if(!n)throw new Error("OpenRouter API key not configured. Set CLAUDE_MEM_OPENROUTER_API_KEY in settings or OPENROUTER_API_KEY environment variable.");if(!e.memorySessionId){let p=`openrouter-${e.contentSessionId}-${Date.now()}`;e.memorySessionId=p,this.dbManager.getSessionStore().updateMemorySessionId(e.sessionDbId,p),b.info("SESSION",`MEMORY_ID_GENERATED | sessionDbId=${e.sessionDbId} | provider=OpenRouter`)}let a=He.getInstance().getActiveMode(),c=e.lastPromptNumber===1?au(e.project,e.contentSessionId,e.userPrompt,a):lu(e.userPrompt,e.lastPromptNumber,e.contentSessionId,a);e.conversationHistory.push({role:"user",content:c});let u=await this.queryOpenRouterMultiTurn(e.conversationHistory,n,i,s,o);if(u.content){let p=u.tokensUsed||0;e.cumulativeInputTokens+=Math.floor(p*.7),e.cumulativeOutputTokens+=Math.floor(p*.3),await _i(u.content,e,this.dbManager,this.sessionManager,r,p,null,"OpenRouter",void 0)}else b.error("SDK","Empty OpenRouter init response - session may lack context",{sessionId:e.sessionDbId,model:i});let l;for await(let p of this.sessionManager.getMessageIterator(e.sessionDbId)){e.processingMessageIds.push(p._persistentId),p.cwd&&(l=p.cwd);let f=e.earliestPendingTimestamp;if(p.type==="observation"){if(p.prompt_number!==void 0&&(e.lastPromptNumber=p.prompt_number),!e.memorySessionId)throw new Error("Cannot process observations: memorySessionId not yet captured. This session may need to be reinitialized.");let m=cu({id:0,tool_name:p.tool_name,tool_input:JSON.stringify(p.tool_input),tool_output:JSON.stringify(p.tool_response),created_at_epoch:f??Date.now(),cwd:p.cwd});e.conversationHistory.push({role:"user",content:m});let h=await this.queryOpenRouterMultiTurn(e.conversationHistory,n,i,s,o),g=0;h.content&&(g=h.tokensUsed||0,e.cumulativeInputTokens+=Math.floor(g*.7),e.cumulativeOutputTokens+=Math.floor(g*.3)),await _i(h.content||"",e,this.dbManager,this.sessionManager,r,g,f,"OpenRouter",l)}else if(p.type==="summarize"){if(!e.memorySessionId)throw new Error("Cannot process summary: memorySessionId not yet captured. This session may need to be reinitialized.");let m=uu({id:e.sessionDbId,memory_session_id:e.memorySessionId,project:e.project,user_prompt:e.userPrompt,last_assistant_message:p.last_assistant_message||""},a);e.conversationHistory.push({role:"user",content:m});let h=await this.queryOpenRouterMultiTurn(e.conversationHistory,n,i,s,o),g=0;h.content&&(g=h.tokensUsed||0,e.cumulativeInputTokens+=Math.floor(g*.7),e.cumulativeOutputTokens+=Math.floor(g*.3)),await _i(h.content||"",e,this.dbManager,this.sessionManager,r,g,f,"OpenRouter",l)}}let d=Date.now()-e.startTime;b.success("SDK","OpenRouter agent completed",{sessionId:e.sessionDbId,duration:`${(d/1e3).toFixed(1)}s`,historyLength:e.conversationHistory.length,model:i})}catch(n){if(Pp(n))throw b.warn("SDK","OpenRouter agent aborted",{sessionId:e.sessionDbId}),n;if(Cp(n)&&this.fallbackAgent)return b.warn("SDK","OpenRouter API failed, falling back to Claude SDK",{sessionDbId:e.sessionDbId,error:n instanceof Error?n.message:String(n),historyLength:e.conversationHistory.length}),this.fallbackAgent.startSession(e,r);throw b.failure("SDK","OpenRouter agent error",{sessionDbId:e.sessionDbId},n),n}}estimateTokens(e){return Math.ceil(e.length/h_e)}truncateHistory(e){let r=Ee.loadFromFile(qt),n=parseInt(r.CLAUDE_MEM_OPENROUTER_MAX_CONTEXT_MESSAGES)||f_e,i=parseInt(r.CLAUDE_MEM_OPENROUTER_MAX_TOKENS)||m_e;if(e.length<=n&&e.reduce((c,u)=>c+this.estimateTokens(u.content),0)<=i)return e;let s=[],o=0;for(let a=e.length-1;a>=0;a--){let c=e[a],u=this.estimateTokens(c.content);if(s.length>=n||o+u>i){b.warn("SDK","Context window truncated to prevent runaway costs",{originalMessages:e.length,keptMessages:s.length,droppedMessages:a+1,estimatedTokens:o,tokenLimit:i});break}s.unshift(c),o+=u}return s}conversationToOpenAIMessages(e){return e.map(r=>({role:r.role==="assistant"?"assistant":"user",content:r.content}))}async queryOpenRouterMultiTurn(e,r,n,i,s){let o=this.truncateHistory(e),a=this.conversationToOpenAIMessages(o),c=o.reduce((m,h)=>m+h.content.length,0),u=this.estimateTokens(o.map(m=>m.content).join(""));b.debug("SDK",`Querying OpenRouter multi-turn (${n})`,{turns:o.length,totalChars:c,estimatedTokens:u});let l=await fetch(p_e,{method:"POST",headers:{Authorization:`Bearer ${r}`,"HTTP-Referer":i||"https://github.com/thedotmack/claude-mem","X-Title":s||"claude-mem","Content-Type":"application/json"},body:JSON.stringify({model:n,messages:a,temperature:.3,max_tokens:4096})});if(!l.ok){let m=await l.text();throw new Error(`OpenRouter API error: ${l.status} - ${m}`)}let d=await l.json();if(d.error)throw new Error(`OpenRouter API error: ${d.error.code} - ${d.error.message}`);if(!d.choices?.[0]?.message?.content)return b.error("SDK","Empty response from OpenRouter"),{content:""};let p=d.choices[0].message.content,f=d.usage?.total_tokens;if(f){let m=d.usage?.prompt_tokens||0,h=d.usage?.completion_tokens||0,g=m/1e6*3+h/1e6*15;b.info("SDK","OpenRouter API usage",{model:n,inputTokens:m,outputTokens:h,totalTokens:f,estimatedCostUSD:g.toFixed(4),messagesInContext:o.length}),f>5e4&&b.warn("SDK","High token usage detected - consider reducing context",{totalTokens:f,estimatedCost:g.toFixed(4)})}return{content:p,tokensUsed:f}}getOpenRouterConfig(){let e=qt,r=Ee.loadFromFile(e),n=r.CLAUDE_MEM_OPENROUTER_API_KEY||Rc("OPENROUTER_API_KEY")||"",i=r.CLAUDE_MEM_OPENROUTER_MODEL||"xiaomi/mimo-v2-flash:free",s=r.CLAUDE_MEM_OPENROUTER_SITE_URL||"",o=r.CLAUDE_MEM_OPENROUTER_APP_NAME||"claude-mem";return{apiKey:n,model:i,siteUrl:s,appName:o}}};function Ea(){let t=qt;return!!(Ee.loadFromFile(t).CLAUDE_MEM_OPENROUTER_API_KEY||Rc("OPENROUTER_API_KEY"))}function Du(){let t=qt;return Ee.loadFromFile(t).CLAUDE_MEM_PROVIDER==="openrouter"}ne();var cy=class{dbManager;constructor(e){this.dbManager=e}stripProjectPath(e,r){let n=`/${r}/`,i=e.indexOf(n);return i!==-1?e.substring(i+n.length):e}stripProjectPaths(e,r){if(!e)return e;try{let i=JSON.parse(e).map(s=>this.stripProjectPath(s,r));return JSON.stringify(i)}catch(n){return b.debug("WORKER","File paths is plain string, using as-is",{},n),e}}sanitizeObservation(e){return{...e,files_read:this.stripProjectPaths(e.files_read,e.project),files_modified:this.stripProjectPaths(e.files_modified,e.project)}}getObservations(e,r,n){let i=this.paginate("observations","id, memory_session_id, project, type, title, subtitle, narrative, text, facts, concepts, files_read, files_modified, prompt_number, created_at, created_at_epoch",e,r,n);return{...i,items:i.items.map(s=>this.sanitizeObservation(s))}}getSummaries(e,r,n){let i=this.dbManager.getSessionStore().db,s=` +2. Set CLAUDE_CODE_PATH in ~/.claude-mem/settings.json`)}getModelId(){let e=f9.default.join((0,p9.homedir)(),".claude-mem","settings.json");return Ee.loadFromFile(e).CLAUDE_MEM_MODEL}};var sy=Me(require("path"),1),oy=require("os");se();rr();Qr();var u_e="https://generativelanguage.googleapis.com/v1/models",l_e={"gemini-2.5-flash-lite":10,"gemini-2.5-flash":10,"gemini-2.5-pro":5,"gemini-2.0-flash":15,"gemini-2.0-flash-lite":30,"gemini-3-flash":10,"gemini-3-flash-preview":5},m9=0;async function d_e(t,e){if(!e)return;let r=l_e[t]||5,n=Math.ceil(6e4/r)+100,s=Date.now()-m9;if(ssetTimeout(a,o))}m9=Date.now()}var iy=class{dbManager;sessionManager;fallbackAgent=null;constructor(e,r){this.dbManager=e,this.sessionManager=r}setFallbackAgent(e){this.fallbackAgent=e}async startSession(e,r){try{let{apiKey:n,model:i,rateLimitingEnabled:s}=this.getGeminiConfig();if(!n)throw new Error("Gemini API key not configured. Set CLAUDE_MEM_GEMINI_API_KEY in settings or GEMINI_API_KEY environment variable.");if(!e.memorySessionId){let d=`gemini-${e.contentSessionId}-${Date.now()}`;e.memorySessionId=d,this.dbManager.getSessionStore().updateMemorySessionId(e.sessionDbId,d),b.info("SESSION",`MEMORY_ID_GENERATED | sessionDbId=${e.sessionDbId} | provider=Gemini`)}let o=He.getInstance().getActiveMode(),a=e.lastPromptNumber===1?au(e.project,e.contentSessionId,e.userPrompt,o):lu(e.userPrompt,e.lastPromptNumber,e.contentSessionId,o);e.conversationHistory.push({role:"user",content:a});let c=await this.queryGeminiMultiTurn(e.conversationHistory,n,i,s);if(c.content){e.conversationHistory.push({role:"assistant",content:c.content});let d=c.tokensUsed||0;e.cumulativeInputTokens+=Math.floor(d*.7),e.cumulativeOutputTokens+=Math.floor(d*.3),await _i(c.content,e,this.dbManager,this.sessionManager,r,d,null,"Gemini")}else b.error("SDK","Empty Gemini init response - session may lack context",{sessionId:e.sessionDbId,model:i});let u;for await(let d of this.sessionManager.getMessageIterator(e.sessionDbId)){e.processingMessageIds.push(d._persistentId),d.cwd&&(u=d.cwd);let p=e.earliestPendingTimestamp;if(d.type==="observation"){if(d.prompt_number!==void 0&&(e.lastPromptNumber=d.prompt_number),!e.memorySessionId)throw new Error("Cannot process observations: memorySessionId not yet captured. This session may need to be reinitialized.");let f=cu({id:0,tool_name:d.tool_name,tool_input:JSON.stringify(d.tool_input),tool_output:JSON.stringify(d.tool_response),created_at_epoch:p??Date.now(),cwd:d.cwd});e.conversationHistory.push({role:"user",content:f});let m=await this.queryGeminiMultiTurn(e.conversationHistory,n,i,s),h=0;m.content&&(e.conversationHistory.push({role:"assistant",content:m.content}),h=m.tokensUsed||0,e.cumulativeInputTokens+=Math.floor(h*.7),e.cumulativeOutputTokens+=Math.floor(h*.3)),m.content?await _i(m.content,e,this.dbManager,this.sessionManager,r,h,p,"Gemini",u):b.warn("SDK","Empty Gemini observation response, skipping processing to preserve message",{sessionId:e.sessionDbId,messageId:e.processingMessageIds[e.processingMessageIds.length-1]})}else if(d.type==="summarize"){if(!e.memorySessionId)throw new Error("Cannot process summary: memorySessionId not yet captured. This session may need to be reinitialized.");let f=uu({id:e.sessionDbId,memory_session_id:e.memorySessionId,project:e.project,user_prompt:e.userPrompt,last_assistant_message:d.last_assistant_message||""},o);e.conversationHistory.push({role:"user",content:f});let m=await this.queryGeminiMultiTurn(e.conversationHistory,n,i,s),h=0;m.content&&(e.conversationHistory.push({role:"assistant",content:m.content}),h=m.tokensUsed||0,e.cumulativeInputTokens+=Math.floor(h*.7),e.cumulativeOutputTokens+=Math.floor(h*.3)),m.content?await _i(m.content,e,this.dbManager,this.sessionManager,r,h,p,"Gemini",u):b.warn("SDK","Empty Gemini summary response, skipping processing to preserve message",{sessionId:e.sessionDbId,messageId:e.processingMessageIds[e.processingMessageIds.length-1]})}}let l=Date.now()-e.startTime;b.success("SDK","Gemini agent completed",{sessionId:e.sessionDbId,duration:`${(l/1e3).toFixed(1)}s`,historyLength:e.conversationHistory.length})}catch(n){if(Pp(n))throw b.warn("SDK","Gemini agent aborted",{sessionId:e.sessionDbId}),n;if(Cp(n)&&this.fallbackAgent)return b.warn("SDK","Gemini API failed, falling back to Claude SDK",{sessionDbId:e.sessionDbId,error:n instanceof Error?n.message:String(n),historyLength:e.conversationHistory.length}),this.fallbackAgent.startSession(e,r);throw b.failure("SDK","Gemini agent error",{sessionDbId:e.sessionDbId},n),n}}conversationToGeminiContents(e){return e.map(r=>({role:r.role==="assistant"?"model":"user",parts:[{text:r.content}]}))}async queryGeminiMultiTurn(e,r,n,i){let s=this.conversationToGeminiContents(e),o=e.reduce((p,f)=>p+f.content.length,0);b.debug("SDK",`Querying Gemini multi-turn (${n})`,{turns:e.length,totalChars:o});let a=`${u_e}/${n}:generateContent?key=${r}`;await d_e(n,i);let c=await fetch(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({contents:s,generationConfig:{temperature:.3,maxOutputTokens:4096}})});if(!c.ok){let p=await c.text();throw new Error(`Gemini API error: ${c.status} - ${p}`)}let u=await c.json();if(!u.candidates?.[0]?.content?.parts?.[0]?.text)return b.error("SDK","Empty response from Gemini"),{content:""};let l=u.candidates[0].content.parts[0].text,d=u.usageMetadata?.totalTokenCount;return{content:l,tokensUsed:d}}getGeminiConfig(){let e=sy.default.join((0,oy.homedir)(),".claude-mem","settings.json"),r=Ee.loadFromFile(e),n=r.CLAUDE_MEM_GEMINI_API_KEY||Rc("GEMINI_API_KEY")||"",i="gemini-2.5-flash",s=r.CLAUDE_MEM_GEMINI_MODEL||i,o=["gemini-2.5-flash-lite","gemini-2.5-flash","gemini-2.5-pro","gemini-2.0-flash","gemini-2.0-flash-lite","gemini-3-flash","gemini-3-flash-preview"],a;o.includes(s)?a=s:(b.warn("SDK",`Invalid Gemini model "${s}", falling back to ${i}`,{configured:s,validModels:o}),a=i);let c=r.CLAUDE_MEM_GEMINI_RATE_LIMITING_ENABLED!=="false";return{apiKey:n,model:a,rateLimitingEnabled:c}}};function wa(){let t=sy.default.join((0,oy.homedir)(),".claude-mem","settings.json");return!!(Ee.loadFromFile(t).CLAUDE_MEM_GEMINI_API_KEY||Rc("GEMINI_API_KEY"))}function Mu(){let t=sy.default.join((0,oy.homedir)(),".claude-mem","settings.json");return Ee.loadFromFile(t).CLAUDE_MEM_PROVIDER==="gemini"}rr();jt();se();Qr();var p_e="https://openrouter.ai/api/v1/chat/completions",f_e=20,m_e=1e5,h_e=4,ay=class{dbManager;sessionManager;fallbackAgent=null;constructor(e,r){this.dbManager=e,this.sessionManager=r}setFallbackAgent(e){this.fallbackAgent=e}async startSession(e,r){try{let{apiKey:n,model:i,siteUrl:s,appName:o}=this.getOpenRouterConfig();if(!n)throw new Error("OpenRouter API key not configured. Set CLAUDE_MEM_OPENROUTER_API_KEY in settings or OPENROUTER_API_KEY environment variable.");if(!e.memorySessionId){let p=`openrouter-${e.contentSessionId}-${Date.now()}`;e.memorySessionId=p,this.dbManager.getSessionStore().updateMemorySessionId(e.sessionDbId,p),b.info("SESSION",`MEMORY_ID_GENERATED | sessionDbId=${e.sessionDbId} | provider=OpenRouter`)}let a=He.getInstance().getActiveMode(),c=e.lastPromptNumber===1?au(e.project,e.contentSessionId,e.userPrompt,a):lu(e.userPrompt,e.lastPromptNumber,e.contentSessionId,a);e.conversationHistory.push({role:"user",content:c});let u=await this.queryOpenRouterMultiTurn(e.conversationHistory,n,i,s,o);if(u.content){let p=u.tokensUsed||0;e.cumulativeInputTokens+=Math.floor(p*.7),e.cumulativeOutputTokens+=Math.floor(p*.3),await _i(u.content,e,this.dbManager,this.sessionManager,r,p,null,"OpenRouter",void 0)}else b.error("SDK","Empty OpenRouter init response - session may lack context",{sessionId:e.sessionDbId,model:i});let l;for await(let p of this.sessionManager.getMessageIterator(e.sessionDbId)){e.processingMessageIds.push(p._persistentId),p.cwd&&(l=p.cwd);let f=e.earliestPendingTimestamp;if(p.type==="observation"){if(p.prompt_number!==void 0&&(e.lastPromptNumber=p.prompt_number),!e.memorySessionId)throw new Error("Cannot process observations: memorySessionId not yet captured. This session may need to be reinitialized.");let m=cu({id:0,tool_name:p.tool_name,tool_input:JSON.stringify(p.tool_input),tool_output:JSON.stringify(p.tool_response),created_at_epoch:f??Date.now(),cwd:p.cwd});e.conversationHistory.push({role:"user",content:m});let h=await this.queryOpenRouterMultiTurn(e.conversationHistory,n,i,s,o),g=0;h.content&&(g=h.tokensUsed||0,e.cumulativeInputTokens+=Math.floor(g*.7),e.cumulativeOutputTokens+=Math.floor(g*.3)),await _i(h.content||"",e,this.dbManager,this.sessionManager,r,g,f,"OpenRouter",l)}else if(p.type==="summarize"){if(!e.memorySessionId)throw new Error("Cannot process summary: memorySessionId not yet captured. This session may need to be reinitialized.");let m=uu({id:e.sessionDbId,memory_session_id:e.memorySessionId,project:e.project,user_prompt:e.userPrompt,last_assistant_message:p.last_assistant_message||""},a);e.conversationHistory.push({role:"user",content:m});let h=await this.queryOpenRouterMultiTurn(e.conversationHistory,n,i,s,o),g=0;h.content&&(g=h.tokensUsed||0,e.cumulativeInputTokens+=Math.floor(g*.7),e.cumulativeOutputTokens+=Math.floor(g*.3)),await _i(h.content||"",e,this.dbManager,this.sessionManager,r,g,f,"OpenRouter",l)}}let d=Date.now()-e.startTime;b.success("SDK","OpenRouter agent completed",{sessionId:e.sessionDbId,duration:`${(d/1e3).toFixed(1)}s`,historyLength:e.conversationHistory.length,model:i})}catch(n){if(Pp(n))throw b.warn("SDK","OpenRouter agent aborted",{sessionId:e.sessionDbId}),n;if(Cp(n)&&this.fallbackAgent)return b.warn("SDK","OpenRouter API failed, falling back to Claude SDK",{sessionDbId:e.sessionDbId,error:n instanceof Error?n.message:String(n),historyLength:e.conversationHistory.length}),this.fallbackAgent.startSession(e,r);throw b.failure("SDK","OpenRouter agent error",{sessionDbId:e.sessionDbId},n),n}}estimateTokens(e){return Math.ceil(e.length/h_e)}truncateHistory(e){let r=Ee.loadFromFile(qt),n=parseInt(r.CLAUDE_MEM_OPENROUTER_MAX_CONTEXT_MESSAGES)||f_e,i=parseInt(r.CLAUDE_MEM_OPENROUTER_MAX_TOKENS)||m_e;if(e.length<=n&&e.reduce((c,u)=>c+this.estimateTokens(u.content),0)<=i)return e;let s=[],o=0;for(let a=e.length-1;a>=0;a--){let c=e[a],u=this.estimateTokens(c.content);if(s.length>=n||o+u>i){b.warn("SDK","Context window truncated to prevent runaway costs",{originalMessages:e.length,keptMessages:s.length,droppedMessages:a+1,estimatedTokens:o,tokenLimit:i});break}s.unshift(c),o+=u}return s}conversationToOpenAIMessages(e){return e.map(r=>({role:r.role==="assistant"?"assistant":"user",content:r.content}))}async queryOpenRouterMultiTurn(e,r,n,i,s){let o=this.truncateHistory(e),a=this.conversationToOpenAIMessages(o),c=o.reduce((m,h)=>m+h.content.length,0),u=this.estimateTokens(o.map(m=>m.content).join(""));b.debug("SDK",`Querying OpenRouter multi-turn (${n})`,{turns:o.length,totalChars:c,estimatedTokens:u});let l=await fetch(p_e,{method:"POST",headers:{Authorization:`Bearer ${r}`,"HTTP-Referer":i||"https://github.com/thedotmack/claude-mem","X-Title":s||"claude-mem","Content-Type":"application/json"},body:JSON.stringify({model:n,messages:a,temperature:.3,max_tokens:4096})});if(!l.ok){let m=await l.text();throw new Error(`OpenRouter API error: ${l.status} - ${m}`)}let d=await l.json();if(d.error)throw new Error(`OpenRouter API error: ${d.error.code} - ${d.error.message}`);if(!d.choices?.[0]?.message?.content)return b.error("SDK","Empty response from OpenRouter"),{content:""};let p=d.choices[0].message.content,f=d.usage?.total_tokens;if(f){let m=d.usage?.prompt_tokens||0,h=d.usage?.completion_tokens||0,g=m/1e6*3+h/1e6*15;b.info("SDK","OpenRouter API usage",{model:n,inputTokens:m,outputTokens:h,totalTokens:f,estimatedCostUSD:g.toFixed(4),messagesInContext:o.length}),f>5e4&&b.warn("SDK","High token usage detected - consider reducing context",{totalTokens:f,estimatedCost:g.toFixed(4)})}return{content:p,tokensUsed:f}}getOpenRouterConfig(){let e=qt,r=Ee.loadFromFile(e),n=r.CLAUDE_MEM_OPENROUTER_API_KEY||Rc("OPENROUTER_API_KEY")||"",i=r.CLAUDE_MEM_OPENROUTER_MODEL||"xiaomi/mimo-v2-flash:free",s=r.CLAUDE_MEM_OPENROUTER_SITE_URL||"",o=r.CLAUDE_MEM_OPENROUTER_APP_NAME||"claude-mem";return{apiKey:n,model:i,siteUrl:s,appName:o}}};function Ea(){let t=qt;return!!(Ee.loadFromFile(t).CLAUDE_MEM_OPENROUTER_API_KEY||Rc("OPENROUTER_API_KEY"))}function Du(){let t=qt;return Ee.loadFromFile(t).CLAUDE_MEM_PROVIDER==="openrouter"}se();var cy=class{dbManager;constructor(e){this.dbManager=e}stripProjectPath(e,r){let n=`/${r}/`,i=e.indexOf(n);return i!==-1?e.substring(i+n.length):e}stripProjectPaths(e,r){if(!e)return e;try{let i=JSON.parse(e).map(s=>this.stripProjectPath(s,r));return JSON.stringify(i)}catch(n){return b.debug("WORKER","File paths is plain string, using as-is",{},n),e}}sanitizeObservation(e){return{...e,files_read:this.stripProjectPaths(e.files_read,e.project),files_modified:this.stripProjectPaths(e.files_modified,e.project)}}getObservations(e,r,n){let i=this.paginate("observations","id, memory_session_id, project, type, title, subtitle, narrative, text, facts, concepts, files_read, files_modified, prompt_number, created_at, created_at_epoch",e,r,n);return{...i,items:i.items.map(s=>this.sanitizeObservation(s))}}getSummaries(e,r,n){let i=this.dbManager.getSessionStore().db,s=` SELECT ss.id, s.content_session_id as session_id, @@ -1393,10 +1394,10 @@ ${n}`}function Cue(t,e){let r=Zt.default.resolve(t);if(r.includes("/.git/")||r.i SELECT up.id, up.content_session_id, s.project, up.prompt_number, up.prompt_text, up.created_at, up.created_at_epoch FROM user_prompts up JOIN sdk_sessions s ON up.content_session_id = s.content_session_id - `,o=[];n&&(s+=" WHERE s.project = ?",o.push(n)),s+=" ORDER BY up.created_at_epoch DESC LIMIT ? OFFSET ?",o.push(r+1,e);let c=i.prepare(s).all(...o);return{items:c.slice(0,r),hasMore:c.length>r,offset:e,limit:r}}paginate(e,r,n,i,s){let o=this.dbManager.getSessionStore().db,a=`SELECT ${r} FROM ${e}`,c=[];s&&(a+=" WHERE project = ?",c.push(s)),a+=" ORDER BY created_at_epoch DESC LIMIT ? OFFSET ?",c.push(i+1,n);let l=o.prepare(a).all(...c);return{items:l.slice(0,i),hasMore:l.length>i,offset:n,limit:i}}};ne();var uy=class{dbManager;defaultSettings={sidebarOpen:!0,selectedProject:null,theme:"system"};constructor(e){this.dbManager=e}getSettings(){let e=this.dbManager.getSessionStore().db;try{let n=e.prepare("SELECT key, value FROM viewer_settings").all(),i={...this.defaultSettings};for(let s of n){let o=s.key;o in i&&(i[o]=JSON.parse(s.value))}return i}catch(r){return b.debug("WORKER","Failed to load settings, using defaults",{},r),{...this.defaultSettings}}}updateSettings(e){let n=this.dbManager.getSessionStore().db.prepare(` + `,o=[];n&&(s+=" WHERE s.project = ?",o.push(n)),s+=" ORDER BY up.created_at_epoch DESC LIMIT ? OFFSET ?",o.push(r+1,e);let c=i.prepare(s).all(...o);return{items:c.slice(0,r),hasMore:c.length>r,offset:e,limit:r}}paginate(e,r,n,i,s){let o=this.dbManager.getSessionStore().db,a=`SELECT ${r} FROM ${e}`,c=[];s&&(a+=" WHERE project = ?",c.push(s)),a+=" ORDER BY created_at_epoch DESC LIMIT ? OFFSET ?",c.push(i+1,n);let l=o.prepare(a).all(...c);return{items:l.slice(0,i),hasMore:l.length>i,offset:n,limit:i}}};se();var uy=class{dbManager;defaultSettings={sidebarOpen:!0,selectedProject:null,theme:"system"};constructor(e){this.dbManager=e}getSettings(){let e=this.dbManager.getSessionStore().db;try{let n=e.prepare("SELECT key, value FROM viewer_settings").all(),i={...this.defaultSettings};for(let s of n){let o=s.key;o in i&&(i[o]=JSON.parse(s.value))}return i}catch(r){return b.debug("WORKER","Failed to load settings, using defaults",{},r),{...this.defaultSettings}}}updateSettings(e){let n=this.dbManager.getSessionStore().db.prepare(` INSERT OR REPLACE INTO viewer_settings (key, value) VALUES (?, ?) - `);for(let[i,s]of Object.entries(e))n.run(i,JSON.stringify(s));return this.getSettings()}};var h9=require("path");ne();ga();Qr();var zs=class{emptyResult(e){return{results:{observations:[],sessions:[],prompts:[]},usedChroma:e==="chroma"||e==="hybrid",fellBack:!1,strategy:e}}};var Dt={RECENCY_WINDOW_DAYS:90,RECENCY_WINDOW_MS:7776e6,DEFAULT_LIMIT:20,CHROMA_BATCH_SIZE:100};ne();var rf=class extends zs{constructor(r,n){super();this.chromaSync=r;this.sessionStore=n}name="chroma";canHandle(r){return!!r.query&&!!this.chromaSync}async search(r){let{query:n,searchType:i="all",obsType:s,concepts:o,files:a,limit:c=Dt.DEFAULT_LIMIT,project:u,orderBy:l="date_desc"}=r;if(!n)return this.emptyResult("chroma");let d=i==="all"||i==="observations",p=i==="all"||i==="sessions",f=i==="all"||i==="prompts",m=[],h=[],g=[];try{let v=this.buildWhereFilter(i,u);b.debug("SEARCH","ChromaSearchStrategy: Querying Chroma",{query:n,searchType:i});let S=await this.chromaSync.queryChroma(n,Dt.CHROMA_BATCH_SIZE,v);if(b.debug("SEARCH","ChromaSearchStrategy: Chroma returned matches",{matchCount:S.ids.length}),S.ids.length===0)return{results:{observations:[],sessions:[],prompts:[]},usedChroma:!0,fellBack:!1,strategy:"chroma"};let _=this.filterByRecency(S);b.debug("SEARCH","ChromaSearchStrategy: Filtered by recency",{count:_.length});let y=this.categorizeByDocType(_,{searchObservations:d,searchSessions:p,searchPrompts:f});if(y.obsIds.length>0){let x={type:s,concepts:o,files:a,orderBy:l,limit:c,project:u};m=this.sessionStore.getObservationsByIds(y.obsIds,x)}return y.sessionIds.length>0&&(h=this.sessionStore.getSessionSummariesByIds(y.sessionIds,{orderBy:l,limit:c,project:u})),y.promptIds.length>0&&(g=this.sessionStore.getUserPromptsByIds(y.promptIds,{orderBy:l,limit:c,project:u})),b.debug("SEARCH","ChromaSearchStrategy: Hydrated results",{observations:m.length,sessions:h.length,prompts:g.length}),{results:{observations:m,sessions:h,prompts:g},usedChroma:!0,fellBack:!1,strategy:"chroma"}}catch(v){return b.error("SEARCH","ChromaSearchStrategy: Search failed",{},v),{results:{observations:[],sessions:[],prompts:[]},usedChroma:!1,fellBack:!1,strategy:"chroma"}}}buildWhereFilter(r,n){let i;switch(r){case"observations":i={doc_type:"observation"};break;case"sessions":i={doc_type:"session_summary"};break;case"prompts":i={doc_type:"user_prompt"};break;default:i=void 0}if(n){let s={project:n};return i?{$and:[i,s]}:s}return i}filterByRecency(r){let n=Date.now()-Dt.RECENCY_WINDOW_MS,i=new Map;for(let s of r.metadatas)s?.sqlite_id!==void 0&&!i.has(s.sqlite_id)&&i.set(s.sqlite_id,s);return r.ids.map(s=>({id:s,meta:i.get(s)})).filter(s=>s.meta&&s.meta.created_at_epoch>n)}categorizeByDocType(r,n){let i=[],s=[],o=[];for(let a of r){let c=a.meta?.doc_type;c==="observation"&&n.searchObservations?i.push(a.id):c==="session_summary"&&n.searchSessions?s.push(a.id):c==="user_prompt"&&n.searchPrompts&&o.push(a.id)}return{obsIds:i,sessionIds:s,promptIds:o}}};ne();var nf=class extends zs{constructor(r){super();this.sessionSearch=r}name="sqlite";canHandle(r){return!r.query||r.strategyHint==="sqlite"}async search(r){let{searchType:n="all",obsType:i,concepts:s,files:o,limit:a=Dt.DEFAULT_LIMIT,offset:c=0,project:u,dateRange:l,orderBy:d="date_desc"}=r,p=n==="all"||n==="observations",f=n==="all"||n==="sessions",m=n==="all"||n==="prompts",h=[],g=[],v=[],S={limit:a,offset:c,orderBy:d,project:u,dateRange:l};b.debug("SEARCH","SQLiteSearchStrategy: Filter-only query",{searchType:n,hasDateRange:!!l,hasProject:!!u});try{if(p){let _={...S,type:i,concepts:s,files:o};h=this.sessionSearch.searchObservations(void 0,_)}return f&&(g=this.sessionSearch.searchSessions(void 0,S)),m&&(v=this.sessionSearch.searchUserPrompts(void 0,S)),b.debug("SEARCH","SQLiteSearchStrategy: Results",{observations:h.length,sessions:g.length,prompts:v.length}),{results:{observations:h,sessions:g,prompts:v},usedChroma:!1,fellBack:!1,strategy:"sqlite"}}catch(_){return b.error("SEARCH","SQLiteSearchStrategy: Search failed",{},_),this.emptyResult("sqlite")}}findByConcept(r,n){let{limit:i=Dt.DEFAULT_LIMIT,project:s,dateRange:o,orderBy:a="date_desc"}=n;return this.sessionSearch.findByConcept(r,{limit:i,project:s,dateRange:o,orderBy:a})}findByType(r,n){let{limit:i=Dt.DEFAULT_LIMIT,project:s,dateRange:o,orderBy:a="date_desc"}=n;return this.sessionSearch.findByType(r,{limit:i,project:s,dateRange:o,orderBy:a})}findByFile(r,n){let{limit:i=Dt.DEFAULT_LIMIT,project:s,dateRange:o,orderBy:a="date_desc"}=n;return this.sessionSearch.findByFile(r,{limit:i,project:s,dateRange:o,orderBy:a})}};ne();var sf=class extends zs{constructor(r,n,i){super();this.chromaSync=r;this.sessionStore=n;this.sessionSearch=i}name="hybrid";canHandle(r){return!!this.chromaSync&&(!!r.concepts||!!r.files||!!r.type&&!!r.query||r.strategyHint==="hybrid")}async search(r){let{query:n,limit:i=Dt.DEFAULT_LIMIT,project:s}=r;return n?this.emptyResult("hybrid"):this.emptyResult("hybrid")}async findByConcept(r,n){let{limit:i=Dt.DEFAULT_LIMIT,project:s,dateRange:o,orderBy:a}=n,c={limit:i,project:s,dateRange:o,orderBy:a};try{b.debug("SEARCH","HybridSearchStrategy: findByConcept",{concept:r});let u=this.sessionSearch.findByConcept(r,c);if(b.debug("SEARCH","HybridSearchStrategy: Found metadata matches",{count:u.length}),u.length===0)return this.emptyResult("hybrid");let l=u.map(f=>f.id),d=await this.chromaSync.queryChroma(r,Math.min(l.length,Dt.CHROMA_BATCH_SIZE)),p=this.intersectWithRanking(l,d.ids);if(b.debug("SEARCH","HybridSearchStrategy: Ranked by semantic relevance",{count:p.length}),p.length>0){let f=this.sessionStore.getObservationsByIds(p,{limit:i});return f.sort((m,h)=>p.indexOf(m.id)-p.indexOf(h.id)),{results:{observations:f,sessions:[],prompts:[]},usedChroma:!0,fellBack:!1,strategy:"hybrid"}}return this.emptyResult("hybrid")}catch(u){return b.error("SEARCH","HybridSearchStrategy: findByConcept failed",{},u),{results:{observations:this.sessionSearch.findByConcept(r,c),sessions:[],prompts:[]},usedChroma:!1,fellBack:!0,strategy:"hybrid"}}}async findByType(r,n){let{limit:i=Dt.DEFAULT_LIMIT,project:s,dateRange:o,orderBy:a}=n,c={limit:i,project:s,dateRange:o,orderBy:a},u=Array.isArray(r)?r.join(", "):r;try{b.debug("SEARCH","HybridSearchStrategy: findByType",{type:u});let l=this.sessionSearch.findByType(r,c);if(b.debug("SEARCH","HybridSearchStrategy: Found metadata matches",{count:l.length}),l.length===0)return this.emptyResult("hybrid");let d=l.map(m=>m.id),p=await this.chromaSync.queryChroma(u,Math.min(d.length,Dt.CHROMA_BATCH_SIZE)),f=this.intersectWithRanking(d,p.ids);if(b.debug("SEARCH","HybridSearchStrategy: Ranked by semantic relevance",{count:f.length}),f.length>0){let m=this.sessionStore.getObservationsByIds(f,{limit:i});return m.sort((h,g)=>f.indexOf(h.id)-f.indexOf(g.id)),{results:{observations:m,sessions:[],prompts:[]},usedChroma:!0,fellBack:!1,strategy:"hybrid"}}return this.emptyResult("hybrid")}catch(l){return b.error("SEARCH","HybridSearchStrategy: findByType failed",{},l),{results:{observations:this.sessionSearch.findByType(r,c),sessions:[],prompts:[]},usedChroma:!1,fellBack:!0,strategy:"hybrid"}}}async findByFile(r,n){let{limit:i=Dt.DEFAULT_LIMIT,project:s,dateRange:o,orderBy:a}=n,c={limit:i,project:s,dateRange:o,orderBy:a};try{b.debug("SEARCH","HybridSearchStrategy: findByFile",{filePath:r});let u=this.sessionSearch.findByFile(r,c);b.debug("SEARCH","HybridSearchStrategy: Found file matches",{observations:u.observations.length,sessions:u.sessions.length});let l=u.sessions;if(u.observations.length===0)return{observations:[],sessions:l,usedChroma:!1};let d=u.observations.map(m=>m.id),p=await this.chromaSync.queryChroma(r,Math.min(d.length,Dt.CHROMA_BATCH_SIZE)),f=this.intersectWithRanking(d,p.ids);if(b.debug("SEARCH","HybridSearchStrategy: Ranked observations",{count:f.length}),f.length>0){let m=this.sessionStore.getObservationsByIds(f,{limit:i});return m.sort((h,g)=>f.indexOf(h.id)-f.indexOf(g.id)),{observations:m,sessions:l,usedChroma:!0}}return{observations:[],sessions:l,usedChroma:!1}}catch(u){b.error("SEARCH","HybridSearchStrategy: findByFile failed",{},u);let l=this.sessionSearch.findByFile(r,c);return{observations:l.observations,sessions:l.sessions,usedChroma:!1}}}intersectWithRanking(r,n){let i=new Set(r),s=[];for(let o of n)i.has(o)&&!s.includes(o)&&s.push(o);return s}};Qr();ga();var g_e=4,of=class{formatSearchResults(e,r,n=!1){let i=e.observations.length+e.sessions.length+e.prompts.length;if(i===0)return n?this.formatChromaFailureMessage():`No results found matching "${r}"`;let s=this.combineResults(e);s.sort((u,l)=>l.epoch-u.epoch);let o=process.cwd(),a=Os(s,u=>u.created_at),c=[];c.push(`Found ${i} result(s) matching "${r}" (${e.observations.length} obs, ${e.sessions.length} sessions, ${e.prompts.length} prompts)`),c.push("");for(let[u,l]of a){c.push(`### ${u}`),c.push("");let d=new Map;for(let p of l){let f="General";if(p.type==="observation"){let m=p.data;f=vi(m.files_modified,o,m.files_read)}d.has(f)||d.set(f,[]),d.get(f).push(p)}for(let[p,f]of d){c.push(`**${p}**`),c.push(this.formatSearchTableHeader());let m="";for(let h of f)if(h.type==="observation"){let g=this.formatObservationSearchRow(h.data,m);c.push(g.row),m=g.time}else if(h.type==="session"){let g=this.formatSessionSearchRow(h.data,m);c.push(g.row),m=g.time}else{let g=this.formatPromptSearchRow(h.data,m);c.push(g.row),m=g.time}c.push("")}}return c.join(` + `);for(let[i,s]of Object.entries(e))n.run(i,JSON.stringify(s));return this.getSettings()}};var h9=require("path");se();ga();Qr();var zs=class{emptyResult(e){return{results:{observations:[],sessions:[],prompts:[]},usedChroma:e==="chroma"||e==="hybrid",fellBack:!1,strategy:e}}};var Dt={RECENCY_WINDOW_DAYS:90,RECENCY_WINDOW_MS:7776e6,DEFAULT_LIMIT:20,CHROMA_BATCH_SIZE:100};se();var rf=class extends zs{constructor(r,n){super();this.chromaSync=r;this.sessionStore=n}name="chroma";canHandle(r){return!!r.query&&!!this.chromaSync}async search(r){let{query:n,searchType:i="all",obsType:s,concepts:o,files:a,limit:c=Dt.DEFAULT_LIMIT,project:u,orderBy:l="date_desc"}=r;if(!n)return this.emptyResult("chroma");let d=i==="all"||i==="observations",p=i==="all"||i==="sessions",f=i==="all"||i==="prompts",m=[],h=[],g=[];try{let v=this.buildWhereFilter(i,u);b.debug("SEARCH","ChromaSearchStrategy: Querying Chroma",{query:n,searchType:i});let S=await this.chromaSync.queryChroma(n,Dt.CHROMA_BATCH_SIZE,v);if(b.debug("SEARCH","ChromaSearchStrategy: Chroma returned matches",{matchCount:S.ids.length}),S.ids.length===0)return{results:{observations:[],sessions:[],prompts:[]},usedChroma:!0,fellBack:!1,strategy:"chroma"};let _=this.filterByRecency(S);b.debug("SEARCH","ChromaSearchStrategy: Filtered by recency",{count:_.length});let y=this.categorizeByDocType(_,{searchObservations:d,searchSessions:p,searchPrompts:f});if(y.obsIds.length>0){let x={type:s,concepts:o,files:a,orderBy:l,limit:c,project:u};m=this.sessionStore.getObservationsByIds(y.obsIds,x)}return y.sessionIds.length>0&&(h=this.sessionStore.getSessionSummariesByIds(y.sessionIds,{orderBy:l,limit:c,project:u})),y.promptIds.length>0&&(g=this.sessionStore.getUserPromptsByIds(y.promptIds,{orderBy:l,limit:c,project:u})),b.debug("SEARCH","ChromaSearchStrategy: Hydrated results",{observations:m.length,sessions:h.length,prompts:g.length}),{results:{observations:m,sessions:h,prompts:g},usedChroma:!0,fellBack:!1,strategy:"chroma"}}catch(v){return b.error("SEARCH","ChromaSearchStrategy: Search failed",{},v),{results:{observations:[],sessions:[],prompts:[]},usedChroma:!1,fellBack:!1,strategy:"chroma"}}}buildWhereFilter(r,n){let i;switch(r){case"observations":i={doc_type:"observation"};break;case"sessions":i={doc_type:"session_summary"};break;case"prompts":i={doc_type:"user_prompt"};break;default:i=void 0}if(n){let s={project:n};return i?{$and:[i,s]}:s}return i}filterByRecency(r){let n=Date.now()-Dt.RECENCY_WINDOW_MS,i=new Map;for(let s of r.metadatas)s?.sqlite_id!==void 0&&!i.has(s.sqlite_id)&&i.set(s.sqlite_id,s);return r.ids.map(s=>({id:s,meta:i.get(s)})).filter(s=>s.meta&&s.meta.created_at_epoch>n)}categorizeByDocType(r,n){let i=[],s=[],o=[];for(let a of r){let c=a.meta?.doc_type;c==="observation"&&n.searchObservations?i.push(a.id):c==="session_summary"&&n.searchSessions?s.push(a.id):c==="user_prompt"&&n.searchPrompts&&o.push(a.id)}return{obsIds:i,sessionIds:s,promptIds:o}}};se();var nf=class extends zs{constructor(r){super();this.sessionSearch=r}name="sqlite";canHandle(r){return!r.query||r.strategyHint==="sqlite"}async search(r){let{searchType:n="all",obsType:i,concepts:s,files:o,limit:a=Dt.DEFAULT_LIMIT,offset:c=0,project:u,dateRange:l,orderBy:d="date_desc"}=r,p=n==="all"||n==="observations",f=n==="all"||n==="sessions",m=n==="all"||n==="prompts",h=[],g=[],v=[],S={limit:a,offset:c,orderBy:d,project:u,dateRange:l};b.debug("SEARCH","SQLiteSearchStrategy: Filter-only query",{searchType:n,hasDateRange:!!l,hasProject:!!u});try{if(p){let _={...S,type:i,concepts:s,files:o};h=this.sessionSearch.searchObservations(void 0,_)}return f&&(g=this.sessionSearch.searchSessions(void 0,S)),m&&(v=this.sessionSearch.searchUserPrompts(void 0,S)),b.debug("SEARCH","SQLiteSearchStrategy: Results",{observations:h.length,sessions:g.length,prompts:v.length}),{results:{observations:h,sessions:g,prompts:v},usedChroma:!1,fellBack:!1,strategy:"sqlite"}}catch(_){return b.error("SEARCH","SQLiteSearchStrategy: Search failed",{},_),this.emptyResult("sqlite")}}findByConcept(r,n){let{limit:i=Dt.DEFAULT_LIMIT,project:s,dateRange:o,orderBy:a="date_desc"}=n;return this.sessionSearch.findByConcept(r,{limit:i,project:s,dateRange:o,orderBy:a})}findByType(r,n){let{limit:i=Dt.DEFAULT_LIMIT,project:s,dateRange:o,orderBy:a="date_desc"}=n;return this.sessionSearch.findByType(r,{limit:i,project:s,dateRange:o,orderBy:a})}findByFile(r,n){let{limit:i=Dt.DEFAULT_LIMIT,project:s,dateRange:o,orderBy:a="date_desc"}=n;return this.sessionSearch.findByFile(r,{limit:i,project:s,dateRange:o,orderBy:a})}};se();var sf=class extends zs{constructor(r,n,i){super();this.chromaSync=r;this.sessionStore=n;this.sessionSearch=i}name="hybrid";canHandle(r){return!!this.chromaSync&&(!!r.concepts||!!r.files||!!r.type&&!!r.query||r.strategyHint==="hybrid")}async search(r){let{query:n,limit:i=Dt.DEFAULT_LIMIT,project:s}=r;return n?this.emptyResult("hybrid"):this.emptyResult("hybrid")}async findByConcept(r,n){let{limit:i=Dt.DEFAULT_LIMIT,project:s,dateRange:o,orderBy:a}=n,c={limit:i,project:s,dateRange:o,orderBy:a};try{b.debug("SEARCH","HybridSearchStrategy: findByConcept",{concept:r});let u=this.sessionSearch.findByConcept(r,c);if(b.debug("SEARCH","HybridSearchStrategy: Found metadata matches",{count:u.length}),u.length===0)return this.emptyResult("hybrid");let l=u.map(f=>f.id),d=await this.chromaSync.queryChroma(r,Math.min(l.length,Dt.CHROMA_BATCH_SIZE)),p=this.intersectWithRanking(l,d.ids);if(b.debug("SEARCH","HybridSearchStrategy: Ranked by semantic relevance",{count:p.length}),p.length>0){let f=this.sessionStore.getObservationsByIds(p,{limit:i});return f.sort((m,h)=>p.indexOf(m.id)-p.indexOf(h.id)),{results:{observations:f,sessions:[],prompts:[]},usedChroma:!0,fellBack:!1,strategy:"hybrid"}}return this.emptyResult("hybrid")}catch(u){return b.error("SEARCH","HybridSearchStrategy: findByConcept failed",{},u),{results:{observations:this.sessionSearch.findByConcept(r,c),sessions:[],prompts:[]},usedChroma:!1,fellBack:!0,strategy:"hybrid"}}}async findByType(r,n){let{limit:i=Dt.DEFAULT_LIMIT,project:s,dateRange:o,orderBy:a}=n,c={limit:i,project:s,dateRange:o,orderBy:a},u=Array.isArray(r)?r.join(", "):r;try{b.debug("SEARCH","HybridSearchStrategy: findByType",{type:u});let l=this.sessionSearch.findByType(r,c);if(b.debug("SEARCH","HybridSearchStrategy: Found metadata matches",{count:l.length}),l.length===0)return this.emptyResult("hybrid");let d=l.map(m=>m.id),p=await this.chromaSync.queryChroma(u,Math.min(d.length,Dt.CHROMA_BATCH_SIZE)),f=this.intersectWithRanking(d,p.ids);if(b.debug("SEARCH","HybridSearchStrategy: Ranked by semantic relevance",{count:f.length}),f.length>0){let m=this.sessionStore.getObservationsByIds(f,{limit:i});return m.sort((h,g)=>f.indexOf(h.id)-f.indexOf(g.id)),{results:{observations:m,sessions:[],prompts:[]},usedChroma:!0,fellBack:!1,strategy:"hybrid"}}return this.emptyResult("hybrid")}catch(l){return b.error("SEARCH","HybridSearchStrategy: findByType failed",{},l),{results:{observations:this.sessionSearch.findByType(r,c),sessions:[],prompts:[]},usedChroma:!1,fellBack:!0,strategy:"hybrid"}}}async findByFile(r,n){let{limit:i=Dt.DEFAULT_LIMIT,project:s,dateRange:o,orderBy:a}=n,c={limit:i,project:s,dateRange:o,orderBy:a};try{b.debug("SEARCH","HybridSearchStrategy: findByFile",{filePath:r});let u=this.sessionSearch.findByFile(r,c);b.debug("SEARCH","HybridSearchStrategy: Found file matches",{observations:u.observations.length,sessions:u.sessions.length});let l=u.sessions;if(u.observations.length===0)return{observations:[],sessions:l,usedChroma:!1};let d=u.observations.map(m=>m.id),p=await this.chromaSync.queryChroma(r,Math.min(d.length,Dt.CHROMA_BATCH_SIZE)),f=this.intersectWithRanking(d,p.ids);if(b.debug("SEARCH","HybridSearchStrategy: Ranked observations",{count:f.length}),f.length>0){let m=this.sessionStore.getObservationsByIds(f,{limit:i});return m.sort((h,g)=>f.indexOf(h.id)-f.indexOf(g.id)),{observations:m,sessions:l,usedChroma:!0}}return{observations:[],sessions:l,usedChroma:!1}}catch(u){b.error("SEARCH","HybridSearchStrategy: findByFile failed",{},u);let l=this.sessionSearch.findByFile(r,c);return{observations:l.observations,sessions:l.sessions,usedChroma:!1}}}intersectWithRanking(r,n){let i=new Set(r),s=[];for(let o of n)i.has(o)&&!s.includes(o)&&s.push(o);return s}};Qr();ga();var g_e=4,of=class{formatSearchResults(e,r,n=!1){let i=e.observations.length+e.sessions.length+e.prompts.length;if(i===0)return n?this.formatChromaFailureMessage():`No results found matching "${r}"`;let s=this.combineResults(e);s.sort((u,l)=>l.epoch-u.epoch);let o=process.cwd(),a=Os(s,u=>u.created_at),c=[];c.push(`Found ${i} result(s) matching "${r}" (${e.observations.length} obs, ${e.sessions.length} sessions, ${e.prompts.length} prompts)`),c.push("");for(let[u,l]of a){c.push(`### ${u}`),c.push("");let d=new Map;for(let p of l){let f="General";if(p.type==="observation"){let m=p.data;f=vi(m.files_modified,o,m.files_read)}d.has(f)||d.set(f,[]),d.get(f).push(p)}for(let[p,f]of d){c.push(`**${p}**`),c.push(this.formatSearchTableHeader());let m="";for(let h of f)if(h.type==="observation"){let g=this.formatObservationSearchRow(h.data,m);c.push(g.row),m=g.time}else if(h.type==="session"){let g=this.formatSessionSearchRow(h.data,m);c.push(g.row),m=g.time}else{let g=this.formatPromptSearchRow(h.data,m);c.push(g.row),m=g.time}c.push("")}}return c.join(` `)}combineResults(e){return[...e.observations.map(r=>({type:"observation",data:r,epoch:r.created_at_epoch,created_at:r.created_at})),...e.sessions.map(r=>({type:"session",data:r,epoch:r.created_at_epoch,created_at:r.created_at})),...e.prompts.map(r=>({type:"prompt",data:r,epoch:r.created_at_epoch,created_at:r.created_at}))]}formatSearchTableHeader(){return`| ID | Time | T | Title | Read | |----|------|---|-------|------|`}formatTableHeader(){return`| ID | Time | T | Title | Read | Work | |-----|------|---|-------|------|------|`}formatObservationSearchRow(e,r){let n=`#${e.id}`,i=pr(e.created_at_epoch),s=He.getInstance().getTypeIcon(e.type),o=e.title||"Untitled",a=this.estimateReadTokens(e);return{row:`| ${n} | ${i===r?'"':i} | ${s} | ${o} | ~${a} |`,time:i}}formatSessionSearchRow(e,r){let n=`#S${e.id}`,i=pr(e.created_at_epoch),s="\u{1F3AF}",o=e.request||`Session ${e.memory_session_id?.substring(0,8)||"unknown"}`;return{row:`| ${n} | ${i===r?'"':i} | ${s} | ${o} | - |`,time:i}}formatPromptSearchRow(e,r){let n=`#P${e.id}`,i=pr(e.created_at_epoch),s="\u{1F4AC}",o=e.prompt_text.length>60?e.prompt_text.substring(0,57)+"...":e.prompt_text;return{row:`| ${n} | ${i===r?'"':i} | ${s} | ${o} | - |`,time:i}}formatObservationIndex(e,r){let n=`#${e.id}`,i=pr(e.created_at_epoch),s=He.getInstance().getTypeIcon(e.type),o=e.title||"Untitled",a=this.estimateReadTokens(e),c=He.getInstance().getWorkEmoji(e.type),u=e.discovery_tokens||0,l=u>0?`${c} ${u}`:"-";return`| ${n} | ${i} | ${s} | ${o} | ~${a} | ${l} |`}formatSessionIndex(e,r){let n=`#S${e.id}`,i=pr(e.created_at_epoch),s="\u{1F3AF}",o=e.request||`Session ${e.memory_session_id?.substring(0,8)||"unknown"}`;return`| ${n} | ${i} | ${s} | ${o} | - | - |`}formatPromptIndex(e,r){let n=`#P${e.id}`,i=pr(e.created_at_epoch),s="\u{1F4AC}",o=e.prompt_text.length>60?e.prompt_text.substring(0,57)+"...":e.prompt_text;return`| ${n} | ${i} | ${s} | ${o} | - | - |`}estimateReadTokens(e){let r=(e.title?.length||0)+(e.subtitle?.length||0)+(e.narrative?.length||0)+(e.facts?.length||0);return Math.ceil(r/g_e)}formatChromaFailureMessage(){return`Vector search failed - semantic search unavailable. @@ -1416,7 +1417,7 @@ Tips: - Filter by type: obs_type="bugfix,feature" - Filter by date: dateStart="2025-01-01" - Sort: orderBy="date_desc" or "date_asc"`}};Qr();ga();var ka=class{buildTimeline(e){let r=[...e.observations.map(n=>({type:"observation",data:n,epoch:n.created_at_epoch})),...e.sessions.map(n=>({type:"session",data:n,epoch:n.created_at_epoch})),...e.prompts.map(n=>({type:"prompt",data:n,epoch:n.created_at_epoch}))];return r.sort((n,i)=>n.epoch-i.epoch),r}filterByDepth(e,r,n,i,s){if(e.length===0)return e;let o=this.findAnchorIndex(e,r,n);if(o===-1)return e;let a=Math.max(0,o-i),c=Math.min(e.length,o+s+1);return e.slice(a,c)}findAnchorIndex(e,r,n){if(typeof r=="number")return e.findIndex(s=>s.type==="observation"&&s.data.id===r);if(typeof r=="string"&&r.startsWith("S")){let s=parseInt(r.slice(1),10);return e.findIndex(o=>o.type==="session"&&o.data.id===s)}let i=e.findIndex(s=>s.epoch>=n);return i===-1?e.length-1:i}formatTimeline(e,r,n={}){let{query:i,depthBefore:s,depthAfter:o,cwd:a=process.cwd()}=n;if(e.length===0)return i?`Found observation matching "${i}", but no timeline context available.`:"No timeline items found";let c=[];if(i&&r){let d=e.find(f=>f.type==="observation"&&f.data.id===r),p=d?d.data.title||"Untitled":"Unknown";c.push(`# Timeline for query: "${i}"`),c.push(`**Anchor:** Observation #${r} - ${p}`)}else r?c.push(`# Timeline around anchor: ${r}`):c.push("# Timeline");s!==void 0&&o!==void 0?c.push(`**Window:** ${s} records before -> ${o} records after | **Items:** ${e.length}`):c.push(`**Items:** ${e.length}`),c.push("");let u=this.groupByDay(e),l=this.sortDaysChronologically(u);for(let[d,p]of l){c.push(`### ${d}`),c.push("");let f=null,m="",h=!1;for(let g of p){let v=this.isAnchorItem(g,r);if(g.type==="session"){h&&(c.push(""),h=!1,f=null,m="");let S=g.data,_=S.request||"Session summary",y=v?" <- **ANCHOR**":"";c.push(`**\u{1F3AF} #S${S.id}** ${_} (${Rn(g.epoch)})${y}`),c.push("")}else if(g.type==="prompt"){h&&(c.push(""),h=!1,f=null,m="");let S=g.data,_=S.prompt_text.length>100?S.prompt_text.substring(0,100)+"...":S.prompt_text;c.push(`**\u{1F4AC} User Prompt #${S.prompt_number}** (${Rn(g.epoch)})`),c.push(`> ${_}`),c.push("")}else if(g.type==="observation"){let S=g.data,_=vi(S.files_modified,a,S.files_read);_!==f&&(h&&c.push(""),c.push(`**${_}**`),c.push("| ID | Time | T | Title | Tokens |"),c.push("|----|------|---|-------|--------|"),f=_,h=!0,m="");let y=He.getInstance().getTypeIcon(S.type),x=pr(g.epoch),w=S.title||"Untitled",E=du(S.narrative),I=x!==m?x:'"';m=x;let A=v?" <- **ANCHOR**":"";c.push(`| #${S.id} | ${I} | ${y} | ${w}${A} | ~${E} |`)}}h&&c.push("")}return c.join(` -`)}groupByDay(e){let r=new Map;for(let n of e){let i=Rs(n.epoch);r.has(i)||r.set(i,[]),r.get(i).push(n)}return r}sortDaysChronologically(e){return Array.from(e.entries()).sort((r,n)=>{let i=new Date(r[0]).getTime(),s=new Date(n[0]).getTime();return i-s})}isAnchorItem(e,r){return r===null?!1:typeof r=="number"&&e.type==="observation"?e.data.id===r:typeof r=="string"&&r.startsWith("S")&&e.type==="session"?`S${e.data.id}`===r:!1}};ne();var af=class{constructor(e,r,n){this.sessionSearch=e;this.sessionStore=r;this.chromaSync=n;this.sqliteStrategy=new nf(e),n&&(this.chromaStrategy=new rf(n,r),this.hybridStrategy=new sf(n,r,e)),this.resultFormatter=new of,this.timelineBuilder=new ka}chromaStrategy=null;sqliteStrategy;hybridStrategy=null;resultFormatter;timelineBuilder;async search(e){let r=this.normalizeParams(e);return await this.executeWithFallback(r)}async executeWithFallback(e){if(!e.query)return b.debug("SEARCH","Orchestrator: Filter-only query, using SQLite",{}),await this.sqliteStrategy.search(e);if(this.chromaStrategy){b.debug("SEARCH","Orchestrator: Using Chroma semantic search",{});let r=await this.chromaStrategy.search(e);return r.usedChroma?r:(b.debug("SEARCH","Orchestrator: Chroma failed, falling back to SQLite",{}),{...await this.sqliteStrategy.search({...e,query:void 0}),fellBack:!0})}return b.debug("SEARCH","Orchestrator: Chroma not available",{}),{results:{observations:[],sessions:[],prompts:[]},usedChroma:!1,fellBack:!1,strategy:"sqlite"}}async findByConcept(e,r){let n=this.normalizeParams(r);return this.hybridStrategy?await this.hybridStrategy.findByConcept(e,n):{results:{observations:this.sqliteStrategy.findByConcept(e,n),sessions:[],prompts:[]},usedChroma:!1,fellBack:!1,strategy:"sqlite"}}async findByType(e,r){let n=this.normalizeParams(r);return this.hybridStrategy?await this.hybridStrategy.findByType(e,n):{results:{observations:this.sqliteStrategy.findByType(e,n),sessions:[],prompts:[]},usedChroma:!1,fellBack:!1,strategy:"sqlite"}}async findByFile(e,r){let n=this.normalizeParams(r);return this.hybridStrategy?await this.hybridStrategy.findByFile(e,n):{...this.sqliteStrategy.findByFile(e,n),usedChroma:!1}}getTimeline(e,r,n,i,s){let o=this.timelineBuilder.buildTimeline(e);return this.timelineBuilder.filterByDepth(o,r,n,i,s)}formatTimeline(e,r,n={}){return this.timelineBuilder.formatTimeline(e,r,n)}formatSearchResults(e,r,n=!1){return this.resultFormatter.formatSearchResults(e,r,n)}getFormatter(){return this.resultFormatter}getTimelineBuilder(){return this.timelineBuilder}normalizeParams(e){let r={...e};return r.concepts&&typeof r.concepts=="string"&&(r.concepts=r.concepts.split(",").map(n=>n.trim()).filter(Boolean)),r.files&&typeof r.files=="string"&&(r.files=r.files.split(",").map(n=>n.trim()).filter(Boolean)),r.obs_type&&typeof r.obs_type=="string"&&(r.obsType=r.obs_type.split(",").map(n=>n.trim()).filter(Boolean),delete r.obs_type),r.type&&typeof r.type=="string"&&r.type.includes(",")&&(r.type=r.type.split(",").map(n=>n.trim()).filter(Boolean)),r.type&&!r.searchType&&["observations","sessions","prompts"].includes(r.type)&&(r.searchType=r.type,delete r.type),(r.dateStart||r.dateEnd)&&(r.dateRange={start:r.dateStart,end:r.dateEnd},delete r.dateStart,delete r.dateEnd),r}isChromaAvailable(){return!!this.chromaSync}};var ly=class{constructor(e,r,n,i,s){this.sessionSearch=e;this.sessionStore=r;this.chromaSync=n;this.formatter=i;this.timelineService=s;this.orchestrator=new af(e,r,n),this.timelineBuilder=new ka}orchestrator;timelineBuilder;async queryChroma(e,r,n){return this.chromaSync?await this.chromaSync.queryChroma(e,r,n):{ids:[],distances:[],metadatas:[]}}normalizeParams(e){let r={...e};return r.filePath&&!r.files&&(r.files=r.filePath,delete r.filePath),r.concepts&&typeof r.concepts=="string"&&(r.concepts=r.concepts.split(",").map(n=>n.trim()).filter(Boolean)),r.files&&typeof r.files=="string"&&(r.files=r.files.split(",").map(n=>n.trim()).filter(Boolean)),r.obs_type&&typeof r.obs_type=="string"&&(r.obs_type=r.obs_type.split(",").map(n=>n.trim()).filter(Boolean)),r.type&&typeof r.type=="string"&&r.type.includes(",")&&(r.type=r.type.split(",").map(n=>n.trim()).filter(Boolean)),(r.dateStart||r.dateEnd)&&(r.dateRange={start:r.dateStart,end:r.dateEnd},delete r.dateStart,delete r.dateEnd),r.isFolder==="true"?r.isFolder=!0:r.isFolder==="false"&&(r.isFolder=!1),r}async search(e){let r=this.normalizeParams(e),{query:n,type:i,obs_type:s,concepts:o,files:a,format:c,...u}=r,l=[],d=[],p=[],f=!1,m=!i||i==="observations",h=!i||i==="sessions",g=!i||i==="prompts";if(n)if(this.chromaSync){let E=!1;b.debug("SEARCH","Using ChromaDB semantic search",{typeFilter:i||"all"});let T;if(i==="observations"?T={doc_type:"observation"}:i==="sessions"?T={doc_type:"session_summary"}:i==="prompts"&&(T={doc_type:"user_prompt"}),u.project){let A={project:u.project};T=T?{$and:[T,A]}:A}let I=await this.queryChroma(n,100,T);if(E=!0,b.debug("SEARCH","ChromaDB returned semantic matches",{matchCount:I.ids.length}),I.ids.length>0){let{dateRange:A}=u,N,U;A?(A.start&&(N=typeof A.start=="number"?A.start:new Date(A.start).getTime()),A.end&&(U=typeof A.end=="number"?A.end:new Date(A.end).getTime())):N=Date.now()-Dt.RECENCY_WINDOW_MS;let V=I.metadatas.map((ze,Et)=>({id:I.ids[Et],meta:ze,isRecent:ze&&ze.created_at_epoch!=null&&(!N||ze.created_at_epoch>=N)&&(!U||ze.created_at_epoch<=U)})).filter(ze=>ze.isRecent);b.debug("SEARCH",A?"Results within user date range":"Results within 90-day window",{count:V.length});let j=[],ae=[],Ne=[];for(let ze of V){let Et=ze.meta?.doc_type;Et==="observation"&&m?j.push(ze.id):Et==="session_summary"&&h?ae.push(ze.id):Et==="user_prompt"&&g&&Ne.push(ze.id)}if(b.debug("SEARCH","Categorized results by type",{observations:j.length,sessions:ae.length,prompts:p.length}),j.length>0){let ze={...u,type:s,concepts:o,files:a};l=this.sessionStore.getObservationsByIds(j,ze)}ae.length>0&&(d=this.sessionStore.getSessionSummariesByIds(ae,{orderBy:"date_desc",limit:u.limit,project:u.project})),Ne.length>0&&(p=this.sessionStore.getUserPromptsByIds(Ne,{orderBy:"date_desc",limit:u.limit,project:u.project})),b.debug("SEARCH","Hydrated results from SQLite",{observations:l.length,sessions:d.length,prompts:p.length})}else b.debug("SEARCH","ChromaDB found no matches (final result, no FTS5 fallback)",{})}else n&&(f=!0,b.debug("SEARCH","ChromaDB not initialized - semantic search unavailable",{}),b.debug("SEARCH","Install UVX/Python to enable vector search",{url:"https://docs.astral.sh/uv/getting-started/installation/"}),l=[],d=[],p=[]);else{b.debug("SEARCH","Filter-only query (no query text), using direct SQLite filtering",{enablesDateFilters:!0});let E={...u,type:s,concepts:o,files:a};m&&(l=this.sessionSearch.searchObservations(void 0,E)),h&&(d=this.sessionSearch.searchSessions(void 0,u)),g&&(p=this.sessionSearch.searchUserPrompts(void 0,u))}let v=l.length+d.length+p.length;if(c==="json")return{observations:l,sessions:d,prompts:p,totalResults:v,query:n||""};if(v===0)return f?{content:[{type:"text",text:`Vector search failed - semantic search unavailable. +`)}groupByDay(e){let r=new Map;for(let n of e){let i=Rs(n.epoch);r.has(i)||r.set(i,[]),r.get(i).push(n)}return r}sortDaysChronologically(e){return Array.from(e.entries()).sort((r,n)=>{let i=new Date(r[0]).getTime(),s=new Date(n[0]).getTime();return i-s})}isAnchorItem(e,r){return r===null?!1:typeof r=="number"&&e.type==="observation"?e.data.id===r:typeof r=="string"&&r.startsWith("S")&&e.type==="session"?`S${e.data.id}`===r:!1}};se();var af=class{constructor(e,r,n){this.sessionSearch=e;this.sessionStore=r;this.chromaSync=n;this.sqliteStrategy=new nf(e),n&&(this.chromaStrategy=new rf(n,r),this.hybridStrategy=new sf(n,r,e)),this.resultFormatter=new of,this.timelineBuilder=new ka}chromaStrategy=null;sqliteStrategy;hybridStrategy=null;resultFormatter;timelineBuilder;async search(e){let r=this.normalizeParams(e);return await this.executeWithFallback(r)}async executeWithFallback(e){if(!e.query)return b.debug("SEARCH","Orchestrator: Filter-only query, using SQLite",{}),await this.sqliteStrategy.search(e);if(this.chromaStrategy){b.debug("SEARCH","Orchestrator: Using Chroma semantic search",{});let r=await this.chromaStrategy.search(e);return r.usedChroma?r:(b.debug("SEARCH","Orchestrator: Chroma failed, falling back to SQLite",{}),{...await this.sqliteStrategy.search({...e,query:void 0}),fellBack:!0})}return b.debug("SEARCH","Orchestrator: Chroma not available",{}),{results:{observations:[],sessions:[],prompts:[]},usedChroma:!1,fellBack:!1,strategy:"sqlite"}}async findByConcept(e,r){let n=this.normalizeParams(r);return this.hybridStrategy?await this.hybridStrategy.findByConcept(e,n):{results:{observations:this.sqliteStrategy.findByConcept(e,n),sessions:[],prompts:[]},usedChroma:!1,fellBack:!1,strategy:"sqlite"}}async findByType(e,r){let n=this.normalizeParams(r);return this.hybridStrategy?await this.hybridStrategy.findByType(e,n):{results:{observations:this.sqliteStrategy.findByType(e,n),sessions:[],prompts:[]},usedChroma:!1,fellBack:!1,strategy:"sqlite"}}async findByFile(e,r){let n=this.normalizeParams(r);return this.hybridStrategy?await this.hybridStrategy.findByFile(e,n):{...this.sqliteStrategy.findByFile(e,n),usedChroma:!1}}getTimeline(e,r,n,i,s){let o=this.timelineBuilder.buildTimeline(e);return this.timelineBuilder.filterByDepth(o,r,n,i,s)}formatTimeline(e,r,n={}){return this.timelineBuilder.formatTimeline(e,r,n)}formatSearchResults(e,r,n=!1){return this.resultFormatter.formatSearchResults(e,r,n)}getFormatter(){return this.resultFormatter}getTimelineBuilder(){return this.timelineBuilder}normalizeParams(e){let r={...e};return r.concepts&&typeof r.concepts=="string"&&(r.concepts=r.concepts.split(",").map(n=>n.trim()).filter(Boolean)),r.files&&typeof r.files=="string"&&(r.files=r.files.split(",").map(n=>n.trim()).filter(Boolean)),r.obs_type&&typeof r.obs_type=="string"&&(r.obsType=r.obs_type.split(",").map(n=>n.trim()).filter(Boolean),delete r.obs_type),r.type&&typeof r.type=="string"&&r.type.includes(",")&&(r.type=r.type.split(",").map(n=>n.trim()).filter(Boolean)),r.type&&!r.searchType&&["observations","sessions","prompts"].includes(r.type)&&(r.searchType=r.type,delete r.type),(r.dateStart||r.dateEnd)&&(r.dateRange={start:r.dateStart,end:r.dateEnd},delete r.dateStart,delete r.dateEnd),r}isChromaAvailable(){return!!this.chromaSync}};var ly=class{constructor(e,r,n,i,s){this.sessionSearch=e;this.sessionStore=r;this.chromaSync=n;this.formatter=i;this.timelineService=s;this.orchestrator=new af(e,r,n),this.timelineBuilder=new ka}orchestrator;timelineBuilder;async queryChroma(e,r,n){return this.chromaSync?await this.chromaSync.queryChroma(e,r,n):{ids:[],distances:[],metadatas:[]}}normalizeParams(e){let r={...e};return r.filePath&&!r.files&&(r.files=r.filePath,delete r.filePath),r.concepts&&typeof r.concepts=="string"&&(r.concepts=r.concepts.split(",").map(n=>n.trim()).filter(Boolean)),r.files&&typeof r.files=="string"&&(r.files=r.files.split(",").map(n=>n.trim()).filter(Boolean)),r.obs_type&&typeof r.obs_type=="string"&&(r.obs_type=r.obs_type.split(",").map(n=>n.trim()).filter(Boolean)),r.type&&typeof r.type=="string"&&r.type.includes(",")&&(r.type=r.type.split(",").map(n=>n.trim()).filter(Boolean)),(r.dateStart||r.dateEnd)&&(r.dateRange={start:r.dateStart,end:r.dateEnd},delete r.dateStart,delete r.dateEnd),r.isFolder==="true"?r.isFolder=!0:r.isFolder==="false"&&(r.isFolder=!1),r}async search(e){let r=this.normalizeParams(e),{query:n,type:i,obs_type:s,concepts:o,files:a,format:c,...u}=r,l=[],d=[],p=[],f=!1,m=!i||i==="observations",h=!i||i==="sessions",g=!i||i==="prompts";if(n)if(this.chromaSync){let E=!1;b.debug("SEARCH","Using ChromaDB semantic search",{typeFilter:i||"all"});let T;if(i==="observations"?T={doc_type:"observation"}:i==="sessions"?T={doc_type:"session_summary"}:i==="prompts"&&(T={doc_type:"user_prompt"}),u.project){let A={project:u.project};T=T?{$and:[T,A]}:A}let I=await this.queryChroma(n,100,T);if(E=!0,b.debug("SEARCH","ChromaDB returned semantic matches",{matchCount:I.ids.length}),I.ids.length>0){let{dateRange:A}=u,N,U;A?(A.start&&(N=typeof A.start=="number"?A.start:new Date(A.start).getTime()),A.end&&(U=typeof A.end=="number"?A.end:new Date(A.end).getTime())):N=Date.now()-Dt.RECENCY_WINDOW_MS;let V=I.metadatas.map((ze,Et)=>({id:I.ids[Et],meta:ze,isRecent:ze&&ze.created_at_epoch!=null&&(!N||ze.created_at_epoch>=N)&&(!U||ze.created_at_epoch<=U)})).filter(ze=>ze.isRecent);b.debug("SEARCH",A?"Results within user date range":"Results within 90-day window",{count:V.length});let j=[],ae=[],Ne=[];for(let ze of V){let Et=ze.meta?.doc_type;Et==="observation"&&m?j.push(ze.id):Et==="session_summary"&&h?ae.push(ze.id):Et==="user_prompt"&&g&&Ne.push(ze.id)}if(b.debug("SEARCH","Categorized results by type",{observations:j.length,sessions:ae.length,prompts:p.length}),j.length>0){let ze={...u,type:s,concepts:o,files:a};l=this.sessionStore.getObservationsByIds(j,ze)}ae.length>0&&(d=this.sessionStore.getSessionSummariesByIds(ae,{orderBy:"date_desc",limit:u.limit,project:u.project})),Ne.length>0&&(p=this.sessionStore.getUserPromptsByIds(Ne,{orderBy:"date_desc",limit:u.limit,project:u.project})),b.debug("SEARCH","Hydrated results from SQLite",{observations:l.length,sessions:d.length,prompts:p.length})}else b.debug("SEARCH","ChromaDB found no matches (final result, no FTS5 fallback)",{})}else n&&(f=!0,b.debug("SEARCH","ChromaDB not initialized - semantic search unavailable",{}),b.debug("SEARCH","Install UVX/Python to enable vector search",{url:"https://docs.astral.sh/uv/getting-started/installation/"}),l=[],d=[],p=[]);else{b.debug("SEARCH","Filter-only query (no query text), using direct SQLite filtering",{enablesDateFilters:!0});let E={...u,type:s,concepts:o,files:a};m&&(l=this.sessionSearch.searchObservations(void 0,E)),h&&(d=this.sessionSearch.searchSessions(void 0,u)),g&&(p=this.sessionSearch.searchUserPrompts(void 0,u))}let v=l.length+d.length+p.length;if(c==="json")return{observations:l,sessions:d,prompts:p,totalResults:v,query:n||""};if(v===0)return f?{content:[{type:"text",text:`Vector search failed - semantic search unavailable. To enable semantic search: 1. Install uv: https://docs.astral.sh/uv/getting-started/installation/ @@ -1476,23 +1477,23 @@ Tips: \u2022 Sort: orderBy="date_desc" or "date_asc"`}formatTime(e){return new Date(e).toLocaleString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0})}estimateReadTokens(e){let r=(e.title?.length||0)+(e.subtitle?.length||0)+(e.narrative?.length||0)+(e.facts?.length||0);return Math.ceil(r/v_e)}formatObservationIndex(e,r){let n=`#${e.id}`,i=this.formatTime(e.created_at_epoch),s=He.getInstance().getTypeIcon(e.type),o=e.title||"Untitled",a=this.estimateReadTokens(e),c=He.getInstance().getWorkEmoji(e.type),u=e.discovery_tokens||0,l=u>0?`${c} ${u}`:"-";return`| ${n} | ${i} | ${s} | ${o} | ~${a} | ${l} |`}formatSessionIndex(e,r){let n=`#S${e.id}`,i=this.formatTime(e.created_at_epoch),s="\u{1F3AF}",o=e.request||`Session ${e.memory_session_id?.substring(0,8)||"unknown"}`;return`| ${n} | ${i} | ${s} | ${o} | - | - |`}formatUserPromptIndex(e,r){let n=`#P${e.id}`,i=this.formatTime(e.created_at_epoch),s="\u{1F4AC}",o=e.prompt_text.length>60?e.prompt_text.substring(0,57)+"...":e.prompt_text;return`| ${n} | ${i} | ${s} | ${o} | - | - |`}formatTableHeader(){return`| ID | Time | T | Title | Read | Work | |-----|------|---|-------|------|------|`}formatSearchTableHeader(){return`| ID | Time | T | Title | Read | |----|------|---|-------|------|`}formatObservationSearchRow(e,r){let n=`#${e.id}`,i=this.formatTime(e.created_at_epoch),s=He.getInstance().getTypeIcon(e.type),o=e.title||"Untitled",a=this.estimateReadTokens(e);return{row:`| ${n} | ${i===r?"\u2033":i} | ${s} | ${o} | ~${a} |`,time:i}}formatSessionSearchRow(e,r){let n=`#S${e.id}`,i=this.formatTime(e.created_at_epoch),s="\u{1F3AF}",o=e.request||`Session ${e.memory_session_id?.substring(0,8)||"unknown"}`;return{row:`| ${n} | ${i===r?"\u2033":i} | ${s} | ${o} | - |`,time:i}}formatUserPromptSearchRow(e,r){let n=`#P${e.id}`,i=this.formatTime(e.created_at_epoch),s="\u{1F4AC}",o=e.prompt_text.length>60?e.prompt_text.substring(0,57)+"...":e.prompt_text;return{row:`| ${n} | ${i===r?"\u2033":i} | ${s} | ${o} | - |`,time:i}}};Qr();var py=class{buildTimeline(e){let r=[...e.observations.map(n=>({type:"observation",data:n,epoch:n.created_at_epoch})),...e.sessions.map(n=>({type:"session",data:n,epoch:n.created_at_epoch})),...e.prompts.map(n=>({type:"prompt",data:n,epoch:n.created_at_epoch}))];return r.sort((n,i)=>n.epoch-i.epoch),r}filterByDepth(e,r,n,i,s){if(e.length===0)return e;let o=-1;if(typeof r=="number")o=e.findIndex(u=>u.type==="observation"&&u.data.id===r);else if(typeof r=="string"&&r.startsWith("S")){let u=parseInt(r.slice(1),10);o=e.findIndex(l=>l.type==="session"&&l.data.id===u)}else o=e.findIndex(u=>u.epoch>=n),o===-1&&(o=e.length-1);if(o===-1)return e;let a=Math.max(0,o-i),c=Math.min(e.length,o+s+1);return e.slice(a,c)}formatTimeline(e,r,n,i,s){if(e.length===0)return n?`Found observation matching "${n}", but no timeline context available.`:"No timeline items found";let o=[];if(n&&r){let u=e.find(d=>d.type==="observation"&&d.data.id===r),l=u?u.data.title||"Untitled":"Unknown";o.push(`# Timeline for query: "${n}"`),o.push(`**Anchor:** Observation #${r} - ${l}`)}else r?o.push(`# Timeline around anchor: ${r}`):o.push("# Timeline");i!==void 0&&s!==void 0?o.push(`**Window:** ${i} records before \u2192 ${s} records after | **Items:** ${e.length}`):o.push(`**Items:** ${e.length}`),o.push(""),o.push("**Legend:** \u{1F3AF} session-request | \u{1F534} bugfix | \u{1F7E3} feature | \u{1F504} refactor | \u2705 change | \u{1F535} discovery | \u{1F9E0} decision"),o.push("");let a=new Map;for(let u of e){let l=this.formatDate(u.epoch);a.has(l)||a.set(l,[]),a.get(l).push(u)}let c=Array.from(a.entries()).sort((u,l)=>{let d=new Date(u[0]).getTime(),p=new Date(l[0]).getTime();return d-p});for(let[u,l]of c){o.push(`### ${u}`),o.push("");let d=null,p="",f=!1;for(let m of l){let h=typeof r=="number"&&m.type==="observation"&&m.data.id===r||typeof r=="string"&&r.startsWith("S")&&m.type==="session"&&`S${m.data.id}`===r;if(m.type==="session"){f&&(o.push(""),f=!1,d=null,p="");let g=m.data,v=g.request||"Session summary",S=h?" \u2190 **ANCHOR**":"";o.push(`**\u{1F3AF} #S${g.id}** ${v} (${this.formatDateTime(m.epoch)})${S}`),o.push("")}else if(m.type==="prompt"){f&&(o.push(""),f=!1,d=null,p="");let g=m.data,v=g.prompt_text.length>100?g.prompt_text.substring(0,100)+"...":g.prompt_text;o.push(`**\u{1F4AC} User Prompt #${g.prompt_number}** (${this.formatDateTime(m.epoch)})`),o.push(`> ${v}`),o.push("")}else if(m.type==="observation"){let g=m.data,v="General";v!==d&&(f&&o.push(""),o.push(`**${v}**`),o.push("| ID | Time | T | Title | Tokens |"),o.push("|----|------|---|-------|--------|"),d=v,f=!0,p="");let S=this.getTypeIcon(g.type),_=this.formatTime(m.epoch),y=g.title||"Untitled",x=this.estimateTokens(g.narrative),E=_!==p?_:"\u2033";p=_;let T=h?" \u2190 **ANCHOR**":"";o.push(`| #${g.id} | ${E} | ${S} | ${y}${T} | ~${x} |`)}}f&&o.push("")}return o.join(` -`)}getTypeIcon(e){return He.getInstance().getTypeIcon(e)}formatDate(e){return new Date(e).toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric"})}formatTime(e){return new Date(e).toLocaleString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0})}formatDateTime(e){return new Date(e).toLocaleString("en-US",{month:"short",day:"numeric",hour:"numeric",minute:"2-digit",hour12:!0})}estimateTokens(e){return e?Math.ceil(e.length/4):0}};var fy=class{constructor(e,r){this.sseBroadcaster=e;this.workerService=r}broadcastNewPrompt(e){this.sseBroadcaster.broadcast({type:"new_prompt",prompt:e}),this.workerService.broadcastProcessingStatus()}broadcastSessionStarted(e,r){this.sseBroadcaster.broadcast({type:"session_started",sessionDbId:e,project:r}),this.workerService.broadcastProcessingStatus()}broadcastObservationQueued(e){this.sseBroadcaster.broadcast({type:"observation_queued",sessionDbId:e}),this.workerService.broadcastProcessingStatus()}broadcastSessionCompleted(e){this.sseBroadcaster.broadcast({type:"session_completed",timestamp:Date.now(),sessionDbId:e}),this.workerService.broadcastProcessingStatus()}broadcastSummarizeQueued(){this.workerService.broadcastProcessingStatus()}};var g9=Me(hv(),1),my=Me(require("path"),1),gy=require("fs");jt();ne();var Ur=class{wrapHandler(e){return(r,n)=>{try{let i=e(r,n);i instanceof Promise&&i.catch(s=>this.handleError(n,s))}catch(i){b.error("HTTP","Route handler error",{path:r.path},i),this.handleError(n,i)}}}parseIntParam(e,r,n){let i=parseInt(e.params[n],10);return isNaN(i)?(this.badRequest(r,`Invalid ${n}`),null):i}validateRequired(e,r,n){for(let i of n)if(e.body[i]===void 0||e.body[i]===null)return this.badRequest(r,`Missing ${i}`),!1;return!0}badRequest(e,r){e.status(400).json({error:r})}notFound(e,r){e.status(404).json({error:r})}handleError(e,r,n){b.failure("WORKER",n||"Request failed",{},r),e.headersSent||e.status(500).json({error:r.message})}};var hy=class extends Ur{constructor(r,n,i){super();this.sseBroadcaster=r;this.dbManager=n;this.sessionManager=i}setupRoutes(r){let n=dn();r.use(g9.default.static(my.default.join(n,"ui"))),r.get("/health",this.handleHealth.bind(this)),r.get("/",this.handleViewerUI.bind(this)),r.get("/stream",this.handleSSEStream.bind(this))}handleHealth=this.wrapHandler((r,n)=>{n.json({status:"ok",timestamp:Date.now()})});handleViewerUI=this.wrapHandler((r,n)=>{let i=dn(),o=[my.default.join(i,"ui","viewer.html"),my.default.join(i,"plugin","ui","viewer.html")].find(c=>(0,gy.existsSync)(c));if(!o)throw new Error("Viewer UI not found at any expected location");let a=(0,gy.readFileSync)(o,"utf-8");n.setHeader("Content-Type","text/html"),n.send(a)});handleSSEStream=this.wrapHandler((r,n)=>{n.setHeader("Content-Type","text/event-stream"),n.setHeader("Cache-Control","no-cache"),n.setHeader("Connection","keep-alive"),this.sseBroadcaster.addClient(n);let i=this.dbManager.getSessionStore().getAllProjects();this.sseBroadcaster.broadcast({type:"initial_load",projects:i,timestamp:Date.now()});let s=this.sessionManager.isAnySessionProcessing(),o=this.sessionManager.getTotalActiveWork();this.sseBroadcaster.broadcast({type:"processing_status",isProcessing:s,queueDepth:o})})};Dr();ne();ne();var v9=100;function y_e(t){let e=(t.match(//g)||[]).length,r=(t.match(//g)||[]).length,n=(t.match(//g)||[]).length,i=(t.match(//g)||[]).length;return e+r+n+i}function y9(t){let e=y_e(t);return e>v9&&b.warn("SYSTEM","tag count exceeds limit",void 0,{tagCount:e,maxAllowed:v9,contentLength:t.length}),t.replace(/[\s\S]*?<\/claude-mem-context>/g,"").replace(/[\s\S]*?<\/private>/g,"").replace(/[\s\S]*?<\/system_instruction>/g,"").replace(/[\s\S]*?<\/system-instruction>/g,"").trim()}function Y$(t){return y9(t)}function _9(t){return y9(t)}var vy=class{constructor(e,r){this.sessionManager=e;this.eventBroadcaster=r}async completeByDbId(e){await this.sessionManager.deleteSession(e),this.eventBroadcaster.broadcastSessionCompleted(e)}};ne();var cf=class{static checkUserPromptPrivacy(e,r,n,i,s,o){let a=e.getUserPrompt(r,n);return!a||a.trim()===""?(b.debug("HOOK",`Skipping ${i} - user prompt was entirely private`,{sessionId:s,promptNumber:n,...o}),null):a}};rr();jt();var yy=class t extends Ur{constructor(r,n,i,s,o,a,c){super();this.sessionManager=r;this.dbManager=n;this.sdkAgent=i;this.geminiAgent=s;this.openRouterAgent=o;this.eventBroadcaster=a;this.workerService=c;this.completionHandler=new vy(r,a)}completionHandler;spawnInProgress=new Map;crashRecoveryScheduled=new Set;getActiveAgent(){if(Du()){if(Ea())return b.debug("SESSION","Using OpenRouter agent"),this.openRouterAgent;throw new Error("OpenRouter provider selected but no API key configured. Set CLAUDE_MEM_OPENROUTER_API_KEY in settings or OPENROUTER_API_KEY environment variable.")}if(Mu()){if(wa())return b.debug("SESSION","Using Gemini agent"),this.geminiAgent;throw new Error("Gemini provider selected but no API key configured. Set CLAUDE_MEM_GEMINI_API_KEY in settings or GEMINI_API_KEY environment variable.")}return this.sdkAgent}getSelectedProvider(){return Du()&&Ea()?"openrouter":Mu()&&wa()?"gemini":"claude"}static STALE_GENERATOR_THRESHOLD_MS=3e4;ensureGeneratorRunning(r,n){let i=this.sessionManager.getSession(r);if(!i)return;if(this.spawnInProgress.get(r)){b.debug("SESSION","Spawn already in progress, skipping",{sessionDbId:r,source:n});return}let s=this.getSelectedProvider();if(!i.generatorPromise){this.spawnInProgress.set(r,!0),this.startGeneratorWithProvider(i,s,n);return}let o=Date.now()-i.lastGeneratorActivity;if(o>t.STALE_GENERATOR_THRESHOLD_MS){b.warn("SESSION","Stale generator detected, aborting to prevent queue stall (#1099)",{sessionId:r,timeSinceActivityMs:o,thresholdMs:t.STALE_GENERATOR_THRESHOLD_MS,source:n}),i.abortController.abort(),i.generatorPromise=null,i.abortController=new AbortController,i.lastGeneratorActivity=Date.now(),this.spawnInProgress.set(r,!0),this.startGeneratorWithProvider(i,s,"stale-recovery");return}i.currentProvider&&i.currentProvider!==s&&b.info("SESSION","Provider changed, will switch after current generator finishes",{sessionId:r,currentProvider:i.currentProvider,selectedProvider:s,historyLength:i.conversationHistory.length})}startGeneratorWithProvider(r,n,i){if(!r)return;r.abortController.signal.aborted&&(b.debug("SESSION","Resetting aborted AbortController before starting generator",{sessionId:r.sessionDbId}),r.abortController=new AbortController);let s=n==="openrouter"?this.openRouterAgent:n==="gemini"?this.geminiAgent:this.sdkAgent,o=n==="openrouter"?"OpenRouter":n==="gemini"?"Gemini":"Claude SDK",c=this.sessionManager.getPendingMessageStore().getPendingCount(r.sessionDbId);b.info("SESSION",`Generator auto-starting (${i}) using ${o}`,{sessionId:r.sessionDbId,queueDepth:c,historyLength:r.conversationHistory.length}),r.currentProvider=n,r.lastGeneratorActivity=Date.now(),r.generatorPromise=s.startSession(r,this.workerService).catch(u=>{if(r.abortController.signal.aborted)return;b.error("SESSION","Generator failed",{sessionId:r.sessionDbId,provider:n,error:u.message},u);let l=this.sessionManager.getPendingMessageStore();try{let d=l.markSessionMessagesFailed(r.sessionDbId);d>0&&b.error("SESSION","Marked messages as failed after generator error",{sessionId:r.sessionDbId,failedCount:d})}catch(d){b.error("SESSION","Failed to mark messages as failed",{sessionId:r.sessionDbId},d)}}).finally(async()=>{let u=go(r.sessionDbId);u&&!u.process.killed&&u.process.exitCode===null&&await vo(u,5e3);let l=r.sessionDbId;this.spawnInProgress.delete(l);let d=r.abortController.signal.aborted;if(d?b.info("SESSION","Generator aborted",{sessionId:l}):b.error("SESSION","Generator exited unexpectedly",{sessionId:l}),r.generatorPromise=null,r.currentProvider=null,this.workerService.broadcastProcessingStatus(),!d)try{let f=this.sessionManager.getPendingMessageStore().getPendingCount(l),m=3;if(f>0){if(this.crashRecoveryScheduled.has(l)){b.debug("SESSION","Crash recovery already scheduled",{sessionDbId:l});return}if(r.consecutiveRestarts=(r.consecutiveRestarts||0)+1,r.consecutiveRestarts>m){b.error("SESSION","CRITICAL: Generator restart limit exceeded - stopping to prevent runaway costs",{sessionId:l,pendingCount:f,consecutiveRestarts:r.consecutiveRestarts,maxRestarts:m,action:"Generator will NOT restart. Check logs for root cause. Messages remain in pending state."}),r.abortController.abort();return}b.info("SESSION","Restarting generator after crash/exit with pending work",{sessionId:l,pendingCount:f,consecutiveRestarts:r.consecutiveRestarts,maxRestarts:m});let h=r.abortController;r.abortController=new AbortController,h.abort(),this.crashRecoveryScheduled.add(l);let g=Math.min(1e3*Math.pow(2,r.consecutiveRestarts-1),8e3);setTimeout(()=>{this.crashRecoveryScheduled.delete(l);let v=this.sessionManager.getSession(l);v&&!v.generatorPromise&&this.startGeneratorWithProvider(v,this.getSelectedProvider(),"crash-recovery")},g)}else r.abortController.abort(),r.consecutiveRestarts=0,b.debug("SESSION","Aborted controller after natural completion",{sessionId:l})}catch(p){b.debug("SESSION","Error during recovery check, aborting to prevent leaks",{sessionId:l,error:p instanceof Error?p.message:String(p)}),r.abortController.abort()}})}setupRoutes(r){r.post("/sessions/:sessionDbId/init",this.handleSessionInit.bind(this)),r.post("/sessions/:sessionDbId/observations",this.handleObservations.bind(this)),r.post("/sessions/:sessionDbId/summarize",this.handleSummarize.bind(this)),r.get("/sessions/:sessionDbId/status",this.handleSessionStatus.bind(this)),r.delete("/sessions/:sessionDbId",this.handleSessionDelete.bind(this)),r.post("/sessions/:sessionDbId/complete",this.handleSessionComplete.bind(this)),r.post("/api/sessions/init",this.handleSessionInitByClaudeId.bind(this)),r.post("/api/sessions/observations",this.handleObservationsByClaudeId.bind(this)),r.post("/api/sessions/summarize",this.handleSummarizeByClaudeId.bind(this)),r.post("/api/sessions/complete",this.handleCompleteByClaudeId.bind(this)),r.get("/api/sessions/status",this.handleStatusByClaudeId.bind(this))}handleSessionInit=this.wrapHandler((r,n)=>{let i=this.parseIntParam(r,n,"sessionDbId");if(i===null)return;let{userPrompt:s,promptNumber:o}=r.body;b.info("HTTP","SessionRoutes: handleSessionInit called",{sessionDbId:i,promptNumber:o,has_userPrompt:!!s});let a=this.sessionManager.initializeSession(i,s,o),c=this.dbManager.getSessionStore().getLatestUserPrompt(a.contentSessionId);if(c){this.eventBroadcaster.broadcastNewPrompt({id:c.id,content_session_id:c.content_session_id,project:c.project,prompt_number:c.prompt_number,prompt_text:c.prompt_text,created_at_epoch:c.created_at_epoch});let u=Date.now(),l=c.prompt_text;this.dbManager.getChromaSync()?.syncUserPrompt(c.id,c.memory_session_id,c.project,l,c.prompt_number,c.created_at_epoch).then(()=>{let d=Date.now()-u,p=l.length>60?l.substring(0,60)+"...":l;b.debug("CHROMA","User prompt synced",{promptId:c.id,duration:`${d}ms`,prompt:p})}).catch(d=>{b.error("CHROMA","User prompt sync failed, continuing without vector search",{promptId:c.id,prompt:l.length>60?l.substring(0,60)+"...":l},d)})}this.ensureGeneratorRunning(i,"init"),this.eventBroadcaster.broadcastSessionStarted(i,a.project),n.json({status:"initialized",sessionDbId:i,port:Jr()})});handleObservations=this.wrapHandler((r,n)=>{let i=this.parseIntParam(r,n,"sessionDbId");if(i===null)return;let{tool_name:s,tool_input:o,tool_response:a,prompt_number:c,cwd:u}=r.body;this.sessionManager.queueObservation(i,{tool_name:s,tool_input:o,tool_response:a,prompt_number:c,cwd:u}),this.ensureGeneratorRunning(i,"observation"),this.eventBroadcaster.broadcastObservationQueued(i),n.json({status:"queued"})});handleSummarize=this.wrapHandler((r,n)=>{let i=this.parseIntParam(r,n,"sessionDbId");if(i===null)return;let{last_assistant_message:s}=r.body;this.sessionManager.queueSummarize(i,s),this.ensureGeneratorRunning(i,"summarize"),this.eventBroadcaster.broadcastSummarizeQueued(),n.json({status:"queued"})});handleSessionStatus=this.wrapHandler((r,n)=>{let i=this.parseIntParam(r,n,"sessionDbId");if(i===null)return;let s=this.sessionManager.getSession(i);if(!s){n.json({status:"not_found"});return}let a=this.sessionManager.getPendingMessageStore().getPendingCount(i);n.json({status:"active",sessionDbId:i,project:s.project,queueLength:a,uptime:Date.now()-s.startTime})});handleSessionDelete=this.wrapHandler(async(r,n)=>{let i=this.parseIntParam(r,n,"sessionDbId");i!==null&&(await this.completionHandler.completeByDbId(i),n.json({status:"deleted"}))});handleSessionComplete=this.wrapHandler(async(r,n)=>{let i=this.parseIntParam(r,n,"sessionDbId");i!==null&&(await this.completionHandler.completeByDbId(i),n.json({success:!0}))});handleObservationsByClaudeId=this.wrapHandler((r,n)=>{let{contentSessionId:i,tool_name:s,tool_input:o,tool_response:a,cwd:c}=r.body;if(!i)return this.badRequest(n,"Missing contentSessionId");let u=Ee.loadFromFile(qt);if(new Set(u.CLAUDE_MEM_SKIP_TOOLS.split(",").map(p=>p.trim()).filter(Boolean)).has(s)){b.debug("SESSION","Skipping observation for tool",{tool_name:s}),n.json({status:"skipped",reason:"tool_excluded"});return}if(new Set(["Edit","Write","Read","NotebookEdit"]).has(s)&&o){let p=o.file_path||o.notebook_path;if(p&&p.includes("session-memory")){b.debug("SESSION","Skipping meta-observation for session-memory file",{tool_name:s,file_path:p}),n.json({status:"skipped",reason:"session_memory_meta"});return}}try{let p=this.dbManager.getSessionStore(),f=p.createSDKSession(i,"",""),m=p.getPromptNumberFromUserPrompts(i);if(!cf.checkUserPromptPrivacy(p,i,m,"observation",f,{tool_name:s})){n.json({status:"skipped",reason:"private"});return}let g=o!==void 0?Y$(JSON.stringify(o)):"{}",v=a!==void 0?Y$(JSON.stringify(a)):"{}";this.sessionManager.queueObservation(f,{tool_name:s,tool_input:g,tool_response:v,prompt_number:m,cwd:c||(b.error("SESSION","Missing cwd when queueing observation in SessionRoutes",{sessionId:f,tool_name:s}),"")}),this.ensureGeneratorRunning(f,"observation"),this.eventBroadcaster.broadcastObservationQueued(f),n.json({status:"queued"})}catch(p){b.error("SESSION","Observation storage failed",{contentSessionId:i,tool_name:s},p),n.json({stored:!1,reason:p.message})}});handleSummarizeByClaudeId=this.wrapHandler((r,n)=>{let{contentSessionId:i,last_assistant_message:s}=r.body;if(!i)return this.badRequest(n,"Missing contentSessionId");let o=this.dbManager.getSessionStore(),a=o.createSDKSession(i,"",""),c=o.getPromptNumberFromUserPrompts(i);if(!cf.checkUserPromptPrivacy(o,i,c,"summarize",a)){n.json({status:"skipped",reason:"private"});return}this.sessionManager.queueSummarize(a,s),this.ensureGeneratorRunning(a,"summarize"),this.eventBroadcaster.broadcastSummarizeQueued(),n.json({status:"queued"})});handleStatusByClaudeId=this.wrapHandler((r,n)=>{let i=r.query.contentSessionId;if(!i)return this.badRequest(n,"Missing contentSessionId query parameter");let o=this.dbManager.getSessionStore().createSDKSession(i,"",""),a=this.sessionManager.getSession(o);if(!a){n.json({status:"not_found",queueLength:0});return}let u=this.sessionManager.getPendingMessageStore().getPendingCount(o);n.json({status:"active",sessionDbId:o,queueLength:u,uptime:Date.now()-a.startTime})});handleCompleteByClaudeId=this.wrapHandler(async(r,n)=>{let{contentSessionId:i}=r.body;if(b.info("HTTP","\u2192 POST /api/sessions/complete",{contentSessionId:i}),!i)return this.badRequest(n,"Missing contentSessionId");let o=this.dbManager.getSessionStore().createSDKSession(i,"","");if(!this.sessionManager.getSession(o)){b.debug("SESSION","session-complete: Session not in active map",{contentSessionId:i,sessionDbId:o}),n.json({status:"skipped",reason:"not_active"});return}await this.completionHandler.completeByDbId(o),b.info("SESSION","Session completed via API",{contentSessionId:i,sessionDbId:o}),n.json({status:"completed",sessionDbId:o})});handleSessionInitByClaudeId=this.wrapHandler((r,n)=>{let{contentSessionId:i}=r.body,s=r.body.project||"unknown",o=r.body.prompt||"[media prompt]",a=r.body.customTitle||void 0;if(b.info("HTTP","SessionRoutes: handleSessionInitByClaudeId called",{contentSessionId:i,project:s,prompt_length:o?.length,customTitle:a}),!this.validateRequired(r,n,["contentSessionId"]))return;let c=this.dbManager.getSessionStore(),u=c.createSDKSession(i,s,o,a),l=c.getSessionById(u),d=!l?.memory_session_id;b.info("SESSION",`CREATED | contentSessionId=${i} \u2192 sessionDbId=${u} | isNew=${d} | project=${s}`,{sessionId:u});let f=c.getPromptNumberFromUserPrompts(i)+1,m=l?.memory_session_id||null;f>1?b.debug("HTTP",`[ALIGNMENT] DB Lookup Proof | contentSessionId=${i} \u2192 memorySessionId=${m||"(not yet captured)"} | prompt#=${f}`):b.debug("HTTP",`[ALIGNMENT] New Session | contentSessionId=${i} | prompt#=${f} | memorySessionId will be captured on first SDK response`);let h=_9(o);if(!h||h.trim()===""){b.debug("HOOK","Session init - prompt entirely private",{sessionId:u,promptNumber:f,originalLength:o.length}),n.json({sessionDbId:u,promptNumber:f,skipped:!0,reason:"private"});return}c.saveUserPrompt(i,f,h);let g=this.sessionManager.getSession(u)!==void 0;b.debug("SESSION","User prompt saved",{sessionId:u,promptNumber:f,contextInjected:g}),n.json({sessionDbId:u,promptNumber:f,skipped:!1,contextInjected:g})})};var Q$=Me(require("path"),1),ju=require("fs");ne();var b9=require("os");jt();Dr();var _y=class extends Ur{constructor(r,n,i,s,o,a){super();this.paginationHelper=r;this.dbManager=n;this.sessionManager=i;this.sseBroadcaster=s;this.workerService=o;this.startTime=a}setupRoutes(r){r.get("/api/observations",this.handleGetObservations.bind(this)),r.get("/api/summaries",this.handleGetSummaries.bind(this)),r.get("/api/prompts",this.handleGetPrompts.bind(this)),r.get("/api/observation/:id",this.handleGetObservationById.bind(this)),r.post("/api/observations/batch",this.handleGetObservationsByIds.bind(this)),r.get("/api/session/:id",this.handleGetSessionById.bind(this)),r.post("/api/sdk-sessions/batch",this.handleGetSdkSessionsByIds.bind(this)),r.get("/api/prompt/:id",this.handleGetPromptById.bind(this)),r.get("/api/stats",this.handleGetStats.bind(this)),r.get("/api/projects",this.handleGetProjects.bind(this)),r.get("/api/processing-status",this.handleGetProcessingStatus.bind(this)),r.post("/api/processing",this.handleSetProcessing.bind(this)),r.get("/api/pending-queue",this.handleGetPendingQueue.bind(this)),r.post("/api/pending-queue/process",this.handleProcessPendingQueue.bind(this)),r.delete("/api/pending-queue/failed",this.handleClearFailedQueue.bind(this)),r.delete("/api/pending-queue/all",this.handleClearAllQueue.bind(this)),r.post("/api/import",this.handleImport.bind(this))}handleGetObservations=this.wrapHandler((r,n)=>{let{offset:i,limit:s,project:o}=this.parsePaginationParams(r),a=this.paginationHelper.getObservations(i,s,o);n.json(a)});handleGetSummaries=this.wrapHandler((r,n)=>{let{offset:i,limit:s,project:o}=this.parsePaginationParams(r),a=this.paginationHelper.getSummaries(i,s,o);n.json(a)});handleGetPrompts=this.wrapHandler((r,n)=>{let{offset:i,limit:s,project:o}=this.parsePaginationParams(r),a=this.paginationHelper.getPrompts(i,s,o);n.json(a)});handleGetObservationById=this.wrapHandler((r,n)=>{let i=this.parseIntParam(r,n,"id");if(i===null)return;let o=this.dbManager.getSessionStore().getObservationById(i);if(!o){this.notFound(n,`Observation #${i} not found`);return}n.json(o)});handleGetObservationsByIds=this.wrapHandler((r,n)=>{let{ids:i,orderBy:s,limit:o,project:a}=r.body;if(typeof i=="string")try{i=JSON.parse(i)}catch{i=i.split(",").map(Number)}if(!i||!Array.isArray(i)){this.badRequest(n,"ids must be an array of numbers");return}if(i.length===0){n.json([]);return}if(!i.every(l=>typeof l=="number"&&Number.isInteger(l))){this.badRequest(n,"All ids must be integers");return}let u=this.dbManager.getSessionStore().getObservationsByIds(i,{orderBy:s,limit:o,project:a});n.json(u)});handleGetSessionById=this.wrapHandler((r,n)=>{let i=this.parseIntParam(r,n,"id");if(i===null)return;let o=this.dbManager.getSessionStore().getSessionSummariesByIds([i]);if(o.length===0){this.notFound(n,`Session #${i} not found`);return}n.json(o[0])});handleGetSdkSessionsByIds=this.wrapHandler((r,n)=>{let{memorySessionIds:i}=r.body;if(typeof i=="string")try{i=JSON.parse(i)}catch{i=i.split(",").map(a=>a.trim())}if(!Array.isArray(i)){this.badRequest(n,"memorySessionIds must be an array");return}let o=this.dbManager.getSessionStore().getSdkSessionsBySessionIds(i);n.json(o)});handleGetPromptById=this.wrapHandler((r,n)=>{let i=this.parseIntParam(r,n,"id");if(i===null)return;let o=this.dbManager.getSessionStore().getUserPromptsByIds([i]);if(o.length===0){this.notFound(n,`Prompt #${i} not found`);return}n.json(o[0])});handleGetStats=this.wrapHandler((r,n)=>{let i=this.dbManager.getSessionStore().db,s=dn(),o=Q$.default.join(s,"package.json"),c=JSON.parse((0,ju.readFileSync)(o,"utf-8")).version,u=i.prepare("SELECT COUNT(*) as count FROM observations").get(),l=i.prepare("SELECT COUNT(*) as count FROM sdk_sessions").get(),d=i.prepare("SELECT COUNT(*) as count FROM session_summaries").get(),p=Q$.default.join((0,b9.homedir)(),".claude-mem","claude-mem.db"),f=0;(0,ju.existsSync)(p)&&(f=(0,ju.statSync)(p).size);let m=Math.floor((Date.now()-this.startTime)/1e3),h=this.sessionManager.getActiveSessionCount(),g=this.sseBroadcaster.getClientCount();n.json({worker:{version:c,uptime:m,activeSessions:h,sseClients:g,port:Jr()},database:{path:p,size:f,observations:u.count,sessions:l.count,summaries:d.count}})});handleGetProjects=this.wrapHandler((r,n)=>{let o=this.dbManager.getSessionStore().db.prepare(` +`)}getTypeIcon(e){return He.getInstance().getTypeIcon(e)}formatDate(e){return new Date(e).toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric"})}formatTime(e){return new Date(e).toLocaleString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0})}formatDateTime(e){return new Date(e).toLocaleString("en-US",{month:"short",day:"numeric",hour:"numeric",minute:"2-digit",hour12:!0})}estimateTokens(e){return e?Math.ceil(e.length/4):0}};var fy=class{constructor(e,r){this.sseBroadcaster=e;this.workerService=r}broadcastNewPrompt(e){this.sseBroadcaster.broadcast({type:"new_prompt",prompt:e}),this.workerService.broadcastProcessingStatus()}broadcastSessionStarted(e,r){this.sseBroadcaster.broadcast({type:"session_started",sessionDbId:e,project:r}),this.workerService.broadcastProcessingStatus()}broadcastObservationQueued(e){this.sseBroadcaster.broadcast({type:"observation_queued",sessionDbId:e}),this.workerService.broadcastProcessingStatus()}broadcastSessionCompleted(e){this.sseBroadcaster.broadcast({type:"session_completed",timestamp:Date.now(),sessionDbId:e}),this.workerService.broadcastProcessingStatus()}broadcastSummarizeQueued(){this.workerService.broadcastProcessingStatus()}};var g9=Me(hv(),1),my=Me(require("path"),1),gy=require("fs");jt();se();var Ur=class{wrapHandler(e){return(r,n)=>{try{let i=e(r,n);i instanceof Promise&&i.catch(s=>this.handleError(n,s))}catch(i){b.error("HTTP","Route handler error",{path:r.path},i),this.handleError(n,i)}}}parseIntParam(e,r,n){let i=parseInt(e.params[n],10);return isNaN(i)?(this.badRequest(r,`Invalid ${n}`),null):i}validateRequired(e,r,n){for(let i of n)if(e.body[i]===void 0||e.body[i]===null)return this.badRequest(r,`Missing ${i}`),!1;return!0}badRequest(e,r){e.status(400).json({error:r})}notFound(e,r){e.status(404).json({error:r})}handleError(e,r,n){b.failure("WORKER",n||"Request failed",{},r),e.headersSent||e.status(500).json({error:r.message})}};var hy=class extends Ur{constructor(r,n,i){super();this.sseBroadcaster=r;this.dbManager=n;this.sessionManager=i}setupRoutes(r){let n=dn();r.use(g9.default.static(my.default.join(n,"ui"))),r.get("/health",this.handleHealth.bind(this)),r.get("/",this.handleViewerUI.bind(this)),r.get("/stream",this.handleSSEStream.bind(this))}handleHealth=this.wrapHandler((r,n)=>{n.json({status:"ok",timestamp:Date.now()})});handleViewerUI=this.wrapHandler((r,n)=>{let i=dn(),o=[my.default.join(i,"ui","viewer.html"),my.default.join(i,"plugin","ui","viewer.html")].find(c=>(0,gy.existsSync)(c));if(!o)throw new Error("Viewer UI not found at any expected location");let a=(0,gy.readFileSync)(o,"utf-8");n.setHeader("Content-Type","text/html"),n.send(a)});handleSSEStream=this.wrapHandler((r,n)=>{n.setHeader("Content-Type","text/event-stream"),n.setHeader("Cache-Control","no-cache"),n.setHeader("Connection","keep-alive"),this.sseBroadcaster.addClient(n);let i=this.dbManager.getSessionStore().getAllProjects();this.sseBroadcaster.broadcast({type:"initial_load",projects:i,timestamp:Date.now()});let s=this.sessionManager.isAnySessionProcessing(),o=this.sessionManager.getTotalActiveWork();this.sseBroadcaster.broadcast({type:"processing_status",isProcessing:s,queueDepth:o})})};Dr();se();se();var v9=100;function y_e(t){let e=(t.match(//g)||[]).length,r=(t.match(//g)||[]).length,n=(t.match(//g)||[]).length,i=(t.match(//g)||[]).length;return e+r+n+i}function y9(t){let e=y_e(t);return e>v9&&b.warn("SYSTEM","tag count exceeds limit",void 0,{tagCount:e,maxAllowed:v9,contentLength:t.length}),t.replace(/[\s\S]*?<\/claude-mem-context>/g,"").replace(/[\s\S]*?<\/private>/g,"").replace(/[\s\S]*?<\/system_instruction>/g,"").replace(/[\s\S]*?<\/system-instruction>/g,"").trim()}function Y$(t){return y9(t)}function _9(t){return y9(t)}var vy=class{constructor(e,r){this.sessionManager=e;this.eventBroadcaster=r}async completeByDbId(e){await this.sessionManager.deleteSession(e),this.eventBroadcaster.broadcastSessionCompleted(e)}};se();var cf=class{static checkUserPromptPrivacy(e,r,n,i,s,o){let a=e.getUserPrompt(r,n);return!a||a.trim()===""?(b.debug("HOOK",`Skipping ${i} - user prompt was entirely private`,{sessionId:s,promptNumber:n,...o}),null):a}};rr();jt();var yy=class t extends Ur{constructor(r,n,i,s,o,a,c){super();this.sessionManager=r;this.dbManager=n;this.sdkAgent=i;this.geminiAgent=s;this.openRouterAgent=o;this.eventBroadcaster=a;this.workerService=c;this.completionHandler=new vy(r,a)}completionHandler;spawnInProgress=new Map;crashRecoveryScheduled=new Set;getActiveAgent(){if(Du()){if(Ea())return b.debug("SESSION","Using OpenRouter agent"),this.openRouterAgent;throw new Error("OpenRouter provider selected but no API key configured. Set CLAUDE_MEM_OPENROUTER_API_KEY in settings or OPENROUTER_API_KEY environment variable.")}if(Mu()){if(wa())return b.debug("SESSION","Using Gemini agent"),this.geminiAgent;throw new Error("Gemini provider selected but no API key configured. Set CLAUDE_MEM_GEMINI_API_KEY in settings or GEMINI_API_KEY environment variable.")}return this.sdkAgent}getSelectedProvider(){return Du()&&Ea()?"openrouter":Mu()&&wa()?"gemini":"claude"}static STALE_GENERATOR_THRESHOLD_MS=3e4;ensureGeneratorRunning(r,n){let i=this.sessionManager.getSession(r);if(!i)return;if(this.spawnInProgress.get(r)){b.debug("SESSION","Spawn already in progress, skipping",{sessionDbId:r,source:n});return}let s=this.getSelectedProvider();if(!i.generatorPromise){this.spawnInProgress.set(r,!0),this.startGeneratorWithProvider(i,s,n);return}let o=Date.now()-i.lastGeneratorActivity;if(o>t.STALE_GENERATOR_THRESHOLD_MS){b.warn("SESSION","Stale generator detected, aborting to prevent queue stall (#1099)",{sessionId:r,timeSinceActivityMs:o,thresholdMs:t.STALE_GENERATOR_THRESHOLD_MS,source:n}),i.abortController.abort(),i.generatorPromise=null,i.abortController=new AbortController,i.lastGeneratorActivity=Date.now(),this.spawnInProgress.set(r,!0),this.startGeneratorWithProvider(i,s,"stale-recovery");return}i.currentProvider&&i.currentProvider!==s&&b.info("SESSION","Provider changed, will switch after current generator finishes",{sessionId:r,currentProvider:i.currentProvider,selectedProvider:s,historyLength:i.conversationHistory.length})}startGeneratorWithProvider(r,n,i){if(!r)return;r.abortController.signal.aborted&&(b.debug("SESSION","Resetting aborted AbortController before starting generator",{sessionId:r.sessionDbId}),r.abortController=new AbortController);let s=n==="openrouter"?this.openRouterAgent:n==="gemini"?this.geminiAgent:this.sdkAgent,o=n==="openrouter"?"OpenRouter":n==="gemini"?"Gemini":"Claude SDK",c=this.sessionManager.getPendingMessageStore().getPendingCount(r.sessionDbId);b.info("SESSION",`Generator auto-starting (${i}) using ${o}`,{sessionId:r.sessionDbId,queueDepth:c,historyLength:r.conversationHistory.length}),r.currentProvider=n,r.lastGeneratorActivity=Date.now(),r.generatorPromise=s.startSession(r,this.workerService).catch(u=>{if(r.abortController.signal.aborted)return;b.error("SESSION","Generator failed",{sessionId:r.sessionDbId,provider:n,error:u.message},u);let l=this.sessionManager.getPendingMessageStore();try{let d=l.markSessionMessagesFailed(r.sessionDbId);d>0&&b.error("SESSION","Marked messages as failed after generator error",{sessionId:r.sessionDbId,failedCount:d})}catch(d){b.error("SESSION","Failed to mark messages as failed",{sessionId:r.sessionDbId},d)}}).finally(async()=>{let u=go(r.sessionDbId);u&&!u.process.killed&&u.process.exitCode===null&&await vo(u,5e3);let l=r.sessionDbId;this.spawnInProgress.delete(l);let d=r.abortController.signal.aborted;if(d?b.info("SESSION","Generator aborted",{sessionId:l}):b.error("SESSION","Generator exited unexpectedly",{sessionId:l}),r.generatorPromise=null,r.currentProvider=null,this.workerService.broadcastProcessingStatus(),!d)try{let f=this.sessionManager.getPendingMessageStore().getPendingCount(l),m=3;if(f>0){if(this.crashRecoveryScheduled.has(l)){b.debug("SESSION","Crash recovery already scheduled",{sessionDbId:l});return}if(r.consecutiveRestarts=(r.consecutiveRestarts||0)+1,r.consecutiveRestarts>m){b.error("SESSION","CRITICAL: Generator restart limit exceeded - stopping to prevent runaway costs",{sessionId:l,pendingCount:f,consecutiveRestarts:r.consecutiveRestarts,maxRestarts:m,action:"Generator will NOT restart. Check logs for root cause. Messages remain in pending state."}),r.abortController.abort();return}b.info("SESSION","Restarting generator after crash/exit with pending work",{sessionId:l,pendingCount:f,consecutiveRestarts:r.consecutiveRestarts,maxRestarts:m});let h=r.abortController;r.abortController=new AbortController,h.abort(),this.crashRecoveryScheduled.add(l);let g=Math.min(1e3*Math.pow(2,r.consecutiveRestarts-1),8e3);setTimeout(()=>{this.crashRecoveryScheduled.delete(l);let v=this.sessionManager.getSession(l);v&&!v.generatorPromise&&this.startGeneratorWithProvider(v,this.getSelectedProvider(),"crash-recovery")},g)}else r.abortController.abort(),r.consecutiveRestarts=0,b.debug("SESSION","Aborted controller after natural completion",{sessionId:l})}catch(p){b.debug("SESSION","Error during recovery check, aborting to prevent leaks",{sessionId:l,error:p instanceof Error?p.message:String(p)}),r.abortController.abort()}})}setupRoutes(r){r.post("/sessions/:sessionDbId/init",this.handleSessionInit.bind(this)),r.post("/sessions/:sessionDbId/observations",this.handleObservations.bind(this)),r.post("/sessions/:sessionDbId/summarize",this.handleSummarize.bind(this)),r.get("/sessions/:sessionDbId/status",this.handleSessionStatus.bind(this)),r.delete("/sessions/:sessionDbId",this.handleSessionDelete.bind(this)),r.post("/sessions/:sessionDbId/complete",this.handleSessionComplete.bind(this)),r.post("/api/sessions/init",this.handleSessionInitByClaudeId.bind(this)),r.post("/api/sessions/observations",this.handleObservationsByClaudeId.bind(this)),r.post("/api/sessions/summarize",this.handleSummarizeByClaudeId.bind(this)),r.post("/api/sessions/complete",this.handleCompleteByClaudeId.bind(this)),r.get("/api/sessions/status",this.handleStatusByClaudeId.bind(this))}handleSessionInit=this.wrapHandler((r,n)=>{let i=this.parseIntParam(r,n,"sessionDbId");if(i===null)return;let{userPrompt:s,promptNumber:o}=r.body;b.info("HTTP","SessionRoutes: handleSessionInit called",{sessionDbId:i,promptNumber:o,has_userPrompt:!!s});let a=this.sessionManager.initializeSession(i,s,o),c=this.dbManager.getSessionStore().getLatestUserPrompt(a.contentSessionId);if(c){this.eventBroadcaster.broadcastNewPrompt({id:c.id,content_session_id:c.content_session_id,project:c.project,prompt_number:c.prompt_number,prompt_text:c.prompt_text,created_at_epoch:c.created_at_epoch});let u=Date.now(),l=c.prompt_text;this.dbManager.getChromaSync()?.syncUserPrompt(c.id,c.memory_session_id,c.project,l,c.prompt_number,c.created_at_epoch).then(()=>{let d=Date.now()-u,p=l.length>60?l.substring(0,60)+"...":l;b.debug("CHROMA","User prompt synced",{promptId:c.id,duration:`${d}ms`,prompt:p})}).catch(d=>{b.error("CHROMA","User prompt sync failed, continuing without vector search",{promptId:c.id,prompt:l.length>60?l.substring(0,60)+"...":l},d)})}this.ensureGeneratorRunning(i,"init"),this.eventBroadcaster.broadcastSessionStarted(i,a.project),n.json({status:"initialized",sessionDbId:i,port:Jr()})});handleObservations=this.wrapHandler((r,n)=>{let i=this.parseIntParam(r,n,"sessionDbId");if(i===null)return;let{tool_name:s,tool_input:o,tool_response:a,prompt_number:c,cwd:u}=r.body;this.sessionManager.queueObservation(i,{tool_name:s,tool_input:o,tool_response:a,prompt_number:c,cwd:u}),this.ensureGeneratorRunning(i,"observation"),this.eventBroadcaster.broadcastObservationQueued(i),n.json({status:"queued"})});handleSummarize=this.wrapHandler((r,n)=>{let i=this.parseIntParam(r,n,"sessionDbId");if(i===null)return;let{last_assistant_message:s}=r.body;this.sessionManager.queueSummarize(i,s),this.ensureGeneratorRunning(i,"summarize"),this.eventBroadcaster.broadcastSummarizeQueued(),n.json({status:"queued"})});handleSessionStatus=this.wrapHandler((r,n)=>{let i=this.parseIntParam(r,n,"sessionDbId");if(i===null)return;let s=this.sessionManager.getSession(i);if(!s){n.json({status:"not_found"});return}let a=this.sessionManager.getPendingMessageStore().getPendingCount(i);n.json({status:"active",sessionDbId:i,project:s.project,queueLength:a,uptime:Date.now()-s.startTime})});handleSessionDelete=this.wrapHandler(async(r,n)=>{let i=this.parseIntParam(r,n,"sessionDbId");i!==null&&(await this.completionHandler.completeByDbId(i),n.json({status:"deleted"}))});handleSessionComplete=this.wrapHandler(async(r,n)=>{let i=this.parseIntParam(r,n,"sessionDbId");i!==null&&(await this.completionHandler.completeByDbId(i),n.json({success:!0}))});handleObservationsByClaudeId=this.wrapHandler((r,n)=>{let{contentSessionId:i,tool_name:s,tool_input:o,tool_response:a,cwd:c}=r.body;if(!i)return this.badRequest(n,"Missing contentSessionId");let u=Ee.loadFromFile(qt);if(new Set(u.CLAUDE_MEM_SKIP_TOOLS.split(",").map(p=>p.trim()).filter(Boolean)).has(s)){b.debug("SESSION","Skipping observation for tool",{tool_name:s}),n.json({status:"skipped",reason:"tool_excluded"});return}if(new Set(["Edit","Write","Read","NotebookEdit"]).has(s)&&o){let p=o.file_path||o.notebook_path;if(p&&p.includes("session-memory")){b.debug("SESSION","Skipping meta-observation for session-memory file",{tool_name:s,file_path:p}),n.json({status:"skipped",reason:"session_memory_meta"});return}}try{let p=this.dbManager.getSessionStore(),f=p.createSDKSession(i,"",""),m=p.getPromptNumberFromUserPrompts(i);if(!cf.checkUserPromptPrivacy(p,i,m,"observation",f,{tool_name:s})){n.json({status:"skipped",reason:"private"});return}let g=o!==void 0?Y$(JSON.stringify(o)):"{}",v=a!==void 0?Y$(JSON.stringify(a)):"{}";this.sessionManager.queueObservation(f,{tool_name:s,tool_input:g,tool_response:v,prompt_number:m,cwd:c||(b.error("SESSION","Missing cwd when queueing observation in SessionRoutes",{sessionId:f,tool_name:s}),"")}),this.ensureGeneratorRunning(f,"observation"),this.eventBroadcaster.broadcastObservationQueued(f),n.json({status:"queued"})}catch(p){b.error("SESSION","Observation storage failed",{contentSessionId:i,tool_name:s},p),n.json({stored:!1,reason:p.message})}});handleSummarizeByClaudeId=this.wrapHandler((r,n)=>{let{contentSessionId:i,last_assistant_message:s}=r.body;if(!i)return this.badRequest(n,"Missing contentSessionId");let o=this.dbManager.getSessionStore(),a=o.createSDKSession(i,"",""),c=o.getPromptNumberFromUserPrompts(i);if(!cf.checkUserPromptPrivacy(o,i,c,"summarize",a)){n.json({status:"skipped",reason:"private"});return}this.sessionManager.queueSummarize(a,s),this.ensureGeneratorRunning(a,"summarize"),this.eventBroadcaster.broadcastSummarizeQueued(),n.json({status:"queued"})});handleStatusByClaudeId=this.wrapHandler((r,n)=>{let i=r.query.contentSessionId;if(!i)return this.badRequest(n,"Missing contentSessionId query parameter");let o=this.dbManager.getSessionStore().createSDKSession(i,"",""),a=this.sessionManager.getSession(o);if(!a){n.json({status:"not_found",queueLength:0});return}let u=this.sessionManager.getPendingMessageStore().getPendingCount(o);n.json({status:"active",sessionDbId:o,queueLength:u,uptime:Date.now()-a.startTime})});handleCompleteByClaudeId=this.wrapHandler(async(r,n)=>{let{contentSessionId:i}=r.body;if(b.info("HTTP","\u2192 POST /api/sessions/complete",{contentSessionId:i}),!i)return this.badRequest(n,"Missing contentSessionId");let o=this.dbManager.getSessionStore().createSDKSession(i,"","");if(!this.sessionManager.getSession(o)){b.debug("SESSION","session-complete: Session not in active map",{contentSessionId:i,sessionDbId:o}),n.json({status:"skipped",reason:"not_active"});return}await this.completionHandler.completeByDbId(o),b.info("SESSION","Session completed via API",{contentSessionId:i,sessionDbId:o}),n.json({status:"completed",sessionDbId:o})});handleSessionInitByClaudeId=this.wrapHandler((r,n)=>{let{contentSessionId:i}=r.body,s=r.body.project||"unknown",o=r.body.prompt||"[media prompt]",a=r.body.customTitle||void 0;if(b.info("HTTP","SessionRoutes: handleSessionInitByClaudeId called",{contentSessionId:i,project:s,prompt_length:o?.length,customTitle:a}),!this.validateRequired(r,n,["contentSessionId"]))return;let c=this.dbManager.getSessionStore(),u=c.createSDKSession(i,s,o,a),l=c.getSessionById(u),d=!l?.memory_session_id;b.info("SESSION",`CREATED | contentSessionId=${i} \u2192 sessionDbId=${u} | isNew=${d} | project=${s}`,{sessionId:u});let f=c.getPromptNumberFromUserPrompts(i)+1,m=l?.memory_session_id||null;f>1?b.debug("HTTP",`[ALIGNMENT] DB Lookup Proof | contentSessionId=${i} \u2192 memorySessionId=${m||"(not yet captured)"} | prompt#=${f}`):b.debug("HTTP",`[ALIGNMENT] New Session | contentSessionId=${i} | prompt#=${f} | memorySessionId will be captured on first SDK response`);let h=_9(o);if(!h||h.trim()===""){b.debug("HOOK","Session init - prompt entirely private",{sessionId:u,promptNumber:f,originalLength:o.length}),n.json({sessionDbId:u,promptNumber:f,skipped:!0,reason:"private"});return}c.saveUserPrompt(i,f,h);let g=this.sessionManager.getSession(u)!==void 0;b.debug("SESSION","User prompt saved",{sessionId:u,promptNumber:f,contextInjected:g}),n.json({sessionDbId:u,promptNumber:f,skipped:!1,contextInjected:g})})};var Q$=Me(require("path"),1),ju=require("fs");se();var b9=require("os");jt();Dr();var _y=class extends Ur{constructor(r,n,i,s,o,a){super();this.paginationHelper=r;this.dbManager=n;this.sessionManager=i;this.sseBroadcaster=s;this.workerService=o;this.startTime=a}setupRoutes(r){r.get("/api/observations",this.handleGetObservations.bind(this)),r.get("/api/summaries",this.handleGetSummaries.bind(this)),r.get("/api/prompts",this.handleGetPrompts.bind(this)),r.get("/api/observation/:id",this.handleGetObservationById.bind(this)),r.post("/api/observations/batch",this.handleGetObservationsByIds.bind(this)),r.get("/api/session/:id",this.handleGetSessionById.bind(this)),r.post("/api/sdk-sessions/batch",this.handleGetSdkSessionsByIds.bind(this)),r.get("/api/prompt/:id",this.handleGetPromptById.bind(this)),r.get("/api/stats",this.handleGetStats.bind(this)),r.get("/api/projects",this.handleGetProjects.bind(this)),r.get("/api/processing-status",this.handleGetProcessingStatus.bind(this)),r.post("/api/processing",this.handleSetProcessing.bind(this)),r.get("/api/pending-queue",this.handleGetPendingQueue.bind(this)),r.post("/api/pending-queue/process",this.handleProcessPendingQueue.bind(this)),r.delete("/api/pending-queue/failed",this.handleClearFailedQueue.bind(this)),r.delete("/api/pending-queue/all",this.handleClearAllQueue.bind(this)),r.post("/api/import",this.handleImport.bind(this))}handleGetObservations=this.wrapHandler((r,n)=>{let{offset:i,limit:s,project:o}=this.parsePaginationParams(r),a=this.paginationHelper.getObservations(i,s,o);n.json(a)});handleGetSummaries=this.wrapHandler((r,n)=>{let{offset:i,limit:s,project:o}=this.parsePaginationParams(r),a=this.paginationHelper.getSummaries(i,s,o);n.json(a)});handleGetPrompts=this.wrapHandler((r,n)=>{let{offset:i,limit:s,project:o}=this.parsePaginationParams(r),a=this.paginationHelper.getPrompts(i,s,o);n.json(a)});handleGetObservationById=this.wrapHandler((r,n)=>{let i=this.parseIntParam(r,n,"id");if(i===null)return;let o=this.dbManager.getSessionStore().getObservationById(i);if(!o){this.notFound(n,`Observation #${i} not found`);return}n.json(o)});handleGetObservationsByIds=this.wrapHandler((r,n)=>{let{ids:i,orderBy:s,limit:o,project:a}=r.body;if(typeof i=="string")try{i=JSON.parse(i)}catch{i=i.split(",").map(Number)}if(!i||!Array.isArray(i)){this.badRequest(n,"ids must be an array of numbers");return}if(i.length===0){n.json([]);return}if(!i.every(l=>typeof l=="number"&&Number.isInteger(l))){this.badRequest(n,"All ids must be integers");return}let u=this.dbManager.getSessionStore().getObservationsByIds(i,{orderBy:s,limit:o,project:a});n.json(u)});handleGetSessionById=this.wrapHandler((r,n)=>{let i=this.parseIntParam(r,n,"id");if(i===null)return;let o=this.dbManager.getSessionStore().getSessionSummariesByIds([i]);if(o.length===0){this.notFound(n,`Session #${i} not found`);return}n.json(o[0])});handleGetSdkSessionsByIds=this.wrapHandler((r,n)=>{let{memorySessionIds:i}=r.body;if(typeof i=="string")try{i=JSON.parse(i)}catch{i=i.split(",").map(a=>a.trim())}if(!Array.isArray(i)){this.badRequest(n,"memorySessionIds must be an array");return}let o=this.dbManager.getSessionStore().getSdkSessionsBySessionIds(i);n.json(o)});handleGetPromptById=this.wrapHandler((r,n)=>{let i=this.parseIntParam(r,n,"id");if(i===null)return;let o=this.dbManager.getSessionStore().getUserPromptsByIds([i]);if(o.length===0){this.notFound(n,`Prompt #${i} not found`);return}n.json(o[0])});handleGetStats=this.wrapHandler((r,n)=>{let i=this.dbManager.getSessionStore().db,s=dn(),o=Q$.default.join(s,"package.json"),c=JSON.parse((0,ju.readFileSync)(o,"utf-8")).version,u=i.prepare("SELECT COUNT(*) as count FROM observations").get(),l=i.prepare("SELECT COUNT(*) as count FROM sdk_sessions").get(),d=i.prepare("SELECT COUNT(*) as count FROM session_summaries").get(),p=Q$.default.join((0,b9.homedir)(),".claude-mem","claude-mem.db"),f=0;(0,ju.existsSync)(p)&&(f=(0,ju.statSync)(p).size);let m=Math.floor((Date.now()-this.startTime)/1e3),h=this.sessionManager.getActiveSessionCount(),g=this.sseBroadcaster.getClientCount();n.json({worker:{version:c,uptime:m,activeSessions:h,sseClients:g,port:Jr()},database:{path:p,size:f,observations:u.count,sessions:l.count,summaries:d.count}})});handleGetProjects=this.wrapHandler((r,n)=>{let o=this.dbManager.getSessionStore().db.prepare(` SELECT DISTINCT project FROM observations WHERE project IS NOT NULL GROUP BY project ORDER BY MAX(created_at_epoch) DESC - `).all().map(a=>a.project);n.json({projects:o})});handleGetProcessingStatus=this.wrapHandler((r,n)=>{let i=this.sessionManager.isAnySessionProcessing(),s=this.sessionManager.getTotalActiveWork();n.json({isProcessing:i,queueDepth:s})});handleSetProcessing=this.wrapHandler((r,n)=>{this.workerService.broadcastProcessingStatus();let i=this.sessionManager.isAnySessionProcessing(),s=this.sessionManager.getTotalQueueDepth(),o=this.sessionManager.getActiveSessionCount();n.json({status:"ok",isProcessing:i,queueDepth:s,activeSessions:o})});parsePaginationParams(r){let n=parseInt(r.query.offset,10)||0,i=Math.min(parseInt(r.query.limit,10)||20,100),s=r.query.project;return{offset:n,limit:i,project:s}}handleImport=this.wrapHandler((r,n)=>{let{sessions:i,summaries:s,observations:o,prompts:a}=r.body,c={sessionsImported:0,sessionsSkipped:0,summariesImported:0,summariesSkipped:0,observationsImported:0,observationsSkipped:0,promptsImported:0,promptsSkipped:0},u=this.dbManager.getSessionStore();if(Array.isArray(i))for(let l of i)u.importSdkSession(l).imported?c.sessionsImported++:c.sessionsSkipped++;if(Array.isArray(s))for(let l of s)u.importSessionSummary(l).imported?c.summariesImported++:c.summariesSkipped++;if(Array.isArray(o))for(let l of o)u.importObservation(l).imported?c.observationsImported++:c.observationsSkipped++;if(Array.isArray(a))for(let l of a)u.importUserPrompt(l).imported?c.promptsImported++:c.promptsSkipped++;n.json({success:!0,stats:c})});handleGetPendingQueue=this.wrapHandler((r,n)=>{let{PendingMessageStore:i}=(ha(),zf(ou)),s=new i(this.dbManager.getSessionStore().db,3),o=s.getQueueMessages(),a=s.getRecentlyProcessed(20,30),c=s.getStuckCount(300*1e3),u=s.getSessionsWithPendingMessages();n.json({queue:{messages:o,totalPending:o.filter(l=>l.status==="pending").length,totalProcessing:o.filter(l=>l.status==="processing").length,totalFailed:o.filter(l=>l.status==="failed").length,stuckCount:c},recentlyProcessed:a,sessionsWithPendingWork:u})});handleProcessPendingQueue=this.wrapHandler(async(r,n)=>{let i=Math.min(Math.max(parseInt(r.body.sessionLimit,10)||10,1),100),s=await this.workerService.processPendingQueues(i);n.json({success:!0,...s})});handleClearFailedQueue=this.wrapHandler((r,n)=>{let{PendingMessageStore:i}=(ha(),zf(ou)),o=new i(this.dbManager.getSessionStore().db,3).clearFailed();b.info("QUEUE","Cleared failed queue messages",{clearedCount:o}),n.json({success:!0,clearedCount:o})});handleClearAllQueue=this.wrapHandler((r,n)=>{let{PendingMessageStore:i}=(ha(),zf(ou)),o=new i(this.dbManager.getSessionStore().db,3).clearAll();b.warn("QUEUE","Cleared ALL queue messages (pending, processing, failed)",{clearedCount:o}),n.json({success:!0,clearedCount:o})})};var $y=class extends Ur{constructor(r){super();this.searchManager=r}setupRoutes(r){r.get("/api/search",this.handleUnifiedSearch.bind(this)),r.get("/api/timeline",this.handleUnifiedTimeline.bind(this)),r.get("/api/decisions",this.handleDecisions.bind(this)),r.get("/api/changes",this.handleChanges.bind(this)),r.get("/api/how-it-works",this.handleHowItWorks.bind(this)),r.get("/api/search/observations",this.handleSearchObservations.bind(this)),r.get("/api/search/sessions",this.handleSearchSessions.bind(this)),r.get("/api/search/prompts",this.handleSearchPrompts.bind(this)),r.get("/api/search/by-concept",this.handleSearchByConcept.bind(this)),r.get("/api/search/by-file",this.handleSearchByFile.bind(this)),r.get("/api/search/by-type",this.handleSearchByType.bind(this)),r.get("/api/context/recent",this.handleGetRecentContext.bind(this)),r.get("/api/context/timeline",this.handleGetContextTimeline.bind(this)),r.get("/api/context/preview",this.handleContextPreview.bind(this)),r.get("/api/context/inject",this.handleContextInject.bind(this)),r.get("/api/timeline/by-query",this.handleGetTimelineByQuery.bind(this)),r.get("/api/search/help",this.handleSearchHelp.bind(this))}handleUnifiedSearch=this.wrapHandler(async(r,n)=>{let i=await this.searchManager.search(r.query);n.json(i)});handleUnifiedTimeline=this.wrapHandler(async(r,n)=>{let i=await this.searchManager.timeline(r.query);n.json(i)});handleDecisions=this.wrapHandler(async(r,n)=>{let i=await this.searchManager.decisions(r.query);n.json(i)});handleChanges=this.wrapHandler(async(r,n)=>{let i=await this.searchManager.changes(r.query);n.json(i)});handleHowItWorks=this.wrapHandler(async(r,n)=>{let i=await this.searchManager.howItWorks(r.query);n.json(i)});handleSearchObservations=this.wrapHandler(async(r,n)=>{let i=await this.searchManager.searchObservations(r.query);n.json(i)});handleSearchSessions=this.wrapHandler(async(r,n)=>{let i=await this.searchManager.searchSessions(r.query);n.json(i)});handleSearchPrompts=this.wrapHandler(async(r,n)=>{let i=await this.searchManager.searchUserPrompts(r.query);n.json(i)});handleSearchByConcept=this.wrapHandler(async(r,n)=>{let i=await this.searchManager.findByConcept(r.query);n.json(i)});handleSearchByFile=this.wrapHandler(async(r,n)=>{let i=await this.searchManager.findByFile(r.query);n.json(i)});handleSearchByType=this.wrapHandler(async(r,n)=>{let i=await this.searchManager.findByType(r.query);n.json(i)});handleGetRecentContext=this.wrapHandler(async(r,n)=>{let i=await this.searchManager.getRecentContext(r.query);n.json(i)});handleGetContextTimeline=this.wrapHandler(async(r,n)=>{let i=await this.searchManager.getContextTimeline(r.query);n.json(i)});handleContextPreview=this.wrapHandler(async(r,n)=>{let i=r.query.project;if(!i){this.badRequest(n,"Project parameter is required");return}let{generateContext:s}=await Promise.resolve().then(()=>(pI(),dI)),o=`/preview/${i}`,a=await s({session_id:"preview-"+Date.now(),cwd:o},!0);n.setHeader("Content-Type","text/plain; charset=utf-8"),n.send(a)});handleContextInject=this.wrapHandler(async(r,n)=>{let i=r.query.projects||r.query.project,s=r.query.colors==="true",o=r.query.full==="true";if(!i){this.badRequest(n,"Project(s) parameter is required");return}let a=i.split(",").map(p=>p.trim()).filter(Boolean);if(a.length===0){this.badRequest(n,"At least one project is required");return}let{generateContext:c}=await Promise.resolve().then(()=>(pI(),dI)),l=`/context/${a[a.length-1]}`,d=await c({session_id:"context-inject-"+Date.now(),cwd:l,projects:a,full:o},s);n.setHeader("Content-Type","text/plain; charset=utf-8"),n.send(d)});handleGetTimelineByQuery=this.wrapHandler(async(r,n)=>{let i=await this.searchManager.getTimelineByQuery(r.query);n.json(i)});handleSearchHelp=this.wrapHandler((r,n)=>{n.json({title:"Claude-Mem Search API",description:"HTTP API for searching persistent memory",endpoints:[{path:"/api/search/observations",method:"GET",description:"Search observations using full-text search",parameters:{query:"Search query (required)",limit:"Number of results (default: 20)",project:"Filter by project name (optional)"}},{path:"/api/search/sessions",method:"GET",description:"Search session summaries using full-text search",parameters:{query:"Search query (required)",limit:"Number of results (default: 20)"}},{path:"/api/search/prompts",method:"GET",description:"Search user prompts using full-text search",parameters:{query:"Search query (required)",limit:"Number of results (default: 20)",project:"Filter by project name (optional)"}},{path:"/api/search/by-concept",method:"GET",description:"Find observations by concept tag",parameters:{concept:"Concept tag (required): discovery, decision, bugfix, feature, refactor",limit:"Number of results (default: 10)",project:"Filter by project name (optional)"}},{path:"/api/search/by-file",method:"GET",description:"Find observations and sessions by file path",parameters:{filePath:"File path or partial path (required)",limit:"Number of results per type (default: 10)",project:"Filter by project name (optional)"}},{path:"/api/search/by-type",method:"GET",description:"Find observations by type",parameters:{type:"Observation type (required): discovery, decision, bugfix, feature, refactor",limit:"Number of results (default: 10)",project:"Filter by project name (optional)"}},{path:"/api/context/recent",method:"GET",description:"Get recent session context including summaries and observations",parameters:{project:"Project name (default: current directory)",limit:"Number of recent sessions (default: 3)"}},{path:"/api/context/timeline",method:"GET",description:"Get unified timeline around a specific point in time",parameters:{anchor:'Anchor point: observation ID, session ID (e.g., "S123"), or ISO timestamp (required)',depth_before:"Number of records before anchor (default: 10)",depth_after:"Number of records after anchor (default: 10)",project:"Filter by project name (optional)"}},{path:"/api/timeline/by-query",method:"GET",description:"Search for best match, then get timeline around it",parameters:{query:"Search query (required)",mode:'Search mode: "auto", "observations", or "sessions" (default: "auto")',depth_before:"Number of records before match (default: 10)",depth_after:"Number of records after match (default: 10)",project:"Filter by project name (optional)"}},{path:"/api/search/help",method:"GET",description:"Get this help documentation"}],examples:['curl "http://localhost:37777/api/search/observations?query=authentication&limit=5"','curl "http://localhost:37777/api/search/by-type?type=bugfix&limit=10"','curl "http://localhost:37777/api/context/recent?project=claude-mem&limit=3"','curl "http://localhost:37777/api/context/timeline?anchor=123&depth_before=5&depth_after=5"']})})};var Ra=Me(require("path"),1),$r=require("fs"),gI=require("os");jt();ne();var mI=require("child_process"),Ia=require("fs"),Iy=require("path");ne();jt();var hf=Ss;function fI(t){return!t||typeof t!="string"?!1:/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/.test(t)&&!t.includes("..")}var O_e=3e5,hI=6e5;function Yn(t){let e=(0,mI.spawnSync)("git",t,{cwd:hf,encoding:"utf-8",timeout:O_e,windowsHide:!0,shell:!1});if(e.error)throw e.error;if(e.status!==0)throw new Error(e.stderr||e.stdout||"Git command failed");return e.stdout.trim()}function x8(t,e=hI){let n=process.platform==="win32"?"npm.cmd":"npm",i=(0,mI.spawnSync)(n,t,{cwd:hf,encoding:"utf-8",timeout:e,windowsHide:!0,shell:!1});if(i.error)throw i.error;if(i.status!==0)throw new Error(i.stderr||i.stdout||"npm command failed");return i.stdout.trim()}function Ry(){let t=(0,Iy.join)(hf,".git");if(!(0,Ia.existsSync)(t))return{branch:null,isBeta:!1,isGitRepo:!1,isDirty:!1,canSwitch:!1,error:"Installed plugin is not a git repository"};try{let e=Yn(["rev-parse","--abbrev-ref","HEAD"]),n=Yn(["status","--porcelain"]).length>0,i=e.startsWith("beta");return{branch:e,isBeta:i,isGitRepo:!0,isDirty:n,canSwitch:!0}}catch(e){return b.error("BRANCH","Failed to get branch info",{},e),{branch:null,isBeta:!1,isGitRepo:!0,isDirty:!1,canSwitch:!1,error:e.message}}}async function w8(t){if(!fI(t))return{success:!1,error:`Invalid branch name: ${t}. Branch names must be alphanumeric with hyphens, underscores, slashes, or dots.`};let e=Ry();if(!e.isGitRepo)return{success:!1,error:"Installed plugin is not a git repository. Please reinstall."};if(e.branch===t)return{success:!0,branch:t,message:`Already on branch ${t}`};try{b.info("BRANCH","Starting branch switch",{from:e.branch,to:t}),b.debug("BRANCH","Discarding local changes"),Yn(["checkout","--","."]),Yn(["clean","-fd"]),b.debug("BRANCH","Fetching from origin"),Yn(["fetch","origin"]),b.debug("BRANCH","Checking out branch",{branch:t});try{Yn(["checkout",t])}catch(n){b.debug("BRANCH","Branch not local, tracking remote",{branch:t,error:n instanceof Error?n.message:String(n)}),Yn(["checkout","-b",t,`origin/${t}`])}b.debug("BRANCH","Pulling latest"),Yn(["pull","origin",t]);let r=(0,Iy.join)(hf,".install-version");return(0,Ia.existsSync)(r)&&(0,Ia.unlinkSync)(r),b.debug("BRANCH","Running npm install"),x8(["install"],hI),b.success("BRANCH","Branch switch complete",{branch:t}),{success:!0,branch:t,message:`Switched to ${t}. Worker will restart automatically.`}}catch(r){b.error("BRANCH","Branch switch failed",{targetBranch:t},r);try{e.branch&&fI(e.branch)&&Yn(["checkout",e.branch])}catch(n){b.error("BRANCH","Recovery checkout also failed",{originalBranch:e.branch},n)}return{success:!1,error:`Branch switch failed: ${r.message}`}}}async function E8(){let t=Ry();if(!t.isGitRepo||!t.branch)return{success:!1,error:"Cannot pull updates: not a git repository"};try{if(!fI(t.branch))return{success:!1,error:`Invalid current branch name: ${t.branch}`};b.info("BRANCH","Pulling updates",{branch:t.branch}),Yn(["checkout","--","."]),Yn(["fetch","origin"]),Yn(["pull","origin",t.branch]);let e=(0,Iy.join)(hf,".install-version");return(0,Ia.existsSync)(e)&&(0,Ia.unlinkSync)(e),x8(["install"],hI),b.success("BRANCH","Updates pulled",{branch:t.branch}),{success:!0,branch:t.branch,message:`Updated ${t.branch}. Worker will restart automatically.`}}catch(e){return b.error("BRANCH","Pull failed",{},e),{success:!1,error:`Pull failed: ${e.message}`}}}rr();Dr();var Oy=class extends Ur{constructor(r){super();this.settingsManager=r}setupRoutes(r){r.get("/api/settings",this.handleGetSettings.bind(this)),r.post("/api/settings",this.handleUpdateSettings.bind(this)),r.get("/api/mcp/status",this.handleGetMcpStatus.bind(this)),r.post("/api/mcp/toggle",this.handleToggleMcp.bind(this)),r.get("/api/branch/status",this.handleGetBranchStatus.bind(this)),r.post("/api/branch/switch",this.handleSwitchBranch.bind(this)),r.post("/api/branch/update",this.handleUpdateBranch.bind(this))}handleGetSettings=this.wrapHandler((r,n)=>{let i=Ra.default.join((0,gI.homedir)(),".claude-mem","settings.json");this.ensureSettingsFile(i);let s=Ee.loadFromFile(i);n.json(s)});handleUpdateSettings=this.wrapHandler((r,n)=>{let i=this.validateSettings(r.body);if(!i.valid){n.status(400).json({success:!1,error:i.error});return}let s=Ra.default.join((0,gI.homedir)(),".claude-mem","settings.json");this.ensureSettingsFile(s);let o={};if((0,$r.existsSync)(s)){let c=(0,$r.readFileSync)(s,"utf-8");try{o=JSON.parse(c)}catch(u){b.error("SETTINGS","Failed to parse settings file",{settingsPath:s},u),n.status(500).json({success:!1,error:"Settings file is corrupted. Delete ~/.claude-mem/settings.json to reset."});return}}let a=["CLAUDE_MEM_MODEL","CLAUDE_MEM_CONTEXT_OBSERVATIONS","CLAUDE_MEM_WORKER_PORT","CLAUDE_MEM_WORKER_HOST","CLAUDE_MEM_PROVIDER","CLAUDE_MEM_GEMINI_API_KEY","CLAUDE_MEM_GEMINI_MODEL","CLAUDE_MEM_GEMINI_RATE_LIMITING_ENABLED","CLAUDE_MEM_OPENROUTER_API_KEY","CLAUDE_MEM_OPENROUTER_MODEL","CLAUDE_MEM_OPENROUTER_SITE_URL","CLAUDE_MEM_OPENROUTER_APP_NAME","CLAUDE_MEM_OPENROUTER_MAX_CONTEXT_MESSAGES","CLAUDE_MEM_OPENROUTER_MAX_TOKENS","CLAUDE_MEM_DATA_DIR","CLAUDE_MEM_LOG_LEVEL","CLAUDE_MEM_PYTHON_VERSION","CLAUDE_CODE_PATH","CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS","CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS","CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT","CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT","CLAUDE_MEM_CONTEXT_OBSERVATION_TYPES","CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS","CLAUDE_MEM_CONTEXT_FULL_COUNT","CLAUDE_MEM_CONTEXT_FULL_FIELD","CLAUDE_MEM_CONTEXT_SESSION_COUNT","CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY","CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE","CLAUDE_MEM_FOLDER_CLAUDEMD_ENABLED"];for(let c of a)r.body[c]!==void 0&&(o[c]=r.body[c]);(0,$r.writeFileSync)(s,JSON.stringify(o,null,2),"utf-8"),lM(),b.info("WORKER","Settings updated"),n.json({success:!0,message:"Settings updated successfully"})});handleGetMcpStatus=this.wrapHandler((r,n)=>{let i=this.isMcpEnabled();n.json({enabled:i})});handleToggleMcp=this.wrapHandler((r,n)=>{let{enabled:i}=r.body;if(typeof i!="boolean"){this.badRequest(n,"enabled must be a boolean");return}this.toggleMcp(i),n.json({success:!0,enabled:this.isMcpEnabled()})});handleGetBranchStatus=this.wrapHandler((r,n)=>{let i=Ry();n.json(i)});handleSwitchBranch=this.wrapHandler(async(r,n)=>{let{branch:i}=r.body;if(!i){n.status(400).json({success:!1,error:"Missing branch parameter"});return}let s=["main","beta/7.0","feature/bun-executable"];if(!s.includes(i)){n.status(400).json({success:!1,error:`Invalid branch. Allowed: ${s.join(", ")}`});return}b.info("WORKER","Branch switch requested",{branch:i});let o=await w8(i);o.success&&setTimeout(()=>{b.info("WORKER","Restarting worker after branch switch"),process.exit(0)},1e3),n.json(o)});handleUpdateBranch=this.wrapHandler(async(r,n)=>{b.info("WORKER","Branch update requested");let i=await E8();i.success&&setTimeout(()=>{b.info("WORKER","Restarting worker after branch update"),process.exit(0)},1e3),n.json(i)});validateSettings(r){if(r.CLAUDE_MEM_PROVIDER&&!["claude","gemini","openrouter"].includes(r.CLAUDE_MEM_PROVIDER))return{valid:!1,error:'CLAUDE_MEM_PROVIDER must be "claude", "gemini", or "openrouter"'};if(r.CLAUDE_MEM_GEMINI_MODEL&&!["gemini-2.5-flash-lite","gemini-2.5-flash","gemini-3-flash-preview"].includes(r.CLAUDE_MEM_GEMINI_MODEL))return{valid:!1,error:"CLAUDE_MEM_GEMINI_MODEL must be one of: gemini-2.5-flash-lite, gemini-2.5-flash, gemini-3-flash-preview"};if(r.CLAUDE_MEM_CONTEXT_OBSERVATIONS){let i=parseInt(r.CLAUDE_MEM_CONTEXT_OBSERVATIONS,10);if(isNaN(i)||i<1||i>200)return{valid:!1,error:"CLAUDE_MEM_CONTEXT_OBSERVATIONS must be between 1 and 200"}}if(r.CLAUDE_MEM_WORKER_PORT){let i=parseInt(r.CLAUDE_MEM_WORKER_PORT,10);if(isNaN(i)||i<1024||i>65535)return{valid:!1,error:"CLAUDE_MEM_WORKER_PORT must be between 1024 and 65535"}}if(r.CLAUDE_MEM_WORKER_HOST){let i=r.CLAUDE_MEM_WORKER_HOST;if(!/^(127\.0\.0\.1|0\.0\.0\.0|localhost|\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/.test(i))return{valid:!1,error:"CLAUDE_MEM_WORKER_HOST must be a valid IP address (e.g., 127.0.0.1, 0.0.0.0)"}}if(r.CLAUDE_MEM_LOG_LEVEL&&!["DEBUG","INFO","WARN","ERROR","SILENT"].includes(r.CLAUDE_MEM_LOG_LEVEL.toUpperCase()))return{valid:!1,error:"CLAUDE_MEM_LOG_LEVEL must be one of: DEBUG, INFO, WARN, ERROR, SILENT"};if(r.CLAUDE_MEM_PYTHON_VERSION&&!/^3\.\d{1,2}$/.test(r.CLAUDE_MEM_PYTHON_VERSION))return{valid:!1,error:'CLAUDE_MEM_PYTHON_VERSION must be in format "3.X" or "3.XX" (e.g., "3.13")'};let n=["CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS","CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS","CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT","CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT","CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY","CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE"];for(let i of n)if(r[i]&&!["true","false"].includes(r[i]))return{valid:!1,error:`${i} must be "true" or "false"`};if(r.CLAUDE_MEM_CONTEXT_FULL_COUNT){let i=parseInt(r.CLAUDE_MEM_CONTEXT_FULL_COUNT,10);if(isNaN(i)||i<0||i>20)return{valid:!1,error:"CLAUDE_MEM_CONTEXT_FULL_COUNT must be between 0 and 20"}}if(r.CLAUDE_MEM_CONTEXT_SESSION_COUNT){let i=parseInt(r.CLAUDE_MEM_CONTEXT_SESSION_COUNT,10);if(isNaN(i)||i<1||i>50)return{valid:!1,error:"CLAUDE_MEM_CONTEXT_SESSION_COUNT must be between 1 and 50"}}if(r.CLAUDE_MEM_CONTEXT_FULL_FIELD&&!["narrative","facts"].includes(r.CLAUDE_MEM_CONTEXT_FULL_FIELD))return{valid:!1,error:'CLAUDE_MEM_CONTEXT_FULL_FIELD must be "narrative" or "facts"'};if(r.CLAUDE_MEM_OPENROUTER_MAX_CONTEXT_MESSAGES){let i=parseInt(r.CLAUDE_MEM_OPENROUTER_MAX_CONTEXT_MESSAGES,10);if(isNaN(i)||i<1||i>100)return{valid:!1,error:"CLAUDE_MEM_OPENROUTER_MAX_CONTEXT_MESSAGES must be between 1 and 100"}}if(r.CLAUDE_MEM_OPENROUTER_MAX_TOKENS){let i=parseInt(r.CLAUDE_MEM_OPENROUTER_MAX_TOKENS,10);if(isNaN(i)||i<1e3||i>1e6)return{valid:!1,error:"CLAUDE_MEM_OPENROUTER_MAX_TOKENS must be between 1000 and 1000000"}}if(r.CLAUDE_MEM_OPENROUTER_SITE_URL)try{new URL(r.CLAUDE_MEM_OPENROUTER_SITE_URL)}catch(i){return b.debug("SETTINGS","Invalid URL format",{url:r.CLAUDE_MEM_OPENROUTER_SITE_URL,error:i instanceof Error?i.message:String(i)}),{valid:!1,error:"CLAUDE_MEM_OPENROUTER_SITE_URL must be a valid URL"}}return{valid:!0}}isMcpEnabled(){let r=dn(),n=Ra.default.join(r,"plugin",".mcp.json");return(0,$r.existsSync)(n)}toggleMcp(r){let n=dn(),i=Ra.default.join(n,"plugin",".mcp.json"),s=Ra.default.join(n,"plugin",".mcp.json.disabled");r&&(0,$r.existsSync)(s)?((0,$r.renameSync)(s,i),b.info("WORKER","MCP search server enabled")):!r&&(0,$r.existsSync)(i)?((0,$r.renameSync)(i,s),b.info("WORKER","MCP search server disabled")):b.debug("WORKER","MCP toggle no-op (already in desired state)",{enabled:r})}ensureSettingsFile(r){if(!(0,$r.existsSync)(r)){let n=Ee.getAllDefaults(),i=Ra.default.dirname(r);(0,$r.existsSync)(i)||(0,$r.mkdirSync)(i,{recursive:!0}),(0,$r.writeFileSync)(r,JSON.stringify(n,null,2),"utf-8"),b.info("SETTINGS","Created settings file with defaults",{settingsPath:r})}}};var Cn=require("fs"),Cy=require("path");ne();rr();function C_e(t,e){let r=(0,Cn.openSync)(t,"r");try{let i=(0,Cn.fstatSync)(r).size;if(i===0)return{lines:"",totalEstimate:0};let s=64*1024,o=10*1024*1024,a=Math.min(s,i),c="",u=0;for(;a<=i&&a<=o;){let m=Math.max(0,i-a),h=i-m,g=Buffer.alloc(h);(0,Cn.readSync)(r,g,0,h,m),c=g.toString("utf-8"),u=0;for(let v=0;va.project);n.json({projects:o})});handleGetProcessingStatus=this.wrapHandler((r,n)=>{let i=this.sessionManager.isAnySessionProcessing(),s=this.sessionManager.getTotalActiveWork();n.json({isProcessing:i,queueDepth:s})});handleSetProcessing=this.wrapHandler((r,n)=>{this.workerService.broadcastProcessingStatus();let i=this.sessionManager.isAnySessionProcessing(),s=this.sessionManager.getTotalQueueDepth(),o=this.sessionManager.getActiveSessionCount();n.json({status:"ok",isProcessing:i,queueDepth:s,activeSessions:o})});parsePaginationParams(r){let n=parseInt(r.query.offset,10)||0,i=Math.min(parseInt(r.query.limit,10)||20,100),s=r.query.project;return{offset:n,limit:i,project:s}}handleImport=this.wrapHandler((r,n)=>{let{sessions:i,summaries:s,observations:o,prompts:a}=r.body,c={sessionsImported:0,sessionsSkipped:0,summariesImported:0,summariesSkipped:0,observationsImported:0,observationsSkipped:0,promptsImported:0,promptsSkipped:0},u=this.dbManager.getSessionStore();if(Array.isArray(i))for(let l of i)u.importSdkSession(l).imported?c.sessionsImported++:c.sessionsSkipped++;if(Array.isArray(s))for(let l of s)u.importSessionSummary(l).imported?c.summariesImported++:c.summariesSkipped++;if(Array.isArray(o))for(let l of o)u.importObservation(l).imported?c.observationsImported++:c.observationsSkipped++;if(Array.isArray(a))for(let l of a)u.importUserPrompt(l).imported?c.promptsImported++:c.promptsSkipped++;n.json({success:!0,stats:c})});handleGetPendingQueue=this.wrapHandler((r,n)=>{let{PendingMessageStore:i}=(ha(),zf(ou)),s=new i(this.dbManager.getSessionStore().db,3),o=s.getQueueMessages(),a=s.getRecentlyProcessed(20,30),c=s.getStuckCount(300*1e3),u=s.getSessionsWithPendingMessages();n.json({queue:{messages:o,totalPending:o.filter(l=>l.status==="pending").length,totalProcessing:o.filter(l=>l.status==="processing").length,totalFailed:o.filter(l=>l.status==="failed").length,stuckCount:c},recentlyProcessed:a,sessionsWithPendingWork:u})});handleProcessPendingQueue=this.wrapHandler(async(r,n)=>{let i=Math.min(Math.max(parseInt(r.body.sessionLimit,10)||10,1),100),s=await this.workerService.processPendingQueues(i);n.json({success:!0,...s})});handleClearFailedQueue=this.wrapHandler((r,n)=>{let{PendingMessageStore:i}=(ha(),zf(ou)),o=new i(this.dbManager.getSessionStore().db,3).clearFailed();b.info("QUEUE","Cleared failed queue messages",{clearedCount:o}),n.json({success:!0,clearedCount:o})});handleClearAllQueue=this.wrapHandler((r,n)=>{let{PendingMessageStore:i}=(ha(),zf(ou)),o=new i(this.dbManager.getSessionStore().db,3).clearAll();b.warn("QUEUE","Cleared ALL queue messages (pending, processing, failed)",{clearedCount:o}),n.json({success:!0,clearedCount:o})})};var $y=class extends Ur{constructor(r){super();this.searchManager=r}setupRoutes(r){r.get("/api/search",this.handleUnifiedSearch.bind(this)),r.get("/api/timeline",this.handleUnifiedTimeline.bind(this)),r.get("/api/decisions",this.handleDecisions.bind(this)),r.get("/api/changes",this.handleChanges.bind(this)),r.get("/api/how-it-works",this.handleHowItWorks.bind(this)),r.get("/api/search/observations",this.handleSearchObservations.bind(this)),r.get("/api/search/sessions",this.handleSearchSessions.bind(this)),r.get("/api/search/prompts",this.handleSearchPrompts.bind(this)),r.get("/api/search/by-concept",this.handleSearchByConcept.bind(this)),r.get("/api/search/by-file",this.handleSearchByFile.bind(this)),r.get("/api/search/by-type",this.handleSearchByType.bind(this)),r.get("/api/context/recent",this.handleGetRecentContext.bind(this)),r.get("/api/context/timeline",this.handleGetContextTimeline.bind(this)),r.get("/api/context/preview",this.handleContextPreview.bind(this)),r.get("/api/context/inject",this.handleContextInject.bind(this)),r.get("/api/timeline/by-query",this.handleGetTimelineByQuery.bind(this)),r.get("/api/search/help",this.handleSearchHelp.bind(this))}handleUnifiedSearch=this.wrapHandler(async(r,n)=>{let i=await this.searchManager.search(r.query);n.json(i)});handleUnifiedTimeline=this.wrapHandler(async(r,n)=>{let i=await this.searchManager.timeline(r.query);n.json(i)});handleDecisions=this.wrapHandler(async(r,n)=>{let i=await this.searchManager.decisions(r.query);n.json(i)});handleChanges=this.wrapHandler(async(r,n)=>{let i=await this.searchManager.changes(r.query);n.json(i)});handleHowItWorks=this.wrapHandler(async(r,n)=>{let i=await this.searchManager.howItWorks(r.query);n.json(i)});handleSearchObservations=this.wrapHandler(async(r,n)=>{let i=await this.searchManager.searchObservations(r.query);n.json(i)});handleSearchSessions=this.wrapHandler(async(r,n)=>{let i=await this.searchManager.searchSessions(r.query);n.json(i)});handleSearchPrompts=this.wrapHandler(async(r,n)=>{let i=await this.searchManager.searchUserPrompts(r.query);n.json(i)});handleSearchByConcept=this.wrapHandler(async(r,n)=>{let i=await this.searchManager.findByConcept(r.query);n.json(i)});handleSearchByFile=this.wrapHandler(async(r,n)=>{let i=await this.searchManager.findByFile(r.query);n.json(i)});handleSearchByType=this.wrapHandler(async(r,n)=>{let i=await this.searchManager.findByType(r.query);n.json(i)});handleGetRecentContext=this.wrapHandler(async(r,n)=>{let i=await this.searchManager.getRecentContext(r.query);n.json(i)});handleGetContextTimeline=this.wrapHandler(async(r,n)=>{let i=await this.searchManager.getContextTimeline(r.query);n.json(i)});handleContextPreview=this.wrapHandler(async(r,n)=>{let i=r.query.project;if(!i){this.badRequest(n,"Project parameter is required");return}let{generateContext:s}=await Promise.resolve().then(()=>(pI(),dI)),o=`/preview/${i}`,a=await s({session_id:"preview-"+Date.now(),cwd:o},!0);n.setHeader("Content-Type","text/plain; charset=utf-8"),n.send(a)});handleContextInject=this.wrapHandler(async(r,n)=>{let i=r.query.projects||r.query.project,s=r.query.colors==="true",o=r.query.full==="true";if(!i){this.badRequest(n,"Project(s) parameter is required");return}let a=i.split(",").map(p=>p.trim()).filter(Boolean);if(a.length===0){this.badRequest(n,"At least one project is required");return}let{generateContext:c}=await Promise.resolve().then(()=>(pI(),dI)),l=`/context/${a[a.length-1]}`,d=await c({session_id:"context-inject-"+Date.now(),cwd:l,projects:a,full:o},s);n.setHeader("Content-Type","text/plain; charset=utf-8"),n.send(d)});handleGetTimelineByQuery=this.wrapHandler(async(r,n)=>{let i=await this.searchManager.getTimelineByQuery(r.query);n.json(i)});handleSearchHelp=this.wrapHandler((r,n)=>{n.json({title:"Claude-Mem Search API",description:"HTTP API for searching persistent memory",endpoints:[{path:"/api/search/observations",method:"GET",description:"Search observations using full-text search",parameters:{query:"Search query (required)",limit:"Number of results (default: 20)",project:"Filter by project name (optional)"}},{path:"/api/search/sessions",method:"GET",description:"Search session summaries using full-text search",parameters:{query:"Search query (required)",limit:"Number of results (default: 20)"}},{path:"/api/search/prompts",method:"GET",description:"Search user prompts using full-text search",parameters:{query:"Search query (required)",limit:"Number of results (default: 20)",project:"Filter by project name (optional)"}},{path:"/api/search/by-concept",method:"GET",description:"Find observations by concept tag",parameters:{concept:"Concept tag (required): discovery, decision, bugfix, feature, refactor",limit:"Number of results (default: 10)",project:"Filter by project name (optional)"}},{path:"/api/search/by-file",method:"GET",description:"Find observations and sessions by file path",parameters:{filePath:"File path or partial path (required)",limit:"Number of results per type (default: 10)",project:"Filter by project name (optional)"}},{path:"/api/search/by-type",method:"GET",description:"Find observations by type",parameters:{type:"Observation type (required): discovery, decision, bugfix, feature, refactor",limit:"Number of results (default: 10)",project:"Filter by project name (optional)"}},{path:"/api/context/recent",method:"GET",description:"Get recent session context including summaries and observations",parameters:{project:"Project name (default: current directory)",limit:"Number of recent sessions (default: 3)"}},{path:"/api/context/timeline",method:"GET",description:"Get unified timeline around a specific point in time",parameters:{anchor:'Anchor point: observation ID, session ID (e.g., "S123"), or ISO timestamp (required)',depth_before:"Number of records before anchor (default: 10)",depth_after:"Number of records after anchor (default: 10)",project:"Filter by project name (optional)"}},{path:"/api/timeline/by-query",method:"GET",description:"Search for best match, then get timeline around it",parameters:{query:"Search query (required)",mode:'Search mode: "auto", "observations", or "sessions" (default: "auto")',depth_before:"Number of records before match (default: 10)",depth_after:"Number of records after match (default: 10)",project:"Filter by project name (optional)"}},{path:"/api/search/help",method:"GET",description:"Get this help documentation"}],examples:['curl "http://localhost:37777/api/search/observations?query=authentication&limit=5"','curl "http://localhost:37777/api/search/by-type?type=bugfix&limit=10"','curl "http://localhost:37777/api/context/recent?project=claude-mem&limit=3"','curl "http://localhost:37777/api/context/timeline?anchor=123&depth_before=5&depth_after=5"']})})};var Ra=Me(require("path"),1),$r=require("fs"),gI=require("os");jt();se();var mI=require("child_process"),Ia=require("fs"),Iy=require("path");se();jt();var hf=Ss;function fI(t){return!t||typeof t!="string"?!1:/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/.test(t)&&!t.includes("..")}var O_e=3e5,hI=6e5;function Yn(t){let e=(0,mI.spawnSync)("git",t,{cwd:hf,encoding:"utf-8",timeout:O_e,windowsHide:!0,shell:!1});if(e.error)throw e.error;if(e.status!==0)throw new Error(e.stderr||e.stdout||"Git command failed");return e.stdout.trim()}function x8(t,e=hI){let n=process.platform==="win32"?"npm.cmd":"npm",i=(0,mI.spawnSync)(n,t,{cwd:hf,encoding:"utf-8",timeout:e,windowsHide:!0,shell:!1});if(i.error)throw i.error;if(i.status!==0)throw new Error(i.stderr||i.stdout||"npm command failed");return i.stdout.trim()}function Ry(){let t=(0,Iy.join)(hf,".git");if(!(0,Ia.existsSync)(t))return{branch:null,isBeta:!1,isGitRepo:!1,isDirty:!1,canSwitch:!1,error:"Installed plugin is not a git repository"};try{let e=Yn(["rev-parse","--abbrev-ref","HEAD"]),n=Yn(["status","--porcelain"]).length>0,i=e.startsWith("beta");return{branch:e,isBeta:i,isGitRepo:!0,isDirty:n,canSwitch:!0}}catch(e){return b.error("BRANCH","Failed to get branch info",{},e),{branch:null,isBeta:!1,isGitRepo:!0,isDirty:!1,canSwitch:!1,error:e.message}}}async function w8(t){if(!fI(t))return{success:!1,error:`Invalid branch name: ${t}. Branch names must be alphanumeric with hyphens, underscores, slashes, or dots.`};let e=Ry();if(!e.isGitRepo)return{success:!1,error:"Installed plugin is not a git repository. Please reinstall."};if(e.branch===t)return{success:!0,branch:t,message:`Already on branch ${t}`};try{b.info("BRANCH","Starting branch switch",{from:e.branch,to:t}),b.debug("BRANCH","Discarding local changes"),Yn(["checkout","--","."]),Yn(["clean","-fd"]),b.debug("BRANCH","Fetching from origin"),Yn(["fetch","origin"]),b.debug("BRANCH","Checking out branch",{branch:t});try{Yn(["checkout",t])}catch(n){b.debug("BRANCH","Branch not local, tracking remote",{branch:t,error:n instanceof Error?n.message:String(n)}),Yn(["checkout","-b",t,`origin/${t}`])}b.debug("BRANCH","Pulling latest"),Yn(["pull","origin",t]);let r=(0,Iy.join)(hf,".install-version");return(0,Ia.existsSync)(r)&&(0,Ia.unlinkSync)(r),b.debug("BRANCH","Running npm install"),x8(["install"],hI),b.success("BRANCH","Branch switch complete",{branch:t}),{success:!0,branch:t,message:`Switched to ${t}. Worker will restart automatically.`}}catch(r){b.error("BRANCH","Branch switch failed",{targetBranch:t},r);try{e.branch&&fI(e.branch)&&Yn(["checkout",e.branch])}catch(n){b.error("BRANCH","Recovery checkout also failed",{originalBranch:e.branch},n)}return{success:!1,error:`Branch switch failed: ${r.message}`}}}async function E8(){let t=Ry();if(!t.isGitRepo||!t.branch)return{success:!1,error:"Cannot pull updates: not a git repository"};try{if(!fI(t.branch))return{success:!1,error:`Invalid current branch name: ${t.branch}`};b.info("BRANCH","Pulling updates",{branch:t.branch}),Yn(["checkout","--","."]),Yn(["fetch","origin"]),Yn(["pull","origin",t.branch]);let e=(0,Iy.join)(hf,".install-version");return(0,Ia.existsSync)(e)&&(0,Ia.unlinkSync)(e),x8(["install"],hI),b.success("BRANCH","Updates pulled",{branch:t.branch}),{success:!0,branch:t.branch,message:`Updated ${t.branch}. Worker will restart automatically.`}}catch(e){return b.error("BRANCH","Pull failed",{},e),{success:!1,error:`Pull failed: ${e.message}`}}}rr();Dr();var Oy=class extends Ur{constructor(r){super();this.settingsManager=r}setupRoutes(r){r.get("/api/settings",this.handleGetSettings.bind(this)),r.post("/api/settings",this.handleUpdateSettings.bind(this)),r.get("/api/mcp/status",this.handleGetMcpStatus.bind(this)),r.post("/api/mcp/toggle",this.handleToggleMcp.bind(this)),r.get("/api/branch/status",this.handleGetBranchStatus.bind(this)),r.post("/api/branch/switch",this.handleSwitchBranch.bind(this)),r.post("/api/branch/update",this.handleUpdateBranch.bind(this))}handleGetSettings=this.wrapHandler((r,n)=>{let i=Ra.default.join((0,gI.homedir)(),".claude-mem","settings.json");this.ensureSettingsFile(i);let s=Ee.loadFromFile(i);n.json(s)});handleUpdateSettings=this.wrapHandler((r,n)=>{let i=this.validateSettings(r.body);if(!i.valid){n.status(400).json({success:!1,error:i.error});return}let s=Ra.default.join((0,gI.homedir)(),".claude-mem","settings.json");this.ensureSettingsFile(s);let o={};if((0,$r.existsSync)(s)){let c=(0,$r.readFileSync)(s,"utf-8");try{o=JSON.parse(c)}catch(u){b.error("SETTINGS","Failed to parse settings file",{settingsPath:s},u),n.status(500).json({success:!1,error:"Settings file is corrupted. Delete ~/.claude-mem/settings.json to reset."});return}}let a=["CLAUDE_MEM_MODEL","CLAUDE_MEM_CONTEXT_OBSERVATIONS","CLAUDE_MEM_WORKER_PORT","CLAUDE_MEM_WORKER_HOST","CLAUDE_MEM_PROVIDER","CLAUDE_MEM_GEMINI_API_KEY","CLAUDE_MEM_GEMINI_MODEL","CLAUDE_MEM_GEMINI_RATE_LIMITING_ENABLED","CLAUDE_MEM_OPENROUTER_API_KEY","CLAUDE_MEM_OPENROUTER_MODEL","CLAUDE_MEM_OPENROUTER_SITE_URL","CLAUDE_MEM_OPENROUTER_APP_NAME","CLAUDE_MEM_OPENROUTER_MAX_CONTEXT_MESSAGES","CLAUDE_MEM_OPENROUTER_MAX_TOKENS","CLAUDE_MEM_DATA_DIR","CLAUDE_MEM_LOG_LEVEL","CLAUDE_MEM_PYTHON_VERSION","CLAUDE_CODE_PATH","CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS","CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS","CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT","CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT","CLAUDE_MEM_CONTEXT_OBSERVATION_TYPES","CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS","CLAUDE_MEM_CONTEXT_FULL_COUNT","CLAUDE_MEM_CONTEXT_FULL_FIELD","CLAUDE_MEM_CONTEXT_SESSION_COUNT","CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY","CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE","CLAUDE_MEM_FOLDER_CLAUDEMD_ENABLED"];for(let c of a)r.body[c]!==void 0&&(o[c]=r.body[c]);(0,$r.writeFileSync)(s,JSON.stringify(o,null,2),"utf-8"),lM(),b.info("WORKER","Settings updated"),n.json({success:!0,message:"Settings updated successfully"})});handleGetMcpStatus=this.wrapHandler((r,n)=>{let i=this.isMcpEnabled();n.json({enabled:i})});handleToggleMcp=this.wrapHandler((r,n)=>{let{enabled:i}=r.body;if(typeof i!="boolean"){this.badRequest(n,"enabled must be a boolean");return}this.toggleMcp(i),n.json({success:!0,enabled:this.isMcpEnabled()})});handleGetBranchStatus=this.wrapHandler((r,n)=>{let i=Ry();n.json(i)});handleSwitchBranch=this.wrapHandler(async(r,n)=>{let{branch:i}=r.body;if(!i){n.status(400).json({success:!1,error:"Missing branch parameter"});return}let s=["main","beta/7.0","feature/bun-executable"];if(!s.includes(i)){n.status(400).json({success:!1,error:`Invalid branch. Allowed: ${s.join(", ")}`});return}b.info("WORKER","Branch switch requested",{branch:i});let o=await w8(i);o.success&&setTimeout(()=>{b.info("WORKER","Restarting worker after branch switch"),process.exit(0)},1e3),n.json(o)});handleUpdateBranch=this.wrapHandler(async(r,n)=>{b.info("WORKER","Branch update requested");let i=await E8();i.success&&setTimeout(()=>{b.info("WORKER","Restarting worker after branch update"),process.exit(0)},1e3),n.json(i)});validateSettings(r){if(r.CLAUDE_MEM_PROVIDER&&!["claude","gemini","openrouter"].includes(r.CLAUDE_MEM_PROVIDER))return{valid:!1,error:'CLAUDE_MEM_PROVIDER must be "claude", "gemini", or "openrouter"'};if(r.CLAUDE_MEM_GEMINI_MODEL&&!["gemini-2.5-flash-lite","gemini-2.5-flash","gemini-3-flash-preview"].includes(r.CLAUDE_MEM_GEMINI_MODEL))return{valid:!1,error:"CLAUDE_MEM_GEMINI_MODEL must be one of: gemini-2.5-flash-lite, gemini-2.5-flash, gemini-3-flash-preview"};if(r.CLAUDE_MEM_CONTEXT_OBSERVATIONS){let i=parseInt(r.CLAUDE_MEM_CONTEXT_OBSERVATIONS,10);if(isNaN(i)||i<1||i>200)return{valid:!1,error:"CLAUDE_MEM_CONTEXT_OBSERVATIONS must be between 1 and 200"}}if(r.CLAUDE_MEM_WORKER_PORT){let i=parseInt(r.CLAUDE_MEM_WORKER_PORT,10);if(isNaN(i)||i<1024||i>65535)return{valid:!1,error:"CLAUDE_MEM_WORKER_PORT must be between 1024 and 65535"}}if(r.CLAUDE_MEM_WORKER_HOST){let i=r.CLAUDE_MEM_WORKER_HOST;if(!/^(127\.0\.0\.1|0\.0\.0\.0|localhost|\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/.test(i))return{valid:!1,error:"CLAUDE_MEM_WORKER_HOST must be a valid IP address (e.g., 127.0.0.1, 0.0.0.0)"}}if(r.CLAUDE_MEM_LOG_LEVEL&&!["DEBUG","INFO","WARN","ERROR","SILENT"].includes(r.CLAUDE_MEM_LOG_LEVEL.toUpperCase()))return{valid:!1,error:"CLAUDE_MEM_LOG_LEVEL must be one of: DEBUG, INFO, WARN, ERROR, SILENT"};if(r.CLAUDE_MEM_PYTHON_VERSION&&!/^3\.\d{1,2}$/.test(r.CLAUDE_MEM_PYTHON_VERSION))return{valid:!1,error:'CLAUDE_MEM_PYTHON_VERSION must be in format "3.X" or "3.XX" (e.g., "3.13")'};let n=["CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS","CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS","CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT","CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT","CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY","CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE"];for(let i of n)if(r[i]&&!["true","false"].includes(r[i]))return{valid:!1,error:`${i} must be "true" or "false"`};if(r.CLAUDE_MEM_CONTEXT_FULL_COUNT){let i=parseInt(r.CLAUDE_MEM_CONTEXT_FULL_COUNT,10);if(isNaN(i)||i<0||i>20)return{valid:!1,error:"CLAUDE_MEM_CONTEXT_FULL_COUNT must be between 0 and 20"}}if(r.CLAUDE_MEM_CONTEXT_SESSION_COUNT){let i=parseInt(r.CLAUDE_MEM_CONTEXT_SESSION_COUNT,10);if(isNaN(i)||i<1||i>50)return{valid:!1,error:"CLAUDE_MEM_CONTEXT_SESSION_COUNT must be between 1 and 50"}}if(r.CLAUDE_MEM_CONTEXT_FULL_FIELD&&!["narrative","facts"].includes(r.CLAUDE_MEM_CONTEXT_FULL_FIELD))return{valid:!1,error:'CLAUDE_MEM_CONTEXT_FULL_FIELD must be "narrative" or "facts"'};if(r.CLAUDE_MEM_OPENROUTER_MAX_CONTEXT_MESSAGES){let i=parseInt(r.CLAUDE_MEM_OPENROUTER_MAX_CONTEXT_MESSAGES,10);if(isNaN(i)||i<1||i>100)return{valid:!1,error:"CLAUDE_MEM_OPENROUTER_MAX_CONTEXT_MESSAGES must be between 1 and 100"}}if(r.CLAUDE_MEM_OPENROUTER_MAX_TOKENS){let i=parseInt(r.CLAUDE_MEM_OPENROUTER_MAX_TOKENS,10);if(isNaN(i)||i<1e3||i>1e6)return{valid:!1,error:"CLAUDE_MEM_OPENROUTER_MAX_TOKENS must be between 1000 and 1000000"}}if(r.CLAUDE_MEM_OPENROUTER_SITE_URL)try{new URL(r.CLAUDE_MEM_OPENROUTER_SITE_URL)}catch(i){return b.debug("SETTINGS","Invalid URL format",{url:r.CLAUDE_MEM_OPENROUTER_SITE_URL,error:i instanceof Error?i.message:String(i)}),{valid:!1,error:"CLAUDE_MEM_OPENROUTER_SITE_URL must be a valid URL"}}return{valid:!0}}isMcpEnabled(){let r=dn(),n=Ra.default.join(r,"plugin",".mcp.json");return(0,$r.existsSync)(n)}toggleMcp(r){let n=dn(),i=Ra.default.join(n,"plugin",".mcp.json"),s=Ra.default.join(n,"plugin",".mcp.json.disabled");r&&(0,$r.existsSync)(s)?((0,$r.renameSync)(s,i),b.info("WORKER","MCP search server enabled")):!r&&(0,$r.existsSync)(i)?((0,$r.renameSync)(i,s),b.info("WORKER","MCP search server disabled")):b.debug("WORKER","MCP toggle no-op (already in desired state)",{enabled:r})}ensureSettingsFile(r){if(!(0,$r.existsSync)(r)){let n=Ee.getAllDefaults(),i=Ra.default.dirname(r);(0,$r.existsSync)(i)||(0,$r.mkdirSync)(i,{recursive:!0}),(0,$r.writeFileSync)(r,JSON.stringify(n,null,2),"utf-8"),b.info("SETTINGS","Created settings file with defaults",{settingsPath:r})}}};var Cn=require("fs"),Cy=require("path");se();rr();function C_e(t,e){let r=(0,Cn.openSync)(t,"r");try{let i=(0,Cn.fstatSync)(r).size;if(i===0)return{lines:"",totalEstimate:0};let s=64*1024,o=10*1024*1024,a=Math.min(s,i),c="",u=0;for(;a<=i&&a<=o;){let m=Math.max(0,i-a),h=i-m,g=Buffer.alloc(h);(0,Cn.readSync)(r,g,0,h,m),c=g.toString("utf-8"),u=0;for(let v=0;v=e||m===0)break;a=Math.min(a*2,i,o)}let l=c.split(` `);l.length>0&&l[l.length-1]===""&&l.pop();let d=Math.max(0,l.length-e),p=l.slice(d),f;if(i<=a)f=l.length;else{let m=c.length/Math.max(u,1);f=Math.round(i/m)}return{lines:p.join(` `),totalEstimate:f}}finally{(0,Cn.closeSync)(r)}}var Py=class extends Ur{getLogFilePath(){let e=Ee.get("CLAUDE_MEM_DATA_DIR"),r=(0,Cy.join)(e,"logs"),n=new Date().toISOString().split("T")[0];return(0,Cy.join)(r,`claude-mem-${n}.log`)}getLogsDir(){let e=Ee.get("CLAUDE_MEM_DATA_DIR");return(0,Cy.join)(e,"logs")}setupRoutes(e){e.get("/api/logs",this.handleGetLogs.bind(this)),e.post("/api/logs/clear",this.handleClearLogs.bind(this))}handleGetLogs=this.wrapHandler((e,r)=>{let n=this.getLogFilePath();if(!(0,Cn.existsSync)(n)){r.json({logs:"",path:n,exists:!1});return}let i=parseInt(e.query.lines||"1000",10),s=Math.min(i,1e4),{lines:o,totalEstimate:a}=C_e(n,s),c=o===""?0:o.split(` -`).length;r.json({logs:o,path:n,exists:!0,totalLines:a,returnedLines:c})});handleClearLogs=this.wrapHandler((e,r)=>{let n=this.getLogFilePath();if(!(0,Cn.existsSync)(n)){r.json({success:!0,message:"Log file does not exist",path:n});return}(0,Cn.writeFileSync)(n,"","utf-8"),b.info("SYSTEM","Log file cleared via UI",{path:n}),r.json({success:!0,message:"Log file cleared",path:n})})};ne();var Ay=class extends Ur{constructor(r,n){super();this.dbManager=r;this.defaultProject=n}setupRoutes(r){r.post("/api/memory/save",this.handleSaveMemory.bind(this))}handleSaveMemory=this.wrapHandler(async(r,n)=>{let{text:i,title:s,project:o}=r.body,a=o||this.defaultProject;if(!i||typeof i!="string"||i.trim().length===0){this.badRequest(n,"text is required and must be non-empty");return}let c=this.dbManager.getSessionStore(),u=this.dbManager.getChromaSync(),l=c.getOrCreateManualSession(a),d={type:"discovery",title:s||i.substring(0,60).trim()+(i.length>60?"...":""),subtitle:"Manual memory",facts:[],narrative:i,concepts:[],files_read:[],files_modified:[]},p=c.storeObservation(l,a,d,0,0);b.info("HTTP","Manual observation saved",{id:p.id,project:a,title:d.title}),u.syncObservation(p.id,l,a,d,0,p.createdAtEpoch,0).catch(f=>{b.error("CHROMA","ChromaDB sync failed",{id:p.id},f)}),n.json({success:!0,id:p.id,title:d.title,project:a,message:`Memory saved as observation #${p.id}`})})};var Ri=require("fs"),u_=require("path");var vI=(t,e,r)=>{let n=t instanceof RegExp?k8(t,r):t,i=e instanceof RegExp?k8(e,r):e,s=n!==null&&i!=null&&P_e(n,i,r);return s&&{start:s[0],end:s[1],pre:r.slice(0,s[0]),body:r.slice(s[0]+n.length,s[1]),post:r.slice(s[1]+i.length)}},k8=(t,e)=>{let r=e.match(t);return r?r[0]:null},P_e=(t,e,r)=>{let n,i,s,o,a,c=r.indexOf(t),u=r.indexOf(e,c+1),l=c;if(c>=0&&u>0){if(t===e)return[c,u];for(n=[],s=r.length;l>=0&&!a;){if(l===c)n.push(l),c=r.indexOf(t,l+1);else if(n.length===1){let d=n.pop();d!==void 0&&(a=[d,u])}else i=n.pop(),i!==void 0&&i=0?c:u}n.length&&o!==void 0&&(a=[s,o])}return a};var T8="\0SLASH"+Math.random()+"\0",$8="\0OPEN"+Math.random()+"\0",_I="\0CLOSE"+Math.random()+"\0",I8="\0COMMA"+Math.random()+"\0",R8="\0PERIOD"+Math.random()+"\0",A_e=new RegExp(T8,"g"),N_e=new RegExp($8,"g"),M_e=new RegExp(_I,"g"),D_e=new RegExp(I8,"g"),j_e=new RegExp(R8,"g"),z_e=/\\\\/g,L_e=/\\{/g,U_e=/\\}/g,F_e=/\\,/g,q_e=/\\./g;function yI(t){return isNaN(t)?t.charCodeAt(0):parseInt(t,10)}function H_e(t){return t.replace(z_e,T8).replace(L_e,$8).replace(U_e,_I).replace(F_e,I8).replace(q_e,R8)}function Z_e(t){return t.replace(A_e,"\\").replace(N_e,"{").replace(M_e,"}").replace(D_e,",").replace(j_e,".")}function O8(t){if(!t)return[""];let e=[],r=vI("{","}",t);if(!r)return t.split(",");let{pre:n,body:i,post:s}=r,o=n.split(",");o[o.length-1]+="{"+i+"}";let a=O8(s);return s.length&&(o[o.length-1]+=a.shift(),o.push.apply(o,a)),e.push.apply(e,o),e}function C8(t){return t?(t.slice(0,2)==="{}"&&(t="\\{\\}"+t.slice(2)),gf(H_e(t),!0).map(Z_e)):[]}function B_e(t){return"{"+t+"}"}function G_e(t){return/^-?0\d/.test(t)}function W_e(t,e){return t<=e}function V_e(t,e){return t>=e}function gf(t,e){let r=[],n=vI("{","}",t);if(!n)return[t];let i=n.pre,s=n.post.length?gf(n.post,!1):[""];if(/\$$/.test(n.pre))for(let o=0;o=0;if(!c&&!u)return n.post.match(/,(?!,).*\}/)?(t=n.pre+"{"+n.body+_I+n.post,gf(t)):[t];let l;if(c)l=n.body.split(/\.\./);else if(l=O8(n.body),l.length===1&&l[0]!==void 0&&(l=gf(l[0],!1).map(B_e),l.length===1))return s.map(p=>n.pre+l[0]+p);let d;if(c&&l[0]!==void 0&&l[1]!==void 0){let p=yI(l[0]),f=yI(l[1]),m=Math.max(l[0].length,l[1].length),h=l.length===3&&l[2]!==void 0?Math.abs(yI(l[2])):1,g=W_e;f0){let w=new Array(x+1).join("0");_<0?y="-"+w+y.slice(1):y=w+y}}d.push(y)}}else{d=[];for(let p=0;p{if(typeof t!="string")throw new TypeError("invalid pattern");if(t.length>65536)throw new TypeError("pattern is too long")};var K_e={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}",!0],"[:alpha:]":["\\p{L}\\p{Nl}",!0],"[:ascii:]":["\\x00-\\x7f",!1],"[:blank:]":["\\p{Zs}\\t",!0],"[:cntrl:]":["\\p{Cc}",!0],"[:digit:]":["\\p{Nd}",!0],"[:graph:]":["\\p{Z}\\p{C}",!0,!0],"[:lower:]":["\\p{Ll}",!0],"[:print:]":["\\p{C}",!0],"[:punct:]":["\\p{P}",!0],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f",!0],"[:upper:]":["\\p{Lu}",!0],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}",!0],"[:xdigit:]":["A-Fa-f0-9",!1]},yf=t=>t.replace(/[[\]\\-]/g,"\\$&"),J_e=t=>t.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),P8=t=>t.join(""),A8=(t,e)=>{let r=e;if(t.charAt(r)!=="[")throw new Error("not in a brace expression");let n=[],i=[],s=r+1,o=!1,a=!1,c=!1,u=!1,l=r,d="";e:for(;sd?n.push(yf(d)+"-"+yf(h)):h===d&&n.push(yf(h)),d="",s++;continue}if(t.startsWith("-]",s+1)){n.push(yf(h+"-")),s+=2;continue}if(t.startsWith("-",s+1)){d=h,s+=2;continue}n.push(yf(h)),s++}if(lr?e?t.replace(/\[([^\/\\])\]/g,"$1"):t.replace(/((?!\\).|^)\[([^\/\\])\]/g,"$1$2").replace(/\\([^\/])/g,"$1"):e?t.replace(/\[([^\/\\{}])\]/g,"$1"):t.replace(/((?!\\).|^)\[([^\/\\{}])\]/g,"$1$2").replace(/\\([^\/{}])/g,"$1");var X_e=new Set(["!","?","+","*","@"]),N8=t=>X_e.has(t),Y_e="(?!(?:^|/)\\.\\.?(?:$|/))",Ny="(?!\\.)",Q_e=new Set(["[","."]),ebe=new Set(["..","."]),tbe=new Set("().*{}+?[]^$\\!"),rbe=t=>t.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),bI="[^/]",M8=bI+"*?",D8=bI+"+?",Uu=class t{type;#e;#r;#s=!1;#i=[];#o;#b;#v;#l=!1;#a;#p;#d=!1;constructor(e,r,n={}){this.type=e,e&&(this.#r=!0),this.#o=r,this.#e=this.#o?this.#o.#e:this,this.#a=this.#e===this?n:this.#e.#a,this.#v=this.#e===this?[]:this.#e.#v,e==="!"&&!this.#e.#l&&this.#v.push(this),this.#b=this.#o?this.#o.#i.length:0}get hasMagic(){if(this.#r!==void 0)return this.#r;for(let e of this.#i)if(typeof e!="string"&&(e.type||e.hasMagic))return this.#r=!0;return this.#r}toString(){return this.#p!==void 0?this.#p:this.type?this.#p=this.type+"("+this.#i.map(e=>String(e)).join("|")+")":this.#p=this.#i.map(e=>String(e)).join("")}#c(){if(this!==this.#e)throw new Error("should only call on root");if(this.#l)return this;this.toString(),this.#l=!0;let e;for(;e=this.#v.pop();){if(e.type!=="!")continue;let r=e,n=r.#o;for(;n;){for(let i=r.#b+1;!n.type&&itypeof r=="string"?r:r.toJSON()):[this.type,...this.#i.map(r=>r.toJSON())];return this.isStart()&&!this.type&&e.unshift([]),this.isEnd()&&(this===this.#e||this.#e.#l&&this.#o?.type==="!")&&e.push({}),e}isStart(){if(this.#e===this)return!0;if(!this.#o?.isStart())return!1;if(this.#b===0)return!0;let e=this.#o;for(let r=0;rtypeof f!="string"),u=this.#i.map(f=>{let[m,h,g,v]=typeof f=="string"?t.#S(f,this.#r,c):f.toRegExpSource(e);return this.#r=this.#r||g,this.#s=this.#s||v,m}).join(""),l="";if(this.isStart()&&typeof this.#i[0]=="string"&&!(this.#i.length===1&&ebe.has(this.#i[0]))){let m=Q_e,h=r&&m.has(u.charAt(0))||u.startsWith("\\.")&&m.has(u.charAt(2))||u.startsWith("\\.\\.")&&m.has(u.charAt(4)),g=!r&&!e&&m.has(u.charAt(0));l=h?Y_e:g?Ny:""}let d="";return this.isEnd()&&this.#e.#l&&this.#o?.type==="!"&&(d="(?:$|\\/)"),[l+u+d,Ei(u),this.#r=!!this.#r,this.#s]}let n=this.type==="*"||this.type==="+",i=this.type==="!"?"(?:(?!(?:":"(?:",s=this.#f(r);if(this.isStart()&&this.isEnd()&&!s&&this.type!=="!"){let c=this.toString();return this.#i=[c],this.type=null,this.#r=void 0,[c,Ei(this.toString()),!1,!1]}let o=!n||e||r||!Ny?"":this.#f(!0);o===s&&(o=""),o&&(s=`(?:${s})(?:${o})*?`);let a="";if(this.type==="!"&&this.#d)a=(this.isStart()&&!r?Ny:"")+D8;else{let c=this.type==="!"?"))"+(this.isStart()&&!r&&!e?Ny:"")+M8+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&o?")":this.type==="*"&&o?")?":`)${this.type}`;a=i+s+c}return[a,Ei(s),this.#r=!!this.#r,this.#s]}#f(e){return this.#i.map(r=>{if(typeof r=="string")throw new Error("string type in extglob ast??");let[n,i,s,o]=r.toRegExpSource(e);return this.#s=this.#s||o,n}).filter(r=>!(this.isStart()&&this.isEnd())||!!r).join("|")}static#S(e,r,n=!1){let i=!1,s="",o=!1;for(let a=0;ar?e?t.replace(/[?*()[\]{}]/g,"[$&]"):t.replace(/[?*()[\]\\{}]/g,"\\$&"):e?t.replace(/[?*()[\]]/g,"[$&]"):t.replace(/[?*()[\]\\]/g,"\\$&");var tn=(t,e,r={})=>(vf(e),!r.nocomment&&e.charAt(0)==="#"?!1:new Pn(e,r).match(t)),nbe=/^\*+([^+@!?\*\[\(]*)$/,ibe=t=>e=>!e.startsWith(".")&&e.endsWith(t),sbe=t=>e=>e.endsWith(t),obe=t=>(t=t.toLowerCase(),e=>!e.startsWith(".")&&e.toLowerCase().endsWith(t)),abe=t=>(t=t.toLowerCase(),e=>e.toLowerCase().endsWith(t)),cbe=/^\*+\.\*+$/,ube=t=>!t.startsWith(".")&&t.includes("."),lbe=t=>t!=="."&&t!==".."&&t.includes("."),dbe=/^\.\*+$/,pbe=t=>t!=="."&&t!==".."&&t.startsWith("."),fbe=/^\*+$/,mbe=t=>t.length!==0&&!t.startsWith("."),hbe=t=>t.length!==0&&t!=="."&&t!=="..",gbe=/^\?+([^+@!?\*\[\(]*)?$/,vbe=([t,e=""])=>{let r=L8([t]);return e?(e=e.toLowerCase(),n=>r(n)&&n.toLowerCase().endsWith(e)):r},ybe=([t,e=""])=>{let r=U8([t]);return e?(e=e.toLowerCase(),n=>r(n)&&n.toLowerCase().endsWith(e)):r},_be=([t,e=""])=>{let r=U8([t]);return e?n=>r(n)&&n.endsWith(e):r},bbe=([t,e=""])=>{let r=L8([t]);return e?n=>r(n)&&n.endsWith(e):r},L8=([t])=>{let e=t.length;return r=>r.length===e&&!r.startsWith(".")},U8=([t])=>{let e=t.length;return r=>r.length===e&&r!=="."&&r!==".."},F8=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",j8={win32:{sep:"\\"},posix:{sep:"/"}},Sbe=F8==="win32"?j8.win32.sep:j8.posix.sep;tn.sep=Sbe;var Ir=Symbol("globstar **");tn.GLOBSTAR=Ir;var xbe="[^/]",wbe=xbe+"*?",Ebe="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",kbe="(?:(?!(?:\\/|^)\\.).)*?",Tbe=(t,e={})=>r=>tn(r,t,e);tn.filter=Tbe;var Qn=(t,e={})=>Object.assign({},t,e),$be=t=>{if(!t||typeof t!="object"||!Object.keys(t).length)return tn;let e=tn;return Object.assign((n,i,s={})=>e(n,i,Qn(t,s)),{Minimatch:class extends e.Minimatch{constructor(i,s={}){super(i,Qn(t,s))}static defaults(i){return e.defaults(Qn(t,i)).Minimatch}},AST:class extends e.AST{constructor(i,s,o={}){super(i,s,Qn(t,o))}static fromGlob(i,s={}){return e.AST.fromGlob(i,Qn(t,s))}},unescape:(n,i={})=>e.unescape(n,Qn(t,i)),escape:(n,i={})=>e.escape(n,Qn(t,i)),filter:(n,i={})=>e.filter(n,Qn(t,i)),defaults:n=>e.defaults(Qn(t,n)),makeRe:(n,i={})=>e.makeRe(n,Qn(t,i)),braceExpand:(n,i={})=>e.braceExpand(n,Qn(t,i)),match:(n,i,s={})=>e.match(n,i,Qn(t,s)),sep:e.sep,GLOBSTAR:Ir})};tn.defaults=$be;var q8=(t,e={})=>(vf(t),e.nobrace||!/\{(?:(?!\{).)*\}/.test(t)?[t]:C8(t));tn.braceExpand=q8;var Ibe=(t,e={})=>new Pn(t,e).makeRe();tn.makeRe=Ibe;var Rbe=(t,e,r={})=>{let n=new Pn(e,r);return t=t.filter(i=>n.match(i)),n.options.nonull&&!t.length&&t.push(e),t};tn.match=Rbe;var z8=/[?*]|[+@!]\(.*?\)|\[|\]/,Obe=t=>t.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Pn=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;regexp;constructor(e,r={}){vf(e),r=r||{},this.options=r,this.pattern=e,this.platform=r.platform||F8,this.isWindows=this.platform==="win32",this.windowsPathsNoEscape=!!r.windowsPathsNoEscape||r.allowWindowsEscape===!1,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,"/")),this.preserveMultipleSlashes=!!r.preserveMultipleSlashes,this.regexp=null,this.negate=!1,this.nonegate=!!r.nonegate,this.comment=!1,this.empty=!1,this.partial=!!r.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=r.windowsNoMagicRoot!==void 0?r.windowsNoMagicRoot:!!(this.isWindows&&this.nocase),this.globSet=[],this.globParts=[],this.set=[],this.make()}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return!0;for(let e of this.set)for(let r of e)if(typeof r!="string")return!0;return!1}debug(...e){}make(){let e=this.pattern,r=this.options;if(!r.nocomment&&e.charAt(0)==="#"){this.comment=!0;return}if(!e){this.empty=!0;return}this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],r.debug&&(this.debug=(...s)=>console.error(...s)),this.debug(this.pattern,this.globSet);let n=this.globSet.map(s=>this.slashSplit(s));this.globParts=this.preprocess(n),this.debug(this.pattern,this.globParts);let i=this.globParts.map((s,o,a)=>{if(this.isWindows&&this.windowsNoMagicRoot){let c=s[0]===""&&s[1]===""&&(s[2]==="?"||!z8.test(s[2]))&&!z8.test(s[3]),u=/^[a-z]:/i.test(s[0]);if(c)return[...s.slice(0,4),...s.slice(4).map(l=>this.parse(l))];if(u)return[s[0],...s.slice(1).map(l=>this.parse(l))]}return s.map(c=>this.parse(c))});if(this.debug(this.pattern,i),this.set=i.filter(s=>s.indexOf(!1)===-1),this.isWindows)for(let s=0;s=2?(e=this.firstPhasePreProcess(e),e=this.secondPhasePreProcess(e)):r>=1?e=this.levelOneOptimize(e):e=this.adjascentGlobstarOptimize(e),e}adjascentGlobstarOptimize(e){return e.map(r=>{let n=-1;for(;(n=r.indexOf("**",n+1))!==-1;){let i=n;for(;r[i+1]==="**";)i++;i!==n&&r.splice(n,i-n)}return r})}levelOneOptimize(e){return e.map(r=>(r=r.reduce((n,i)=>{let s=n[n.length-1];return i==="**"&&s==="**"?n:i===".."&&s&&s!==".."&&s!=="."&&s!=="**"?(n.pop(),n):(n.push(i),n)},[]),r.length===0?[""]:r))}levelTwoFileOptimize(e){Array.isArray(e)||(e=this.slashSplit(e));let r=!1;do{if(r=!1,!this.preserveMultipleSlashes){for(let i=1;ii&&n.splice(i+1,o-i);let a=n[i+1],c=n[i+2],u=n[i+3];if(a!==".."||!c||c==="."||c===".."||!u||u==="."||u==="..")continue;r=!0,n.splice(i,1);let l=n.slice(0);l[i]="**",e.push(l),i--}if(!this.preserveMultipleSlashes){for(let o=1;or.length)}partsMatch(e,r,n=!1){let i=0,s=0,o=[],a="";for(;i_?r=r.slice(y):_>y&&(e=e.slice(_)))}}let{optimizationLevel:s=1}=this.options;s>=2&&(e=this.levelTwoFileOptimize(e)),this.debug("matchOne",this,{file:e,pattern:r}),this.debug("matchOne",e.length,r.length);for(var o=0,a=0,c=e.length,u=r.length;o{let n=this.getLogFilePath();if(!(0,Cn.existsSync)(n)){r.json({success:!0,message:"Log file does not exist",path:n});return}(0,Cn.writeFileSync)(n,"","utf-8"),b.info("SYSTEM","Log file cleared via UI",{path:n}),r.json({success:!0,message:"Log file cleared",path:n})})};se();var Ay=class extends Ur{constructor(r,n){super();this.dbManager=r;this.defaultProject=n}setupRoutes(r){r.post("/api/memory/save",this.handleSaveMemory.bind(this))}handleSaveMemory=this.wrapHandler(async(r,n)=>{let{text:i,title:s,project:o}=r.body,a=o||this.defaultProject;if(!i||typeof i!="string"||i.trim().length===0){this.badRequest(n,"text is required and must be non-empty");return}let c=this.dbManager.getSessionStore(),u=this.dbManager.getChromaSync(),l=c.getOrCreateManualSession(a),d={type:"discovery",title:s||i.substring(0,60).trim()+(i.length>60?"...":""),subtitle:"Manual memory",facts:[],narrative:i,concepts:[],files_read:[],files_modified:[]},p=c.storeObservation(l,a,d,0,0);b.info("HTTP","Manual observation saved",{id:p.id,project:a,title:d.title}),u.syncObservation(p.id,l,a,d,0,p.createdAtEpoch,0).catch(f=>{b.error("CHROMA","ChromaDB sync failed",{id:p.id},f)}),n.json({success:!0,id:p.id,title:d.title,project:a,message:`Memory saved as observation #${p.id}`})})};var Ri=require("fs"),u_=require("path");var vI=(t,e,r)=>{let n=t instanceof RegExp?k8(t,r):t,i=e instanceof RegExp?k8(e,r):e,s=n!==null&&i!=null&&P_e(n,i,r);return s&&{start:s[0],end:s[1],pre:r.slice(0,s[0]),body:r.slice(s[0]+n.length,s[1]),post:r.slice(s[1]+i.length)}},k8=(t,e)=>{let r=e.match(t);return r?r[0]:null},P_e=(t,e,r)=>{let n,i,s,o,a,c=r.indexOf(t),u=r.indexOf(e,c+1),l=c;if(c>=0&&u>0){if(t===e)return[c,u];for(n=[],s=r.length;l>=0&&!a;){if(l===c)n.push(l),c=r.indexOf(t,l+1);else if(n.length===1){let d=n.pop();d!==void 0&&(a=[d,u])}else i=n.pop(),i!==void 0&&i=0?c:u}n.length&&o!==void 0&&(a=[s,o])}return a};var T8="\0SLASH"+Math.random()+"\0",$8="\0OPEN"+Math.random()+"\0",_I="\0CLOSE"+Math.random()+"\0",I8="\0COMMA"+Math.random()+"\0",R8="\0PERIOD"+Math.random()+"\0",A_e=new RegExp(T8,"g"),N_e=new RegExp($8,"g"),M_e=new RegExp(_I,"g"),D_e=new RegExp(I8,"g"),j_e=new RegExp(R8,"g"),z_e=/\\\\/g,L_e=/\\{/g,U_e=/\\}/g,F_e=/\\,/g,q_e=/\\./g;function yI(t){return isNaN(t)?t.charCodeAt(0):parseInt(t,10)}function H_e(t){return t.replace(z_e,T8).replace(L_e,$8).replace(U_e,_I).replace(F_e,I8).replace(q_e,R8)}function Z_e(t){return t.replace(A_e,"\\").replace(N_e,"{").replace(M_e,"}").replace(D_e,",").replace(j_e,".")}function O8(t){if(!t)return[""];let e=[],r=vI("{","}",t);if(!r)return t.split(",");let{pre:n,body:i,post:s}=r,o=n.split(",");o[o.length-1]+="{"+i+"}";let a=O8(s);return s.length&&(o[o.length-1]+=a.shift(),o.push.apply(o,a)),e.push.apply(e,o),e}function C8(t){return t?(t.slice(0,2)==="{}"&&(t="\\{\\}"+t.slice(2)),gf(H_e(t),!0).map(Z_e)):[]}function B_e(t){return"{"+t+"}"}function G_e(t){return/^-?0\d/.test(t)}function W_e(t,e){return t<=e}function V_e(t,e){return t>=e}function gf(t,e){let r=[],n=vI("{","}",t);if(!n)return[t];let i=n.pre,s=n.post.length?gf(n.post,!1):[""];if(/\$$/.test(n.pre))for(let o=0;o=0;if(!c&&!u)return n.post.match(/,(?!,).*\}/)?(t=n.pre+"{"+n.body+_I+n.post,gf(t)):[t];let l;if(c)l=n.body.split(/\.\./);else if(l=O8(n.body),l.length===1&&l[0]!==void 0&&(l=gf(l[0],!1).map(B_e),l.length===1))return s.map(p=>n.pre+l[0]+p);let d;if(c&&l[0]!==void 0&&l[1]!==void 0){let p=yI(l[0]),f=yI(l[1]),m=Math.max(l[0].length,l[1].length),h=l.length===3&&l[2]!==void 0?Math.abs(yI(l[2])):1,g=W_e;f0){let w=new Array(x+1).join("0");_<0?y="-"+w+y.slice(1):y=w+y}}d.push(y)}}else{d=[];for(let p=0;p{if(typeof t!="string")throw new TypeError("invalid pattern");if(t.length>65536)throw new TypeError("pattern is too long")};var K_e={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}",!0],"[:alpha:]":["\\p{L}\\p{Nl}",!0],"[:ascii:]":["\\x00-\\x7f",!1],"[:blank:]":["\\p{Zs}\\t",!0],"[:cntrl:]":["\\p{Cc}",!0],"[:digit:]":["\\p{Nd}",!0],"[:graph:]":["\\p{Z}\\p{C}",!0,!0],"[:lower:]":["\\p{Ll}",!0],"[:print:]":["\\p{C}",!0],"[:punct:]":["\\p{P}",!0],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f",!0],"[:upper:]":["\\p{Lu}",!0],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}",!0],"[:xdigit:]":["A-Fa-f0-9",!1]},yf=t=>t.replace(/[[\]\\-]/g,"\\$&"),J_e=t=>t.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),P8=t=>t.join(""),A8=(t,e)=>{let r=e;if(t.charAt(r)!=="[")throw new Error("not in a brace expression");let n=[],i=[],s=r+1,o=!1,a=!1,c=!1,u=!1,l=r,d="";e:for(;sd?n.push(yf(d)+"-"+yf(h)):h===d&&n.push(yf(h)),d="",s++;continue}if(t.startsWith("-]",s+1)){n.push(yf(h+"-")),s+=2;continue}if(t.startsWith("-",s+1)){d=h,s+=2;continue}n.push(yf(h)),s++}if(lr?e?t.replace(/\[([^\/\\])\]/g,"$1"):t.replace(/((?!\\).|^)\[([^\/\\])\]/g,"$1$2").replace(/\\([^\/])/g,"$1"):e?t.replace(/\[([^\/\\{}])\]/g,"$1"):t.replace(/((?!\\).|^)\[([^\/\\{}])\]/g,"$1$2").replace(/\\([^\/{}])/g,"$1");var X_e=new Set(["!","?","+","*","@"]),N8=t=>X_e.has(t),Y_e="(?!(?:^|/)\\.\\.?(?:$|/))",Ny="(?!\\.)",Q_e=new Set(["[","."]),ebe=new Set(["..","."]),tbe=new Set("().*{}+?[]^$\\!"),rbe=t=>t.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),bI="[^/]",M8=bI+"*?",D8=bI+"+?",Uu=class t{type;#e;#r;#s=!1;#i=[];#o;#b;#v;#l=!1;#a;#p;#d=!1;constructor(e,r,n={}){this.type=e,e&&(this.#r=!0),this.#o=r,this.#e=this.#o?this.#o.#e:this,this.#a=this.#e===this?n:this.#e.#a,this.#v=this.#e===this?[]:this.#e.#v,e==="!"&&!this.#e.#l&&this.#v.push(this),this.#b=this.#o?this.#o.#i.length:0}get hasMagic(){if(this.#r!==void 0)return this.#r;for(let e of this.#i)if(typeof e!="string"&&(e.type||e.hasMagic))return this.#r=!0;return this.#r}toString(){return this.#p!==void 0?this.#p:this.type?this.#p=this.type+"("+this.#i.map(e=>String(e)).join("|")+")":this.#p=this.#i.map(e=>String(e)).join("")}#c(){if(this!==this.#e)throw new Error("should only call on root");if(this.#l)return this;this.toString(),this.#l=!0;let e;for(;e=this.#v.pop();){if(e.type!=="!")continue;let r=e,n=r.#o;for(;n;){for(let i=r.#b+1;!n.type&&itypeof r=="string"?r:r.toJSON()):[this.type,...this.#i.map(r=>r.toJSON())];return this.isStart()&&!this.type&&e.unshift([]),this.isEnd()&&(this===this.#e||this.#e.#l&&this.#o?.type==="!")&&e.push({}),e}isStart(){if(this.#e===this)return!0;if(!this.#o?.isStart())return!1;if(this.#b===0)return!0;let e=this.#o;for(let r=0;rtypeof f!="string"),u=this.#i.map(f=>{let[m,h,g,v]=typeof f=="string"?t.#S(f,this.#r,c):f.toRegExpSource(e);return this.#r=this.#r||g,this.#s=this.#s||v,m}).join(""),l="";if(this.isStart()&&typeof this.#i[0]=="string"&&!(this.#i.length===1&&ebe.has(this.#i[0]))){let m=Q_e,h=r&&m.has(u.charAt(0))||u.startsWith("\\.")&&m.has(u.charAt(2))||u.startsWith("\\.\\.")&&m.has(u.charAt(4)),g=!r&&!e&&m.has(u.charAt(0));l=h?Y_e:g?Ny:""}let d="";return this.isEnd()&&this.#e.#l&&this.#o?.type==="!"&&(d="(?:$|\\/)"),[l+u+d,Ei(u),this.#r=!!this.#r,this.#s]}let n=this.type==="*"||this.type==="+",i=this.type==="!"?"(?:(?!(?:":"(?:",s=this.#f(r);if(this.isStart()&&this.isEnd()&&!s&&this.type!=="!"){let c=this.toString();return this.#i=[c],this.type=null,this.#r=void 0,[c,Ei(this.toString()),!1,!1]}let o=!n||e||r||!Ny?"":this.#f(!0);o===s&&(o=""),o&&(s=`(?:${s})(?:${o})*?`);let a="";if(this.type==="!"&&this.#d)a=(this.isStart()&&!r?Ny:"")+D8;else{let c=this.type==="!"?"))"+(this.isStart()&&!r&&!e?Ny:"")+M8+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&o?")":this.type==="*"&&o?")?":`)${this.type}`;a=i+s+c}return[a,Ei(s),this.#r=!!this.#r,this.#s]}#f(e){return this.#i.map(r=>{if(typeof r=="string")throw new Error("string type in extglob ast??");let[n,i,s,o]=r.toRegExpSource(e);return this.#s=this.#s||o,n}).filter(r=>!(this.isStart()&&this.isEnd())||!!r).join("|")}static#S(e,r,n=!1){let i=!1,s="",o=!1;for(let a=0;ar?e?t.replace(/[?*()[\]{}]/g,"[$&]"):t.replace(/[?*()[\]\\{}]/g,"\\$&"):e?t.replace(/[?*()[\]]/g,"[$&]"):t.replace(/[?*()[\]\\]/g,"\\$&");var tn=(t,e,r={})=>(vf(e),!r.nocomment&&e.charAt(0)==="#"?!1:new Pn(e,r).match(t)),nbe=/^\*+([^+@!?\*\[\(]*)$/,ibe=t=>e=>!e.startsWith(".")&&e.endsWith(t),sbe=t=>e=>e.endsWith(t),obe=t=>(t=t.toLowerCase(),e=>!e.startsWith(".")&&e.toLowerCase().endsWith(t)),abe=t=>(t=t.toLowerCase(),e=>e.toLowerCase().endsWith(t)),cbe=/^\*+\.\*+$/,ube=t=>!t.startsWith(".")&&t.includes("."),lbe=t=>t!=="."&&t!==".."&&t.includes("."),dbe=/^\.\*+$/,pbe=t=>t!=="."&&t!==".."&&t.startsWith("."),fbe=/^\*+$/,mbe=t=>t.length!==0&&!t.startsWith("."),hbe=t=>t.length!==0&&t!=="."&&t!=="..",gbe=/^\?+([^+@!?\*\[\(]*)?$/,vbe=([t,e=""])=>{let r=L8([t]);return e?(e=e.toLowerCase(),n=>r(n)&&n.toLowerCase().endsWith(e)):r},ybe=([t,e=""])=>{let r=U8([t]);return e?(e=e.toLowerCase(),n=>r(n)&&n.toLowerCase().endsWith(e)):r},_be=([t,e=""])=>{let r=U8([t]);return e?n=>r(n)&&n.endsWith(e):r},bbe=([t,e=""])=>{let r=L8([t]);return e?n=>r(n)&&n.endsWith(e):r},L8=([t])=>{let e=t.length;return r=>r.length===e&&!r.startsWith(".")},U8=([t])=>{let e=t.length;return r=>r.length===e&&r!=="."&&r!==".."},F8=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",j8={win32:{sep:"\\"},posix:{sep:"/"}},Sbe=F8==="win32"?j8.win32.sep:j8.posix.sep;tn.sep=Sbe;var Ir=Symbol("globstar **");tn.GLOBSTAR=Ir;var xbe="[^/]",wbe=xbe+"*?",Ebe="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",kbe="(?:(?!(?:\\/|^)\\.).)*?",Tbe=(t,e={})=>r=>tn(r,t,e);tn.filter=Tbe;var Qn=(t,e={})=>Object.assign({},t,e),$be=t=>{if(!t||typeof t!="object"||!Object.keys(t).length)return tn;let e=tn;return Object.assign((n,i,s={})=>e(n,i,Qn(t,s)),{Minimatch:class extends e.Minimatch{constructor(i,s={}){super(i,Qn(t,s))}static defaults(i){return e.defaults(Qn(t,i)).Minimatch}},AST:class extends e.AST{constructor(i,s,o={}){super(i,s,Qn(t,o))}static fromGlob(i,s={}){return e.AST.fromGlob(i,Qn(t,s))}},unescape:(n,i={})=>e.unescape(n,Qn(t,i)),escape:(n,i={})=>e.escape(n,Qn(t,i)),filter:(n,i={})=>e.filter(n,Qn(t,i)),defaults:n=>e.defaults(Qn(t,n)),makeRe:(n,i={})=>e.makeRe(n,Qn(t,i)),braceExpand:(n,i={})=>e.braceExpand(n,Qn(t,i)),match:(n,i,s={})=>e.match(n,i,Qn(t,s)),sep:e.sep,GLOBSTAR:Ir})};tn.defaults=$be;var q8=(t,e={})=>(vf(t),e.nobrace||!/\{(?:(?!\{).)*\}/.test(t)?[t]:C8(t));tn.braceExpand=q8;var Ibe=(t,e={})=>new Pn(t,e).makeRe();tn.makeRe=Ibe;var Rbe=(t,e,r={})=>{let n=new Pn(e,r);return t=t.filter(i=>n.match(i)),n.options.nonull&&!t.length&&t.push(e),t};tn.match=Rbe;var z8=/[?*]|[+@!]\(.*?\)|\[|\]/,Obe=t=>t.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Pn=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;regexp;constructor(e,r={}){vf(e),r=r||{},this.options=r,this.pattern=e,this.platform=r.platform||F8,this.isWindows=this.platform==="win32",this.windowsPathsNoEscape=!!r.windowsPathsNoEscape||r.allowWindowsEscape===!1,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,"/")),this.preserveMultipleSlashes=!!r.preserveMultipleSlashes,this.regexp=null,this.negate=!1,this.nonegate=!!r.nonegate,this.comment=!1,this.empty=!1,this.partial=!!r.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=r.windowsNoMagicRoot!==void 0?r.windowsNoMagicRoot:!!(this.isWindows&&this.nocase),this.globSet=[],this.globParts=[],this.set=[],this.make()}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return!0;for(let e of this.set)for(let r of e)if(typeof r!="string")return!0;return!1}debug(...e){}make(){let e=this.pattern,r=this.options;if(!r.nocomment&&e.charAt(0)==="#"){this.comment=!0;return}if(!e){this.empty=!0;return}this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],r.debug&&(this.debug=(...s)=>console.error(...s)),this.debug(this.pattern,this.globSet);let n=this.globSet.map(s=>this.slashSplit(s));this.globParts=this.preprocess(n),this.debug(this.pattern,this.globParts);let i=this.globParts.map((s,o,a)=>{if(this.isWindows&&this.windowsNoMagicRoot){let c=s[0]===""&&s[1]===""&&(s[2]==="?"||!z8.test(s[2]))&&!z8.test(s[3]),u=/^[a-z]:/i.test(s[0]);if(c)return[...s.slice(0,4),...s.slice(4).map(l=>this.parse(l))];if(u)return[s[0],...s.slice(1).map(l=>this.parse(l))]}return s.map(c=>this.parse(c))});if(this.debug(this.pattern,i),this.set=i.filter(s=>s.indexOf(!1)===-1),this.isWindows)for(let s=0;s=2?(e=this.firstPhasePreProcess(e),e=this.secondPhasePreProcess(e)):r>=1?e=this.levelOneOptimize(e):e=this.adjascentGlobstarOptimize(e),e}adjascentGlobstarOptimize(e){return e.map(r=>{let n=-1;for(;(n=r.indexOf("**",n+1))!==-1;){let i=n;for(;r[i+1]==="**";)i++;i!==n&&r.splice(n,i-n)}return r})}levelOneOptimize(e){return e.map(r=>(r=r.reduce((n,i)=>{let s=n[n.length-1];return i==="**"&&s==="**"?n:i===".."&&s&&s!==".."&&s!=="."&&s!=="**"?(n.pop(),n):(n.push(i),n)},[]),r.length===0?[""]:r))}levelTwoFileOptimize(e){Array.isArray(e)||(e=this.slashSplit(e));let r=!1;do{if(r=!1,!this.preserveMultipleSlashes){for(let i=1;ii&&n.splice(i+1,o-i);let a=n[i+1],c=n[i+2],u=n[i+3];if(a!==".."||!c||c==="."||c===".."||!u||u==="."||u==="..")continue;r=!0,n.splice(i,1);let l=n.slice(0);l[i]="**",e.push(l),i--}if(!this.preserveMultipleSlashes){for(let o=1;or.length)}partsMatch(e,r,n=!1){let i=0,s=0,o=[],a="";for(;i_?r=r.slice(y):_>y&&(e=e.slice(_)))}}let{optimizationLevel:s=1}=this.options;s>=2&&(e=this.levelTwoFileOptimize(e)),this.debug("matchOne",this,{file:e,pattern:r}),this.debug("matchOne",e.length,r.length);for(var o=0,a=0,c=e.length,u=r.length;o>> no match, partial?`,e,p,r,f),p===c))}let h;if(typeof l=="string"?(h=d===l,this.debug("string match",l,d,h)):(h=l.test(d),this.debug("pattern match",l,d,h)),!h)return!1}if(o===c&&a===u)return!0;if(o===c)return n;if(a===u)return o===c-1&&e[o]==="";throw new Error("wtf?")}braceExpand(){return q8(this.pattern,this.options)}parse(e){vf(e);let r=this.options;if(e==="**")return Ir;if(e==="")return"";let n,i=null;(n=e.match(fbe))?i=r.dot?hbe:mbe:(n=e.match(nbe))?i=(r.nocase?r.dot?abe:obe:r.dot?sbe:ibe)(n[1]):(n=e.match(gbe))?i=(r.nocase?r.dot?ybe:vbe:r.dot?_be:bbe)(n):(n=e.match(cbe))?i=r.dot?lbe:ube:(n=e.match(dbe))&&(i=pbe);let s=Uu.fromGlob(e,this.options).toMMPattern();return i&&typeof s=="object"&&Reflect.defineProperty(s,"test",{value:i}),s}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let e=this.set;if(!e.length)return this.regexp=!1,this.regexp;let r=this.options,n=r.noglobstar?wbe:r.dot?Ebe:kbe,i=new Set(r.nocase?["i"]:[]),s=e.map(c=>{let u=c.map(d=>{if(d instanceof RegExp)for(let p of d.flags.split(""))i.add(p);return typeof d=="string"?Obe(d):d===Ir?Ir:d._src});u.forEach((d,p)=>{let f=u[p+1],m=u[p-1];d!==Ir||m===Ir||(m===void 0?f!==void 0&&f!==Ir?u[p+1]="(?:\\/|"+n+"\\/)?"+f:u[p]=n:f===void 0?u[p-1]=m+"(?:\\/|\\/"+n+")?":f!==Ir&&(u[p-1]=m+"(?:\\/|\\/"+n+"\\/)"+f,u[p+1]=Ir))});let l=u.filter(d=>d!==Ir);if(this.partial&&l.length>=1){let d=[];for(let p=1;p<=l.length;p++)d.push(l.slice(0,p).join("/"));return"(?:"+d.join("|")+")"}return l.join("/")}).join("|"),[o,a]=e.length>1?["(?:",")"]:["",""];s="^"+o+s+a+"$",this.partial&&(s="^(?:\\/|"+o+s.slice(1,-1)+a+")$"),this.negate&&(s="^(?!"+s+").+$");try{this.regexp=new RegExp(s,[...i].join(""))}catch{this.regexp=!1}return this.regexp}slashSplit(e){return this.preserveMultipleSlashes?e.split("/"):this.isWindows&&/^\/\/[^\/]+/.test(e)?["",...e.split(/\/+/)]:e.split(/\/+/)}match(e,r=this.partial){if(this.debug("match",e,this.pattern),this.comment)return!1;if(this.empty)return e==="";if(e==="/"&&r)return!0;let n=this.options;this.isWindows&&(e=e.split("\\").join("/"));let i=this.slashSplit(e);this.debug(this.pattern,"split",i);let s=this.set;this.debug(this.pattern,"set",s);let o=i[i.length-1];if(!o)for(let a=i.length-2;!o&&a>=0;a--)o=i[a];for(let a=0;a{typeof SI.emitWarning=="function"?SI.emitWarning(t,e,r,n):console.error(`[${r}] ${e}: ${t}`)},My=globalThis.AbortController,H8=globalThis.AbortSignal;if(typeof My>"u"){H8=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(n,i){this._onabort.push(i)}},My=class{constructor(){e()}signal=new H8;abort(n){if(!this.signal.aborted){this.signal.reason=n,this.signal.aborted=!0;for(let i of this.signal._onabort)i(n);this.signal.onabort?.(n)}}};let t=SI.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",e=()=>{t&&(t=!1,B8("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",e))}}var Pbe=t=>!Z8.has(t);var Eo=t=>t&&t===Math.floor(t)&&t>0&&isFinite(t),G8=t=>Eo(t)?t<=Math.pow(2,8)?Uint8Array:t<=Math.pow(2,16)?Uint16Array:t<=Math.pow(2,32)?Uint32Array:t<=Number.MAX_SAFE_INTEGER?qu:null:null,qu=class extends Array{constructor(e){super(e),this.fill(0)}},xI=class t{heap;length;static#e=!1;static create(e){let r=G8(e);if(!r)return[];t.#e=!0;let n=new t(e,r);return t.#e=!1,n}constructor(e,r){if(!t.#e)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new r(e),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}},Oa=class t{#e;#r;#s;#i;#o;#b;#v;#l;get perf(){return this.#l}ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#a;#p;#d;#c;#n;#f;#S;#_;#m;#I;#h;#E;#k;#g;#y;#x;#T;#t;#N;static unsafeExposeInternals(e){return{starts:e.#k,ttls:e.#g,autopurgeTimers:e.#y,sizes:e.#E,keyMap:e.#d,keyList:e.#c,valList:e.#n,next:e.#f,prev:e.#S,get head(){return e.#_},get tail(){return e.#m},free:e.#I,isBackgroundFetch:r=>e.#u(r),backgroundFetch:(r,n,i,s)=>e.#q(r,n,i,s),moveToTail:r=>e.#D(r),indexes:r=>e.#O(r),rindexes:r=>e.#C(r),isStale:r=>e.#w(r)}}get max(){return this.#e}get maxSize(){return this.#r}get calculatedSize(){return this.#p}get size(){return this.#a}get fetchMethod(){return this.#b}get memoMethod(){return this.#v}get dispose(){return this.#s}get onInsert(){return this.#i}get disposeAfter(){return this.#o}constructor(e){let{max:r=0,ttl:n,ttlResolution:i=1,ttlAutopurge:s,updateAgeOnGet:o,updateAgeOnHas:a,allowStale:c,dispose:u,onInsert:l,disposeAfter:d,noDisposeOnSet:p,noUpdateTTL:f,maxSize:m=0,maxEntrySize:h=0,sizeCalculation:g,fetchMethod:v,memoMethod:S,noDeleteOnFetchRejection:_,noDeleteOnStaleGet:y,allowStaleOnFetchRejection:x,allowStaleOnFetchAbort:w,ignoreFetchAbort:E,perf:T}=e;if(T!==void 0&&typeof T?.now!="function")throw new TypeError("perf option must have a now() method if specified");if(this.#l=T??Cbe,r!==0&&!Eo(r))throw new TypeError("max option must be a nonnegative integer");let I=r?G8(r):Array;if(!I)throw new Error("invalid max value: "+r);if(this.#e=r,this.#r=m,this.maxEntrySize=h||this.#r,this.sizeCalculation=g,this.sizeCalculation){if(!this.#r&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(S!==void 0&&typeof S!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#v=S,v!==void 0&&typeof v!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#b=v,this.#T=!!v,this.#d=new Map,this.#c=new Array(r).fill(void 0),this.#n=new Array(r).fill(void 0),this.#f=new I(r),this.#S=new I(r),this.#_=0,this.#m=0,this.#I=xI.create(r),this.#a=0,this.#p=0,typeof u=="function"&&(this.#s=u),typeof l=="function"&&(this.#i=l),typeof d=="function"?(this.#o=d,this.#h=[]):(this.#o=void 0,this.#h=void 0),this.#x=!!this.#s,this.#N=!!this.#i,this.#t=!!this.#o,this.noDisposeOnSet=!!p,this.noUpdateTTL=!!f,this.noDeleteOnFetchRejection=!!_,this.allowStaleOnFetchRejection=!!x,this.allowStaleOnFetchAbort=!!w,this.ignoreFetchAbort=!!E,this.maxEntrySize!==0){if(this.#r!==0&&!Eo(this.#r))throw new TypeError("maxSize must be a positive integer if specified");if(!Eo(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#Z()}if(this.allowStale=!!c,this.noDeleteOnStaleGet=!!y,this.updateAgeOnGet=!!o,this.updateAgeOnHas=!!a,this.ttlResolution=Eo(i)||i===0?i:1,this.ttlAutopurge=!!s,this.ttl=n||0,this.ttl){if(!Eo(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#P()}if(this.#e===0&&this.ttl===0&&this.#r===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#e&&!this.#r){let A="LRU_CACHE_UNBOUNDED";Pbe(A)&&(Z8.add(A),B8("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",A,t))}}getRemainingTTL(e){return this.#d.has(e)?1/0:0}#P(){let e=new qu(this.#e),r=new qu(this.#e);this.#g=e,this.#k=r;let n=this.ttlAutopurge?new Array(this.#e):void 0;this.#y=n,this.#z=(o,a,c=this.#l.now())=>{if(r[o]=a!==0?c:0,e[o]=a,n?.[o]&&(clearTimeout(n[o]),n[o]=void 0),a!==0&&n){let u=setTimeout(()=>{this.#w(o)&&this.#R(this.#c[o],"expire")},a+1);u.unref&&u.unref(),n[o]=u}},this.#$=o=>{r[o]=e[o]!==0?this.#l.now():0},this.#A=(o,a)=>{if(e[a]){let c=e[a],u=r[a];if(!c||!u)return;o.ttl=c,o.start=u,o.now=i||s();let l=o.now-u;o.remainingTTL=c-l}};let i=0,s=()=>{let o=this.#l.now();if(this.ttlResolution>0){i=o;let a=setTimeout(()=>i=0,this.ttlResolution);a.unref&&a.unref()}return o};this.getRemainingTTL=o=>{let a=this.#d.get(o);if(a===void 0)return 0;let c=e[a],u=r[a];if(!c||!u)return 1/0;let l=(i||s())-u;return c-l},this.#w=o=>{let a=r[o],c=e[o];return!!c&&!!a&&(i||s())-a>c}}#$=()=>{};#A=()=>{};#z=()=>{};#w=()=>!1;#Z(){let e=new qu(this.#e);this.#p=0,this.#E=e,this.#j=r=>{this.#p-=e[r],e[r]=0},this.#L=(r,n,i,s)=>{if(this.#u(n))return 0;if(!Eo(i))if(s){if(typeof s!="function")throw new TypeError("sizeCalculation must be a function");if(i=s(n,r),!Eo(i))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return i},this.#M=(r,n,i)=>{if(e[r]=n,this.#r){let s=this.#r-e[r];for(;this.#p>s;)this.#F(!0)}this.#p+=e[r],i&&(i.entrySize=n,i.totalCalculatedSize=this.#p)}}#j=e=>{};#M=(e,r,n)=>{};#L=(e,r,n,i)=>{if(n||i)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#O({allowStale:e=this.allowStale}={}){if(this.#a)for(let r=this.#m;!(!this.#U(r)||((e||!this.#w(r))&&(yield r),r===this.#_));)r=this.#S[r]}*#C({allowStale:e=this.allowStale}={}){if(this.#a)for(let r=this.#_;!(!this.#U(r)||((e||!this.#w(r))&&(yield r),r===this.#m));)r=this.#f[r]}#U(e){return e!==void 0&&this.#d.get(this.#c[e])===e}*entries(){for(let e of this.#O())this.#n[e]!==void 0&&this.#c[e]!==void 0&&!this.#u(this.#n[e])&&(yield[this.#c[e],this.#n[e]])}*rentries(){for(let e of this.#C())this.#n[e]!==void 0&&this.#c[e]!==void 0&&!this.#u(this.#n[e])&&(yield[this.#c[e],this.#n[e]])}*keys(){for(let e of this.#O()){let r=this.#c[e];r!==void 0&&!this.#u(this.#n[e])&&(yield r)}}*rkeys(){for(let e of this.#C()){let r=this.#c[e];r!==void 0&&!this.#u(this.#n[e])&&(yield r)}}*values(){for(let e of this.#O())this.#n[e]!==void 0&&!this.#u(this.#n[e])&&(yield this.#n[e])}*rvalues(){for(let e of this.#C())this.#n[e]!==void 0&&!this.#u(this.#n[e])&&(yield this.#n[e])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(e,r={}){for(let n of this.#O()){let i=this.#n[n],s=this.#u(i)?i.__staleWhileFetching:i;if(s!==void 0&&e(s,this.#c[n],this))return this.get(this.#c[n],r)}}forEach(e,r=this){for(let n of this.#O()){let i=this.#n[n],s=this.#u(i)?i.__staleWhileFetching:i;s!==void 0&&e.call(r,s,this.#c[n],this)}}rforEach(e,r=this){for(let n of this.#C()){let i=this.#n[n],s=this.#u(i)?i.__staleWhileFetching:i;s!==void 0&&e.call(r,s,this.#c[n],this)}}purgeStale(){let e=!1;for(let r of this.#C({allowStale:!0}))this.#w(r)&&(this.#R(this.#c[r],"expire"),e=!0);return e}info(e){let r=this.#d.get(e);if(r===void 0)return;let n=this.#n[r],i=this.#u(n)?n.__staleWhileFetching:n;if(i===void 0)return;let s={value:i};if(this.#g&&this.#k){let o=this.#g[r],a=this.#k[r];if(o&&a){let c=o-(this.#l.now()-a);s.ttl=c,s.start=Date.now()}}return this.#E&&(s.size=this.#E[r]),s}dump(){let e=[];for(let r of this.#O({allowStale:!0})){let n=this.#c[r],i=this.#n[r],s=this.#u(i)?i.__staleWhileFetching:i;if(s===void 0||n===void 0)continue;let o={value:s};if(this.#g&&this.#k){o.ttl=this.#g[r];let a=this.#l.now()-this.#k[r];o.start=Math.floor(Date.now()-a)}this.#E&&(o.size=this.#E[r]),e.unshift([n,o])}return e}load(e){this.clear();for(let[r,n]of e){if(n.start){let i=Date.now()-n.start;n.start=this.#l.now()-i}this.set(r,n.value,n)}}set(e,r,n={}){if(r===void 0)return this.delete(e),this;let{ttl:i=this.ttl,start:s,noDisposeOnSet:o=this.noDisposeOnSet,sizeCalculation:a=this.sizeCalculation,status:c}=n,{noUpdateTTL:u=this.noUpdateTTL}=n,l=this.#L(e,r,n.size||0,a);if(this.maxEntrySize&&l>this.maxEntrySize)return c&&(c.set="miss",c.maxEntrySizeExceeded=!0),this.#R(e,"set"),this;let d=this.#a===0?void 0:this.#d.get(e);if(d===void 0)d=this.#a===0?this.#m:this.#I.length!==0?this.#I.pop():this.#a===this.#e?this.#F(!1):this.#a,this.#c[d]=e,this.#n[d]=r,this.#d.set(e,d),this.#f[this.#m]=d,this.#S[d]=this.#m,this.#m=d,this.#a++,this.#M(d,l,c),c&&(c.set="add"),u=!1,this.#N&&this.#i?.(r,e,"add");else{this.#D(d);let p=this.#n[d];if(r!==p){if(this.#T&&this.#u(p)){p.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:f}=p;f!==void 0&&!o&&(this.#x&&this.#s?.(f,e,"set"),this.#t&&this.#h?.push([f,e,"set"]))}else o||(this.#x&&this.#s?.(p,e,"set"),this.#t&&this.#h?.push([p,e,"set"]));if(this.#j(d),this.#M(d,l,c),this.#n[d]=r,c){c.set="replace";let f=p&&this.#u(p)?p.__staleWhileFetching:p;f!==void 0&&(c.oldValue=f)}}else c&&(c.set="update");this.#N&&this.onInsert?.(r,e,r===p?"update":"replace")}if(i!==0&&!this.#g&&this.#P(),this.#g&&(u||this.#z(d,i,s),c&&this.#A(c,d)),!o&&this.#t&&this.#h){let p=this.#h,f;for(;f=p?.shift();)this.#o?.(...f)}return this}pop(){try{for(;this.#a;){let e=this.#n[this.#_];if(this.#F(!0),this.#u(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(e!==void 0)return e}}finally{if(this.#t&&this.#h){let e=this.#h,r;for(;r=e?.shift();)this.#o?.(...r)}}}#F(e){let r=this.#_,n=this.#c[r],i=this.#n[r];return this.#T&&this.#u(i)?i.__abortController.abort(new Error("evicted")):(this.#x||this.#t)&&(this.#x&&this.#s?.(i,n,"evict"),this.#t&&this.#h?.push([i,n,"evict"])),this.#j(r),this.#y?.[r]&&(clearTimeout(this.#y[r]),this.#y[r]=void 0),e&&(this.#c[r]=void 0,this.#n[r]=void 0,this.#I.push(r)),this.#a===1?(this.#_=this.#m=0,this.#I.length=0):this.#_=this.#f[r],this.#d.delete(n),this.#a--,r}has(e,r={}){let{updateAgeOnHas:n=this.updateAgeOnHas,status:i}=r,s=this.#d.get(e);if(s!==void 0){let o=this.#n[s];if(this.#u(o)&&o.__staleWhileFetching===void 0)return!1;if(this.#w(s))i&&(i.has="stale",this.#A(i,s));else return n&&this.#$(s),i&&(i.has="hit",this.#A(i,s)),!0}else i&&(i.has="miss");return!1}peek(e,r={}){let{allowStale:n=this.allowStale}=r,i=this.#d.get(e);if(i===void 0||!n&&this.#w(i))return;let s=this.#n[i];return this.#u(s)?s.__staleWhileFetching:s}#q(e,r,n,i){let s=r===void 0?void 0:this.#n[r];if(this.#u(s))return s;let o=new My,{signal:a}=n;a?.addEventListener("abort",()=>o.abort(a.reason),{signal:o.signal});let c={signal:o.signal,options:n,context:i},u=(h,g=!1)=>{let{aborted:v}=o.signal,S=n.ignoreFetchAbort&&h!==void 0;if(n.status&&(v&&!g?(n.status.fetchAborted=!0,n.status.fetchError=o.signal.reason,S&&(n.status.fetchAbortIgnored=!0)):n.status.fetchResolved=!0),v&&!S&&!g)return d(o.signal.reason);let _=f,y=this.#n[r];return(y===f||S&&g&&y===void 0)&&(h===void 0?_.__staleWhileFetching!==void 0?this.#n[r]=_.__staleWhileFetching:this.#R(e,"fetch"):(n.status&&(n.status.fetchUpdated=!0),this.set(e,h,c.options))),h},l=h=>(n.status&&(n.status.fetchRejected=!0,n.status.fetchError=h),d(h)),d=h=>{let{aborted:g}=o.signal,v=g&&n.allowStaleOnFetchAbort,S=v||n.allowStaleOnFetchRejection,_=S||n.noDeleteOnFetchRejection,y=f;if(this.#n[r]===f&&(!_||y.__staleWhileFetching===void 0?this.#R(e,"fetch"):v||(this.#n[r]=y.__staleWhileFetching)),S)return n.status&&y.__staleWhileFetching!==void 0&&(n.status.returnedStale=!0),y.__staleWhileFetching;if(y.__returned===y)throw h},p=(h,g)=>{let v=this.#b?.(e,s,c);v&&v instanceof Promise&&v.then(S=>h(S===void 0?void 0:S),g),o.signal.addEventListener("abort",()=>{(!n.ignoreFetchAbort||n.allowStaleOnFetchAbort)&&(h(void 0),n.allowStaleOnFetchAbort&&(h=S=>u(S,!0)))})};n.status&&(n.status.fetchDispatched=!0);let f=new Promise(p).then(u,l),m=Object.assign(f,{__abortController:o,__staleWhileFetching:s,__returned:void 0});return r===void 0?(this.set(e,m,{...c.options,status:void 0}),r=this.#d.get(e)):this.#n[r]=m,m}#u(e){if(!this.#T)return!1;let r=e;return!!r&&r instanceof Promise&&r.hasOwnProperty("__staleWhileFetching")&&r.__abortController instanceof My}async fetch(e,r={}){let{allowStale:n=this.allowStale,updateAgeOnGet:i=this.updateAgeOnGet,noDeleteOnStaleGet:s=this.noDeleteOnStaleGet,ttl:o=this.ttl,noDisposeOnSet:a=this.noDisposeOnSet,size:c=0,sizeCalculation:u=this.sizeCalculation,noUpdateTTL:l=this.noUpdateTTL,noDeleteOnFetchRejection:d=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:p=this.allowStaleOnFetchRejection,ignoreFetchAbort:f=this.ignoreFetchAbort,allowStaleOnFetchAbort:m=this.allowStaleOnFetchAbort,context:h,forceRefresh:g=!1,status:v,signal:S}=r;if(!this.#T)return v&&(v.fetch="get"),this.get(e,{allowStale:n,updateAgeOnGet:i,noDeleteOnStaleGet:s,status:v});let _={allowStale:n,updateAgeOnGet:i,noDeleteOnStaleGet:s,ttl:o,noDisposeOnSet:a,size:c,sizeCalculation:u,noUpdateTTL:l,noDeleteOnFetchRejection:d,allowStaleOnFetchRejection:p,allowStaleOnFetchAbort:m,ignoreFetchAbort:f,status:v,signal:S},y=this.#d.get(e);if(y===void 0){v&&(v.fetch="miss");let x=this.#q(e,y,_,h);return x.__returned=x}else{let x=this.#n[y];if(this.#u(x)){let A=n&&x.__staleWhileFetching!==void 0;return v&&(v.fetch="inflight",A&&(v.returnedStale=!0)),A?x.__staleWhileFetching:x.__returned=x}let w=this.#w(y);if(!g&&!w)return v&&(v.fetch="hit"),this.#D(y),i&&this.#$(y),v&&this.#A(v,y),x;let E=this.#q(e,y,_,h),I=E.__staleWhileFetching!==void 0&&n;return v&&(v.fetch=w?"stale":"refresh",I&&w&&(v.returnedStale=!0)),I?E.__staleWhileFetching:E.__returned=E}}async forceFetch(e,r={}){let n=await this.fetch(e,r);if(n===void 0)throw new Error("fetch() returned undefined");return n}memo(e,r={}){let n=this.#v;if(!n)throw new Error("no memoMethod provided to constructor");let{context:i,forceRefresh:s,...o}=r,a=this.get(e,o);if(!s&&a!==void 0)return a;let c=n(e,a,{options:o,context:i});return this.set(e,c,o),c}get(e,r={}){let{allowStale:n=this.allowStale,updateAgeOnGet:i=this.updateAgeOnGet,noDeleteOnStaleGet:s=this.noDeleteOnStaleGet,status:o}=r,a=this.#d.get(e);if(a!==void 0){let c=this.#n[a],u=this.#u(c);return o&&this.#A(o,a),this.#w(a)?(o&&(o.get="stale"),u?(o&&n&&c.__staleWhileFetching!==void 0&&(o.returnedStale=!0),n?c.__staleWhileFetching:void 0):(s||this.#R(e,"expire"),o&&n&&(o.returnedStale=!0),n?c:void 0)):(o&&(o.get="hit"),u?c.__staleWhileFetching:(this.#D(a),i&&this.#$(a),c))}else o&&(o.get="miss")}#H(e,r){this.#S[r]=e,this.#f[e]=r}#D(e){e!==this.#m&&(e===this.#_?this.#_=this.#f[e]:this.#H(this.#S[e],this.#f[e]),this.#H(this.#m,e),this.#m=e)}delete(e){return this.#R(e,"delete")}#R(e,r){let n=!1;if(this.#a!==0){let i=this.#d.get(e);if(i!==void 0)if(this.#y?.[i]&&(clearTimeout(this.#y?.[i]),this.#y[i]=void 0),n=!0,this.#a===1)this.#B(r);else{this.#j(i);let s=this.#n[i];if(this.#u(s)?s.__abortController.abort(new Error("deleted")):(this.#x||this.#t)&&(this.#x&&this.#s?.(s,e,r),this.#t&&this.#h?.push([s,e,r])),this.#d.delete(e),this.#c[i]=void 0,this.#n[i]=void 0,i===this.#m)this.#m=this.#S[i];else if(i===this.#_)this.#_=this.#f[i];else{let o=this.#S[i];this.#f[o]=this.#f[i];let a=this.#f[i];this.#S[a]=this.#S[i]}this.#a--,this.#I.push(i)}}if(this.#t&&this.#h?.length){let i=this.#h,s;for(;s=i?.shift();)this.#o?.(...s)}return n}clear(){return this.#B("delete")}#B(e){for(let r of this.#C({allowStale:!0})){let n=this.#n[r];if(this.#u(n))n.__abortController.abort(new Error("deleted"));else{let i=this.#c[r];this.#x&&this.#s?.(n,i,e),this.#t&&this.#h?.push([n,i,e])}}if(this.#d.clear(),this.#n.fill(void 0),this.#c.fill(void 0),this.#g&&this.#k){this.#g.fill(0),this.#k.fill(0);for(let r of this.#y??[])r!==void 0&&clearTimeout(r);this.#y?.fill(void 0)}if(this.#E&&this.#E.fill(0),this.#_=0,this.#m=0,this.#I.length=0,this.#p=0,this.#a=0,this.#t&&this.#h){let r=this.#h,n;for(;n=r?.shift();)this.#o?.(...n)}}};var Bu=require("node:path"),r5=require("node:url"),rs=require("fs"),qbe=Me(require("node:fs"),1),$o=require("node:fs/promises");var qy=require("node:events"),RI=Me(require("node:stream"),1),X8=require("node:string_decoder"),W8=typeof process=="object"&&process?process:{stdout:null,stderr:null},Abe=t=>!!t&&typeof t=="object"&&(t instanceof To||t instanceof RI.default||Nbe(t)||Mbe(t)),Nbe=t=>!!t&&typeof t=="object"&&t instanceof qy.EventEmitter&&typeof t.pipe=="function"&&t.pipe!==RI.default.Writable.prototype.pipe,Mbe=t=>!!t&&typeof t=="object"&&t instanceof qy.EventEmitter&&typeof t.write=="function"&&typeof t.end=="function",Ls=Symbol("EOF"),Us=Symbol("maybeEmitEnd"),ko=Symbol("emittedEnd"),Dy=Symbol("emittingEnd"),_f=Symbol("emittedError"),jy=Symbol("closed"),V8=Symbol("read"),zy=Symbol("flush"),K8=Symbol("flushChunk"),ki=Symbol("encoding"),Hu=Symbol("decoder"),fr=Symbol("flowing"),bf=Symbol("paused"),Zu=Symbol("resume"),mr=Symbol("buffer"),rn=Symbol("pipes"),hr=Symbol("bufferLength"),wI=Symbol("bufferPush"),Ly=Symbol("bufferShift"),Fr=Symbol("objectMode"),Xt=Symbol("destroyed"),EI=Symbol("error"),kI=Symbol("emitData"),J8=Symbol("emitEnd"),TI=Symbol("emitEnd2"),es=Symbol("async"),$I=Symbol("abort"),Uy=Symbol("aborted"),Sf=Symbol("signal"),Ca=Symbol("dataListeners"),An=Symbol("discarded"),xf=t=>Promise.resolve().then(t),Dbe=t=>t(),jbe=t=>t==="end"||t==="finish"||t==="prefinish",zbe=t=>t instanceof ArrayBuffer||!!t&&typeof t=="object"&&t.constructor&&t.constructor.name==="ArrayBuffer"&&t.byteLength>=0,Lbe=t=>!Buffer.isBuffer(t)&&ArrayBuffer.isView(t),Fy=class{src;dest;opts;ondrain;constructor(e,r,n){this.src=e,this.dest=r,this.opts=n,this.ondrain=()=>e[Zu](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(e){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},II=class extends Fy{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe()}constructor(e,r,n){super(e,r,n),this.proxyErrors=i=>r.emit("error",i),e.on("error",this.proxyErrors)}},Ube=t=>!!t.objectMode,Fbe=t=>!t.objectMode&&!!t.encoding&&t.encoding!=="buffer",To=class extends qy.EventEmitter{[fr]=!1;[bf]=!1;[rn]=[];[mr]=[];[Fr];[ki];[es];[Hu];[Ls]=!1;[ko]=!1;[Dy]=!1;[jy]=!1;[_f]=null;[hr]=0;[Xt]=!1;[Sf];[Uy]=!1;[Ca]=0;[An]=!1;writable=!0;readable=!0;constructor(...e){let r=e[0]||{};if(super(),r.objectMode&&typeof r.encoding=="string")throw new TypeError("Encoding and objectMode may not be used together");Ube(r)?(this[Fr]=!0,this[ki]=null):Fbe(r)?(this[ki]=r.encoding,this[Fr]=!1):(this[Fr]=!1,this[ki]=null),this[es]=!!r.async,this[Hu]=this[ki]?new X8.StringDecoder(this[ki]):null,r&&r.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[mr]}),r&&r.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[rn]});let{signal:n}=r;n&&(this[Sf]=n,n.aborted?this[$I]():n.addEventListener("abort",()=>this[$I]()))}get bufferLength(){return this[hr]}get encoding(){return this[ki]}set encoding(e){throw new Error("Encoding must be set at instantiation time")}setEncoding(e){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[Fr]}set objectMode(e){throw new Error("objectMode must be set at instantiation time")}get async(){return this[es]}set async(e){this[es]=this[es]||!!e}[$I](){this[Uy]=!0,this.emit("abort",this[Sf]?.reason),this.destroy(this[Sf]?.reason)}get aborted(){return this[Uy]}set aborted(e){}write(e,r,n){if(this[Uy])return!1;if(this[Ls])throw new Error("write after end");if(this[Xt])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;typeof r=="function"&&(n=r,r="utf8"),r||(r="utf8");let i=this[es]?xf:Dbe;if(!this[Fr]&&!Buffer.isBuffer(e)){if(Lbe(e))e=Buffer.from(e.buffer,e.byteOffset,e.byteLength);else if(zbe(e))e=Buffer.from(e);else if(typeof e!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[Fr]?(this[fr]&&this[hr]!==0&&this[zy](!0),this[fr]?this.emit("data",e):this[wI](e),this[hr]!==0&&this.emit("readable"),n&&i(n),this[fr]):e.length?(typeof e=="string"&&!(r===this[ki]&&!this[Hu]?.lastNeed)&&(e=Buffer.from(e,r)),Buffer.isBuffer(e)&&this[ki]&&(e=this[Hu].write(e)),this[fr]&&this[hr]!==0&&this[zy](!0),this[fr]?this.emit("data",e):this[wI](e),this[hr]!==0&&this.emit("readable"),n&&i(n),this[fr]):(this[hr]!==0&&this.emit("readable"),n&&i(n),this[fr])}read(e){if(this[Xt])return null;if(this[An]=!1,this[hr]===0||e===0||e&&e>this[hr])return this[Us](),null;this[Fr]&&(e=null),this[mr].length>1&&!this[Fr]&&(this[mr]=[this[ki]?this[mr].join(""):Buffer.concat(this[mr],this[hr])]);let r=this[V8](e||null,this[mr][0]);return this[Us](),r}[V8](e,r){if(this[Fr])this[Ly]();else{let n=r;e===n.length||e===null?this[Ly]():typeof n=="string"?(this[mr][0]=n.slice(e),r=n.slice(0,e),this[hr]-=e):(this[mr][0]=n.subarray(e),r=n.subarray(0,e),this[hr]-=e)}return this.emit("data",r),!this[mr].length&&!this[Ls]&&this.emit("drain"),r}end(e,r,n){return typeof e=="function"&&(n=e,e=void 0),typeof r=="function"&&(n=r,r="utf8"),e!==void 0&&this.write(e,r),n&&this.once("end",n),this[Ls]=!0,this.writable=!1,(this[fr]||!this[bf])&&this[Us](),this}[Zu](){this[Xt]||(!this[Ca]&&!this[rn].length&&(this[An]=!0),this[bf]=!1,this[fr]=!0,this.emit("resume"),this[mr].length?this[zy]():this[Ls]?this[Us]():this.emit("drain"))}resume(){return this[Zu]()}pause(){this[fr]=!1,this[bf]=!0,this[An]=!1}get destroyed(){return this[Xt]}get flowing(){return this[fr]}get paused(){return this[bf]}[wI](e){this[Fr]?this[hr]+=1:this[hr]+=e.length,this[mr].push(e)}[Ly](){return this[Fr]?this[hr]-=1:this[hr]-=this[mr][0].length,this[mr].shift()}[zy](e=!1){do;while(this[K8](this[Ly]())&&this[mr].length);!e&&!this[mr].length&&!this[Ls]&&this.emit("drain")}[K8](e){return this.emit("data",e),this[fr]}pipe(e,r){if(this[Xt])return e;this[An]=!1;let n=this[ko];return r=r||{},e===W8.stdout||e===W8.stderr?r.end=!1:r.end=r.end!==!1,r.proxyErrors=!!r.proxyErrors,n?r.end&&e.end():(this[rn].push(r.proxyErrors?new II(this,e,r):new Fy(this,e,r)),this[es]?xf(()=>this[Zu]()):this[Zu]()),e}unpipe(e){let r=this[rn].find(n=>n.dest===e);r&&(this[rn].length===1?(this[fr]&&this[Ca]===0&&(this[fr]=!1),this[rn]=[]):this[rn].splice(this[rn].indexOf(r),1),r.unpipe())}addListener(e,r){return this.on(e,r)}on(e,r){let n=super.on(e,r);if(e==="data")this[An]=!1,this[Ca]++,!this[rn].length&&!this[fr]&&this[Zu]();else if(e==="readable"&&this[hr]!==0)super.emit("readable");else if(jbe(e)&&this[ko])super.emit(e),this.removeAllListeners(e);else if(e==="error"&&this[_f]){let i=r;this[es]?xf(()=>i.call(this,this[_f])):i.call(this,this[_f])}return n}removeListener(e,r){return this.off(e,r)}off(e,r){let n=super.off(e,r);return e==="data"&&(this[Ca]=this.listeners("data").length,this[Ca]===0&&!this[An]&&!this[rn].length&&(this[fr]=!1)),n}removeAllListeners(e){let r=super.removeAllListeners(e);return(e==="data"||e===void 0)&&(this[Ca]=0,!this[An]&&!this[rn].length&&(this[fr]=!1)),r}get emittedEnd(){return this[ko]}[Us](){!this[Dy]&&!this[ko]&&!this[Xt]&&this[mr].length===0&&this[Ls]&&(this[Dy]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[jy]&&this.emit("close"),this[Dy]=!1)}emit(e,...r){let n=r[0];if(e!=="error"&&e!=="close"&&e!==Xt&&this[Xt])return!1;if(e==="data")return!this[Fr]&&!n?!1:this[es]?(xf(()=>this[kI](n)),!0):this[kI](n);if(e==="end")return this[J8]();if(e==="close"){if(this[jy]=!0,!this[ko]&&!this[Xt])return!1;let s=super.emit("close");return this.removeAllListeners("close"),s}else if(e==="error"){this[_f]=n,super.emit(EI,n);let s=!this[Sf]||this.listeners("error").length?super.emit("error",n):!1;return this[Us](),s}else if(e==="resume"){let s=super.emit("resume");return this[Us](),s}else if(e==="finish"||e==="prefinish"){let s=super.emit(e);return this.removeAllListeners(e),s}let i=super.emit(e,...r);return this[Us](),i}[kI](e){for(let n of this[rn])n.dest.write(e)===!1&&this.pause();let r=this[An]?!1:super.emit("data",e);return this[Us](),r}[J8](){return this[ko]?!1:(this[ko]=!0,this.readable=!1,this[es]?(xf(()=>this[TI]()),!0):this[TI]())}[TI](){if(this[Hu]){let r=this[Hu].end();if(r){for(let n of this[rn])n.dest.write(r);this[An]||super.emit("data",r)}}for(let r of this[rn])r.end();let e=super.emit("end");return this.removeAllListeners("end"),e}async collect(){let e=Object.assign([],{dataLength:0});this[Fr]||(e.dataLength=0);let r=this.promise();return this.on("data",n=>{e.push(n),this[Fr]||(e.dataLength+=n.length)}),await r,e}async concat(){if(this[Fr])throw new Error("cannot concat in objectMode");let e=await this.collect();return this[ki]?e.join(""):Buffer.concat(e,e.dataLength)}async promise(){return new Promise((e,r)=>{this.on(Xt,()=>r(new Error("stream destroyed"))),this.on("error",n=>r(n)),this.on("end",()=>e())})}[Symbol.asyncIterator](){this[An]=!1;let e=!1,r=async()=>(this.pause(),e=!0,{value:void 0,done:!0});return{next:()=>{if(e)return r();let i=this.read();if(i!==null)return Promise.resolve({done:!1,value:i});if(this[Ls])return r();let s,o,a=d=>{this.off("data",c),this.off("end",u),this.off(Xt,l),r(),o(d)},c=d=>{this.off("error",a),this.off("end",u),this.off(Xt,l),this.pause(),s({value:d,done:!!this[Ls]})},u=()=>{this.off("error",a),this.off("data",c),this.off(Xt,l),r(),s({done:!0,value:void 0})},l=()=>a(new Error("stream destroyed"));return new Promise((d,p)=>{o=p,s=d,this.once(Xt,l),this.once("error",a),this.once("end",u),this.once("data",c)})},throw:r,return:r,[Symbol.asyncIterator](){return this}}}[Symbol.iterator](){this[An]=!1;let e=!1,r=()=>(this.pause(),this.off(EI,r),this.off(Xt,r),this.off("end",r),e=!0,{done:!0,value:void 0}),n=()=>{if(e)return r();let i=this.read();return i===null?r():{done:!1,value:i}};return this.once("end",r),this.once(EI,r),this.once(Xt,r),{next:n,throw:r,return:r,[Symbol.iterator](){return this}}}destroy(e){if(this[Xt])return e?this.emit("error",e):this.emit(Xt),this;this[Xt]=!0,this[An]=!0,this[mr].length=0,this[hr]=0;let r=this;return typeof r.close=="function"&&!this[jy]&&r.close(),e?this.emit("error",e):this.emit(Xt),this}static get isStream(){return Abe}};var Hbe=rs.realpathSync.native,Ef={lstatSync:rs.lstatSync,readdir:rs.readdir,readdirSync:rs.readdirSync,readlinkSync:rs.readlinkSync,realpathSync:Hbe,promises:{lstat:$o.lstat,readdir:$o.readdir,readlink:$o.readlink,realpath:$o.realpath}},n5=t=>!t||t===Ef||t===qbe?Ef:{...Ef,...t,promises:{...Ef.promises,...t.promises||{}}},i5=/^\\\\\?\\([a-z]:)\\?$/i,Zbe=t=>t.replace(/\//g,"\\").replace(i5,"$1\\"),Bbe=/[\\\/]/,ti=0,s5=1,o5=2,ts=4,a5=6,c5=8,Pa=10,u5=12,ei=15,wf=~ei,OI=16,Y8=32,kf=64,Ti=128,Hy=256,By=512,Q8=kf|Ti|By,Gbe=1023,CI=t=>t.isFile()?c5:t.isDirectory()?ts:t.isSymbolicLink()?Pa:t.isCharacterDevice()?o5:t.isBlockDevice()?a5:t.isSocket()?u5:t.isFIFO()?s5:ti,e5=new Oa({max:2**12}),Tf=t=>{let e=e5.get(t);if(e)return e;let r=t.normalize("NFKD");return e5.set(t,r),r},t5=new Oa({max:2**12}),Zy=t=>{let e=t5.get(t);if(e)return e;let r=Tf(t.toLowerCase());return t5.set(t,r),r},Gy=class extends Oa{constructor(){super({max:256})}},PI=class extends Oa{constructor(e=16*1024){super({maxSize:e,sizeCalculation:r=>r.length+1})}},l5=Symbol("PathScurry setAsCwd"),qr=class{name;root;roots;parent;nocase;isCWD=!1;#e;#r;get dev(){return this.#r}#s;get mode(){return this.#s}#i;get nlink(){return this.#i}#o;get uid(){return this.#o}#b;get gid(){return this.#b}#v;get rdev(){return this.#v}#l;get blksize(){return this.#l}#a;get ino(){return this.#a}#p;get size(){return this.#p}#d;get blocks(){return this.#d}#c;get atimeMs(){return this.#c}#n;get mtimeMs(){return this.#n}#f;get ctimeMs(){return this.#f}#S;get birthtimeMs(){return this.#S}#_;get atime(){return this.#_}#m;get mtime(){return this.#m}#I;get ctime(){return this.#I}#h;get birthtime(){return this.#h}#E;#k;#g;#y;#x;#T;#t;#N;#P;#$;get parentPath(){return(this.parent||this).fullpath()}get path(){return this.parentPath}constructor(e,r=ti,n,i,s,o,a){this.name=e,this.#E=s?Zy(e):Tf(e),this.#t=r&Gbe,this.nocase=s,this.roots=i,this.root=n||this,this.#N=o,this.#g=a.fullpath,this.#x=a.relative,this.#T=a.relativePosix,this.parent=a.parent,this.parent?this.#e=this.parent.#e:this.#e=n5(a.fs)}depth(){return this.#k!==void 0?this.#k:this.parent?this.#k=this.parent.depth()+1:this.#k=0}childrenCache(){return this.#N}resolve(e){if(!e)return this;let r=this.getRootString(e),i=e.substring(r.length).split(this.splitSep);return r?this.getRoot(r).#A(i):this.#A(i)}#A(e){let r=this;for(let n of e)r=r.child(n);return r}children(){let e=this.#N.get(this);if(e)return e;let r=Object.assign([],{provisional:0});return this.#N.set(this,r),this.#t&=~OI,r}child(e,r){if(e===""||e===".")return this;if(e==="..")return this.parent||this;let n=this.children(),i=this.nocase?Zy(e):Tf(e);for(let c of n)if(c.#E===i)return c;let s=this.parent?this.sep:"",o=this.#g?this.#g+s+e:void 0,a=this.newChild(e,ti,{...r,parent:this,fullpath:o});return this.canReaddir()||(a.#t|=Ti),n.push(a),a}relative(){if(this.isCWD)return"";if(this.#x!==void 0)return this.#x;let e=this.name,r=this.parent;if(!r)return this.#x=this.name;let n=r.relative();return n+(!n||!r.parent?"":this.sep)+e}relativePosix(){if(this.sep==="/")return this.relative();if(this.isCWD)return"";if(this.#T!==void 0)return this.#T;let e=this.name,r=this.parent;if(!r)return this.#T=this.fullpathPosix();let n=r.relativePosix();return n+(!n||!r.parent?"":"/")+e}fullpath(){if(this.#g!==void 0)return this.#g;let e=this.name,r=this.parent;if(!r)return this.#g=this.name;let i=r.fullpath()+(r.parent?this.sep:"")+e;return this.#g=i}fullpathPosix(){if(this.#y!==void 0)return this.#y;if(this.sep==="/")return this.#y=this.fullpath();if(!this.parent){let i=this.fullpath().replace(/\\/g,"/");return/^[a-z]:\//i.test(i)?this.#y=`//?/${i}`:this.#y=i}let e=this.parent,r=e.fullpathPosix(),n=r+(!r||!e.parent?"":"/")+this.name;return this.#y=n}isUnknown(){return(this.#t&ei)===ti}isType(e){return this[`is${e}`]()}getType(){return this.isUnknown()?"Unknown":this.isDirectory()?"Directory":this.isFile()?"File":this.isSymbolicLink()?"SymbolicLink":this.isFIFO()?"FIFO":this.isCharacterDevice()?"CharacterDevice":this.isBlockDevice()?"BlockDevice":this.isSocket()?"Socket":"Unknown"}isFile(){return(this.#t&ei)===c5}isDirectory(){return(this.#t&ei)===ts}isCharacterDevice(){return(this.#t&ei)===o5}isBlockDevice(){return(this.#t&ei)===a5}isFIFO(){return(this.#t&ei)===s5}isSocket(){return(this.#t&ei)===u5}isSymbolicLink(){return(this.#t&Pa)===Pa}lstatCached(){return this.#t&Y8?this:void 0}readlinkCached(){return this.#P}realpathCached(){return this.#$}readdirCached(){let e=this.children();return e.slice(0,e.provisional)}canReadlink(){if(this.#P)return!0;if(!this.parent)return!1;let e=this.#t&ei;return!(e!==ti&&e!==Pa||this.#t&Hy||this.#t&Ti)}calledReaddir(){return!!(this.#t&OI)}isENOENT(){return!!(this.#t&Ti)}isNamed(e){return this.nocase?this.#E===Zy(e):this.#E===Tf(e)}async readlink(){let e=this.#P;if(e)return e;if(this.canReadlink()&&this.parent)try{let r=await this.#e.promises.readlink(this.fullpath()),n=(await this.parent.realpath())?.resolve(r);if(n)return this.#P=n}catch(r){this.#C(r.code);return}}readlinkSync(){let e=this.#P;if(e)return e;if(this.canReadlink()&&this.parent)try{let r=this.#e.readlinkSync(this.fullpath()),n=this.parent.realpathSync()?.resolve(r);if(n)return this.#P=n}catch(r){this.#C(r.code);return}}#z(e){this.#t|=OI;for(let r=e.provisional;rn(null,e))}readdirCB(e,r=!1){if(!this.canReaddir()){r?e(null,[]):queueMicrotask(()=>e(null,[]));return}let n=this.children();if(this.calledReaddir()){let s=n.slice(0,n.provisional);r?e(null,s):queueMicrotask(()=>e(null,s));return}if(this.#D.push(e),this.#R)return;this.#R=!0;let i=this.fullpath();this.#e.readdir(i,{withFileTypes:!0},(s,o)=>{if(s)this.#L(s.code),n.provisional=0;else{for(let a of o)this.#U(a,n);this.#z(n)}this.#B(n.slice(0,n.provisional))})}#G;async readdir(){if(!this.canReaddir())return[];let e=this.children();if(this.calledReaddir())return e.slice(0,e.provisional);let r=this.fullpath();if(this.#G)await this.#G;else{let n=()=>{};this.#G=new Promise(i=>n=i);try{for(let i of await this.#e.promises.readdir(r,{withFileTypes:!0}))this.#U(i,e);this.#z(e)}catch(i){this.#L(i.code),e.provisional=0}this.#G=void 0,n()}return e.slice(0,e.provisional)}readdirSync(){if(!this.canReaddir())return[];let e=this.children();if(this.calledReaddir())return e.slice(0,e.provisional);let r=this.fullpath();try{for(let n of this.#e.readdirSync(r,{withFileTypes:!0}))this.#U(n,e);this.#z(e)}catch(n){this.#L(n.code),e.provisional=0}return e.slice(0,e.provisional)}canReaddir(){if(this.#t&Q8)return!1;let e=ei&this.#t;return e===ti||e===ts||e===Pa}shouldWalk(e,r){return(this.#t&ts)===ts&&!(this.#t&Q8)&&!e.has(this)&&(!r||r(this))}async realpath(){if(this.#$)return this.#$;if(!((By|Hy|Ti)&this.#t))try{let e=await this.#e.promises.realpath(this.fullpath());return this.#$=this.resolve(e)}catch{this.#j()}}realpathSync(){if(this.#$)return this.#$;if(!((By|Hy|Ti)&this.#t))try{let e=this.#e.realpathSync(this.fullpath());return this.#$=this.resolve(e)}catch{this.#j()}}[l5](e){if(e===this)return;e.isCWD=!1,this.isCWD=!0;let r=new Set([]),n=[],i=this;for(;i&&i.parent;)r.add(i),i.#x=n.join(this.sep),i.#T=n.join("/"),i=i.parent,n.push("..");for(i=e;i&&i.parent&&!r.has(i);)i.#x=void 0,i.#T=void 0,i=i.parent}},Wy=class t extends qr{sep="\\";splitSep=Bbe;constructor(e,r=ti,n,i,s,o,a){super(e,r,n,i,s,o,a)}newChild(e,r=ti,n={}){return new t(e,r,this.root,this.roots,this.nocase,this.childrenCache(),n)}getRootString(e){return Bu.win32.parse(e).root}getRoot(e){if(e=Zbe(e.toUpperCase()),e===this.root.name)return this.root;for(let[r,n]of Object.entries(this.roots))if(this.sameRoot(e,r))return this.roots[e]=n;return this.roots[e]=new Gu(e,this).root}sameRoot(e,r=this.root.name){return e=e.toUpperCase().replace(/\//g,"\\").replace(i5,"$1\\"),e===r}},Vy=class t extends qr{splitSep="/";sep="/";constructor(e,r=ti,n,i,s,o,a){super(e,r,n,i,s,o,a)}getRootString(e){return e.startsWith("/")?"/":""}getRoot(e){return this.root}newChild(e,r=ti,n={}){return new t(e,r,this.root,this.roots,this.nocase,this.childrenCache(),n)}},Ky=class{root;rootPath;roots;cwd;#e;#r;#s;nocase;#i;constructor(e=process.cwd(),r,n,{nocase:i,childrenCacheSize:s=16*1024,fs:o=Ef}={}){this.#i=n5(o),(e instanceof URL||e.startsWith("file://"))&&(e=(0,r5.fileURLToPath)(e));let a=r.resolve(e);this.roots=Object.create(null),this.rootPath=this.parseRootPath(a),this.#e=new Gy,this.#r=new Gy,this.#s=new PI(s);let c=a.substring(this.rootPath.length).split(n);if(c.length===1&&!c[0]&&c.pop(),i===void 0)throw new TypeError("must provide nocase setting to PathScurryBase ctor");this.nocase=i,this.root=this.newRoot(this.#i),this.roots[this.rootPath]=this.root;let u=this.root,l=c.length-1,d=r.sep,p=this.rootPath,f=!1;for(let m of c){let h=l--;u=u.child(m,{relative:new Array(h).fill("..").join(d),relativePosix:new Array(h).fill("..").join("/"),fullpath:p+=(f?"":d)+m}),f=!0}this.cwd=u}depth(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.depth()}childrenCache(){return this.#s}resolve(...e){let r="";for(let s=e.length-1;s>=0;s--){let o=e[s];if(!(!o||o===".")&&(r=r?`${o}/${r}`:o,this.isAbsolute(o)))break}let n=this.#e.get(r);if(n!==void 0)return n;let i=this.cwd.resolve(r).fullpath();return this.#e.set(r,i),i}resolvePosix(...e){let r="";for(let s=e.length-1;s>=0;s--){let o=e[s];if(!(!o||o===".")&&(r=r?`${o}/${r}`:o,this.isAbsolute(o)))break}let n=this.#r.get(r);if(n!==void 0)return n;let i=this.cwd.resolve(r).fullpathPosix();return this.#r.set(r,i),i}relative(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.relative()}relativePosix(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.relativePosix()}basename(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.name}dirname(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),(e.parent||e).fullpath()}async readdir(e=this.cwd,r={withFileTypes:!0}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof qr||(r=e,e=this.cwd);let{withFileTypes:n}=r;if(e.canReaddir()){let i=await e.readdir();return n?i:i.map(s=>s.name)}else return[]}readdirSync(e=this.cwd,r={withFileTypes:!0}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof qr||(r=e,e=this.cwd);let{withFileTypes:n=!0}=r;return e.canReaddir()?n?e.readdirSync():e.readdirSync().map(i=>i.name):[]}async lstat(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.lstat()}lstatSync(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.lstatSync()}async readlink(e=this.cwd,{withFileTypes:r}={withFileTypes:!1}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof qr||(r=e.withFileTypes,e=this.cwd);let n=await e.readlink();return r?n:n?.fullpath()}readlinkSync(e=this.cwd,{withFileTypes:r}={withFileTypes:!1}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof qr||(r=e.withFileTypes,e=this.cwd);let n=e.readlinkSync();return r?n:n?.fullpath()}async realpath(e=this.cwd,{withFileTypes:r}={withFileTypes:!1}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof qr||(r=e.withFileTypes,e=this.cwd);let n=await e.realpath();return r?n:n?.fullpath()}realpathSync(e=this.cwd,{withFileTypes:r}={withFileTypes:!1}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof qr||(r=e.withFileTypes,e=this.cwd);let n=e.realpathSync();return r?n:n?.fullpath()}async walk(e=this.cwd,r={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof qr||(r=e,e=this.cwd);let{withFileTypes:n=!0,follow:i=!1,filter:s,walkFilter:o}=r,a=[];(!s||s(e))&&a.push(n?e:e.fullpath());let c=new Set,u=(d,p)=>{c.add(d),d.readdirCB((f,m)=>{if(f)return p(f);let h=m.length;if(!h)return p();let g=()=>{--h===0&&p()};for(let v of m)(!s||s(v))&&a.push(n?v:v.fullpath()),i&&v.isSymbolicLink()?v.realpath().then(S=>S?.isUnknown()?S.lstat():S).then(S=>S?.shouldWalk(c,o)?u(S,g):g()):v.shouldWalk(c,o)?u(v,g):g()},!0)},l=e;return new Promise((d,p)=>{u(l,f=>{if(f)return p(f);d(a)})})}walkSync(e=this.cwd,r={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof qr||(r=e,e=this.cwd);let{withFileTypes:n=!0,follow:i=!1,filter:s,walkFilter:o}=r,a=[];(!s||s(e))&&a.push(n?e:e.fullpath());let c=new Set([e]);for(let u of c){let l=u.readdirSync();for(let d of l){(!s||s(d))&&a.push(n?d:d.fullpath());let p=d;if(d.isSymbolicLink()){if(!(i&&(p=d.realpathSync())))continue;p.isUnknown()&&p.lstatSync()}p.shouldWalk(c,o)&&c.add(p)}}return a}[Symbol.asyncIterator](){return this.iterate()}iterate(e=this.cwd,r={}){return typeof e=="string"?e=this.cwd.resolve(e):e instanceof qr||(r=e,e=this.cwd),this.stream(e,r)[Symbol.asyncIterator]()}[Symbol.iterator](){return this.iterateSync()}*iterateSync(e=this.cwd,r={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof qr||(r=e,e=this.cwd);let{withFileTypes:n=!0,follow:i=!1,filter:s,walkFilter:o}=r;(!s||s(e))&&(yield n?e:e.fullpath());let a=new Set([e]);for(let c of a){let u=c.readdirSync();for(let l of u){(!s||s(l))&&(yield n?l:l.fullpath());let d=l;if(l.isSymbolicLink()){if(!(i&&(d=l.realpathSync())))continue;d.isUnknown()&&d.lstatSync()}d.shouldWalk(a,o)&&a.add(d)}}}stream(e=this.cwd,r={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof qr||(r=e,e=this.cwd);let{withFileTypes:n=!0,follow:i=!1,filter:s,walkFilter:o}=r,a=new To({objectMode:!0});(!s||s(e))&&a.write(n?e:e.fullpath());let c=new Set,u=[e],l=0,d=()=>{let p=!1;for(;!p;){let f=u.shift();if(!f){l===0&&a.end();return}l++,c.add(f);let m=(g,v,S=!1)=>{if(g)return a.emit("error",g);if(i&&!S){let _=[];for(let y of v)y.isSymbolicLink()&&_.push(y.realpath().then(x=>x?.isUnknown()?x.lstat():x));if(_.length){Promise.all(_).then(()=>m(null,v,!0));return}}for(let _ of v)_&&(!s||s(_))&&(a.write(n?_:_.fullpath())||(p=!0));l--;for(let _ of v){let y=_.realpathCached()||_;y.shouldWalk(c,o)&&u.push(y)}p&&!a.flowing?a.once("drain",d):h||d()},h=!0;f.readdirCB(m,!0),h=!1}};return d(),a}streamSync(e=this.cwd,r={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof qr||(r=e,e=this.cwd);let{withFileTypes:n=!0,follow:i=!1,filter:s,walkFilter:o}=r,a=new To({objectMode:!0}),c=new Set;(!s||s(e))&&a.write(n?e:e.fullpath());let u=[e],l=0,d=()=>{let p=!1;for(;!p;){let f=u.shift();if(!f){l===0&&a.end();return}l++,c.add(f);let m=f.readdirSync();for(let h of m)(!s||s(h))&&(a.write(n?h:h.fullpath())||(p=!0));l--;for(let h of m){let g=h;if(h.isSymbolicLink()){if(!(i&&(g=h.realpathSync())))continue;g.isUnknown()&&g.lstatSync()}g.shouldWalk(c,o)&&u.push(g)}}p&&!a.flowing&&a.once("drain",d)};return d(),a}chdir(e=this.cwd){let r=this.cwd;this.cwd=typeof e=="string"?this.cwd.resolve(e):e,this.cwd[l5](r)}},Gu=class extends Ky{sep="\\";constructor(e=process.cwd(),r={}){let{nocase:n=!0}=r;super(e,Bu.win32,"\\",{...r,nocase:n}),this.nocase=n;for(let i=this.cwd;i;i=i.parent)i.nocase=this.nocase}parseRootPath(e){return Bu.win32.parse(e).root.toUpperCase()}newRoot(e){return new Wy(this.rootPath,ts,void 0,this.roots,this.nocase,this.childrenCache(),{fs:e})}isAbsolute(e){return e.startsWith("/")||e.startsWith("\\")||/^[a-z]:(\/|\\)/i.test(e)}},Wu=class extends Ky{sep="/";constructor(e=process.cwd(),r={}){let{nocase:n=!1}=r;super(e,Bu.posix,"/",{...r,nocase:n}),this.nocase=n}parseRootPath(e){return"/"}newRoot(e){return new Vy(this.rootPath,ts,void 0,this.roots,this.nocase,this.childrenCache(),{fs:e})}isAbsolute(e){return e.startsWith("/")}},$f=class extends Wu{constructor(e=process.cwd(),r={}){let{nocase:n=!0}=r;super(e,{...r,nocase:n})}},wUe=process.platform==="win32"?Wy:Vy,d5=process.platform==="win32"?Gu:process.platform==="darwin"?$f:Wu;var Wbe=t=>t.length>=1,Vbe=t=>t.length>=1,Vu=class t{#e;#r;#s;length;#i;#o;#b;#v;#l;#a;#p=!0;constructor(e,r,n,i){if(!Wbe(e))throw new TypeError("empty pattern list");if(!Vbe(r))throw new TypeError("empty glob list");if(r.length!==e.length)throw new TypeError("mismatched pattern list and glob list lengths");if(this.length=e.length,n<0||n>=this.length)throw new TypeError("index out of range");if(this.#e=e,this.#r=r,this.#s=n,this.#i=i,this.#s===0){if(this.isUNC()){let[s,o,a,c,...u]=this.#e,[l,d,p,f,...m]=this.#r;u[0]===""&&(u.shift(),m.shift());let h=[s,o,a,c,""].join("/"),g=[l,d,p,f,""].join("/");this.#e=[h,...u],this.#r=[g,...m],this.length=this.#e.length}else if(this.isDrive()||this.isAbsolute()){let[s,...o]=this.#e,[a,...c]=this.#r;o[0]===""&&(o.shift(),c.shift());let u=s+"/",l=a+"/";this.#e=[u,...o],this.#r=[l,...c],this.length=this.#e.length}}}pattern(){return this.#e[this.#s]}isString(){return typeof this.#e[this.#s]=="string"}isGlobstar(){return this.#e[this.#s]===Ir}isRegExp(){return this.#e[this.#s]instanceof RegExp}globString(){return this.#b=this.#b||(this.#s===0?this.isAbsolute()?this.#r[0]+this.#r.slice(1).join("/"):this.#r.join("/"):this.#r.slice(this.#s).join("/"))}hasMore(){return this.length>this.#s+1}rest(){return this.#o!==void 0?this.#o:this.hasMore()?(this.#o=new t(this.#e,this.#r,this.#s+1,this.#i),this.#o.#a=this.#a,this.#o.#l=this.#l,this.#o.#v=this.#v,this.#o):this.#o=null}isUNC(){let e=this.#e;return this.#l!==void 0?this.#l:this.#l=this.#i==="win32"&&this.#s===0&&e[0]===""&&e[1]===""&&typeof e[2]=="string"&&!!e[2]&&typeof e[3]=="string"&&!!e[3]}isDrive(){let e=this.#e;return this.#v!==void 0?this.#v:this.#v=this.#i==="win32"&&this.#s===0&&this.length>1&&typeof e[0]=="string"&&/^[a-z]:$/i.test(e[0])}isAbsolute(){let e=this.#e;return this.#a!==void 0?this.#a:this.#a=e[0]===""&&e.length>1||this.isDrive()||this.isUNC()}root(){let e=this.#e[0];return typeof e=="string"&&this.isAbsolute()&&this.#s===0?e:""}checkFollowGlobstar(){return!(this.#s===0||!this.isGlobstar()||!this.#p)}markFollowGlobstar(){return this.#s===0||!this.isGlobstar()||!this.#p?!1:(this.#p=!1,!0)}};var Kbe=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",Ku=class{relative;relativeChildren;absolute;absoluteChildren;platform;mmopts;constructor(e,{nobrace:r,nocase:n,noext:i,noglobstar:s,platform:o=Kbe}){this.relative=[],this.absolute=[],this.relativeChildren=[],this.absoluteChildren=[],this.platform=o,this.mmopts={dot:!0,nobrace:r,nocase:n,noext:i,noglobstar:s,optimizationLevel:2,platform:o,nocomment:!0,nonegate:!0};for(let a of e)this.add(a)}add(e){let r=new Pn(e,this.mmopts);for(let n=0;n[e,!!(r&2),!!(r&1)])}},MI=class{store=new Map;add(e,r){if(!e.canReaddir())return;let n=this.store.get(e);n?n.find(i=>i.globString()===r.globString())||n.push(r):this.store.set(e,[r])}get(e){let r=this.store.get(e);if(!r)throw new Error("attempting to walk unknown path");return r}entries(){return this.keys().map(e=>[e,this.store.get(e)])}keys(){return[...this.store.keys()].filter(e=>e.canReaddir())}},If=class t{hasWalkedCache;matches=new NI;subwalks=new MI;patterns;follow;dot;opts;constructor(e,r){this.opts=e,this.follow=!!e.follow,this.dot=!!e.dot,this.hasWalkedCache=r?r.copy():new AI}processPatterns(e,r){this.patterns=r;let n=r.map(i=>[e,i]);for(let[i,s]of n){this.hasWalkedCache.storeWalked(i,s);let o=s.root(),a=s.isAbsolute()&&this.opts.absolute!==!1;if(o){i=i.resolve(o==="/"&&this.opts.root!==void 0?this.opts.root:o);let d=s.rest();if(d)s=d;else{this.matches.add(i,!0,!1);continue}}if(i.isENOENT())continue;let c,u,l=!1;for(;typeof(c=s.pattern())=="string"&&(u=s.rest());)i=i.resolve(c),s=u,l=!0;if(c=s.pattern(),u=s.rest(),l){if(this.hasWalkedCache.hasWalked(i,s))continue;this.hasWalkedCache.storeWalked(i,s)}if(typeof c=="string"){let d=c===".."||c===""||c===".";this.matches.add(i.resolve(c),a,d);continue}else if(c===Ir){(!i.isSymbolicLink()||this.follow||s.checkFollowGlobstar())&&this.subwalks.add(i,s);let d=u?.pattern(),p=u?.rest();if(!u||(d===""||d===".")&&!p)this.matches.add(i,a,d===""||d===".");else if(d===".."){let f=i.parent||i;p?this.hasWalkedCache.hasWalked(f,p)||this.subwalks.add(f,p):this.matches.add(f,a,!0)}}else c instanceof RegExp&&this.subwalks.add(i,s)}return this}subwalkTargets(){return this.subwalks.keys()}child(){return new t(this.opts,this.hasWalkedCache)}filterEntries(e,r){let n=this.subwalks.get(e),i=this.child();for(let s of r)for(let o of n){let a=o.isAbsolute(),c=o.pattern(),u=o.rest();c===Ir?i.testGlobstar(s,o,u,a):c instanceof RegExp?i.testRegExp(s,c,u,a):i.testString(s,c,u,a)}return i}testGlobstar(e,r,n,i){if((this.dot||!e.name.startsWith("."))&&(r.hasMore()||this.matches.add(e,i,!1),e.canReaddir()&&(this.follow||!e.isSymbolicLink()?this.subwalks.add(e,r):e.isSymbolicLink()&&(n&&r.checkFollowGlobstar()?this.subwalks.add(e,n):r.markFollowGlobstar()&&this.subwalks.add(e,r)))),n){let s=n.pattern();if(typeof s=="string"&&s!==".."&&s!==""&&s!==".")this.testString(e,s,n.rest(),i);else if(s===".."){let o=e.parent||e;this.subwalks.add(o,n)}else s instanceof RegExp&&this.testRegExp(e,s,n.rest(),i)}}testRegExp(e,r,n,i){r.test(e.name)&&(n?this.subwalks.add(e,n):this.matches.add(e,i,!1))}testString(e,r,n,i){e.isNamed(r)&&(n?this.subwalks.add(e,n):this.matches.add(e,i,!1))}};var Jbe=(t,e)=>typeof t=="string"?new Ku([t],e):Array.isArray(t)?new Ku(t,e):t,Jy=class{path;patterns;opts;seen=new Set;paused=!1;aborted=!1;#e=[];#r;#s;signal;maxDepth;includeChildMatches;constructor(e,r,n){if(this.patterns=e,this.path=r,this.opts=n,this.#s=!n.posix&&n.platform==="win32"?"\\":"/",this.includeChildMatches=n.includeChildMatches!==!1,(n.ignore||!this.includeChildMatches)&&(this.#r=Jbe(n.ignore??[],n),!this.includeChildMatches&&typeof this.#r.add!="function")){let i="cannot ignore child matches, ignore lacks add() method.";throw new Error(i)}this.maxDepth=n.maxDepth||1/0,n.signal&&(this.signal=n.signal,this.signal.addEventListener("abort",()=>{this.#e.length=0}))}#i(e){return this.seen.has(e)||!!this.#r?.ignored?.(e)}#o(e){return!!this.#r?.childrenIgnored?.(e)}pause(){this.paused=!0}resume(){if(this.signal?.aborted)return;this.paused=!1;let e;for(;!this.paused&&(e=this.#e.shift());)e()}onResume(e){this.signal?.aborted||(this.paused?this.#e.push(e):e())}async matchCheck(e,r){if(r&&this.opts.nodir)return;let n;if(this.opts.realpath){if(n=e.realpathCached()||await e.realpath(),!n)return;e=n}let s=e.isUnknown()||this.opts.stat?await e.lstat():e;if(this.opts.follow&&this.opts.nodir&&s?.isSymbolicLink()){let o=await s.realpath();o&&(o.isUnknown()||this.opts.stat)&&await o.lstat()}return this.matchCheckTest(s,r)}matchCheckTest(e,r){return e&&(this.maxDepth===1/0||e.depth()<=this.maxDepth)&&(!r||e.canReaddir())&&(!this.opts.nodir||!e.isDirectory())&&(!this.opts.nodir||!this.opts.follow||!e.isSymbolicLink()||!e.realpathCached()?.isDirectory())&&!this.#i(e)?e:void 0}matchCheckSync(e,r){if(r&&this.opts.nodir)return;let n;if(this.opts.realpath){if(n=e.realpathCached()||e.realpathSync(),!n)return;e=n}let s=e.isUnknown()||this.opts.stat?e.lstatSync():e;if(this.opts.follow&&this.opts.nodir&&s?.isSymbolicLink()){let o=s.realpathSync();o&&(o?.isUnknown()||this.opts.stat)&&o.lstatSync()}return this.matchCheckTest(s,r)}matchFinish(e,r){if(this.#i(e))return;if(!this.includeChildMatches&&this.#r?.add){let s=`${e.relativePosix()}/**`;this.#r.add(s)}let n=this.opts.absolute===void 0?r:this.opts.absolute;this.seen.add(e);let i=this.opts.mark&&e.isDirectory()?this.#s:"";if(this.opts.withFileTypes)this.matchEmit(e);else if(n){let s=this.opts.posix?e.fullpathPosix():e.fullpath();this.matchEmit(s+i)}else{let s=this.opts.posix?e.relativePosix():e.relative(),o=this.opts.dotRelative&&!s.startsWith(".."+this.#s)?"."+this.#s:"";this.matchEmit(s?o+s+i:"."+i)}}async match(e,r,n){let i=await this.matchCheck(e,n);i&&this.matchFinish(i,r)}matchSync(e,r,n){let i=this.matchCheckSync(e,n);i&&this.matchFinish(i,r)}walkCB(e,r,n){this.signal?.aborted&&n(),this.walkCB2(e,r,new If(this.opts),n)}walkCB2(e,r,n,i){if(this.#o(e))return i();if(this.signal?.aborted&&i(),this.paused){this.onResume(()=>this.walkCB2(e,r,n,i));return}n.processPatterns(e,r);let s=1,o=()=>{--s===0&&i()};for(let[a,c,u]of n.matches.entries())this.#i(a)||(s++,this.match(a,c,u).then(()=>o()));for(let a of n.subwalkTargets()){if(this.maxDepth!==1/0&&a.depth()>=this.maxDepth)continue;s++;let c=a.readdirCached();a.calledReaddir()?this.walkCB3(a,c,n,o):a.readdirCB((u,l)=>this.walkCB3(a,l,n,o),!0)}o()}walkCB3(e,r,n,i){n=n.filterEntries(e,r);let s=1,o=()=>{--s===0&&i()};for(let[a,c,u]of n.matches.entries())this.#i(a)||(s++,this.match(a,c,u).then(()=>o()));for(let[a,c]of n.subwalks.entries())s++,this.walkCB2(a,c,n.child(),o);o()}walkCBSync(e,r,n){this.signal?.aborted&&n(),this.walkCB2Sync(e,r,new If(this.opts),n)}walkCB2Sync(e,r,n,i){if(this.#o(e))return i();if(this.signal?.aborted&&i(),this.paused){this.onResume(()=>this.walkCB2Sync(e,r,n,i));return}n.processPatterns(e,r);let s=1,o=()=>{--s===0&&i()};for(let[a,c,u]of n.matches.entries())this.#i(a)||this.matchSync(a,c,u);for(let a of n.subwalkTargets()){if(this.maxDepth!==1/0&&a.depth()>=this.maxDepth)continue;s++;let c=a.readdirSync();this.walkCB3Sync(a,c,n,o)}o()}walkCB3Sync(e,r,n,i){n=n.filterEntries(e,r);let s=1,o=()=>{--s===0&&i()};for(let[a,c,u]of n.matches.entries())this.#i(a)||this.matchSync(a,c,u);for(let[a,c]of n.subwalks.entries())s++,this.walkCB2Sync(a,c,n.child(),o);o()}},Rf=class extends Jy{matches=new Set;constructor(e,r,n){super(e,r,n)}matchEmit(e){this.matches.add(e)}async walk(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&await this.path.lstat(),await new Promise((e,r)=>{this.walkCB(this.path,this.patterns,()=>{this.signal?.aborted?r(this.signal.reason):e(this.matches)})}),this.matches}walkSync(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>{if(this.signal?.aborted)throw this.signal.reason}),this.matches}},Of=class extends Jy{results;constructor(e,r,n){super(e,r,n),this.results=new To({signal:this.signal,objectMode:!0}),this.results.on("drain",()=>this.resume()),this.results.on("resume",()=>this.resume())}matchEmit(e){this.results.write(e),this.results.flowing||this.pause()}stream(){let e=this.path;return e.isUnknown()?e.lstat().then(()=>{this.walkCB(e,this.patterns,()=>this.results.end())}):this.walkCB(e,this.patterns,()=>this.results.end()),this.results}streamSync(){return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>this.results.end()),this.results}};var Xbe=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",$i=class{absolute;cwd;root;dot;dotRelative;follow;ignore;magicalBraces;mark;matchBase;maxDepth;nobrace;nocase;nodir;noext;noglobstar;pattern;platform;realpath;scurry;stat;signal;windowsPathsNoEscape;withFileTypes;includeChildMatches;opts;patterns;constructor(e,r){if(!r)throw new TypeError("glob options required");if(this.withFileTypes=!!r.withFileTypes,this.signal=r.signal,this.follow=!!r.follow,this.dot=!!r.dot,this.dotRelative=!!r.dotRelative,this.nodir=!!r.nodir,this.mark=!!r.mark,r.cwd?(r.cwd instanceof URL||r.cwd.startsWith("file://"))&&(r.cwd=(0,p5.fileURLToPath)(r.cwd)):this.cwd="",this.cwd=r.cwd||"",this.root=r.root,this.magicalBraces=!!r.magicalBraces,this.nobrace=!!r.nobrace,this.noext=!!r.noext,this.realpath=!!r.realpath,this.absolute=r.absolute,this.includeChildMatches=r.includeChildMatches!==!1,this.noglobstar=!!r.noglobstar,this.matchBase=!!r.matchBase,this.maxDepth=typeof r.maxDepth=="number"?r.maxDepth:1/0,this.stat=!!r.stat,this.ignore=r.ignore,this.withFileTypes&&this.absolute!==void 0)throw new Error("cannot set absolute and withFileTypes:true");if(typeof e=="string"&&(e=[e]),this.windowsPathsNoEscape=!!r.windowsPathsNoEscape||r.allowWindowsEscape===!1,this.windowsPathsNoEscape&&(e=e.map(c=>c.replace(/\\/g,"/"))),this.matchBase){if(r.noglobstar)throw new TypeError("base matching requires globstar");e=e.map(c=>c.includes("/")?c:`./**/${c}`)}if(this.pattern=e,this.platform=r.platform||Xbe,this.opts={...r,platform:this.platform},r.scurry){if(this.scurry=r.scurry,r.nocase!==void 0&&r.nocase!==r.scurry.nocase)throw new Error("nocase option contradicts provided scurry option")}else{let c=r.platform==="win32"?Gu:r.platform==="darwin"?$f:r.platform?Wu:d5;this.scurry=new c(this.cwd,{nocase:r.nocase,fs:r.fs})}this.nocase=this.scurry.nocase;let n=this.platform==="darwin"||this.platform==="win32",i={...r,dot:this.dot,matchBase:this.matchBase,nobrace:this.nobrace,nocase:this.nocase,nocaseMagicOnly:n,nocomment:!0,noext:this.noext,nonegate:!0,optimizationLevel:2,platform:this.platform,windowsPathsNoEscape:this.windowsPathsNoEscape,debug:!!this.opts.debug},s=this.pattern.map(c=>new Pn(c,i)),[o,a]=s.reduce((c,u)=>(c[0].push(...u.set),c[1].push(...u.globParts),c),[[],[]]);this.patterns=o.map((c,u)=>{let l=a[u];if(!l)throw new Error("invalid pattern object");return new Vu(c,l,0,this.platform)})}async walk(){return[...await new Rf(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).walk()]}walkSync(){return[...new Rf(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).walkSync()]}stream(){return new Of(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).stream()}streamSync(){return new Of(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).streamSync()}iterateSync(){return this.streamSync()[Symbol.iterator]()}[Symbol.iterator](){return this.iterateSync()}iterate(){return this.stream()[Symbol.asyncIterator]()}[Symbol.asyncIterator](){return this.iterate()}};var DI=(t,e={})=>{Array.isArray(t)||(t=[t]);for(let r of t)if(new Pn(r,e).hasMagic())return!0;return!1};function Xy(t,e={}){return new $i(t,e).streamSync()}function h5(t,e={}){return new $i(t,e).stream()}function Cf(t,e={}){return new $i(t,e).walkSync()}async function f5(t,e={}){return new $i(t,e).walk()}function Yy(t,e={}){return new $i(t,e).iterateSync()}function g5(t,e={}){return new $i(t,e).iterate()}var Ybe=Xy,Qbe=Object.assign(h5,{sync:Xy}),eSe=Yy,tSe=Object.assign(g5,{sync:Yy}),rSe=Object.assign(Cf,{stream:Xy,iterate:Yy}),m5=Object.assign(f5,{glob:f5,globSync:Cf,sync:rSe,globStream:h5,stream:Qbe,globStreamSync:Xy,streamSync:Ybe,globIterate:g5,iterate:tSe,globIterateSync:Yy,iterateSync:eSe,Glob:$i,hasMagic:DI,escape:Fu,unescape:Ei});m5.glob=m5;ne();var Ju=require("fs"),Qy=require("os"),Pf=require("path"),e_=(0,Pf.join)((0,Qy.homedir)(),".claude-mem","transcript-watch.json"),nSe=(0,Pf.join)((0,Qy.homedir)(),".claude-mem","transcript-watch-state.json");function Aa(t){return t&&(t.startsWith("~")?(0,Pf.join)((0,Qy.homedir)(),t.slice(1)):t)}function v5(t=e_){let e=Aa(t);if(!(0,Ju.existsSync)(e))throw new Error(`Transcript watch config not found: ${e}`);let r=(0,Ju.readFileSync)(e,"utf-8"),n=JSON.parse(r);if(!n.version||!n.watches)throw new Error(`Invalid transcript watch config: ${e}`);return n.stateFile||(n.stateFile=nSe),n}var Fs=require("fs"),y5=require("path");ne();function _5(t){try{if(!(0,Fs.existsSync)(t))return{offsets:{}};let e=(0,Fs.readFileSync)(t,"utf-8"),r=JSON.parse(e);return r.offsets?r:{offsets:{}}}catch(e){return b.warn("TRANSCRIPT","Failed to load watch state, starting fresh",{statePath:t,error:e instanceof Error?e.message:String(e)}),{offsets:{}}}}function b5(t,e){try{let r=(0,y5.dirname)(t);(0,Fs.existsSync)(r)||(0,Fs.mkdirSync)(r,{recursive:!0}),(0,Fs.writeFileSync)(t,JSON.stringify(e,null,2))}catch(r){b.warn("TRANSCRIPT","Failed to save watch state",{statePath:t,error:r instanceof Error?r.message:String(r)})}}r_();n_();i_();s_();Dr();ne();lf();var Ii=require("fs"),o_=require("path");ne();function x5(t,e){if(!t)return;let r=(0,o_.resolve)(t);if(r.includes("/.git/")||r.includes("\\.git\\")||r.endsWith("/.git")||r.endsWith("\\.git"))return;let n=(0,o_.dirname)(t);(0,Ii.existsSync)(n)||(0,Ii.mkdirSync)(n,{recursive:!0});let i="";(0,Ii.existsSync)(t)&&(i=(0,Ii.readFileSync)(t,"utf-8"));let s=`# Memory Context +>>> no match, partial?`,e,p,r,f),p===c))}let h;if(typeof l=="string"?(h=d===l,this.debug("string match",l,d,h)):(h=l.test(d),this.debug("pattern match",l,d,h)),!h)return!1}if(o===c&&a===u)return!0;if(o===c)return n;if(a===u)return o===c-1&&e[o]==="";throw new Error("wtf?")}braceExpand(){return q8(this.pattern,this.options)}parse(e){vf(e);let r=this.options;if(e==="**")return Ir;if(e==="")return"";let n,i=null;(n=e.match(fbe))?i=r.dot?hbe:mbe:(n=e.match(nbe))?i=(r.nocase?r.dot?abe:obe:r.dot?sbe:ibe)(n[1]):(n=e.match(gbe))?i=(r.nocase?r.dot?ybe:vbe:r.dot?_be:bbe)(n):(n=e.match(cbe))?i=r.dot?lbe:ube:(n=e.match(dbe))&&(i=pbe);let s=Uu.fromGlob(e,this.options).toMMPattern();return i&&typeof s=="object"&&Reflect.defineProperty(s,"test",{value:i}),s}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let e=this.set;if(!e.length)return this.regexp=!1,this.regexp;let r=this.options,n=r.noglobstar?wbe:r.dot?Ebe:kbe,i=new Set(r.nocase?["i"]:[]),s=e.map(c=>{let u=c.map(d=>{if(d instanceof RegExp)for(let p of d.flags.split(""))i.add(p);return typeof d=="string"?Obe(d):d===Ir?Ir:d._src});u.forEach((d,p)=>{let f=u[p+1],m=u[p-1];d!==Ir||m===Ir||(m===void 0?f!==void 0&&f!==Ir?u[p+1]="(?:\\/|"+n+"\\/)?"+f:u[p]=n:f===void 0?u[p-1]=m+"(?:\\/|\\/"+n+")?":f!==Ir&&(u[p-1]=m+"(?:\\/|\\/"+n+"\\/)"+f,u[p+1]=Ir))});let l=u.filter(d=>d!==Ir);if(this.partial&&l.length>=1){let d=[];for(let p=1;p<=l.length;p++)d.push(l.slice(0,p).join("/"));return"(?:"+d.join("|")+")"}return l.join("/")}).join("|"),[o,a]=e.length>1?["(?:",")"]:["",""];s="^"+o+s+a+"$",this.partial&&(s="^(?:\\/|"+o+s.slice(1,-1)+a+")$"),this.negate&&(s="^(?!"+s+").+$");try{this.regexp=new RegExp(s,[...i].join(""))}catch{this.regexp=!1}return this.regexp}slashSplit(e){return this.preserveMultipleSlashes?e.split("/"):this.isWindows&&/^\/\/[^\/]+/.test(e)?["",...e.split(/\/+/)]:e.split(/\/+/)}match(e,r=this.partial){if(this.debug("match",e,this.pattern),this.comment)return!1;if(this.empty)return e==="";if(e==="/"&&r)return!0;let n=this.options;this.isWindows&&(e=e.split("\\").join("/"));let i=this.slashSplit(e);this.debug(this.pattern,"split",i);let s=this.set;this.debug(this.pattern,"set",s);let o=i[i.length-1];if(!o)for(let a=i.length-2;!o&&a>=0;a--)o=i[a];for(let a=0;a{typeof SI.emitWarning=="function"?SI.emitWarning(t,e,r,n):console.error(`[${r}] ${e}: ${t}`)},My=globalThis.AbortController,H8=globalThis.AbortSignal;if(typeof My>"u"){H8=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(n,i){this._onabort.push(i)}},My=class{constructor(){e()}signal=new H8;abort(n){if(!this.signal.aborted){this.signal.reason=n,this.signal.aborted=!0;for(let i of this.signal._onabort)i(n);this.signal.onabort?.(n)}}};let t=SI.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",e=()=>{t&&(t=!1,B8("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",e))}}var Pbe=t=>!Z8.has(t);var Eo=t=>t&&t===Math.floor(t)&&t>0&&isFinite(t),G8=t=>Eo(t)?t<=Math.pow(2,8)?Uint8Array:t<=Math.pow(2,16)?Uint16Array:t<=Math.pow(2,32)?Uint32Array:t<=Number.MAX_SAFE_INTEGER?qu:null:null,qu=class extends Array{constructor(e){super(e),this.fill(0)}},xI=class t{heap;length;static#e=!1;static create(e){let r=G8(e);if(!r)return[];t.#e=!0;let n=new t(e,r);return t.#e=!1,n}constructor(e,r){if(!t.#e)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new r(e),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}},Oa=class t{#e;#r;#s;#i;#o;#b;#v;#l;get perf(){return this.#l}ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#a;#p;#d;#c;#n;#f;#S;#_;#m;#I;#h;#E;#k;#g;#y;#x;#T;#t;#N;static unsafeExposeInternals(e){return{starts:e.#k,ttls:e.#g,autopurgeTimers:e.#y,sizes:e.#E,keyMap:e.#d,keyList:e.#c,valList:e.#n,next:e.#f,prev:e.#S,get head(){return e.#_},get tail(){return e.#m},free:e.#I,isBackgroundFetch:r=>e.#u(r),backgroundFetch:(r,n,i,s)=>e.#q(r,n,i,s),moveToTail:r=>e.#D(r),indexes:r=>e.#O(r),rindexes:r=>e.#C(r),isStale:r=>e.#w(r)}}get max(){return this.#e}get maxSize(){return this.#r}get calculatedSize(){return this.#p}get size(){return this.#a}get fetchMethod(){return this.#b}get memoMethod(){return this.#v}get dispose(){return this.#s}get onInsert(){return this.#i}get disposeAfter(){return this.#o}constructor(e){let{max:r=0,ttl:n,ttlResolution:i=1,ttlAutopurge:s,updateAgeOnGet:o,updateAgeOnHas:a,allowStale:c,dispose:u,onInsert:l,disposeAfter:d,noDisposeOnSet:p,noUpdateTTL:f,maxSize:m=0,maxEntrySize:h=0,sizeCalculation:g,fetchMethod:v,memoMethod:S,noDeleteOnFetchRejection:_,noDeleteOnStaleGet:y,allowStaleOnFetchRejection:x,allowStaleOnFetchAbort:w,ignoreFetchAbort:E,perf:T}=e;if(T!==void 0&&typeof T?.now!="function")throw new TypeError("perf option must have a now() method if specified");if(this.#l=T??Cbe,r!==0&&!Eo(r))throw new TypeError("max option must be a nonnegative integer");let I=r?G8(r):Array;if(!I)throw new Error("invalid max value: "+r);if(this.#e=r,this.#r=m,this.maxEntrySize=h||this.#r,this.sizeCalculation=g,this.sizeCalculation){if(!this.#r&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(S!==void 0&&typeof S!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#v=S,v!==void 0&&typeof v!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#b=v,this.#T=!!v,this.#d=new Map,this.#c=new Array(r).fill(void 0),this.#n=new Array(r).fill(void 0),this.#f=new I(r),this.#S=new I(r),this.#_=0,this.#m=0,this.#I=xI.create(r),this.#a=0,this.#p=0,typeof u=="function"&&(this.#s=u),typeof l=="function"&&(this.#i=l),typeof d=="function"?(this.#o=d,this.#h=[]):(this.#o=void 0,this.#h=void 0),this.#x=!!this.#s,this.#N=!!this.#i,this.#t=!!this.#o,this.noDisposeOnSet=!!p,this.noUpdateTTL=!!f,this.noDeleteOnFetchRejection=!!_,this.allowStaleOnFetchRejection=!!x,this.allowStaleOnFetchAbort=!!w,this.ignoreFetchAbort=!!E,this.maxEntrySize!==0){if(this.#r!==0&&!Eo(this.#r))throw new TypeError("maxSize must be a positive integer if specified");if(!Eo(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#Z()}if(this.allowStale=!!c,this.noDeleteOnStaleGet=!!y,this.updateAgeOnGet=!!o,this.updateAgeOnHas=!!a,this.ttlResolution=Eo(i)||i===0?i:1,this.ttlAutopurge=!!s,this.ttl=n||0,this.ttl){if(!Eo(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#P()}if(this.#e===0&&this.ttl===0&&this.#r===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#e&&!this.#r){let A="LRU_CACHE_UNBOUNDED";Pbe(A)&&(Z8.add(A),B8("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",A,t))}}getRemainingTTL(e){return this.#d.has(e)?1/0:0}#P(){let e=new qu(this.#e),r=new qu(this.#e);this.#g=e,this.#k=r;let n=this.ttlAutopurge?new Array(this.#e):void 0;this.#y=n,this.#z=(o,a,c=this.#l.now())=>{if(r[o]=a!==0?c:0,e[o]=a,n?.[o]&&(clearTimeout(n[o]),n[o]=void 0),a!==0&&n){let u=setTimeout(()=>{this.#w(o)&&this.#R(this.#c[o],"expire")},a+1);u.unref&&u.unref(),n[o]=u}},this.#$=o=>{r[o]=e[o]!==0?this.#l.now():0},this.#A=(o,a)=>{if(e[a]){let c=e[a],u=r[a];if(!c||!u)return;o.ttl=c,o.start=u,o.now=i||s();let l=o.now-u;o.remainingTTL=c-l}};let i=0,s=()=>{let o=this.#l.now();if(this.ttlResolution>0){i=o;let a=setTimeout(()=>i=0,this.ttlResolution);a.unref&&a.unref()}return o};this.getRemainingTTL=o=>{let a=this.#d.get(o);if(a===void 0)return 0;let c=e[a],u=r[a];if(!c||!u)return 1/0;let l=(i||s())-u;return c-l},this.#w=o=>{let a=r[o],c=e[o];return!!c&&!!a&&(i||s())-a>c}}#$=()=>{};#A=()=>{};#z=()=>{};#w=()=>!1;#Z(){let e=new qu(this.#e);this.#p=0,this.#E=e,this.#j=r=>{this.#p-=e[r],e[r]=0},this.#L=(r,n,i,s)=>{if(this.#u(n))return 0;if(!Eo(i))if(s){if(typeof s!="function")throw new TypeError("sizeCalculation must be a function");if(i=s(n,r),!Eo(i))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return i},this.#M=(r,n,i)=>{if(e[r]=n,this.#r){let s=this.#r-e[r];for(;this.#p>s;)this.#F(!0)}this.#p+=e[r],i&&(i.entrySize=n,i.totalCalculatedSize=this.#p)}}#j=e=>{};#M=(e,r,n)=>{};#L=(e,r,n,i)=>{if(n||i)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#O({allowStale:e=this.allowStale}={}){if(this.#a)for(let r=this.#m;!(!this.#U(r)||((e||!this.#w(r))&&(yield r),r===this.#_));)r=this.#S[r]}*#C({allowStale:e=this.allowStale}={}){if(this.#a)for(let r=this.#_;!(!this.#U(r)||((e||!this.#w(r))&&(yield r),r===this.#m));)r=this.#f[r]}#U(e){return e!==void 0&&this.#d.get(this.#c[e])===e}*entries(){for(let e of this.#O())this.#n[e]!==void 0&&this.#c[e]!==void 0&&!this.#u(this.#n[e])&&(yield[this.#c[e],this.#n[e]])}*rentries(){for(let e of this.#C())this.#n[e]!==void 0&&this.#c[e]!==void 0&&!this.#u(this.#n[e])&&(yield[this.#c[e],this.#n[e]])}*keys(){for(let e of this.#O()){let r=this.#c[e];r!==void 0&&!this.#u(this.#n[e])&&(yield r)}}*rkeys(){for(let e of this.#C()){let r=this.#c[e];r!==void 0&&!this.#u(this.#n[e])&&(yield r)}}*values(){for(let e of this.#O())this.#n[e]!==void 0&&!this.#u(this.#n[e])&&(yield this.#n[e])}*rvalues(){for(let e of this.#C())this.#n[e]!==void 0&&!this.#u(this.#n[e])&&(yield this.#n[e])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(e,r={}){for(let n of this.#O()){let i=this.#n[n],s=this.#u(i)?i.__staleWhileFetching:i;if(s!==void 0&&e(s,this.#c[n],this))return this.get(this.#c[n],r)}}forEach(e,r=this){for(let n of this.#O()){let i=this.#n[n],s=this.#u(i)?i.__staleWhileFetching:i;s!==void 0&&e.call(r,s,this.#c[n],this)}}rforEach(e,r=this){for(let n of this.#C()){let i=this.#n[n],s=this.#u(i)?i.__staleWhileFetching:i;s!==void 0&&e.call(r,s,this.#c[n],this)}}purgeStale(){let e=!1;for(let r of this.#C({allowStale:!0}))this.#w(r)&&(this.#R(this.#c[r],"expire"),e=!0);return e}info(e){let r=this.#d.get(e);if(r===void 0)return;let n=this.#n[r],i=this.#u(n)?n.__staleWhileFetching:n;if(i===void 0)return;let s={value:i};if(this.#g&&this.#k){let o=this.#g[r],a=this.#k[r];if(o&&a){let c=o-(this.#l.now()-a);s.ttl=c,s.start=Date.now()}}return this.#E&&(s.size=this.#E[r]),s}dump(){let e=[];for(let r of this.#O({allowStale:!0})){let n=this.#c[r],i=this.#n[r],s=this.#u(i)?i.__staleWhileFetching:i;if(s===void 0||n===void 0)continue;let o={value:s};if(this.#g&&this.#k){o.ttl=this.#g[r];let a=this.#l.now()-this.#k[r];o.start=Math.floor(Date.now()-a)}this.#E&&(o.size=this.#E[r]),e.unshift([n,o])}return e}load(e){this.clear();for(let[r,n]of e){if(n.start){let i=Date.now()-n.start;n.start=this.#l.now()-i}this.set(r,n.value,n)}}set(e,r,n={}){if(r===void 0)return this.delete(e),this;let{ttl:i=this.ttl,start:s,noDisposeOnSet:o=this.noDisposeOnSet,sizeCalculation:a=this.sizeCalculation,status:c}=n,{noUpdateTTL:u=this.noUpdateTTL}=n,l=this.#L(e,r,n.size||0,a);if(this.maxEntrySize&&l>this.maxEntrySize)return c&&(c.set="miss",c.maxEntrySizeExceeded=!0),this.#R(e,"set"),this;let d=this.#a===0?void 0:this.#d.get(e);if(d===void 0)d=this.#a===0?this.#m:this.#I.length!==0?this.#I.pop():this.#a===this.#e?this.#F(!1):this.#a,this.#c[d]=e,this.#n[d]=r,this.#d.set(e,d),this.#f[this.#m]=d,this.#S[d]=this.#m,this.#m=d,this.#a++,this.#M(d,l,c),c&&(c.set="add"),u=!1,this.#N&&this.#i?.(r,e,"add");else{this.#D(d);let p=this.#n[d];if(r!==p){if(this.#T&&this.#u(p)){p.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:f}=p;f!==void 0&&!o&&(this.#x&&this.#s?.(f,e,"set"),this.#t&&this.#h?.push([f,e,"set"]))}else o||(this.#x&&this.#s?.(p,e,"set"),this.#t&&this.#h?.push([p,e,"set"]));if(this.#j(d),this.#M(d,l,c),this.#n[d]=r,c){c.set="replace";let f=p&&this.#u(p)?p.__staleWhileFetching:p;f!==void 0&&(c.oldValue=f)}}else c&&(c.set="update");this.#N&&this.onInsert?.(r,e,r===p?"update":"replace")}if(i!==0&&!this.#g&&this.#P(),this.#g&&(u||this.#z(d,i,s),c&&this.#A(c,d)),!o&&this.#t&&this.#h){let p=this.#h,f;for(;f=p?.shift();)this.#o?.(...f)}return this}pop(){try{for(;this.#a;){let e=this.#n[this.#_];if(this.#F(!0),this.#u(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(e!==void 0)return e}}finally{if(this.#t&&this.#h){let e=this.#h,r;for(;r=e?.shift();)this.#o?.(...r)}}}#F(e){let r=this.#_,n=this.#c[r],i=this.#n[r];return this.#T&&this.#u(i)?i.__abortController.abort(new Error("evicted")):(this.#x||this.#t)&&(this.#x&&this.#s?.(i,n,"evict"),this.#t&&this.#h?.push([i,n,"evict"])),this.#j(r),this.#y?.[r]&&(clearTimeout(this.#y[r]),this.#y[r]=void 0),e&&(this.#c[r]=void 0,this.#n[r]=void 0,this.#I.push(r)),this.#a===1?(this.#_=this.#m=0,this.#I.length=0):this.#_=this.#f[r],this.#d.delete(n),this.#a--,r}has(e,r={}){let{updateAgeOnHas:n=this.updateAgeOnHas,status:i}=r,s=this.#d.get(e);if(s!==void 0){let o=this.#n[s];if(this.#u(o)&&o.__staleWhileFetching===void 0)return!1;if(this.#w(s))i&&(i.has="stale",this.#A(i,s));else return n&&this.#$(s),i&&(i.has="hit",this.#A(i,s)),!0}else i&&(i.has="miss");return!1}peek(e,r={}){let{allowStale:n=this.allowStale}=r,i=this.#d.get(e);if(i===void 0||!n&&this.#w(i))return;let s=this.#n[i];return this.#u(s)?s.__staleWhileFetching:s}#q(e,r,n,i){let s=r===void 0?void 0:this.#n[r];if(this.#u(s))return s;let o=new My,{signal:a}=n;a?.addEventListener("abort",()=>o.abort(a.reason),{signal:o.signal});let c={signal:o.signal,options:n,context:i},u=(h,g=!1)=>{let{aborted:v}=o.signal,S=n.ignoreFetchAbort&&h!==void 0;if(n.status&&(v&&!g?(n.status.fetchAborted=!0,n.status.fetchError=o.signal.reason,S&&(n.status.fetchAbortIgnored=!0)):n.status.fetchResolved=!0),v&&!S&&!g)return d(o.signal.reason);let _=f,y=this.#n[r];return(y===f||S&&g&&y===void 0)&&(h===void 0?_.__staleWhileFetching!==void 0?this.#n[r]=_.__staleWhileFetching:this.#R(e,"fetch"):(n.status&&(n.status.fetchUpdated=!0),this.set(e,h,c.options))),h},l=h=>(n.status&&(n.status.fetchRejected=!0,n.status.fetchError=h),d(h)),d=h=>{let{aborted:g}=o.signal,v=g&&n.allowStaleOnFetchAbort,S=v||n.allowStaleOnFetchRejection,_=S||n.noDeleteOnFetchRejection,y=f;if(this.#n[r]===f&&(!_||y.__staleWhileFetching===void 0?this.#R(e,"fetch"):v||(this.#n[r]=y.__staleWhileFetching)),S)return n.status&&y.__staleWhileFetching!==void 0&&(n.status.returnedStale=!0),y.__staleWhileFetching;if(y.__returned===y)throw h},p=(h,g)=>{let v=this.#b?.(e,s,c);v&&v instanceof Promise&&v.then(S=>h(S===void 0?void 0:S),g),o.signal.addEventListener("abort",()=>{(!n.ignoreFetchAbort||n.allowStaleOnFetchAbort)&&(h(void 0),n.allowStaleOnFetchAbort&&(h=S=>u(S,!0)))})};n.status&&(n.status.fetchDispatched=!0);let f=new Promise(p).then(u,l),m=Object.assign(f,{__abortController:o,__staleWhileFetching:s,__returned:void 0});return r===void 0?(this.set(e,m,{...c.options,status:void 0}),r=this.#d.get(e)):this.#n[r]=m,m}#u(e){if(!this.#T)return!1;let r=e;return!!r&&r instanceof Promise&&r.hasOwnProperty("__staleWhileFetching")&&r.__abortController instanceof My}async fetch(e,r={}){let{allowStale:n=this.allowStale,updateAgeOnGet:i=this.updateAgeOnGet,noDeleteOnStaleGet:s=this.noDeleteOnStaleGet,ttl:o=this.ttl,noDisposeOnSet:a=this.noDisposeOnSet,size:c=0,sizeCalculation:u=this.sizeCalculation,noUpdateTTL:l=this.noUpdateTTL,noDeleteOnFetchRejection:d=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:p=this.allowStaleOnFetchRejection,ignoreFetchAbort:f=this.ignoreFetchAbort,allowStaleOnFetchAbort:m=this.allowStaleOnFetchAbort,context:h,forceRefresh:g=!1,status:v,signal:S}=r;if(!this.#T)return v&&(v.fetch="get"),this.get(e,{allowStale:n,updateAgeOnGet:i,noDeleteOnStaleGet:s,status:v});let _={allowStale:n,updateAgeOnGet:i,noDeleteOnStaleGet:s,ttl:o,noDisposeOnSet:a,size:c,sizeCalculation:u,noUpdateTTL:l,noDeleteOnFetchRejection:d,allowStaleOnFetchRejection:p,allowStaleOnFetchAbort:m,ignoreFetchAbort:f,status:v,signal:S},y=this.#d.get(e);if(y===void 0){v&&(v.fetch="miss");let x=this.#q(e,y,_,h);return x.__returned=x}else{let x=this.#n[y];if(this.#u(x)){let A=n&&x.__staleWhileFetching!==void 0;return v&&(v.fetch="inflight",A&&(v.returnedStale=!0)),A?x.__staleWhileFetching:x.__returned=x}let w=this.#w(y);if(!g&&!w)return v&&(v.fetch="hit"),this.#D(y),i&&this.#$(y),v&&this.#A(v,y),x;let E=this.#q(e,y,_,h),I=E.__staleWhileFetching!==void 0&&n;return v&&(v.fetch=w?"stale":"refresh",I&&w&&(v.returnedStale=!0)),I?E.__staleWhileFetching:E.__returned=E}}async forceFetch(e,r={}){let n=await this.fetch(e,r);if(n===void 0)throw new Error("fetch() returned undefined");return n}memo(e,r={}){let n=this.#v;if(!n)throw new Error("no memoMethod provided to constructor");let{context:i,forceRefresh:s,...o}=r,a=this.get(e,o);if(!s&&a!==void 0)return a;let c=n(e,a,{options:o,context:i});return this.set(e,c,o),c}get(e,r={}){let{allowStale:n=this.allowStale,updateAgeOnGet:i=this.updateAgeOnGet,noDeleteOnStaleGet:s=this.noDeleteOnStaleGet,status:o}=r,a=this.#d.get(e);if(a!==void 0){let c=this.#n[a],u=this.#u(c);return o&&this.#A(o,a),this.#w(a)?(o&&(o.get="stale"),u?(o&&n&&c.__staleWhileFetching!==void 0&&(o.returnedStale=!0),n?c.__staleWhileFetching:void 0):(s||this.#R(e,"expire"),o&&n&&(o.returnedStale=!0),n?c:void 0)):(o&&(o.get="hit"),u?c.__staleWhileFetching:(this.#D(a),i&&this.#$(a),c))}else o&&(o.get="miss")}#H(e,r){this.#S[r]=e,this.#f[e]=r}#D(e){e!==this.#m&&(e===this.#_?this.#_=this.#f[e]:this.#H(this.#S[e],this.#f[e]),this.#H(this.#m,e),this.#m=e)}delete(e){return this.#R(e,"delete")}#R(e,r){let n=!1;if(this.#a!==0){let i=this.#d.get(e);if(i!==void 0)if(this.#y?.[i]&&(clearTimeout(this.#y?.[i]),this.#y[i]=void 0),n=!0,this.#a===1)this.#B(r);else{this.#j(i);let s=this.#n[i];if(this.#u(s)?s.__abortController.abort(new Error("deleted")):(this.#x||this.#t)&&(this.#x&&this.#s?.(s,e,r),this.#t&&this.#h?.push([s,e,r])),this.#d.delete(e),this.#c[i]=void 0,this.#n[i]=void 0,i===this.#m)this.#m=this.#S[i];else if(i===this.#_)this.#_=this.#f[i];else{let o=this.#S[i];this.#f[o]=this.#f[i];let a=this.#f[i];this.#S[a]=this.#S[i]}this.#a--,this.#I.push(i)}}if(this.#t&&this.#h?.length){let i=this.#h,s;for(;s=i?.shift();)this.#o?.(...s)}return n}clear(){return this.#B("delete")}#B(e){for(let r of this.#C({allowStale:!0})){let n=this.#n[r];if(this.#u(n))n.__abortController.abort(new Error("deleted"));else{let i=this.#c[r];this.#x&&this.#s?.(n,i,e),this.#t&&this.#h?.push([n,i,e])}}if(this.#d.clear(),this.#n.fill(void 0),this.#c.fill(void 0),this.#g&&this.#k){this.#g.fill(0),this.#k.fill(0);for(let r of this.#y??[])r!==void 0&&clearTimeout(r);this.#y?.fill(void 0)}if(this.#E&&this.#E.fill(0),this.#_=0,this.#m=0,this.#I.length=0,this.#p=0,this.#a=0,this.#t&&this.#h){let r=this.#h,n;for(;n=r?.shift();)this.#o?.(...n)}}};var Bu=require("node:path"),r5=require("node:url"),rs=require("fs"),qbe=Me(require("node:fs"),1),$o=require("node:fs/promises");var qy=require("node:events"),RI=Me(require("node:stream"),1),X8=require("node:string_decoder"),W8=typeof process=="object"&&process?process:{stdout:null,stderr:null},Abe=t=>!!t&&typeof t=="object"&&(t instanceof To||t instanceof RI.default||Nbe(t)||Mbe(t)),Nbe=t=>!!t&&typeof t=="object"&&t instanceof qy.EventEmitter&&typeof t.pipe=="function"&&t.pipe!==RI.default.Writable.prototype.pipe,Mbe=t=>!!t&&typeof t=="object"&&t instanceof qy.EventEmitter&&typeof t.write=="function"&&typeof t.end=="function",Ls=Symbol("EOF"),Us=Symbol("maybeEmitEnd"),ko=Symbol("emittedEnd"),Dy=Symbol("emittingEnd"),_f=Symbol("emittedError"),jy=Symbol("closed"),V8=Symbol("read"),zy=Symbol("flush"),K8=Symbol("flushChunk"),ki=Symbol("encoding"),Hu=Symbol("decoder"),fr=Symbol("flowing"),bf=Symbol("paused"),Zu=Symbol("resume"),mr=Symbol("buffer"),rn=Symbol("pipes"),hr=Symbol("bufferLength"),wI=Symbol("bufferPush"),Ly=Symbol("bufferShift"),Fr=Symbol("objectMode"),Xt=Symbol("destroyed"),EI=Symbol("error"),kI=Symbol("emitData"),J8=Symbol("emitEnd"),TI=Symbol("emitEnd2"),es=Symbol("async"),$I=Symbol("abort"),Uy=Symbol("aborted"),Sf=Symbol("signal"),Ca=Symbol("dataListeners"),An=Symbol("discarded"),xf=t=>Promise.resolve().then(t),Dbe=t=>t(),jbe=t=>t==="end"||t==="finish"||t==="prefinish",zbe=t=>t instanceof ArrayBuffer||!!t&&typeof t=="object"&&t.constructor&&t.constructor.name==="ArrayBuffer"&&t.byteLength>=0,Lbe=t=>!Buffer.isBuffer(t)&&ArrayBuffer.isView(t),Fy=class{src;dest;opts;ondrain;constructor(e,r,n){this.src=e,this.dest=r,this.opts=n,this.ondrain=()=>e[Zu](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(e){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},II=class extends Fy{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe()}constructor(e,r,n){super(e,r,n),this.proxyErrors=i=>r.emit("error",i),e.on("error",this.proxyErrors)}},Ube=t=>!!t.objectMode,Fbe=t=>!t.objectMode&&!!t.encoding&&t.encoding!=="buffer",To=class extends qy.EventEmitter{[fr]=!1;[bf]=!1;[rn]=[];[mr]=[];[Fr];[ki];[es];[Hu];[Ls]=!1;[ko]=!1;[Dy]=!1;[jy]=!1;[_f]=null;[hr]=0;[Xt]=!1;[Sf];[Uy]=!1;[Ca]=0;[An]=!1;writable=!0;readable=!0;constructor(...e){let r=e[0]||{};if(super(),r.objectMode&&typeof r.encoding=="string")throw new TypeError("Encoding and objectMode may not be used together");Ube(r)?(this[Fr]=!0,this[ki]=null):Fbe(r)?(this[ki]=r.encoding,this[Fr]=!1):(this[Fr]=!1,this[ki]=null),this[es]=!!r.async,this[Hu]=this[ki]?new X8.StringDecoder(this[ki]):null,r&&r.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[mr]}),r&&r.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[rn]});let{signal:n}=r;n&&(this[Sf]=n,n.aborted?this[$I]():n.addEventListener("abort",()=>this[$I]()))}get bufferLength(){return this[hr]}get encoding(){return this[ki]}set encoding(e){throw new Error("Encoding must be set at instantiation time")}setEncoding(e){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[Fr]}set objectMode(e){throw new Error("objectMode must be set at instantiation time")}get async(){return this[es]}set async(e){this[es]=this[es]||!!e}[$I](){this[Uy]=!0,this.emit("abort",this[Sf]?.reason),this.destroy(this[Sf]?.reason)}get aborted(){return this[Uy]}set aborted(e){}write(e,r,n){if(this[Uy])return!1;if(this[Ls])throw new Error("write after end");if(this[Xt])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;typeof r=="function"&&(n=r,r="utf8"),r||(r="utf8");let i=this[es]?xf:Dbe;if(!this[Fr]&&!Buffer.isBuffer(e)){if(Lbe(e))e=Buffer.from(e.buffer,e.byteOffset,e.byteLength);else if(zbe(e))e=Buffer.from(e);else if(typeof e!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[Fr]?(this[fr]&&this[hr]!==0&&this[zy](!0),this[fr]?this.emit("data",e):this[wI](e),this[hr]!==0&&this.emit("readable"),n&&i(n),this[fr]):e.length?(typeof e=="string"&&!(r===this[ki]&&!this[Hu]?.lastNeed)&&(e=Buffer.from(e,r)),Buffer.isBuffer(e)&&this[ki]&&(e=this[Hu].write(e)),this[fr]&&this[hr]!==0&&this[zy](!0),this[fr]?this.emit("data",e):this[wI](e),this[hr]!==0&&this.emit("readable"),n&&i(n),this[fr]):(this[hr]!==0&&this.emit("readable"),n&&i(n),this[fr])}read(e){if(this[Xt])return null;if(this[An]=!1,this[hr]===0||e===0||e&&e>this[hr])return this[Us](),null;this[Fr]&&(e=null),this[mr].length>1&&!this[Fr]&&(this[mr]=[this[ki]?this[mr].join(""):Buffer.concat(this[mr],this[hr])]);let r=this[V8](e||null,this[mr][0]);return this[Us](),r}[V8](e,r){if(this[Fr])this[Ly]();else{let n=r;e===n.length||e===null?this[Ly]():typeof n=="string"?(this[mr][0]=n.slice(e),r=n.slice(0,e),this[hr]-=e):(this[mr][0]=n.subarray(e),r=n.subarray(0,e),this[hr]-=e)}return this.emit("data",r),!this[mr].length&&!this[Ls]&&this.emit("drain"),r}end(e,r,n){return typeof e=="function"&&(n=e,e=void 0),typeof r=="function"&&(n=r,r="utf8"),e!==void 0&&this.write(e,r),n&&this.once("end",n),this[Ls]=!0,this.writable=!1,(this[fr]||!this[bf])&&this[Us](),this}[Zu](){this[Xt]||(!this[Ca]&&!this[rn].length&&(this[An]=!0),this[bf]=!1,this[fr]=!0,this.emit("resume"),this[mr].length?this[zy]():this[Ls]?this[Us]():this.emit("drain"))}resume(){return this[Zu]()}pause(){this[fr]=!1,this[bf]=!0,this[An]=!1}get destroyed(){return this[Xt]}get flowing(){return this[fr]}get paused(){return this[bf]}[wI](e){this[Fr]?this[hr]+=1:this[hr]+=e.length,this[mr].push(e)}[Ly](){return this[Fr]?this[hr]-=1:this[hr]-=this[mr][0].length,this[mr].shift()}[zy](e=!1){do;while(this[K8](this[Ly]())&&this[mr].length);!e&&!this[mr].length&&!this[Ls]&&this.emit("drain")}[K8](e){return this.emit("data",e),this[fr]}pipe(e,r){if(this[Xt])return e;this[An]=!1;let n=this[ko];return r=r||{},e===W8.stdout||e===W8.stderr?r.end=!1:r.end=r.end!==!1,r.proxyErrors=!!r.proxyErrors,n?r.end&&e.end():(this[rn].push(r.proxyErrors?new II(this,e,r):new Fy(this,e,r)),this[es]?xf(()=>this[Zu]()):this[Zu]()),e}unpipe(e){let r=this[rn].find(n=>n.dest===e);r&&(this[rn].length===1?(this[fr]&&this[Ca]===0&&(this[fr]=!1),this[rn]=[]):this[rn].splice(this[rn].indexOf(r),1),r.unpipe())}addListener(e,r){return this.on(e,r)}on(e,r){let n=super.on(e,r);if(e==="data")this[An]=!1,this[Ca]++,!this[rn].length&&!this[fr]&&this[Zu]();else if(e==="readable"&&this[hr]!==0)super.emit("readable");else if(jbe(e)&&this[ko])super.emit(e),this.removeAllListeners(e);else if(e==="error"&&this[_f]){let i=r;this[es]?xf(()=>i.call(this,this[_f])):i.call(this,this[_f])}return n}removeListener(e,r){return this.off(e,r)}off(e,r){let n=super.off(e,r);return e==="data"&&(this[Ca]=this.listeners("data").length,this[Ca]===0&&!this[An]&&!this[rn].length&&(this[fr]=!1)),n}removeAllListeners(e){let r=super.removeAllListeners(e);return(e==="data"||e===void 0)&&(this[Ca]=0,!this[An]&&!this[rn].length&&(this[fr]=!1)),r}get emittedEnd(){return this[ko]}[Us](){!this[Dy]&&!this[ko]&&!this[Xt]&&this[mr].length===0&&this[Ls]&&(this[Dy]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[jy]&&this.emit("close"),this[Dy]=!1)}emit(e,...r){let n=r[0];if(e!=="error"&&e!=="close"&&e!==Xt&&this[Xt])return!1;if(e==="data")return!this[Fr]&&!n?!1:this[es]?(xf(()=>this[kI](n)),!0):this[kI](n);if(e==="end")return this[J8]();if(e==="close"){if(this[jy]=!0,!this[ko]&&!this[Xt])return!1;let s=super.emit("close");return this.removeAllListeners("close"),s}else if(e==="error"){this[_f]=n,super.emit(EI,n);let s=!this[Sf]||this.listeners("error").length?super.emit("error",n):!1;return this[Us](),s}else if(e==="resume"){let s=super.emit("resume");return this[Us](),s}else if(e==="finish"||e==="prefinish"){let s=super.emit(e);return this.removeAllListeners(e),s}let i=super.emit(e,...r);return this[Us](),i}[kI](e){for(let n of this[rn])n.dest.write(e)===!1&&this.pause();let r=this[An]?!1:super.emit("data",e);return this[Us](),r}[J8](){return this[ko]?!1:(this[ko]=!0,this.readable=!1,this[es]?(xf(()=>this[TI]()),!0):this[TI]())}[TI](){if(this[Hu]){let r=this[Hu].end();if(r){for(let n of this[rn])n.dest.write(r);this[An]||super.emit("data",r)}}for(let r of this[rn])r.end();let e=super.emit("end");return this.removeAllListeners("end"),e}async collect(){let e=Object.assign([],{dataLength:0});this[Fr]||(e.dataLength=0);let r=this.promise();return this.on("data",n=>{e.push(n),this[Fr]||(e.dataLength+=n.length)}),await r,e}async concat(){if(this[Fr])throw new Error("cannot concat in objectMode");let e=await this.collect();return this[ki]?e.join(""):Buffer.concat(e,e.dataLength)}async promise(){return new Promise((e,r)=>{this.on(Xt,()=>r(new Error("stream destroyed"))),this.on("error",n=>r(n)),this.on("end",()=>e())})}[Symbol.asyncIterator](){this[An]=!1;let e=!1,r=async()=>(this.pause(),e=!0,{value:void 0,done:!0});return{next:()=>{if(e)return r();let i=this.read();if(i!==null)return Promise.resolve({done:!1,value:i});if(this[Ls])return r();let s,o,a=d=>{this.off("data",c),this.off("end",u),this.off(Xt,l),r(),o(d)},c=d=>{this.off("error",a),this.off("end",u),this.off(Xt,l),this.pause(),s({value:d,done:!!this[Ls]})},u=()=>{this.off("error",a),this.off("data",c),this.off(Xt,l),r(),s({done:!0,value:void 0})},l=()=>a(new Error("stream destroyed"));return new Promise((d,p)=>{o=p,s=d,this.once(Xt,l),this.once("error",a),this.once("end",u),this.once("data",c)})},throw:r,return:r,[Symbol.asyncIterator](){return this}}}[Symbol.iterator](){this[An]=!1;let e=!1,r=()=>(this.pause(),this.off(EI,r),this.off(Xt,r),this.off("end",r),e=!0,{done:!0,value:void 0}),n=()=>{if(e)return r();let i=this.read();return i===null?r():{done:!1,value:i}};return this.once("end",r),this.once(EI,r),this.once(Xt,r),{next:n,throw:r,return:r,[Symbol.iterator](){return this}}}destroy(e){if(this[Xt])return e?this.emit("error",e):this.emit(Xt),this;this[Xt]=!0,this[An]=!0,this[mr].length=0,this[hr]=0;let r=this;return typeof r.close=="function"&&!this[jy]&&r.close(),e?this.emit("error",e):this.emit(Xt),this}static get isStream(){return Abe}};var Hbe=rs.realpathSync.native,Ef={lstatSync:rs.lstatSync,readdir:rs.readdir,readdirSync:rs.readdirSync,readlinkSync:rs.readlinkSync,realpathSync:Hbe,promises:{lstat:$o.lstat,readdir:$o.readdir,readlink:$o.readlink,realpath:$o.realpath}},n5=t=>!t||t===Ef||t===qbe?Ef:{...Ef,...t,promises:{...Ef.promises,...t.promises||{}}},i5=/^\\\\\?\\([a-z]:)\\?$/i,Zbe=t=>t.replace(/\//g,"\\").replace(i5,"$1\\"),Bbe=/[\\\/]/,ti=0,s5=1,o5=2,ts=4,a5=6,c5=8,Pa=10,u5=12,ei=15,wf=~ei,OI=16,Y8=32,kf=64,Ti=128,Hy=256,By=512,Q8=kf|Ti|By,Gbe=1023,CI=t=>t.isFile()?c5:t.isDirectory()?ts:t.isSymbolicLink()?Pa:t.isCharacterDevice()?o5:t.isBlockDevice()?a5:t.isSocket()?u5:t.isFIFO()?s5:ti,e5=new Oa({max:2**12}),Tf=t=>{let e=e5.get(t);if(e)return e;let r=t.normalize("NFKD");return e5.set(t,r),r},t5=new Oa({max:2**12}),Zy=t=>{let e=t5.get(t);if(e)return e;let r=Tf(t.toLowerCase());return t5.set(t,r),r},Gy=class extends Oa{constructor(){super({max:256})}},PI=class extends Oa{constructor(e=16*1024){super({maxSize:e,sizeCalculation:r=>r.length+1})}},l5=Symbol("PathScurry setAsCwd"),qr=class{name;root;roots;parent;nocase;isCWD=!1;#e;#r;get dev(){return this.#r}#s;get mode(){return this.#s}#i;get nlink(){return this.#i}#o;get uid(){return this.#o}#b;get gid(){return this.#b}#v;get rdev(){return this.#v}#l;get blksize(){return this.#l}#a;get ino(){return this.#a}#p;get size(){return this.#p}#d;get blocks(){return this.#d}#c;get atimeMs(){return this.#c}#n;get mtimeMs(){return this.#n}#f;get ctimeMs(){return this.#f}#S;get birthtimeMs(){return this.#S}#_;get atime(){return this.#_}#m;get mtime(){return this.#m}#I;get ctime(){return this.#I}#h;get birthtime(){return this.#h}#E;#k;#g;#y;#x;#T;#t;#N;#P;#$;get parentPath(){return(this.parent||this).fullpath()}get path(){return this.parentPath}constructor(e,r=ti,n,i,s,o,a){this.name=e,this.#E=s?Zy(e):Tf(e),this.#t=r&Gbe,this.nocase=s,this.roots=i,this.root=n||this,this.#N=o,this.#g=a.fullpath,this.#x=a.relative,this.#T=a.relativePosix,this.parent=a.parent,this.parent?this.#e=this.parent.#e:this.#e=n5(a.fs)}depth(){return this.#k!==void 0?this.#k:this.parent?this.#k=this.parent.depth()+1:this.#k=0}childrenCache(){return this.#N}resolve(e){if(!e)return this;let r=this.getRootString(e),i=e.substring(r.length).split(this.splitSep);return r?this.getRoot(r).#A(i):this.#A(i)}#A(e){let r=this;for(let n of e)r=r.child(n);return r}children(){let e=this.#N.get(this);if(e)return e;let r=Object.assign([],{provisional:0});return this.#N.set(this,r),this.#t&=~OI,r}child(e,r){if(e===""||e===".")return this;if(e==="..")return this.parent||this;let n=this.children(),i=this.nocase?Zy(e):Tf(e);for(let c of n)if(c.#E===i)return c;let s=this.parent?this.sep:"",o=this.#g?this.#g+s+e:void 0,a=this.newChild(e,ti,{...r,parent:this,fullpath:o});return this.canReaddir()||(a.#t|=Ti),n.push(a),a}relative(){if(this.isCWD)return"";if(this.#x!==void 0)return this.#x;let e=this.name,r=this.parent;if(!r)return this.#x=this.name;let n=r.relative();return n+(!n||!r.parent?"":this.sep)+e}relativePosix(){if(this.sep==="/")return this.relative();if(this.isCWD)return"";if(this.#T!==void 0)return this.#T;let e=this.name,r=this.parent;if(!r)return this.#T=this.fullpathPosix();let n=r.relativePosix();return n+(!n||!r.parent?"":"/")+e}fullpath(){if(this.#g!==void 0)return this.#g;let e=this.name,r=this.parent;if(!r)return this.#g=this.name;let i=r.fullpath()+(r.parent?this.sep:"")+e;return this.#g=i}fullpathPosix(){if(this.#y!==void 0)return this.#y;if(this.sep==="/")return this.#y=this.fullpath();if(!this.parent){let i=this.fullpath().replace(/\\/g,"/");return/^[a-z]:\//i.test(i)?this.#y=`//?/${i}`:this.#y=i}let e=this.parent,r=e.fullpathPosix(),n=r+(!r||!e.parent?"":"/")+this.name;return this.#y=n}isUnknown(){return(this.#t&ei)===ti}isType(e){return this[`is${e}`]()}getType(){return this.isUnknown()?"Unknown":this.isDirectory()?"Directory":this.isFile()?"File":this.isSymbolicLink()?"SymbolicLink":this.isFIFO()?"FIFO":this.isCharacterDevice()?"CharacterDevice":this.isBlockDevice()?"BlockDevice":this.isSocket()?"Socket":"Unknown"}isFile(){return(this.#t&ei)===c5}isDirectory(){return(this.#t&ei)===ts}isCharacterDevice(){return(this.#t&ei)===o5}isBlockDevice(){return(this.#t&ei)===a5}isFIFO(){return(this.#t&ei)===s5}isSocket(){return(this.#t&ei)===u5}isSymbolicLink(){return(this.#t&Pa)===Pa}lstatCached(){return this.#t&Y8?this:void 0}readlinkCached(){return this.#P}realpathCached(){return this.#$}readdirCached(){let e=this.children();return e.slice(0,e.provisional)}canReadlink(){if(this.#P)return!0;if(!this.parent)return!1;let e=this.#t&ei;return!(e!==ti&&e!==Pa||this.#t&Hy||this.#t&Ti)}calledReaddir(){return!!(this.#t&OI)}isENOENT(){return!!(this.#t&Ti)}isNamed(e){return this.nocase?this.#E===Zy(e):this.#E===Tf(e)}async readlink(){let e=this.#P;if(e)return e;if(this.canReadlink()&&this.parent)try{let r=await this.#e.promises.readlink(this.fullpath()),n=(await this.parent.realpath())?.resolve(r);if(n)return this.#P=n}catch(r){this.#C(r.code);return}}readlinkSync(){let e=this.#P;if(e)return e;if(this.canReadlink()&&this.parent)try{let r=this.#e.readlinkSync(this.fullpath()),n=this.parent.realpathSync()?.resolve(r);if(n)return this.#P=n}catch(r){this.#C(r.code);return}}#z(e){this.#t|=OI;for(let r=e.provisional;rn(null,e))}readdirCB(e,r=!1){if(!this.canReaddir()){r?e(null,[]):queueMicrotask(()=>e(null,[]));return}let n=this.children();if(this.calledReaddir()){let s=n.slice(0,n.provisional);r?e(null,s):queueMicrotask(()=>e(null,s));return}if(this.#D.push(e),this.#R)return;this.#R=!0;let i=this.fullpath();this.#e.readdir(i,{withFileTypes:!0},(s,o)=>{if(s)this.#L(s.code),n.provisional=0;else{for(let a of o)this.#U(a,n);this.#z(n)}this.#B(n.slice(0,n.provisional))})}#G;async readdir(){if(!this.canReaddir())return[];let e=this.children();if(this.calledReaddir())return e.slice(0,e.provisional);let r=this.fullpath();if(this.#G)await this.#G;else{let n=()=>{};this.#G=new Promise(i=>n=i);try{for(let i of await this.#e.promises.readdir(r,{withFileTypes:!0}))this.#U(i,e);this.#z(e)}catch(i){this.#L(i.code),e.provisional=0}this.#G=void 0,n()}return e.slice(0,e.provisional)}readdirSync(){if(!this.canReaddir())return[];let e=this.children();if(this.calledReaddir())return e.slice(0,e.provisional);let r=this.fullpath();try{for(let n of this.#e.readdirSync(r,{withFileTypes:!0}))this.#U(n,e);this.#z(e)}catch(n){this.#L(n.code),e.provisional=0}return e.slice(0,e.provisional)}canReaddir(){if(this.#t&Q8)return!1;let e=ei&this.#t;return e===ti||e===ts||e===Pa}shouldWalk(e,r){return(this.#t&ts)===ts&&!(this.#t&Q8)&&!e.has(this)&&(!r||r(this))}async realpath(){if(this.#$)return this.#$;if(!((By|Hy|Ti)&this.#t))try{let e=await this.#e.promises.realpath(this.fullpath());return this.#$=this.resolve(e)}catch{this.#j()}}realpathSync(){if(this.#$)return this.#$;if(!((By|Hy|Ti)&this.#t))try{let e=this.#e.realpathSync(this.fullpath());return this.#$=this.resolve(e)}catch{this.#j()}}[l5](e){if(e===this)return;e.isCWD=!1,this.isCWD=!0;let r=new Set([]),n=[],i=this;for(;i&&i.parent;)r.add(i),i.#x=n.join(this.sep),i.#T=n.join("/"),i=i.parent,n.push("..");for(i=e;i&&i.parent&&!r.has(i);)i.#x=void 0,i.#T=void 0,i=i.parent}},Wy=class t extends qr{sep="\\";splitSep=Bbe;constructor(e,r=ti,n,i,s,o,a){super(e,r,n,i,s,o,a)}newChild(e,r=ti,n={}){return new t(e,r,this.root,this.roots,this.nocase,this.childrenCache(),n)}getRootString(e){return Bu.win32.parse(e).root}getRoot(e){if(e=Zbe(e.toUpperCase()),e===this.root.name)return this.root;for(let[r,n]of Object.entries(this.roots))if(this.sameRoot(e,r))return this.roots[e]=n;return this.roots[e]=new Gu(e,this).root}sameRoot(e,r=this.root.name){return e=e.toUpperCase().replace(/\//g,"\\").replace(i5,"$1\\"),e===r}},Vy=class t extends qr{splitSep="/";sep="/";constructor(e,r=ti,n,i,s,o,a){super(e,r,n,i,s,o,a)}getRootString(e){return e.startsWith("/")?"/":""}getRoot(e){return this.root}newChild(e,r=ti,n={}){return new t(e,r,this.root,this.roots,this.nocase,this.childrenCache(),n)}},Ky=class{root;rootPath;roots;cwd;#e;#r;#s;nocase;#i;constructor(e=process.cwd(),r,n,{nocase:i,childrenCacheSize:s=16*1024,fs:o=Ef}={}){this.#i=n5(o),(e instanceof URL||e.startsWith("file://"))&&(e=(0,r5.fileURLToPath)(e));let a=r.resolve(e);this.roots=Object.create(null),this.rootPath=this.parseRootPath(a),this.#e=new Gy,this.#r=new Gy,this.#s=new PI(s);let c=a.substring(this.rootPath.length).split(n);if(c.length===1&&!c[0]&&c.pop(),i===void 0)throw new TypeError("must provide nocase setting to PathScurryBase ctor");this.nocase=i,this.root=this.newRoot(this.#i),this.roots[this.rootPath]=this.root;let u=this.root,l=c.length-1,d=r.sep,p=this.rootPath,f=!1;for(let m of c){let h=l--;u=u.child(m,{relative:new Array(h).fill("..").join(d),relativePosix:new Array(h).fill("..").join("/"),fullpath:p+=(f?"":d)+m}),f=!0}this.cwd=u}depth(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.depth()}childrenCache(){return this.#s}resolve(...e){let r="";for(let s=e.length-1;s>=0;s--){let o=e[s];if(!(!o||o===".")&&(r=r?`${o}/${r}`:o,this.isAbsolute(o)))break}let n=this.#e.get(r);if(n!==void 0)return n;let i=this.cwd.resolve(r).fullpath();return this.#e.set(r,i),i}resolvePosix(...e){let r="";for(let s=e.length-1;s>=0;s--){let o=e[s];if(!(!o||o===".")&&(r=r?`${o}/${r}`:o,this.isAbsolute(o)))break}let n=this.#r.get(r);if(n!==void 0)return n;let i=this.cwd.resolve(r).fullpathPosix();return this.#r.set(r,i),i}relative(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.relative()}relativePosix(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.relativePosix()}basename(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.name}dirname(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),(e.parent||e).fullpath()}async readdir(e=this.cwd,r={withFileTypes:!0}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof qr||(r=e,e=this.cwd);let{withFileTypes:n}=r;if(e.canReaddir()){let i=await e.readdir();return n?i:i.map(s=>s.name)}else return[]}readdirSync(e=this.cwd,r={withFileTypes:!0}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof qr||(r=e,e=this.cwd);let{withFileTypes:n=!0}=r;return e.canReaddir()?n?e.readdirSync():e.readdirSync().map(i=>i.name):[]}async lstat(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.lstat()}lstatSync(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.lstatSync()}async readlink(e=this.cwd,{withFileTypes:r}={withFileTypes:!1}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof qr||(r=e.withFileTypes,e=this.cwd);let n=await e.readlink();return r?n:n?.fullpath()}readlinkSync(e=this.cwd,{withFileTypes:r}={withFileTypes:!1}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof qr||(r=e.withFileTypes,e=this.cwd);let n=e.readlinkSync();return r?n:n?.fullpath()}async realpath(e=this.cwd,{withFileTypes:r}={withFileTypes:!1}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof qr||(r=e.withFileTypes,e=this.cwd);let n=await e.realpath();return r?n:n?.fullpath()}realpathSync(e=this.cwd,{withFileTypes:r}={withFileTypes:!1}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof qr||(r=e.withFileTypes,e=this.cwd);let n=e.realpathSync();return r?n:n?.fullpath()}async walk(e=this.cwd,r={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof qr||(r=e,e=this.cwd);let{withFileTypes:n=!0,follow:i=!1,filter:s,walkFilter:o}=r,a=[];(!s||s(e))&&a.push(n?e:e.fullpath());let c=new Set,u=(d,p)=>{c.add(d),d.readdirCB((f,m)=>{if(f)return p(f);let h=m.length;if(!h)return p();let g=()=>{--h===0&&p()};for(let v of m)(!s||s(v))&&a.push(n?v:v.fullpath()),i&&v.isSymbolicLink()?v.realpath().then(S=>S?.isUnknown()?S.lstat():S).then(S=>S?.shouldWalk(c,o)?u(S,g):g()):v.shouldWalk(c,o)?u(v,g):g()},!0)},l=e;return new Promise((d,p)=>{u(l,f=>{if(f)return p(f);d(a)})})}walkSync(e=this.cwd,r={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof qr||(r=e,e=this.cwd);let{withFileTypes:n=!0,follow:i=!1,filter:s,walkFilter:o}=r,a=[];(!s||s(e))&&a.push(n?e:e.fullpath());let c=new Set([e]);for(let u of c){let l=u.readdirSync();for(let d of l){(!s||s(d))&&a.push(n?d:d.fullpath());let p=d;if(d.isSymbolicLink()){if(!(i&&(p=d.realpathSync())))continue;p.isUnknown()&&p.lstatSync()}p.shouldWalk(c,o)&&c.add(p)}}return a}[Symbol.asyncIterator](){return this.iterate()}iterate(e=this.cwd,r={}){return typeof e=="string"?e=this.cwd.resolve(e):e instanceof qr||(r=e,e=this.cwd),this.stream(e,r)[Symbol.asyncIterator]()}[Symbol.iterator](){return this.iterateSync()}*iterateSync(e=this.cwd,r={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof qr||(r=e,e=this.cwd);let{withFileTypes:n=!0,follow:i=!1,filter:s,walkFilter:o}=r;(!s||s(e))&&(yield n?e:e.fullpath());let a=new Set([e]);for(let c of a){let u=c.readdirSync();for(let l of u){(!s||s(l))&&(yield n?l:l.fullpath());let d=l;if(l.isSymbolicLink()){if(!(i&&(d=l.realpathSync())))continue;d.isUnknown()&&d.lstatSync()}d.shouldWalk(a,o)&&a.add(d)}}}stream(e=this.cwd,r={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof qr||(r=e,e=this.cwd);let{withFileTypes:n=!0,follow:i=!1,filter:s,walkFilter:o}=r,a=new To({objectMode:!0});(!s||s(e))&&a.write(n?e:e.fullpath());let c=new Set,u=[e],l=0,d=()=>{let p=!1;for(;!p;){let f=u.shift();if(!f){l===0&&a.end();return}l++,c.add(f);let m=(g,v,S=!1)=>{if(g)return a.emit("error",g);if(i&&!S){let _=[];for(let y of v)y.isSymbolicLink()&&_.push(y.realpath().then(x=>x?.isUnknown()?x.lstat():x));if(_.length){Promise.all(_).then(()=>m(null,v,!0));return}}for(let _ of v)_&&(!s||s(_))&&(a.write(n?_:_.fullpath())||(p=!0));l--;for(let _ of v){let y=_.realpathCached()||_;y.shouldWalk(c,o)&&u.push(y)}p&&!a.flowing?a.once("drain",d):h||d()},h=!0;f.readdirCB(m,!0),h=!1}};return d(),a}streamSync(e=this.cwd,r={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof qr||(r=e,e=this.cwd);let{withFileTypes:n=!0,follow:i=!1,filter:s,walkFilter:o}=r,a=new To({objectMode:!0}),c=new Set;(!s||s(e))&&a.write(n?e:e.fullpath());let u=[e],l=0,d=()=>{let p=!1;for(;!p;){let f=u.shift();if(!f){l===0&&a.end();return}l++,c.add(f);let m=f.readdirSync();for(let h of m)(!s||s(h))&&(a.write(n?h:h.fullpath())||(p=!0));l--;for(let h of m){let g=h;if(h.isSymbolicLink()){if(!(i&&(g=h.realpathSync())))continue;g.isUnknown()&&g.lstatSync()}g.shouldWalk(c,o)&&u.push(g)}}p&&!a.flowing&&a.once("drain",d)};return d(),a}chdir(e=this.cwd){let r=this.cwd;this.cwd=typeof e=="string"?this.cwd.resolve(e):e,this.cwd[l5](r)}},Gu=class extends Ky{sep="\\";constructor(e=process.cwd(),r={}){let{nocase:n=!0}=r;super(e,Bu.win32,"\\",{...r,nocase:n}),this.nocase=n;for(let i=this.cwd;i;i=i.parent)i.nocase=this.nocase}parseRootPath(e){return Bu.win32.parse(e).root.toUpperCase()}newRoot(e){return new Wy(this.rootPath,ts,void 0,this.roots,this.nocase,this.childrenCache(),{fs:e})}isAbsolute(e){return e.startsWith("/")||e.startsWith("\\")||/^[a-z]:(\/|\\)/i.test(e)}},Wu=class extends Ky{sep="/";constructor(e=process.cwd(),r={}){let{nocase:n=!1}=r;super(e,Bu.posix,"/",{...r,nocase:n}),this.nocase=n}parseRootPath(e){return"/"}newRoot(e){return new Vy(this.rootPath,ts,void 0,this.roots,this.nocase,this.childrenCache(),{fs:e})}isAbsolute(e){return e.startsWith("/")}},$f=class extends Wu{constructor(e=process.cwd(),r={}){let{nocase:n=!0}=r;super(e,{...r,nocase:n})}},xUe=process.platform==="win32"?Wy:Vy,d5=process.platform==="win32"?Gu:process.platform==="darwin"?$f:Wu;var Wbe=t=>t.length>=1,Vbe=t=>t.length>=1,Vu=class t{#e;#r;#s;length;#i;#o;#b;#v;#l;#a;#p=!0;constructor(e,r,n,i){if(!Wbe(e))throw new TypeError("empty pattern list");if(!Vbe(r))throw new TypeError("empty glob list");if(r.length!==e.length)throw new TypeError("mismatched pattern list and glob list lengths");if(this.length=e.length,n<0||n>=this.length)throw new TypeError("index out of range");if(this.#e=e,this.#r=r,this.#s=n,this.#i=i,this.#s===0){if(this.isUNC()){let[s,o,a,c,...u]=this.#e,[l,d,p,f,...m]=this.#r;u[0]===""&&(u.shift(),m.shift());let h=[s,o,a,c,""].join("/"),g=[l,d,p,f,""].join("/");this.#e=[h,...u],this.#r=[g,...m],this.length=this.#e.length}else if(this.isDrive()||this.isAbsolute()){let[s,...o]=this.#e,[a,...c]=this.#r;o[0]===""&&(o.shift(),c.shift());let u=s+"/",l=a+"/";this.#e=[u,...o],this.#r=[l,...c],this.length=this.#e.length}}}pattern(){return this.#e[this.#s]}isString(){return typeof this.#e[this.#s]=="string"}isGlobstar(){return this.#e[this.#s]===Ir}isRegExp(){return this.#e[this.#s]instanceof RegExp}globString(){return this.#b=this.#b||(this.#s===0?this.isAbsolute()?this.#r[0]+this.#r.slice(1).join("/"):this.#r.join("/"):this.#r.slice(this.#s).join("/"))}hasMore(){return this.length>this.#s+1}rest(){return this.#o!==void 0?this.#o:this.hasMore()?(this.#o=new t(this.#e,this.#r,this.#s+1,this.#i),this.#o.#a=this.#a,this.#o.#l=this.#l,this.#o.#v=this.#v,this.#o):this.#o=null}isUNC(){let e=this.#e;return this.#l!==void 0?this.#l:this.#l=this.#i==="win32"&&this.#s===0&&e[0]===""&&e[1]===""&&typeof e[2]=="string"&&!!e[2]&&typeof e[3]=="string"&&!!e[3]}isDrive(){let e=this.#e;return this.#v!==void 0?this.#v:this.#v=this.#i==="win32"&&this.#s===0&&this.length>1&&typeof e[0]=="string"&&/^[a-z]:$/i.test(e[0])}isAbsolute(){let e=this.#e;return this.#a!==void 0?this.#a:this.#a=e[0]===""&&e.length>1||this.isDrive()||this.isUNC()}root(){let e=this.#e[0];return typeof e=="string"&&this.isAbsolute()&&this.#s===0?e:""}checkFollowGlobstar(){return!(this.#s===0||!this.isGlobstar()||!this.#p)}markFollowGlobstar(){return this.#s===0||!this.isGlobstar()||!this.#p?!1:(this.#p=!1,!0)}};var Kbe=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",Ku=class{relative;relativeChildren;absolute;absoluteChildren;platform;mmopts;constructor(e,{nobrace:r,nocase:n,noext:i,noglobstar:s,platform:o=Kbe}){this.relative=[],this.absolute=[],this.relativeChildren=[],this.absoluteChildren=[],this.platform=o,this.mmopts={dot:!0,nobrace:r,nocase:n,noext:i,noglobstar:s,optimizationLevel:2,platform:o,nocomment:!0,nonegate:!0};for(let a of e)this.add(a)}add(e){let r=new Pn(e,this.mmopts);for(let n=0;n[e,!!(r&2),!!(r&1)])}},MI=class{store=new Map;add(e,r){if(!e.canReaddir())return;let n=this.store.get(e);n?n.find(i=>i.globString()===r.globString())||n.push(r):this.store.set(e,[r])}get(e){let r=this.store.get(e);if(!r)throw new Error("attempting to walk unknown path");return r}entries(){return this.keys().map(e=>[e,this.store.get(e)])}keys(){return[...this.store.keys()].filter(e=>e.canReaddir())}},If=class t{hasWalkedCache;matches=new NI;subwalks=new MI;patterns;follow;dot;opts;constructor(e,r){this.opts=e,this.follow=!!e.follow,this.dot=!!e.dot,this.hasWalkedCache=r?r.copy():new AI}processPatterns(e,r){this.patterns=r;let n=r.map(i=>[e,i]);for(let[i,s]of n){this.hasWalkedCache.storeWalked(i,s);let o=s.root(),a=s.isAbsolute()&&this.opts.absolute!==!1;if(o){i=i.resolve(o==="/"&&this.opts.root!==void 0?this.opts.root:o);let d=s.rest();if(d)s=d;else{this.matches.add(i,!0,!1);continue}}if(i.isENOENT())continue;let c,u,l=!1;for(;typeof(c=s.pattern())=="string"&&(u=s.rest());)i=i.resolve(c),s=u,l=!0;if(c=s.pattern(),u=s.rest(),l){if(this.hasWalkedCache.hasWalked(i,s))continue;this.hasWalkedCache.storeWalked(i,s)}if(typeof c=="string"){let d=c===".."||c===""||c===".";this.matches.add(i.resolve(c),a,d);continue}else if(c===Ir){(!i.isSymbolicLink()||this.follow||s.checkFollowGlobstar())&&this.subwalks.add(i,s);let d=u?.pattern(),p=u?.rest();if(!u||(d===""||d===".")&&!p)this.matches.add(i,a,d===""||d===".");else if(d===".."){let f=i.parent||i;p?this.hasWalkedCache.hasWalked(f,p)||this.subwalks.add(f,p):this.matches.add(f,a,!0)}}else c instanceof RegExp&&this.subwalks.add(i,s)}return this}subwalkTargets(){return this.subwalks.keys()}child(){return new t(this.opts,this.hasWalkedCache)}filterEntries(e,r){let n=this.subwalks.get(e),i=this.child();for(let s of r)for(let o of n){let a=o.isAbsolute(),c=o.pattern(),u=o.rest();c===Ir?i.testGlobstar(s,o,u,a):c instanceof RegExp?i.testRegExp(s,c,u,a):i.testString(s,c,u,a)}return i}testGlobstar(e,r,n,i){if((this.dot||!e.name.startsWith("."))&&(r.hasMore()||this.matches.add(e,i,!1),e.canReaddir()&&(this.follow||!e.isSymbolicLink()?this.subwalks.add(e,r):e.isSymbolicLink()&&(n&&r.checkFollowGlobstar()?this.subwalks.add(e,n):r.markFollowGlobstar()&&this.subwalks.add(e,r)))),n){let s=n.pattern();if(typeof s=="string"&&s!==".."&&s!==""&&s!==".")this.testString(e,s,n.rest(),i);else if(s===".."){let o=e.parent||e;this.subwalks.add(o,n)}else s instanceof RegExp&&this.testRegExp(e,s,n.rest(),i)}}testRegExp(e,r,n,i){r.test(e.name)&&(n?this.subwalks.add(e,n):this.matches.add(e,i,!1))}testString(e,r,n,i){e.isNamed(r)&&(n?this.subwalks.add(e,n):this.matches.add(e,i,!1))}};var Jbe=(t,e)=>typeof t=="string"?new Ku([t],e):Array.isArray(t)?new Ku(t,e):t,Jy=class{path;patterns;opts;seen=new Set;paused=!1;aborted=!1;#e=[];#r;#s;signal;maxDepth;includeChildMatches;constructor(e,r,n){if(this.patterns=e,this.path=r,this.opts=n,this.#s=!n.posix&&n.platform==="win32"?"\\":"/",this.includeChildMatches=n.includeChildMatches!==!1,(n.ignore||!this.includeChildMatches)&&(this.#r=Jbe(n.ignore??[],n),!this.includeChildMatches&&typeof this.#r.add!="function")){let i="cannot ignore child matches, ignore lacks add() method.";throw new Error(i)}this.maxDepth=n.maxDepth||1/0,n.signal&&(this.signal=n.signal,this.signal.addEventListener("abort",()=>{this.#e.length=0}))}#i(e){return this.seen.has(e)||!!this.#r?.ignored?.(e)}#o(e){return!!this.#r?.childrenIgnored?.(e)}pause(){this.paused=!0}resume(){if(this.signal?.aborted)return;this.paused=!1;let e;for(;!this.paused&&(e=this.#e.shift());)e()}onResume(e){this.signal?.aborted||(this.paused?this.#e.push(e):e())}async matchCheck(e,r){if(r&&this.opts.nodir)return;let n;if(this.opts.realpath){if(n=e.realpathCached()||await e.realpath(),!n)return;e=n}let s=e.isUnknown()||this.opts.stat?await e.lstat():e;if(this.opts.follow&&this.opts.nodir&&s?.isSymbolicLink()){let o=await s.realpath();o&&(o.isUnknown()||this.opts.stat)&&await o.lstat()}return this.matchCheckTest(s,r)}matchCheckTest(e,r){return e&&(this.maxDepth===1/0||e.depth()<=this.maxDepth)&&(!r||e.canReaddir())&&(!this.opts.nodir||!e.isDirectory())&&(!this.opts.nodir||!this.opts.follow||!e.isSymbolicLink()||!e.realpathCached()?.isDirectory())&&!this.#i(e)?e:void 0}matchCheckSync(e,r){if(r&&this.opts.nodir)return;let n;if(this.opts.realpath){if(n=e.realpathCached()||e.realpathSync(),!n)return;e=n}let s=e.isUnknown()||this.opts.stat?e.lstatSync():e;if(this.opts.follow&&this.opts.nodir&&s?.isSymbolicLink()){let o=s.realpathSync();o&&(o?.isUnknown()||this.opts.stat)&&o.lstatSync()}return this.matchCheckTest(s,r)}matchFinish(e,r){if(this.#i(e))return;if(!this.includeChildMatches&&this.#r?.add){let s=`${e.relativePosix()}/**`;this.#r.add(s)}let n=this.opts.absolute===void 0?r:this.opts.absolute;this.seen.add(e);let i=this.opts.mark&&e.isDirectory()?this.#s:"";if(this.opts.withFileTypes)this.matchEmit(e);else if(n){let s=this.opts.posix?e.fullpathPosix():e.fullpath();this.matchEmit(s+i)}else{let s=this.opts.posix?e.relativePosix():e.relative(),o=this.opts.dotRelative&&!s.startsWith(".."+this.#s)?"."+this.#s:"";this.matchEmit(s?o+s+i:"."+i)}}async match(e,r,n){let i=await this.matchCheck(e,n);i&&this.matchFinish(i,r)}matchSync(e,r,n){let i=this.matchCheckSync(e,n);i&&this.matchFinish(i,r)}walkCB(e,r,n){this.signal?.aborted&&n(),this.walkCB2(e,r,new If(this.opts),n)}walkCB2(e,r,n,i){if(this.#o(e))return i();if(this.signal?.aborted&&i(),this.paused){this.onResume(()=>this.walkCB2(e,r,n,i));return}n.processPatterns(e,r);let s=1,o=()=>{--s===0&&i()};for(let[a,c,u]of n.matches.entries())this.#i(a)||(s++,this.match(a,c,u).then(()=>o()));for(let a of n.subwalkTargets()){if(this.maxDepth!==1/0&&a.depth()>=this.maxDepth)continue;s++;let c=a.readdirCached();a.calledReaddir()?this.walkCB3(a,c,n,o):a.readdirCB((u,l)=>this.walkCB3(a,l,n,o),!0)}o()}walkCB3(e,r,n,i){n=n.filterEntries(e,r);let s=1,o=()=>{--s===0&&i()};for(let[a,c,u]of n.matches.entries())this.#i(a)||(s++,this.match(a,c,u).then(()=>o()));for(let[a,c]of n.subwalks.entries())s++,this.walkCB2(a,c,n.child(),o);o()}walkCBSync(e,r,n){this.signal?.aborted&&n(),this.walkCB2Sync(e,r,new If(this.opts),n)}walkCB2Sync(e,r,n,i){if(this.#o(e))return i();if(this.signal?.aborted&&i(),this.paused){this.onResume(()=>this.walkCB2Sync(e,r,n,i));return}n.processPatterns(e,r);let s=1,o=()=>{--s===0&&i()};for(let[a,c,u]of n.matches.entries())this.#i(a)||this.matchSync(a,c,u);for(let a of n.subwalkTargets()){if(this.maxDepth!==1/0&&a.depth()>=this.maxDepth)continue;s++;let c=a.readdirSync();this.walkCB3Sync(a,c,n,o)}o()}walkCB3Sync(e,r,n,i){n=n.filterEntries(e,r);let s=1,o=()=>{--s===0&&i()};for(let[a,c,u]of n.matches.entries())this.#i(a)||this.matchSync(a,c,u);for(let[a,c]of n.subwalks.entries())s++,this.walkCB2Sync(a,c,n.child(),o);o()}},Rf=class extends Jy{matches=new Set;constructor(e,r,n){super(e,r,n)}matchEmit(e){this.matches.add(e)}async walk(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&await this.path.lstat(),await new Promise((e,r)=>{this.walkCB(this.path,this.patterns,()=>{this.signal?.aborted?r(this.signal.reason):e(this.matches)})}),this.matches}walkSync(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>{if(this.signal?.aborted)throw this.signal.reason}),this.matches}},Of=class extends Jy{results;constructor(e,r,n){super(e,r,n),this.results=new To({signal:this.signal,objectMode:!0}),this.results.on("drain",()=>this.resume()),this.results.on("resume",()=>this.resume())}matchEmit(e){this.results.write(e),this.results.flowing||this.pause()}stream(){let e=this.path;return e.isUnknown()?e.lstat().then(()=>{this.walkCB(e,this.patterns,()=>this.results.end())}):this.walkCB(e,this.patterns,()=>this.results.end()),this.results}streamSync(){return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>this.results.end()),this.results}};var Xbe=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",$i=class{absolute;cwd;root;dot;dotRelative;follow;ignore;magicalBraces;mark;matchBase;maxDepth;nobrace;nocase;nodir;noext;noglobstar;pattern;platform;realpath;scurry;stat;signal;windowsPathsNoEscape;withFileTypes;includeChildMatches;opts;patterns;constructor(e,r){if(!r)throw new TypeError("glob options required");if(this.withFileTypes=!!r.withFileTypes,this.signal=r.signal,this.follow=!!r.follow,this.dot=!!r.dot,this.dotRelative=!!r.dotRelative,this.nodir=!!r.nodir,this.mark=!!r.mark,r.cwd?(r.cwd instanceof URL||r.cwd.startsWith("file://"))&&(r.cwd=(0,p5.fileURLToPath)(r.cwd)):this.cwd="",this.cwd=r.cwd||"",this.root=r.root,this.magicalBraces=!!r.magicalBraces,this.nobrace=!!r.nobrace,this.noext=!!r.noext,this.realpath=!!r.realpath,this.absolute=r.absolute,this.includeChildMatches=r.includeChildMatches!==!1,this.noglobstar=!!r.noglobstar,this.matchBase=!!r.matchBase,this.maxDepth=typeof r.maxDepth=="number"?r.maxDepth:1/0,this.stat=!!r.stat,this.ignore=r.ignore,this.withFileTypes&&this.absolute!==void 0)throw new Error("cannot set absolute and withFileTypes:true");if(typeof e=="string"&&(e=[e]),this.windowsPathsNoEscape=!!r.windowsPathsNoEscape||r.allowWindowsEscape===!1,this.windowsPathsNoEscape&&(e=e.map(c=>c.replace(/\\/g,"/"))),this.matchBase){if(r.noglobstar)throw new TypeError("base matching requires globstar");e=e.map(c=>c.includes("/")?c:`./**/${c}`)}if(this.pattern=e,this.platform=r.platform||Xbe,this.opts={...r,platform:this.platform},r.scurry){if(this.scurry=r.scurry,r.nocase!==void 0&&r.nocase!==r.scurry.nocase)throw new Error("nocase option contradicts provided scurry option")}else{let c=r.platform==="win32"?Gu:r.platform==="darwin"?$f:r.platform?Wu:d5;this.scurry=new c(this.cwd,{nocase:r.nocase,fs:r.fs})}this.nocase=this.scurry.nocase;let n=this.platform==="darwin"||this.platform==="win32",i={...r,dot:this.dot,matchBase:this.matchBase,nobrace:this.nobrace,nocase:this.nocase,nocaseMagicOnly:n,nocomment:!0,noext:this.noext,nonegate:!0,optimizationLevel:2,platform:this.platform,windowsPathsNoEscape:this.windowsPathsNoEscape,debug:!!this.opts.debug},s=this.pattern.map(c=>new Pn(c,i)),[o,a]=s.reduce((c,u)=>(c[0].push(...u.set),c[1].push(...u.globParts),c),[[],[]]);this.patterns=o.map((c,u)=>{let l=a[u];if(!l)throw new Error("invalid pattern object");return new Vu(c,l,0,this.platform)})}async walk(){return[...await new Rf(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).walk()]}walkSync(){return[...new Rf(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).walkSync()]}stream(){return new Of(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).stream()}streamSync(){return new Of(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).streamSync()}iterateSync(){return this.streamSync()[Symbol.iterator]()}[Symbol.iterator](){return this.iterateSync()}iterate(){return this.stream()[Symbol.asyncIterator]()}[Symbol.asyncIterator](){return this.iterate()}};var DI=(t,e={})=>{Array.isArray(t)||(t=[t]);for(let r of t)if(new Pn(r,e).hasMagic())return!0;return!1};function Xy(t,e={}){return new $i(t,e).streamSync()}function h5(t,e={}){return new $i(t,e).stream()}function Cf(t,e={}){return new $i(t,e).walkSync()}async function f5(t,e={}){return new $i(t,e).walk()}function Yy(t,e={}){return new $i(t,e).iterateSync()}function g5(t,e={}){return new $i(t,e).iterate()}var Ybe=Xy,Qbe=Object.assign(h5,{sync:Xy}),eSe=Yy,tSe=Object.assign(g5,{sync:Yy}),rSe=Object.assign(Cf,{stream:Xy,iterate:Yy}),m5=Object.assign(f5,{glob:f5,globSync:Cf,sync:rSe,globStream:h5,stream:Qbe,globStreamSync:Xy,streamSync:Ybe,globIterate:g5,iterate:tSe,globIterateSync:Yy,iterateSync:eSe,Glob:$i,hasMagic:DI,escape:Fu,unescape:Ei});m5.glob=m5;se();var Ju=require("fs"),Qy=require("os"),Pf=require("path"),e_=(0,Pf.join)((0,Qy.homedir)(),".claude-mem","transcript-watch.json"),nSe=(0,Pf.join)((0,Qy.homedir)(),".claude-mem","transcript-watch-state.json");function Aa(t){return t&&(t.startsWith("~")?(0,Pf.join)((0,Qy.homedir)(),t.slice(1)):t)}function v5(t=e_){let e=Aa(t);if(!(0,Ju.existsSync)(e))throw new Error(`Transcript watch config not found: ${e}`);let r=(0,Ju.readFileSync)(e,"utf-8"),n=JSON.parse(r);if(!n.version||!n.watches)throw new Error(`Invalid transcript watch config: ${e}`);return n.stateFile||(n.stateFile=nSe),n}var Fs=require("fs"),y5=require("path");se();function _5(t){try{if(!(0,Fs.existsSync)(t))return{offsets:{}};let e=(0,Fs.readFileSync)(t,"utf-8"),r=JSON.parse(e);return r.offsets?r:{offsets:{}}}catch(e){return b.warn("TRANSCRIPT","Failed to load watch state, starting fresh",{statePath:t,error:e instanceof Error?e.message:String(e)}),{offsets:{}}}}function b5(t,e){try{let r=(0,y5.dirname)(t);(0,Fs.existsSync)(r)||(0,Fs.mkdirSync)(r,{recursive:!0}),(0,Fs.writeFileSync)(t,JSON.stringify(e,null,2))}catch(r){b.warn("TRANSCRIPT","Failed to save watch state",{statePath:t,error:r instanceof Error?r.message:String(r)})}}r_();n_();i_();s_();Dr();se();lf();var Ii=require("fs"),o_=require("path");se();function x5(t,e){if(!t)return;let r=(0,o_.resolve)(t);if(r.includes("/.git/")||r.includes("\\.git\\")||r.endsWith("/.git")||r.endsWith("\\.git"))return;let n=(0,o_.dirname)(t);(0,Ii.existsSync)(n)||(0,Ii.mkdirSync)(n,{recursive:!0});let i="";(0,Ii.existsSync)(t)&&(i=(0,Ii.readFileSync)(t,"utf-8"));let s=`# Memory Context ${e}`,o=n$(i,s),a=`${t}.tmp`;try{(0,Ii.writeFileSync)(a,o),(0,Ii.renameSync)(a,t)}catch(c){b.error("AGENTS_MD","Failed to write AGENTS.md",{agentsPath:t},c)}}function sSe(t){let e=t.trim().replace(/^\$\.?/,"");if(!e)return[];let r=[],n=e.split(".");for(let i of n){let s=/([^[\]]+)|\[(\d+)\]/g,o;for(;(o=s.exec(i))!==null;)o[1]?r.push(o[1]):o[2]&&r.push(parseInt(o[2],10))}return r}function zI(t,e){if(!e)return;let r=sSe(e),n=t;for(let i of r){if(n==null)return;n=n[i]}return n}function w5(t){return t==null||t===""}function E5(t,e){if(t.startsWith("$watch.")){let r=t.slice(7);return e.watch[r]}if(t.startsWith("$schema.")){let r=t.slice(8);return e.schema[r]}if(t.startsWith("$session.")){let r=t.slice(9);return e.session?e.session[r]:void 0}if(t==="$cwd")return e.watch.workspace;if(t==="$project")return e.watch.project}function Xu(t,e,r){if(t!==void 0){if(typeof t=="string"){let n=E5(t,r);return n!==void 0?n:zI(e,t)}if(t.coalesce&&Array.isArray(t.coalesce))for(let n of t.coalesce){let i=Xu(n,e,r);if(!w5(i))return i}if(t.path){let n=E5(t.path,r);if(n!==void 0)return n;let i=zI(e,t.path);if(!w5(i))return i}if(t.value!==void 0)return t.value;if(t.default!==void 0)return t.default}}function k5(t,e,r){let n={};if(!t)return n;for(let[i,s]of Object.entries(t))n[i]=Xu(s,e,r);return n}function T5(t,e,r){if(!e)return!0;let n=e.path||r.eventTypePath||"type",i=n?zI(t,n):void 0;if(e.exists&&(i==null||i===""))return!1;if(e.equals!==void 0)return i===e.equals;if(e.in&&Array.isArray(e.in))return e.in.includes(i);if(e.contains!==void 0)return typeof i=="string"&&i.includes(e.contains);if(e.regex)try{return new RegExp(e.regex).test(String(i??""))}catch{return!1}return!0}var a_=class{sessions=new Map;async processEntry(e,r,n,i){for(let s of n.events)T5(e,s.match,n)&&await this.handleEvent(e,r,n,s,i??void 0)}getSessionKey(e,r){return`${e.name}:${r}`}getOrCreateSession(e,r){let n=this.getSessionKey(e,r),i=this.sessions.get(n);return i||(i={sessionId:r,pendingTools:new Map},this.sessions.set(n,i)),i}resolveSessionId(e,r,n,i,s){let o={watch:r,schema:n},a=i.fields?.sessionId??(n.sessionIdPath?{path:n.sessionIdPath}:void 0),c=Xu(a,e,o);return typeof c=="string"&&c.trim()?c:typeof c=="number"?String(c):s&&s.trim()?s:null}resolveCwd(e,r,n,i,s){let o={watch:r,schema:n,session:s},a=i.fields?.cwd??(n.cwdPath?{path:n.cwdPath}:void 0),c=Xu(a,e,o);return typeof c=="string"&&c.trim()?c:r.workspace?r.workspace:s.cwd}resolveProject(e,r,n,i,s){let o={watch:r,schema:n,session:s},a=i.fields?.project??(n.projectPath?{path:n.projectPath}:void 0),c=Xu(a,e,o);return typeof c=="string"&&c.trim()?c:r.project?r.project:s.cwd?Ta(s.cwd):s.project}async handleEvent(e,r,n,i,s){let o=this.resolveSessionId(e,r,n,i,s);if(!o){b.debug("TRANSCRIPT","Skipping event without sessionId",{event:i.name,watch:r.name});return}let a=this.getOrCreateSession(r,o),c=this.resolveCwd(e,r,n,i,a);c&&(a.cwd=c);let u=this.resolveProject(e,r,n,i,a);u&&(a.project=u);let l=k5(i.fields,e,{watch:r,schema:n,session:a});switch(i.action){case"session_context":this.applySessionContext(a,l);break;case"session_init":await this.handleSessionInit(a,l),r.context?.updateOn?.includes("session_start")&&await this.updateContext(a,r);break;case"user_message":typeof l.message=="string"&&(a.lastUserMessage=l.message),typeof l.prompt=="string"&&(a.lastUserMessage=l.prompt);break;case"assistant_message":typeof l.message=="string"&&(a.lastAssistantMessage=l.message);break;case"tool_use":await this.handleToolUse(a,l);break;case"tool_result":await this.handleToolResult(a,l);break;case"observation":await this.sendObservation(a,l);break;case"file_edit":await this.sendFileEdit(a,l);break;case"session_end":await this.handleSessionEnd(a,r);break;default:break}}applySessionContext(e,r){let n=typeof r.cwd=="string"?r.cwd:void 0,i=typeof r.project=="string"?r.project:void 0;n&&(e.cwd=n),i&&(e.project=i)}async handleSessionInit(e,r){let n=typeof r.prompt=="string"?r.prompt:"",i=e.cwd??process.cwd();n&&(e.lastUserMessage=n),await Af.execute({sessionId:e.sessionId,cwd:i,prompt:n,platform:"transcript"})}async handleToolUse(e,r){let n=typeof r.toolId=="string"?r.toolId:void 0,i=typeof r.toolName=="string"?r.toolName:void 0,s=this.maybeParseJson(r.toolInput),o=this.maybeParseJson(r.toolResponse),a={id:n,name:i,input:s,response:o};if(n&&e.pendingTools.set(n,{name:a.name,input:a.input}),i==="apply_patch"&&typeof s=="string"){let c=this.parseApplyPatchFiles(s);for(let u of c)await this.sendFileEdit(e,{filePath:u,edits:[{type:"apply_patch",patch:s}]})}o!==void 0&&i&&await this.sendObservation(e,{toolName:i,toolInput:s,toolResponse:o})}async handleToolResult(e,r){let n=typeof r.toolId=="string"?r.toolId:void 0,i=typeof r.toolName=="string"?r.toolName:void 0,s=this.maybeParseJson(r.toolResponse),o=this.maybeParseJson(r.toolInput),a=i;if(n&&e.pendingTools.has(n)){let c=e.pendingTools.get(n);o=c.input??o,a=a??c.name,e.pendingTools.delete(n)}a&&await this.sendObservation(e,{toolName:a,toolInput:o,toolResponse:s})}async sendObservation(e,r){let n=typeof r.toolName=="string"?r.toolName:void 0;n&&await Nf.execute({sessionId:e.sessionId,cwd:e.cwd??process.cwd(),toolName:n,toolInput:this.maybeParseJson(r.toolInput),toolResponse:this.maybeParseJson(r.toolResponse),platform:"transcript"})}async sendFileEdit(e,r){let n=typeof r.filePath=="string"?r.filePath:void 0;n&&await Mf.execute({sessionId:e.sessionId,cwd:e.cwd??process.cwd(),filePath:n,edits:Array.isArray(r.edits)?r.edits:void 0,platform:"transcript"})}maybeParseJson(e){if(typeof e!="string")return e;let r=e.trim();if(!r||!(r.startsWith("{")||r.startsWith("[")))return e;try{return JSON.parse(r)}catch{return e}}parseApplyPatchFiles(e){let r=[],n=e.split(` `);for(let i of n){let s=i.trim();if(s.startsWith("*** Update File: "))r.push(s.replace("*** Update File: ","").trim());else if(s.startsWith("*** Add File: "))r.push(s.replace("*** Add File: ","").trim());else if(s.startsWith("*** Delete File: "))r.push(s.replace("*** Delete File: ","").trim());else if(s.startsWith("*** Move to: "))r.push(s.replace("*** Move to: ","").trim());else if(s.startsWith("+++ ")){let o=s.replace("+++ ","").replace(/^b\//,"").trim();o&&o!=="/dev/null"&&r.push(o)}}return Array.from(new Set(r))}async handleSessionEnd(e,r){await this.queueSummary(e),await Df.execute({sessionId:e.sessionId,cwd:e.cwd??process.cwd(),platform:"transcript"}),await this.updateContext(e,r),e.pendingTools.clear();let n=this.getSessionKey(r,e.sessionId);this.sessions.delete(n)}async queueSummary(e){if(!await kr())return;let n=e.lastAssistantMessage??"";try{await ft("/api/sessions/summarize",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({contentSessionId:e.sessionId,last_assistant_message:n})})}catch(i){b.warn("TRANSCRIPT","Summary request failed",{error:i instanceof Error?i.message:String(i)})}}async updateContext(e,r){if(!r.context||r.context.mode!=="agents"||!await kr())return;let i=e.cwd??r.workspace;if(!i)return;let o=xy(i).allProjects.join(",");try{let a=await ft(`/api/context/inject?projects=${encodeURIComponent(o)}`);if(!a.ok)return;let c=(await a.text()).trim();if(!c)return;let u=Aa(r.context.path??`${i}/AGENTS.md`);x5(u,c),b.debug("TRANSCRIPT","Updated AGENTS.md context",{agentsPath:u,watch:r.name})}catch(a){b.warn("TRANSCRIPT","Failed to update AGENTS.md context",{error:a instanceof Error?a.message:String(a)})}}};var LI=class{constructor(e,r,n,i){this.filePath=e;this.onLine=n;this.onOffset=i;this.tailState={offset:r,partial:""}}watcher=null;tailState;start(){this.readNewData().catch(()=>{}),this.watcher=(0,Ri.watch)(this.filePath,{persistent:!0},()=>{this.readNewData().catch(()=>{})})}close(){this.watcher?.close(),this.watcher=null}async readNewData(){if(!(0,Ri.existsSync)(this.filePath))return;let e=0;try{e=(0,Ri.statSync)(this.filePath).size}catch{return}if(e{let a=this.resolveWatchFiles(n);for(let c of a)this.tailers.has(c)||await this.addTailer(c,e,r)},s);this.rescanTimers.push(o)}resolveSchema(e){return typeof e.schema=="string"?this.config.schemas?.[e.schema]??null:e.schema}resolveWatchFiles(e){if(this.hasGlob(e))return Cf(e,{nodir:!0,absolute:!0});if((0,Ri.existsSync)(e))try{if((0,Ri.statSync)(e).isDirectory()){let n=(0,u_.join)(e,"**","*.jsonl");return Cf(n,{nodir:!0,absolute:!0})}return[e]}catch{return[]}return[]}hasGlob(e){return/[*?[\]{}()]/.test(e)}async addTailer(e,r,n){if(this.tailers.has(e))return;let i=this.extractSessionIdFromPath(e),s=this.state.offsets[e]??0;if(s===0&&r.startAtEnd)try{s=(0,Ri.statSync)(e).size}catch{s=0}let o=new LI(e,s,async a=>{await this.handleLine(a,r,n,e,i)},a=>{this.state.offsets[e]=a,b5(this.statePath,this.state)});o.start(),this.tailers.set(e,o),b.info("TRANSCRIPT","Watching transcript file",{file:e,watch:r.name,schema:n.name})}async handleLine(e,r,n,i,s){try{let o=JSON.parse(e);await this.processor.processEntry(o,r,n,s??void 0)}catch(o){b.debug("TRANSCRIPT","Failed to parse transcript line",{watch:r.name,file:(0,u_.basename)(i)},o)}}extractSessionIdFromPath(e){let r=e.match(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i);return r?r[0]:null}};var MSe={},$Se=120*1e3;function XI(){return JI.default.join(Ee.get("CLAUDE_MEM_DATA_DIR"),".worker-start-attempted")}function ISe(){if(process.platform!=="win32")return!1;let t=XI();if(!(0,ns.existsSync)(t))return!1;try{let e=(0,ns.statSync)(t).mtimeMs;return Date.now()-e<$Se}catch{return!1}}function RSe(){if(process.platform==="win32")try{(0,ns.writeFileSync)(XI(),"","utf-8")}catch{}}function OSe(){if(process.platform==="win32")try{let t=XI();(0,ns.existsSync)(t)&&(0,ns.unlinkSync)(t)}catch{}}var CSe="10.6.3";function eH(t,e){return{continue:!0,suppressOutput:!0,status:t,...e&&{message:e}}}var d_=class{server;startTime=Date.now();mcpClient;mcpReady=!1;initializationCompleteFlag=!1;isShuttingDown=!1;dbManager;sessionManager;sseBroadcaster;sdkAgent;geminiAgent;openRouterAgent;paginationHelper;settingsManager;sessionEventBroadcaster;searchRoutes=null;chromaMcpManager=null;initializationComplete;resolveInitialization;stopOrphanReaper=null;staleSessionReaperInterval=null;transcriptWatcher=null;lastAiInteraction=null;constructor(){this.initializationComplete=new Promise(e=>{this.resolveInitialization=e}),this.dbManager=new bv,this.sessionManager=new Ev(this.dbManager),this.sseBroadcaster=new kv,this.sdkAgent=new ny(this.dbManager,this.sessionManager),this.geminiAgent=new iy(this.dbManager,this.sessionManager),this.openRouterAgent=new ay(this.dbManager,this.sessionManager),this.paginationHelper=new cy(this.dbManager),this.settingsManager=new uy(this.dbManager),this.sessionEventBroadcaster=new fy(this.sseBroadcaster,this),this.sessionManager.setOnSessionDeleted(()=>{this.broadcastProcessingStatus()}),this.mcpClient=new Ec({name:"worker-search-proxy",version:CSe},{capabilities:{}}),this.server=new gv({getInitializationComplete:()=>this.initializationCompleteFlag,getMcpReady:()=>this.mcpReady,onShutdown:()=>this.shutdown(),onRestart:()=>this.shutdown(),workerPath:__filename,getAiStatus:()=>{let e="claude";return Du()&&Ea()?e="openrouter":Mu()&&wa()&&(e="gemini"),{provider:e,authMethod:Xh(),lastInteraction:this.lastAiInteraction?{timestamp:this.lastAiInteraction.timestamp,success:this.lastAiInteraction.success,...this.lastAiInteraction.error&&{error:this.lastAiInteraction.error}}:null}}}),this.registerRoutes(),this.registerSignalHandlers()}registerSignalHandlers(){$M(async()=>{this.isShuttingDown=!0,await this.shutdown()})}registerRoutes(){this.server.app.get("/api/context/inject",async(e,r,n)=>{if(!this.initializationCompleteFlag||!this.searchRoutes){b.warn("SYSTEM","Context requested before initialization complete, returning empty"),r.status(200).json({content:[{type:"text",text:""}]});return}n()}),this.server.app.use("/api",async(e,r,n)=>{if(this.initializationCompleteFlag){n();return}let i=3e4,s=new Promise((o,a)=>setTimeout(()=>a(new Error("Database initialization timeout")),i));try{await Promise.race([this.initializationComplete,s]),n()}catch(o){b.error("HTTP",`Request to ${e.method} ${e.path} rejected \u2014 DB not initialized`,{},o),r.status(503).json({error:"Service initializing",message:"Database is still initializing, please retry"})}}),this.server.registerRoutes(new hy(this.sseBroadcaster,this.dbManager,this.sessionManager)),this.server.registerRoutes(new yy(this.sessionManager,this.dbManager,this.sdkAgent,this.geminiAgent,this.openRouterAgent,this.sessionEventBroadcaster,this)),this.server.registerRoutes(new _y(this.paginationHelper,this.dbManager,this.sessionManager,this.sseBroadcaster,this,this.startTime)),this.server.registerRoutes(new Oy(this.settingsManager)),this.server.registerRoutes(new Py),this.server.registerRoutes(new Ay(this.dbManager,"claude-mem"))}async start(){let e=Jr(),r=SE();await kM(),await this.server.listen(e,r),zM({pid:process.pid,port:e,startedAt:new Date().toISOString()}),vt().registerProcess("worker",{pid:process.pid,type:"worker",startedAt:new Date().toISOString()}),b.info("SYSTEM","Worker started",{host:r,port:e,pid:process.pid}),this.initializeBackground().catch(n=>{b.error("SYSTEM","Background initialization failed",{},n)})}async initializeBackground(){try{await LM();let{ModeManager:e}=await Promise.resolve().then(()=>(Qr(),A6)),{SettingsDefaultsManager:r}=await Promise.resolve().then(()=>(rr(),eM)),{USER_SETTINGS_PATH:n}=await Promise.resolve().then(()=>(jt(),cM)),i=r.loadFromFile(n);(i.CLAUDE_MEM_MODE==="local"||!i.CLAUDE_MEM_MODE)&&UM(),i.CLAUDE_MEM_CHROMA_ENABLED!=="false"?(this.chromaMcpManager=ws.getInstance(),b.info("SYSTEM","ChromaMcpManager initialized (lazy - connects on first use)")):b.info("SYSTEM","Chroma disabled via CLAUDE_MEM_CHROMA_ENABLED=false, skipping ChromaMcpManager");let o=i.CLAUDE_MEM_MODE;e.getInstance().loadMode(o),b.info("SYSTEM",`Mode loaded: ${o}`),await this.dbManager.initialize();let{PendingMessageStore:a}=await Promise.resolve().then(()=>(ha(),ou)),u=new a(this.dbManager.getSessionStore().db,3).resetStaleProcessingMessages(0);u>0&&b.info("SYSTEM",`Reset ${u} stale processing messages to pending`);let l=new dy,d=new py,p=new ly(this.dbManager.getSessionSearch(),this.dbManager.getSessionStore(),this.dbManager.getChromaSync(),l,d);if(this.searchRoutes=new $y(p),this.server.registerRoutes(this.searchRoutes),b.info("WORKER","SearchManager initialized and search routes registered"),this.initializationCompleteFlag=!0,this.resolveInitialization(),b.info("SYSTEM","Core initialization complete (DB + search ready)"),(0,ns.existsSync)(e_))try{let y=v5(e_);if(y.watches.length>0){let x=Aa(y.stateFile??"~/.claude-mem/transcript-watch-state.json");this.transcriptWatcher=new c_(y,x),await this.transcriptWatcher.start(),b.info("SYSTEM",`Transcript watcher started with ${y.watches.length} watch target(s)`)}}catch(y){b.warn("SYSTEM","Failed to start transcript watcher (non-fatal)",{},y)}this.chromaMcpManager&&Cc.backfillAllProjects().then(()=>{b.info("CHROMA_SYNC","Backfill check complete for all projects")}).catch(y=>{b.error("CHROMA_SYNC","Backfill failed (non-blocking)",{},y)});let f=JI.default.join(__dirname,"mcp-server.cjs");vt().assertCanSpawn("mcp server");let m=new $c({command:"node",args:[f],env:Ui(process.env)}),h=3e5,g=this.mcpClient.connect(m),v,S=new Promise((y,x)=>{v=setTimeout(()=>x(new Error("MCP connection timeout after 5 minutes")),h)});try{await Promise.race([g,S])}catch(y){clearTimeout(v),b.warn("WORKER","MCP server connection failed, cleaning up subprocess",{error:y instanceof Error?y.message:String(y)});try{await m.close()}catch{}throw y}clearTimeout(v);let _=m._process;_?.pid&&(vt().registerProcess("mcp-server",{pid:_.pid,type:"mcp",startedAt:new Date().toISOString()},_),_.once("exit",()=>{vt().unregisterProcess("mcp-server")})),this.mcpReady=!0,b.success("WORKER","MCP server connected"),this.stopOrphanReaper=C6(()=>{let y=new Set;for(let[x]of this.sessionManager.sessions)y.add(x);return y}),b.info("SYSTEM","Started orphan reaper (runs every 30 seconds)"),this.staleSessionReaperInterval=setInterval(async()=>{try{let y=await this.sessionManager.reapStaleSessions();y>0&&b.info("SYSTEM",`Reaped ${y} stale sessions`)}catch(y){b.error("SYSTEM","Stale session reaper error",{error:y instanceof Error?y.message:String(y)})}},120*1e3),this.processPendingQueues(50).then(y=>{y.sessionsStarted>0&&b.info("SYSTEM",`Auto-recovered ${y.sessionsStarted} sessions with pending work`,{totalPending:y.totalPendingSessions,started:y.sessionsStarted,sessionIds:y.startedSessionIds})}).catch(y=>{b.error("SYSTEM","Auto-recovery of pending queues failed",{},y)})}catch(e){throw b.error("SYSTEM","Background initialization failed",{},e),e}}getActiveAgent(){return Du()&&Ea()?this.openRouterAgent:Mu()&&wa()?this.geminiAgent:this.sdkAgent}startSessionProcessor(e,r){if(!e)return;let n=e.sessionDbId,i=this.getActiveAgent(),s=i.constructor.name;e.abortController.signal.aborted&&(b.debug("SYSTEM","Replacing aborted AbortController before starting generator",{sessionId:e.sessionDbId}),e.abortController=new AbortController);let o=!1,a=!1;b.info("SYSTEM",`Starting generator (${r}) using ${s}`,{sessionId:n}),e.lastGeneratorActivity=Date.now(),e.generatorPromise=i.startSession(e,this).catch(async c=>{let u=c?.message||"";if(["Claude executable not found","CLAUDE_CODE_PATH","ENOENT","spawn","Invalid API key","API_KEY_INVALID","API key expired","API key not valid","PERMISSION_DENIED","Gemini API error: 400","Gemini API error: 401","Gemini API error: 403","FOREIGN KEY constraint failed"].some(d=>u.includes(d))){o=!0,this.lastAiInteraction={timestamp:Date.now(),success:!1,provider:s,error:u},b.error("SDK","Unrecoverable generator error - will NOT restart",{sessionId:e.sessionDbId,project:e.project,errorMessage:u});return}if(this.isSessionTerminatedError(c))return b.warn("SDK","SDK resume failed, falling back to standalone processing",{sessionId:e.sessionDbId,project:e.project,reason:c instanceof Error?c.message:String(c)}),this.runFallbackForTerminatedSession(e,c);throw(u.includes("aborted by user")||u.includes("No conversation found"))&&e.memorySessionId&&(b.warn("SDK","Detected stale resume failure, clearing memorySessionId for fresh start",{sessionId:e.sessionDbId,memorySessionId:e.memorySessionId,errorMessage:u}),this.dbManager.getSessionStore().updateMemorySessionId(e.sessionDbId,null),e.memorySessionId=null,e.forceInit=!0),b.error("SDK","Session generator failed",{sessionId:e.sessionDbId,project:e.project,provider:s},c),a=!0,this.lastAiInteraction={timestamp:Date.now(),success:!1,provider:s,error:u},c}).finally(async()=>{let c=go(e.sessionDbId);if(c&&c.process.exitCode===null&&await vo(c,5e3),e.generatorPromise=null,!a&&!o&&(this.lastAiInteraction={timestamp:Date.now(),success:!0,provider:s}),o){this.terminateSession(e.sessionDbId,"unrecoverable_error");return}let l=this.sessionManager.getPendingMessageStore().getPendingCount(e.sessionDbId);if(e.idleTimedOut&&(e.idleTimedOut=!1,l===0)){this.terminateSession(e.sessionDbId,"idle_timeout");return}let d=3;if(l>0){if(e.consecutiveRestarts=(e.consecutiveRestarts||0)+1,e.consecutiveRestarts>d){b.error("SYSTEM","Exceeded max pending-work restarts, stopping to prevent infinite loop",{sessionId:e.sessionDbId,pendingCount:l,consecutiveRestarts:e.consecutiveRestarts}),e.consecutiveRestarts=0,this.terminateSession(e.sessionDbId,"max_restarts_exceeded");return}b.info("SYSTEM","Pending work remains after generator exit, restarting with fresh AbortController",{sessionId:e.sessionDbId,pendingCount:l,attempt:e.consecutiveRestarts}),e.abortController=new AbortController,this.startSessionProcessor(e,"pending-work-restart"),this.broadcastProcessingStatus()}else e.consecutiveRestarts=0,this.sessionManager.removeSessionImmediate(e.sessionDbId)})}isSessionTerminatedError(e){let n=(e instanceof Error?e.message:String(e)).toLowerCase();return n.includes("process aborted by user")||n.includes("processtransport")||n.includes("not ready for writing")||n.includes("session generator failed")||n.includes("claude code process")}async runFallbackForTerminatedSession(e,r){if(!e)return;let n=e.sessionDbId;if(!e.memorySessionId){let o=`fallback-${n}-${Date.now()}`;e.memorySessionId=o,this.dbManager.getSessionStore().updateMemorySessionId(n,o)}if(wa())try{await this.geminiAgent.startSession(e,this);return}catch(o){b.warn("SDK","Fallback Gemini failed, trying OpenRouter",{sessionId:n,error:o instanceof Error?o.message:String(o)})}if(Ea())try{await this.openRouterAgent.startSession(e,this);return}catch(o){b.warn("SDK","Fallback OpenRouter failed",{sessionId:n,error:o instanceof Error?o.message:String(o)})}let s=this.sessionManager.getPendingMessageStore().markAllSessionMessagesAbandoned(n);s>0&&b.warn("SDK","No fallback available; marked pending messages abandoned",{sessionId:n,abandoned:s}),this.sessionManager.removeSessionImmediate(n),this.sessionEventBroadcaster.broadcastSessionCompleted(n)}terminateSession(e,r){let i=this.sessionManager.getPendingMessageStore().markAllSessionMessagesAbandoned(e);b.info("SYSTEM","Session terminated",{sessionId:e,reason:r,abandonedMessages:i}),this.sessionManager.removeSessionImmediate(e)}async processPendingQueues(e=10){let{PendingMessageStore:r}=await Promise.resolve().then(()=>(ha(),ou)),n=new r(this.dbManager.getSessionStore().db,3),i=this.dbManager.getSessionStore(),s=360*60*1e3,o=Date.now()-s;try{let u=i.db.prepare(` +`);this.tailState.partial=s.pop()??"";for(let o of s){let a=o.trim();a&&await this.onLine(a)}}},c_=class{constructor(e,r){this.config=e;this.statePath=r;this.state=_5(r)}processor=new a_;tailers=new Map;state;rescanTimers=[];async start(){for(let e of this.config.watches)await this.setupWatch(e)}stop(){for(let e of this.tailers.values())e.close();this.tailers.clear();for(let e of this.rescanTimers)clearInterval(e);this.rescanTimers=[]}async setupWatch(e){let r=this.resolveSchema(e);if(!r){b.warn("TRANSCRIPT","Missing schema for watch",{watch:e.name});return}let n=Aa(e.path),i=this.resolveWatchFiles(n);for(let a of i)await this.addTailer(a,e,r);let s=e.rescanIntervalMs??5e3,o=setInterval(async()=>{let a=this.resolveWatchFiles(n);for(let c of a)this.tailers.has(c)||await this.addTailer(c,e,r)},s);this.rescanTimers.push(o)}resolveSchema(e){return typeof e.schema=="string"?this.config.schemas?.[e.schema]??null:e.schema}resolveWatchFiles(e){if(this.hasGlob(e))return Cf(e,{nodir:!0,absolute:!0});if((0,Ri.existsSync)(e))try{if((0,Ri.statSync)(e).isDirectory()){let n=(0,u_.join)(e,"**","*.jsonl");return Cf(n,{nodir:!0,absolute:!0})}return[e]}catch{return[]}return[]}hasGlob(e){return/[*?[\]{}()]/.test(e)}async addTailer(e,r,n){if(this.tailers.has(e))return;let i=this.extractSessionIdFromPath(e),s=this.state.offsets[e]??0;if(s===0&&r.startAtEnd)try{s=(0,Ri.statSync)(e).size}catch{s=0}let o=new LI(e,s,async a=>{await this.handleLine(a,r,n,e,i)},a=>{this.state.offsets[e]=a,b5(this.statePath,this.state)});o.start(),this.tailers.set(e,o),b.info("TRANSCRIPT","Watching transcript file",{file:e,watch:r.name,schema:n.name})}async handleLine(e,r,n,i,s){try{let o=JSON.parse(e);await this.processor.processEntry(o,r,n,s??void 0)}catch(o){b.debug("TRANSCRIPT","Failed to parse transcript line",{watch:r.name,file:(0,u_.basename)(i)},o)}}extractSessionIdFromPath(e){let r=e.match(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i);return r?r[0]:null}};var MSe={},$Se=120*1e3;function XI(){return JI.default.join(Ee.get("CLAUDE_MEM_DATA_DIR"),".worker-start-attempted")}function ISe(){if(process.platform!=="win32")return!1;let t=XI();if(!(0,ns.existsSync)(t))return!1;try{let e=(0,ns.statSync)(t).mtimeMs;return Date.now()-e<$Se}catch{return!1}}function RSe(){if(process.platform==="win32")try{(0,ns.writeFileSync)(XI(),"","utf-8")}catch{}}function OSe(){if(process.platform==="win32")try{let t=XI();(0,ns.existsSync)(t)&&(0,ns.unlinkSync)(t)}catch{}}var CSe="10.7.0";function eH(t,e){return{continue:!0,suppressOutput:!0,status:t,...e&&{message:e}}}var d_=class{server;startTime=Date.now();mcpClient;mcpReady=!1;initializationCompleteFlag=!1;isShuttingDown=!1;dbManager;sessionManager;sseBroadcaster;sdkAgent;geminiAgent;openRouterAgent;paginationHelper;settingsManager;sessionEventBroadcaster;searchRoutes=null;chromaMcpManager=null;initializationComplete;resolveInitialization;stopOrphanReaper=null;staleSessionReaperInterval=null;transcriptWatcher=null;lastAiInteraction=null;constructor(){this.initializationComplete=new Promise(e=>{this.resolveInitialization=e}),this.dbManager=new bv,this.sessionManager=new Ev(this.dbManager),this.sseBroadcaster=new kv,this.sdkAgent=new ny(this.dbManager,this.sessionManager),this.geminiAgent=new iy(this.dbManager,this.sessionManager),this.openRouterAgent=new ay(this.dbManager,this.sessionManager),this.paginationHelper=new cy(this.dbManager),this.settingsManager=new uy(this.dbManager),this.sessionEventBroadcaster=new fy(this.sseBroadcaster,this),this.sessionManager.setOnSessionDeleted(()=>{this.broadcastProcessingStatus()}),this.mcpClient=new Ec({name:"worker-search-proxy",version:CSe},{capabilities:{}}),this.server=new gv({getInitializationComplete:()=>this.initializationCompleteFlag,getMcpReady:()=>this.mcpReady,onShutdown:()=>this.shutdown(),onRestart:()=>this.shutdown(),workerPath:__filename,getAiStatus:()=>{let e="claude";return Du()&&Ea()?e="openrouter":Mu()&&wa()&&(e="gemini"),{provider:e,authMethod:Xh(),lastInteraction:this.lastAiInteraction?{timestamp:this.lastAiInteraction.timestamp,success:this.lastAiInteraction.success,...this.lastAiInteraction.error&&{error:this.lastAiInteraction.error}}:null}}}),this.registerRoutes(),this.registerSignalHandlers()}registerSignalHandlers(){$M(async()=>{this.isShuttingDown=!0,await this.shutdown()})}registerRoutes(){this.server.app.get("/api/context/inject",async(e,r,n)=>{if(!this.initializationCompleteFlag||!this.searchRoutes){b.warn("SYSTEM","Context requested before initialization complete, returning empty"),r.status(200).json({content:[{type:"text",text:""}]});return}n()}),this.server.app.use("/api",async(e,r,n)=>{if(this.initializationCompleteFlag){n();return}let i=3e4,s=new Promise((o,a)=>setTimeout(()=>a(new Error("Database initialization timeout")),i));try{await Promise.race([this.initializationComplete,s]),n()}catch(o){b.error("HTTP",`Request to ${e.method} ${e.path} rejected \u2014 DB not initialized`,{},o),r.status(503).json({error:"Service initializing",message:"Database is still initializing, please retry"})}}),this.server.registerRoutes(new hy(this.sseBroadcaster,this.dbManager,this.sessionManager)),this.server.registerRoutes(new yy(this.sessionManager,this.dbManager,this.sdkAgent,this.geminiAgent,this.openRouterAgent,this.sessionEventBroadcaster,this)),this.server.registerRoutes(new _y(this.paginationHelper,this.dbManager,this.sessionManager,this.sseBroadcaster,this,this.startTime)),this.server.registerRoutes(new Oy(this.settingsManager)),this.server.registerRoutes(new Py),this.server.registerRoutes(new Ay(this.dbManager,"claude-mem"))}async start(){let e=Jr(),r=SE();await kM(),await this.server.listen(e,r),zM({pid:process.pid,port:e,startedAt:new Date().toISOString()}),vt().registerProcess("worker",{pid:process.pid,type:"worker",startedAt:new Date().toISOString()}),b.info("SYSTEM","Worker started",{host:r,port:e,pid:process.pid}),this.initializeBackground().catch(n=>{b.error("SYSTEM","Background initialization failed",{},n)})}async initializeBackground(){try{await LM();let{ModeManager:e}=await Promise.resolve().then(()=>(Qr(),A6)),{SettingsDefaultsManager:r}=await Promise.resolve().then(()=>(rr(),eM)),{USER_SETTINGS_PATH:n}=await Promise.resolve().then(()=>(jt(),cM)),i=r.loadFromFile(n);(i.CLAUDE_MEM_MODE==="local"||!i.CLAUDE_MEM_MODE)&&UM(),i.CLAUDE_MEM_CHROMA_ENABLED!=="false"?(this.chromaMcpManager=ws.getInstance(),b.info("SYSTEM","ChromaMcpManager initialized (lazy - connects on first use)")):b.info("SYSTEM","Chroma disabled via CLAUDE_MEM_CHROMA_ENABLED=false, skipping ChromaMcpManager");let o=i.CLAUDE_MEM_MODE;e.getInstance().loadMode(o),b.info("SYSTEM",`Mode loaded: ${o}`),await this.dbManager.initialize();let{PendingMessageStore:a}=await Promise.resolve().then(()=>(ha(),ou)),u=new a(this.dbManager.getSessionStore().db,3).resetStaleProcessingMessages(0);u>0&&b.info("SYSTEM",`Reset ${u} stale processing messages to pending`);let l=new dy,d=new py,p=new ly(this.dbManager.getSessionSearch(),this.dbManager.getSessionStore(),this.dbManager.getChromaSync(),l,d);if(this.searchRoutes=new $y(p),this.server.registerRoutes(this.searchRoutes),b.info("WORKER","SearchManager initialized and search routes registered"),this.initializationCompleteFlag=!0,this.resolveInitialization(),b.info("SYSTEM","Core initialization complete (DB + search ready)"),(0,ns.existsSync)(e_))try{let y=v5(e_);if(y.watches.length>0){let x=Aa(y.stateFile??"~/.claude-mem/transcript-watch-state.json");this.transcriptWatcher=new c_(y,x),await this.transcriptWatcher.start(),b.info("SYSTEM",`Transcript watcher started with ${y.watches.length} watch target(s)`)}}catch(y){b.warn("SYSTEM","Failed to start transcript watcher (non-fatal)",{},y)}this.chromaMcpManager&&Cc.backfillAllProjects().then(()=>{b.info("CHROMA_SYNC","Backfill check complete for all projects")}).catch(y=>{b.error("CHROMA_SYNC","Backfill failed (non-blocking)",{},y)});let f=JI.default.join(__dirname,"mcp-server.cjs");vt().assertCanSpawn("mcp server");let m=new $c({command:"node",args:[f],env:Ui(process.env)}),h=3e5,g=this.mcpClient.connect(m),v,S=new Promise((y,x)=>{v=setTimeout(()=>x(new Error("MCP connection timeout after 5 minutes")),h)});try{await Promise.race([g,S])}catch(y){clearTimeout(v),b.warn("WORKER","MCP server connection failed, cleaning up subprocess",{error:y instanceof Error?y.message:String(y)});try{await m.close()}catch{}throw y}clearTimeout(v);let _=m._process;_?.pid&&(vt().registerProcess("mcp-server",{pid:_.pid,type:"mcp",startedAt:new Date().toISOString()},_),_.once("exit",()=>{vt().unregisterProcess("mcp-server")})),this.mcpReady=!0,b.success("WORKER","MCP server connected"),this.stopOrphanReaper=C6(()=>{let y=new Set;for(let[x]of this.sessionManager.sessions)y.add(x);return y}),b.info("SYSTEM","Started orphan reaper (runs every 30 seconds)"),this.staleSessionReaperInterval=setInterval(async()=>{try{let y=await this.sessionManager.reapStaleSessions();y>0&&b.info("SYSTEM",`Reaped ${y} stale sessions`)}catch(y){b.error("SYSTEM","Stale session reaper error",{error:y instanceof Error?y.message:String(y)})}},120*1e3),this.processPendingQueues(50).then(y=>{y.sessionsStarted>0&&b.info("SYSTEM",`Auto-recovered ${y.sessionsStarted} sessions with pending work`,{totalPending:y.totalPendingSessions,started:y.sessionsStarted,sessionIds:y.startedSessionIds})}).catch(y=>{b.error("SYSTEM","Auto-recovery of pending queues failed",{},y)})}catch(e){throw b.error("SYSTEM","Background initialization failed",{},e),e}}getActiveAgent(){return Du()&&Ea()?this.openRouterAgent:Mu()&&wa()?this.geminiAgent:this.sdkAgent}startSessionProcessor(e,r){if(!e)return;let n=e.sessionDbId,i=this.getActiveAgent(),s=i.constructor.name;e.abortController.signal.aborted&&(b.debug("SYSTEM","Replacing aborted AbortController before starting generator",{sessionId:e.sessionDbId}),e.abortController=new AbortController);let o=!1,a=!1;b.info("SYSTEM",`Starting generator (${r}) using ${s}`,{sessionId:n}),e.lastGeneratorActivity=Date.now(),e.generatorPromise=i.startSession(e,this).catch(async c=>{let u=c?.message||"";if(["Claude executable not found","CLAUDE_CODE_PATH","ENOENT","spawn","Invalid API key","API_KEY_INVALID","API key expired","API key not valid","PERMISSION_DENIED","Gemini API error: 400","Gemini API error: 401","Gemini API error: 403","FOREIGN KEY constraint failed"].some(d=>u.includes(d))){o=!0,this.lastAiInteraction={timestamp:Date.now(),success:!1,provider:s,error:u},b.error("SDK","Unrecoverable generator error - will NOT restart",{sessionId:e.sessionDbId,project:e.project,errorMessage:u});return}if(this.isSessionTerminatedError(c))return b.warn("SDK","SDK resume failed, falling back to standalone processing",{sessionId:e.sessionDbId,project:e.project,reason:c instanceof Error?c.message:String(c)}),this.runFallbackForTerminatedSession(e,c);throw(u.includes("aborted by user")||u.includes("No conversation found"))&&e.memorySessionId&&(b.warn("SDK","Detected stale resume failure, clearing memorySessionId for fresh start",{sessionId:e.sessionDbId,memorySessionId:e.memorySessionId,errorMessage:u}),this.dbManager.getSessionStore().updateMemorySessionId(e.sessionDbId,null),e.memorySessionId=null,e.forceInit=!0),b.error("SDK","Session generator failed",{sessionId:e.sessionDbId,project:e.project,provider:s},c),a=!0,this.lastAiInteraction={timestamp:Date.now(),success:!1,provider:s,error:u},c}).finally(async()=>{let c=go(e.sessionDbId);if(c&&c.process.exitCode===null&&await vo(c,5e3),e.generatorPromise=null,!a&&!o&&(this.lastAiInteraction={timestamp:Date.now(),success:!0,provider:s}),o){this.terminateSession(e.sessionDbId,"unrecoverable_error");return}let l=this.sessionManager.getPendingMessageStore().getPendingCount(e.sessionDbId);if(e.idleTimedOut&&(e.idleTimedOut=!1,l===0)){this.terminateSession(e.sessionDbId,"idle_timeout");return}let d=3;if(l>0){if(e.consecutiveRestarts=(e.consecutiveRestarts||0)+1,e.consecutiveRestarts>d){b.error("SYSTEM","Exceeded max pending-work restarts, stopping to prevent infinite loop",{sessionId:e.sessionDbId,pendingCount:l,consecutiveRestarts:e.consecutiveRestarts}),e.consecutiveRestarts=0,this.terminateSession(e.sessionDbId,"max_restarts_exceeded");return}b.info("SYSTEM","Pending work remains after generator exit, restarting with fresh AbortController",{sessionId:e.sessionDbId,pendingCount:l,attempt:e.consecutiveRestarts}),e.abortController=new AbortController,this.startSessionProcessor(e,"pending-work-restart"),this.broadcastProcessingStatus()}else e.consecutiveRestarts=0,this.sessionManager.removeSessionImmediate(e.sessionDbId)})}isSessionTerminatedError(e){let n=(e instanceof Error?e.message:String(e)).toLowerCase();return n.includes("process aborted by user")||n.includes("processtransport")||n.includes("not ready for writing")||n.includes("session generator failed")||n.includes("claude code process")}async runFallbackForTerminatedSession(e,r){if(!e)return;let n=e.sessionDbId;if(!e.memorySessionId){let o=`fallback-${n}-${Date.now()}`;e.memorySessionId=o,this.dbManager.getSessionStore().updateMemorySessionId(n,o)}if(wa())try{await this.geminiAgent.startSession(e,this);return}catch(o){b.warn("SDK","Fallback Gemini failed, trying OpenRouter",{sessionId:n,error:o instanceof Error?o.message:String(o)})}if(Ea())try{await this.openRouterAgent.startSession(e,this);return}catch(o){b.warn("SDK","Fallback OpenRouter failed",{sessionId:n,error:o instanceof Error?o.message:String(o)})}let s=this.sessionManager.getPendingMessageStore().markAllSessionMessagesAbandoned(n);s>0&&b.warn("SDK","No fallback available; marked pending messages abandoned",{sessionId:n,abandoned:s}),this.sessionManager.removeSessionImmediate(n),this.sessionEventBroadcaster.broadcastSessionCompleted(n)}terminateSession(e,r){let i=this.sessionManager.getPendingMessageStore().markAllSessionMessagesAbandoned(e);b.info("SYSTEM","Session terminated",{sessionId:e,reason:r,abandonedMessages:i}),this.sessionManager.removeSessionImmediate(e)}async processPendingQueues(e=10){let{PendingMessageStore:r}=await Promise.resolve().then(()=>(ha(),ou)),n=new r(this.dbManager.getSessionStore().db,3),i=this.dbManager.getSessionStore(),s=360*60*1e3,o=Date.now()-s;try{let u=i.db.prepare(` SELECT id FROM sdk_sessions WHERE status = 'active' AND started_at_epoch < ? `).all(o);if(u.length>0){let l=u.map(f=>f.id),d=l.map(()=>"?").join(",");i.db.prepare(` diff --git a/plugin/skills/version-bump/SKILL.md b/plugin/skills/version-bump/SKILL.md new file mode 100644 index 00000000..73e4cc57 --- /dev/null +++ b/plugin/skills/version-bump/SKILL.md @@ -0,0 +1,42 @@ +--- +name: claude-code-plugin-release +description: Automated semantic versioning and release workflow for Claude Code plugins. Handles version increments across package.json, marketplace.json, and plugin.json, build verification, git tagging, GitHub releases, and changelog generation. +--- + +# Version Bump & Release Workflow + +**IMPORTANT:** You must first plan and write detailed release notes before starting the version bump workflow. + +**CRITICAL:** ALWAYS commit EVERYTHING (including build artifacts). At the end of this workflow, NOTHING should be left uncommitted or unpushed. Run `git status` at the end to verify. + +## Preparation + +1. **Analyze**: Determine if the change is a **PATCH** (bug fixes), **MINOR** (features), or **MAJOR** (breaking) update. +2. **Environment**: Identify the repository owner and name (e.g., from `git remote -v`). +3. **Paths**: Verify existence of `package.json`, `.claude-plugin/marketplace.json`, and `plugin/.claude-plugin/plugin.json`. + +## Workflow + +1. **Update**: Increment version strings in all configuration files. +2. **Verify**: Use `grep` to ensure all files match the new version. +3. **Build**: Run `npm run build` to generate fresh artifacts. +4. **Commit**: Stage all changes including artifacts: `git add -A && git commit -m "chore: bump version to X.Y.Z"`. +5. **Tag**: Create an annotated tag: `git tag -a vX.Y.Z -m "Version X.Y.Z"`. +6. **Push**: `git push origin main && git push origin vX.Y.Z`. +7. **Release**: `gh release create vX.Y.Z --title "vX.Y.Z" --notes "RELEASE_NOTES"`. +8. **Changelog**: Regenerate `CHANGELOG.md` using the GitHub API and the provided script: + ```bash + gh api repos/{owner}/{repo}/releases --paginate | ./scripts/generate_changelog.js > CHANGELOG.md + ``` +9. **Sync**: Commit and push the updated `CHANGELOG.md`. +10. **Notify**: Run `npm run discord:notify vX.Y.Z` if applicable. +11. **Finalize**: Run `git status` to ensure a clean working tree. + +## Checklist + +- [ ] All config files have matching versions +- [ ] `npm run build` succeeded +- [ ] Git tag created and pushed +- [ ] GitHub release created with notes +- [ ] `CHANGELOG.md` updated and pushed +- [ ] `git status` shows clean tree diff --git a/plugin/skills/version-bump/scripts/generate_changelog.js b/plugin/skills/version-bump/scripts/generate_changelog.js new file mode 100755 index 00000000..faa82e02 --- /dev/null +++ b/plugin/skills/version-bump/scripts/generate_changelog.js @@ -0,0 +1,37 @@ +#!/usr/bin/env node +const fs = require('fs'); + +/** + * Processes GitHub release JSON from stdin and outputs a formatted CHANGELOG.md + */ +function generate() { + try { + const input = fs.readFileSync(0, 'utf8'); + if (!input || input.trim() === '') { + process.stderr.write('No input received on stdin +'); + process.exit(1); + } + + const releases = JSON.parse(input); + const lines = ['# Changelog', '', 'All notable changes to this project.', '']; + + releases.slice(0, 50).forEach(r => { + const date = r.published_at.split('T')[0]; + lines.push(`## [${r.tag_name}] - ${date}`); + lines.push(''); + if (r.body) lines.push(r.body.trim()); + lines.push(''); + }); + + process.stdout.write(lines.join(' +') + ' +'); + } catch (err) { + process.stderr.write(`Error generating changelog: ${err.message} +`); + process.exit(1); + } +} + +generate();